repo_name
stringlengths 6
91
| path
stringlengths 8
968
| copies
stringclasses 210
values | size
stringlengths 2
7
| content
stringlengths 61
1.01M
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 6
99.8
| line_max
int64 12
1k
| alpha_frac
float64 0.3
0.91
| ratio
float64 2
9.89
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
cuappdev/eatery | Eatery/Views/Eateries/FilterBar.swift | 1 | 5506 | import UIKit
import SnapKit
enum Filter: String {
static let areaFilters: Set<Filter> = [
.north,
.west,
.central
]
static let categoryFilters: Set<Filter> = [
.pizza,
.chinese,
.wings,
.korean,
.japanese,
.thai,
.burgers,
.mexican,
.bubbleTea
]
case nearest = "Nearest First"
case north = "North"
case west = "West"
case central = "Central"
case swipes = "Swipes"
case brb = "BRB"
case pizza = "Pizza"
case chinese = "Chinese"
case wings = "Wings"
case korean = "Korean"
case japanese = "Japanese"
case thai = "Thai"
case burgers = "Burgers"
case mexican = "Mexican"
case bubbleTea = "Bubble Tea"
}
protocol FilterBarDelegate: AnyObject {
func filterBar(_ filterBar: FilterBar, selectedFiltersDidChange newValue: [Filter])
func filterBar(_ filterBar: FilterBar, filterWasSelected filter: Filter)
}
class FilterBar: UIView {
private var buttons: [Filter : UIButton] = [:]
weak var delegate: FilterBarDelegate?
var scrollView: UIScrollView!
let padding: CGFloat = EateriesViewController.collectionViewMargin
var displayedFilters: [Filter] = [] {
didSet {
layoutButtons(filters: displayedFilters)
if let prevFilters = UserDefaults.standard.stringArray(forKey: "filters") {
for string in prevFilters {
if let filter = Filter(rawValue: string), buttons.keys.contains(filter) {
selectedFilters.insert(filter)
buttons[filter]!.isSelected = true
}
}
delegate?.filterBar(self, selectedFiltersDidChange: Array(selectedFilters))
}
}
}
var selectedFilters: Set<Filter> = []
override init(frame: CGRect) {
super.init(frame: frame)
backgroundColor = .clear
scrollView = UIScrollView()
scrollView.showsHorizontalScrollIndicator = false
scrollView.contentInset.left = padding
scrollView.contentInset.right = padding
scrollView.alwaysBounceHorizontal = true
addSubview(scrollView)
scrollView.snp.makeConstraints { make in
make.edges.equalToSuperview()
}
snp.makeConstraints { make in
make.height.equalTo(44)
}
}
func layoutButtons(filters: [Filter]) {
var totalWidth: CGFloat = 0.0
var previousLayout: UIButton?
for (index, filter) in filters.enumerated() {
let button = UIButton()
button.setTitle(filter.rawValue, for: .normal)
button.setTitleColor(UIColor.eateryBlue.withAlphaComponent(0.8), for: .normal)
button.setTitleColor(UIColor.eateryBlue.withAlphaComponent(0.8), for: .highlighted)
button.setTitleColor(.white, for: .selected)
button.setBackgroundImage(UIImage.image(withColor: UIColor(white: 0.95, alpha: 1.0)), for: .normal)
button.setBackgroundImage(UIImage.image(withColor: UIColor(white: 0.85, alpha: 1.0)), for: .highlighted)
button.setBackgroundImage(UIImage.image(withColor: UIColor.eateryBlue), for: .selected)
button.setBackgroundImage(UIImage.image(withColor: UIColor.transparentEateryBlue), for: .focused)
button.layer.cornerRadius = 8.0
button.clipsToBounds = true
button.titleLabel?.font = UIFont.systemFont(ofSize: 14.0, weight: .medium)
button.isSelected = selectedFilters.contains(filter)
button.sizeToFit()
button.frame.size.width += 16.0
button.frame.size.height = frame.height
button.center.y = frame.height / 2
button.tag = index
button.addTarget(self, action: #selector(buttonPressed(sender:)), for: .touchUpInside)
scrollView.addSubview(button)
button.snp.makeConstraints { make in
make.centerY.equalTo(snp.centerY)
make.width.equalTo(button.frame.size.width)
make.height.equalToSuperview().offset(-padding)
if previousLayout == nil {
make.leading.equalToSuperview()
} else {
make.leading.equalTo(previousLayout!.snp.trailing).offset(padding / 2)
}
}
buttons[filter] = button
previousLayout = button
totalWidth += button.frame.width + (index == filters.count - 1 ? 0.0 : padding / 2)
}
scrollView.contentSize = CGSize(width: totalWidth, height: frame.height)
scrollView.setContentOffset(CGPoint(x: -padding, y: 0), animated: false)
}
@objc func buttonPressed(sender: UIButton) {
sender.isSelected.toggle()
if sender.isSelected {
let filter = displayedFilters[sender.tag]
selectedFilters.insert(filter)
delegate?.filterBar(self, filterWasSelected: filter)
} else {
selectedFilters.remove(displayedFilters[sender.tag])
}
let defaults = UserDefaults.standard
defaults.set(selectedFilters.map { $0.rawValue }, forKey: "filters")
delegate?.filterBar(self, selectedFiltersDidChange: Array(selectedFilters))
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| mit | 3ea4052378a7077ab0846d3b91b3372b | 31.579882 | 116 | 0.608972 | 4.670059 | false | false | false | false |
timmystephani/monopoly | ios/Monopoly/Monopoly/Player.swift | 1 | 535 | //
// Player.swift
// Monopoly
//
// Created by Tim Stephani on 7/18/15.
// Copyright (c) 2015 Tim Stephani. All rights reserved.
//
class Player {
var id : Int
//var user_id : Int
var name : String
var cash : Int
var in_jail : Bool
var position : Int
var user : User?
init(id: Int, name: String, cash: Int, in_jail: Bool, position: Int) {
self.id = id
self.name = name
self.cash = cash
self.in_jail = in_jail
self.position = position
}
}
| mit | 1a472dda4cbbafaa8bbc1133a0f85849 | 18.814815 | 74 | 0.551402 | 3.262195 | false | false | false | false |
rolson/arcgis-runtime-samples-ios | arcgis-ios-sdk-samples/Scenes/Scene properties expressions/ScenePropertiesExpressionsViewController.swift | 1 | 3353 | //
// Copyright 2016 Esri.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import UIKit
import ArcGIS
class ScenePropertiesExpressionsViewController: UIViewController {
@IBOutlet var sceneView: AGSSceneView!
@IBOutlet var headingLabel: UILabel!
@IBOutlet var pitchLabel: UILabel!
private var coneGraphic: AGSGraphic!
override func viewDidLoad() {
super.viewDidLoad()
//add the source code button item to the right of navigation bar
(self.navigationItem.rightBarButtonItem as! SourceCodeBarButtonItem).filenames = ["ScenePropertiesExpressionsViewController"]
//initialize scene with topographic basemap
let scene = AGSScene(basemap: AGSBasemap.streetsBasemap())
//assign scene to the scene view
self.sceneView.scene = scene
//set the viewpoint camera
let point = AGSPoint(x: 83.9, y: 28.4, z: 5200, spatialReference: AGSSpatialReference.WGS84())
let camera = AGSCamera(lookAtPoint: point, distance: 1000, heading: 0, pitch: 50, roll: 0)
self.sceneView.setViewpointCamera(camera)
//create a graphics overlay
let graphicsOverlay = AGSGraphicsOverlay()
graphicsOverlay.sceneProperties?.surfacePlacement = .Relative
//add it to the scene view
self.sceneView.graphicsOverlays.addObject(graphicsOverlay)
//add renderer using rotation expressions
let renderer = AGSSimpleRenderer()
renderer.sceneProperties?.headingExpression = "[HEADING]"
renderer.sceneProperties?.pitchExpression = "[PITCH]"
graphicsOverlay.renderer = renderer
//create a red cone graphic
let coneSymbol = AGSSimpleMarkerSceneSymbol(style: .Cone, color: UIColor.redColor(), height: 200, width: 100, depth: 100, anchorPosition: .Center)
coneSymbol.pitch = -90 //correct symbol's default pitch
let conePoint = AGSPoint(x: 83.9, y: 28.404, z: 5000, spatialReference: AGSSpatialReference.WGS84())
let coneAttributes = ["HEADING": 0, "PITCH": 0]
self.coneGraphic = AGSGraphic(geometry: conePoint, symbol: coneSymbol, attributes: coneAttributes)
graphicsOverlay.graphics.addObject(self.coneGraphic)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func headingSliderValueChanged(slider: UISlider) {
coneGraphic.attributes["HEADING"] = slider.value
//update label
self.headingLabel.text = "\(Int(slider.value))"
}
@IBAction func pitchSliderValueChanged(slider: UISlider) {
coneGraphic.attributes["PITCH"] = slider.value
//update label
self.pitchLabel.text = "\(Int(slider.value))"
}
}
| apache-2.0 | d41befb261b55972df8c25187beb2e9b | 40.395062 | 154 | 0.688637 | 4.67643 | false | false | false | false |
zxpLearnios/MyProject | test_projectDemo1/GuideVC/Voice&&vedio/MyMusicPlayer.swift | 1 | 1693 | //
// MyMusicPlayer.swift
// test_projectDemo1
//
// Created by Jingnan Zhang on 16/6/16.
// Copyright © 2016年 Jingnan Zhang. All rights reserved.
// 播放音频
// 1. AVPlayer、AVAudioPlayer 播放本地都可以(不需要AVPlayerItem);2.AVPlayer播放远程音频,必须是打开就播放的那种;
// 3.
import UIKit
import AVFoundation
class MyMusicPlayer: AVPlayer {
fileprivate var musicPlayer:AVAudioPlayer!, voicePlayer:AVPlayer!, playeItem:AVPlayerItem!
override init() {
super.init()
// 1.
let str = "http://m2.music.126.net/feplW2VPVs9Y8lE_I08BQQ==/1386484166585821.mp3" // http://v1.mukewang.com/a45016f4-08d6-4277-abe6-bcfd5244c201/L.mp4
let onlineUrl = URL.init(string: str)
playeItem = AVPlayerItem.init(url: onlineUrl!)
voicePlayer = AVPlayer.init(url: onlineUrl!) // 播放网络音频
// 2.
let path = Bundle.main.path(forResource: "背叛情歌.mp3", ofType: nil)
let localUrl = URL(fileURLWithPath: path!)
// musicPlayer = try! AVAudioPlayer.init(contentsOfURL: localUrl) // 播放本地音频
// voicePlayer = AVPlayer( localUrl) // 播放本地音频
}
override func play() {
super.play()
// musicPlayer.play()
voicePlayer.play()
}
override func pause() {
super.pause()
// musicPlayer.pause()
voicePlayer.pause()
}
// class func playLocalMusicResource(){
// let url = NSBundle.mainBundle().pathForResource("背叛情歌.mp3", ofType: nil)
// musicPlayer = try! AVAudioPlayer.init(contentsOfURL: NSURL.fileURLWithPath(url!))
// }
}
| mit | 550d0f8ec2dc94f63529d8e5b6e7586b | 30.28 | 158 | 0.637468 | 3.414847 | false | false | false | false |
mihaicris/digi-cloud | Digi Cloud/Controller/Bookmarks/ManageBookmarksViewController.swift | 1 | 13533 | //
// ManageBookmarksViewController.swift
// Digi Cloud
//
// Created by Mihai Cristescu on 06/03/2017.
// Copyright © 2017 Mihai Cristescu. All rights reserved.
//
import UIKit
final class ManageBookmarksViewController: UITableViewController {
// MARK: - Internal Properties
var onFinish: (() -> Void)?
var onSelect: ((Location) -> Void)?
var onUpdateNeeded: (() -> Void)?
// MARK: - Private Properties
private var mountsMapping: [String: Mount] = [:]
private var bookmarks: [Bookmark] = []
private let dispatchGroup = DispatchGroup()
lazy private var deleteButton: UIBarButtonItem = {
let button = UIBarButtonItem(title: NSLocalizedString("Delete All", comment: ""), style: .done, target: self, action: #selector(handleDeleteAllButtonTouched))
return button
}()
lazy private var cancelEditButton: UIBarButtonItem = {
let button = UIBarButtonItem(title: NSLocalizedString("Cancel", comment: ""), style: .done, target: self, action: #selector(handleCancelEditButtonTouched))
return button
}()
lazy private var dismissButton: UIBarButtonItem = {
let button = UIBarButtonItem(title: NSLocalizedString("Close", comment: ""), style: .done, target: self, action: #selector(handleCloseButtonTouched))
return button
}()
private let activityIndicator: UIActivityIndicatorView = {
let activityIndicator = UIActivityIndicatorView(activityIndicatorStyle: .gray)
activityIndicator.translatesAutoresizingMaskIntoConstraints = false
activityIndicator.startAnimating()
activityIndicator.hidesWhenStopped = true
return activityIndicator
}()
private let messageLabel: UILabel = {
let lable = UILabel()
lable.translatesAutoresizingMaskIntoConstraints = false
lable.textColor = .lightGray
lable.isHidden = true
return lable
}()
// MARK: - Initializers and Deinitializers
init() {
super.init(style: .plain)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
deinit {
NotificationCenter.default.removeObserver(self)
}
}
// MARK: - UIViewController Methods
extension ManageBookmarksViewController {
override func viewDidLoad() {
super.viewDidLoad()
self.registerForNotificationCenter()
self.setupViews()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
self.updateButtonsToMatchTableState()
getBookmarksAndMounts()
}
}
// MARK: - Delegate Confomance
extension ManageBookmarksViewController {
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return bookmarks.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let cell = tableView.dequeueReusableCell(withIdentifier: String(describing: BookmarkViewCell.self),
for: indexPath) as? BookmarkViewCell else {
return UITableViewCell()
}
if let mountName = mountsMapping[bookmarks[indexPath.row].mountId]?.name {
cell.bookmarkNameLabel.text = bookmarks[indexPath.row].name
cell.pathLabel.text = mountName + String(bookmarks[indexPath.row].path.dropLast())
}
return cell
}
override func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
self.updateDeleteButtonTitle()
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if tableView.isEditing {
self.updateButtonsToMatchTableState()
} else {
tableView.deselectRow(at: indexPath, animated: false)
let bookmark = bookmarks[indexPath.row]
guard let mount = mountsMapping[bookmark.mountId] else {
print("Mount for bookmark not found.")
return
}
let location = Location(mount: mount, path: bookmark.path)
dismiss(animated: true) {
self.onSelect?(location)
}
}
}
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
deleteBookmarks(at: [indexPath])
}
}
}
// MARK: - Target-Action Methods
private extension ManageBookmarksViewController {
@objc func handleDeleteSelectedBookmarks(_ action: UIAlertAction) {
var indexPaths: [IndexPath] = []
if let indexPathsForSelectedRows = tableView.indexPathsForSelectedRows {
// Some or all rows selected
indexPaths = indexPathsForSelectedRows
} else {
// No rows selected, means all rows.
for index in bookmarks.indices {
indexPaths.append(IndexPath(row: index, section: 0))
}
}
deleteBookmarks(at: indexPaths)
}
@objc func handleToogleEditMode() {
var button: UIBarButtonItem
if tableView.isEditing {
button = UIBarButtonItem(title: NSLocalizedString("Edit", comment: ""),
style: UIBarButtonItemStyle.plain,
target: self,
action: #selector(handleToogleEditMode))
} else {
button = UIBarButtonItem(title: NSLocalizedString("Done", comment: ""),
style: UIBarButtonItemStyle.plain,
target: self,
action: #selector(handleToogleEditMode))
}
navigationItem.setRightBarButton(button, animated: false)
tableView.setEditing(!tableView.isEditing, animated: true)
}
@objc func handleEnterEditMode() {
self.tableView.setEditing(true, animated: true)
self.updateButtonsToMatchTableState()
}
@objc func handleDeleteAllButtonTouched() {
var messageString: String
if self.tableView.indexPathsForSelectedRows?.count == 1 {
messageString = NSLocalizedString("Are you sure you want to remove this bookmark?", comment: "")
} else {
messageString = NSLocalizedString("Are you sure you want to remove these bookmarks?", comment: "")
}
let alertController = UIAlertController(title: NSLocalizedString("Delete confirmation", comment: ""),
message: messageString,
preferredStyle: .alert)
let cancelAction = UIAlertAction(title: NSLocalizedString("Cancel", comment: ""),
style: .cancel,
handler: nil)
let okAction = UIAlertAction(title: NSLocalizedString("Yes", comment: ""),
style: .destructive,
handler: handleDeleteSelectedBookmarks)
alertController.addAction(cancelAction)
alertController.addAction(okAction)
present(alertController, animated: true, completion: nil)
}
@objc func handleCancelEditButtonTouched() {
self.tableView.setEditing(false, animated: true)
self.updateButtonsToMatchTableState()
}
@objc func handleCloseButtonTouched() {
self.dismiss(animated: true, completion: nil)
}
}
// MARK: - Private Methods
private extension ManageBookmarksViewController {
func registerForNotificationCenter() {
NotificationCenter.default.addObserver(
self,
selector: #selector(handleCloseButtonTouched),
name: .UIApplicationWillResignActive,
object: nil)
}
func setupViews() {
self.title = NSLocalizedString("Bookmarks", comment: "")
tableView.register(BookmarkViewCell.self, forCellReuseIdentifier: String(describing: BookmarkViewCell.self))
tableView.allowsMultipleSelectionDuringEditing = true
tableView.tableFooterView = UIView(frame: CGRect(x: 0, y: 0, width: 1, height: 1))
tableView.rowHeight = AppSettings.tableViewRowHeight
view.addSubview(activityIndicator)
view.addSubview(messageLabel)
NSLayoutConstraint.activate([
activityIndicator.centerXAnchor.constraint(equalTo: view.centerXAnchor),
activityIndicator.centerYAnchor.constraint(equalTo: view.centerYAnchor, constant: -40),
messageLabel.centerXAnchor.constraint(equalTo: view.centerXAnchor),
messageLabel.centerYAnchor.constraint(equalTo: view.centerYAnchor, constant: -40)
])
}
func updateButtonsToMatchTableState() {
if self.tableView.isEditing {
self.navigationItem.rightBarButtonItem = self.cancelEditButton
self.updateDeleteButtonTitle()
self.navigationItem.leftBarButtonItem = self.deleteButton
} else {
// Not in editing mode.
self.navigationItem.leftBarButtonItem = dismissButton
if bookmarks.count != 0 {
self.navigationItem.rightBarButtonItem = UIBarButtonItem(
title: NSLocalizedString("Edit", comment: ""),
style: .done,
target: self,
action: #selector(handleEnterEditMode))
}
}
}
func updateDeleteButtonTitle() {
var newTitle = NSLocalizedString("Delete All", comment: "")
if let indexPathsForSelectedRows = self.tableView.indexPathsForSelectedRows {
if indexPathsForSelectedRows.count != bookmarks.count {
let titleFormatString = NSLocalizedString("Delete (%d)", comment: "")
newTitle = String(format: titleFormatString, indexPathsForSelectedRows.count)
}
}
UIView.performWithoutAnimation {
self.deleteButton.title = newTitle
}
}
func getBookmarksAndMounts() {
var resultBookmarks: [Bookmark] = []
var resultMounts: [Mount] = []
var hasFetchedSuccessfully = true
// Get the bookmarks
dispatchGroup.enter()
DigiClient.shared.getBookmarks { result, error in
self.dispatchGroup.leave()
guard error == nil, result != nil else {
hasFetchedSuccessfully = false
logNSError(error! as NSError)
return
}
resultBookmarks = result!
}
// Get the mounts
dispatchGroup.enter()
DigiClient.shared.getMounts { result, error in
self.dispatchGroup.leave()
guard error == nil, result != nil else {
hasFetchedSuccessfully = false
logNSError(error! as NSError)
return
}
resultMounts = result!
}
// Create dictionary with mountId: Mount
dispatchGroup.notify(queue: .main) {
self.activityIndicator.stopAnimating()
if hasFetchedSuccessfully {
let mountsIDs = resultMounts.map { $0.identifier }
for bookmark in resultBookmarks.enumerated().reversed() {
if !mountsIDs.contains(bookmark.element.mountId) {
resultBookmarks.remove(at: bookmark.offset)
}
}
for mount in resultMounts {
self.mountsMapping[mount.identifier] = mount
}
self.bookmarks = resultBookmarks
if self.bookmarks.count == 0 {
self.messageLabel.text = NSLocalizedString("No bookmarks", comment: "")
self.messageLabel.isHidden = false
return
}
self.tableView.reloadData()
self.updateButtonsToMatchTableState()
} else {
self.messageLabel.text = NSLocalizedString("Error on fetching bookmarks", comment: "")
self.messageLabel.isHidden = false
}
}
}
func deleteBookmarks(at indexPaths: [IndexPath]) {
var newBookmarks = bookmarks
for indexPath in indexPaths.reversed() {
newBookmarks.remove(at: indexPath.row)
}
// TODO: Start Activity Indicator
DigiClient.shared.setBookmarks(bookmarks: newBookmarks) { error in
// TODO: Stop Activity Indicator
guard error == nil else {
// TODO: Show error to user
logNSError(error! as NSError)
return
}
// Success:
self.bookmarks = newBookmarks
self.tableView.deleteRows(at: indexPaths, with: .fade)
if self.bookmarks.count == 0 {
self.dismiss(animated: true) {
self.onFinish?()
}
} else {
// Update main list
self.onUpdateNeeded?()
if self.tableView.isEditing {
self.handleToogleEditMode()
self.updateButtonsToMatchTableState()
}
}
}
}
}
| mit | 6ad0757402d1d7ebc8cfffbad18be5a1 | 32.248157 | 166 | 0.597842 | 5.673795 | false | false | false | false |
barbaramartina/swift-code-snippets | snippets/swift-ac-avltree.swift | 1 | 11087 | ---
title: Swift Algorithm Club AVLTree
completion-scope: TopLevel
summary: An implementation of AVLTree
---
// The MIT License (MIT)
// Copyright (c) 2016 Mike Taghavi (mitghi[at]me.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.
public class TreeNode<Key: Comparable, Payload> {
public typealias Node = TreeNode<Key, Payload>
var payload: Payload?
fileprivate var key: Key
internal var leftChild: Node?
internal var rightChild: Node?
fileprivate var height: Int
fileprivate weak var parent: Node?
public init(key: Key, payload: Payload?, leftChild: Node?, rightChild: Node?, parent: Node?, height: Int) {
self.key = key
self.payload = payload
self.leftChild = leftChild
self.rightChild = rightChild
self.parent = parent
self.height = height
self.leftChild?.parent = self
self.rightChild?.parent = self
}
public convenience init(key: Key, payload: Payload?) {
self.init(key: key, payload: payload, leftChild: nil, rightChild: nil, parent: nil, height: 1)
}
public convenience init(key: Key) {
self.init(key: key, payload: nil)
}
var isRoot: Bool {
return parent == nil
}
var isLeaf: Bool {
return rightChild == nil && leftChild == nil
}
var isLeftChild: Bool {
return parent?.leftChild === self
}
var isRightChild: Bool {
return parent?.rightChild === self
}
var hasLeftChild: Bool {
return leftChild != nil
}
var hasRightChild: Bool {
return rightChild != nil
}
var hasAnyChild: Bool {
return leftChild != nil || rightChild != nil
}
var hasBothChildren: Bool {
return leftChild != nil && rightChild != nil
}
}
// MARK: - The AVL tree
open class AVLTree<Key: Comparable, Payload> {
public typealias Node = TreeNode<Key, Payload>
fileprivate(set) var root: Node?
fileprivate(set) var size = 0
public init() { }
}
// MARK: - Searching
extension TreeNode {
public func minimum() -> TreeNode? {
if let leftChild = self.leftChild {
return leftChild.minimum()
}
return self
}
public func maximum() -> TreeNode? {
if let rightChild = self.rightChild {
return rightChild.maximum()
}
return self
}
}
extension AVLTree {
subscript(key: Key) -> Payload? {
get { return search(input: key) }
set { insert(key: key, payload: newValue) }
}
public func search(input: Key) -> Payload? {
if let result = search(key: input, node: root) {
return result.payload
} else {
return nil
}
}
fileprivate func search(key: Key, node: Node?) -> Node? {
if let node = node {
if key == node.key {
return node
} else if key < node.key {
return search(key: key, node: node.leftChild)
} else {
return search(key: key, node: node.rightChild)
}
}
return nil
}
}
// MARK: - Inserting new items
extension AVLTree {
public func insert(key: Key, payload: Payload? = nil) {
if let root = root {
insert(input: key, payload: payload, node: root)
} else {
root = Node(key: key, payload: payload)
}
size += 1
}
private func insert(input: Key, payload: Payload?, node: Node) {
if input < node.key {
if let child = node.leftChild {
insert(input: input, payload: payload, node: child)
} else {
let child = Node(key: input, payload: payload, leftChild: nil, rightChild: nil, parent: node, height: 1)
node.leftChild = child
balance(node: child)
}
} else {
if let child = node.rightChild {
insert(input: input, payload: payload, node: child)
} else {
let child = Node(key: input, payload: payload, leftChild: nil, rightChild: nil, parent: node, height: 1)
node.rightChild = child
balance(node: child)
}
}
}
}
// MARK: - Balancing tree
extension AVLTree {
fileprivate func updateHeightUpwards(node: Node?) {
if let node = node {
let lHeight = node.leftChild?.height ?? 0
let rHeight = node.rightChild?.height ?? 0
node.height = max(lHeight, rHeight) + 1
updateHeightUpwards(node: node.parent)
}
}
fileprivate func lrDifference(node: Node?) -> Int {
let lHeight = node?.leftChild?.height ?? 0
let rHeight = node?.rightChild?.height ?? 0
return lHeight - rHeight
}
fileprivate func balance(node: Node?) {
guard let node = node else {
return
}
updateHeightUpwards(node: node.leftChild)
updateHeightUpwards(node: node.rightChild)
var nodes = [Node?](repeating: nil, count: 3)
var subtrees = [Node?](repeating: nil, count: 4)
let nodeParent = node.parent
let lrFactor = lrDifference(node: node)
if lrFactor > 1 {
// left-left or left-right
if lrDifference(node: node.leftChild) > 0 {
// left-left
nodes[0] = node
nodes[2] = node.leftChild
nodes[1] = nodes[2]?.leftChild
subtrees[0] = nodes[1]?.leftChild
subtrees[1] = nodes[1]?.rightChild
subtrees[2] = nodes[2]?.rightChild
subtrees[3] = nodes[0]?.rightChild
} else {
// left-right
nodes[0] = node
nodes[1] = node.leftChild
nodes[2] = nodes[1]?.rightChild
subtrees[0] = nodes[1]?.leftChild
subtrees[1] = nodes[2]?.leftChild
subtrees[2] = nodes[2]?.rightChild
subtrees[3] = nodes[0]?.rightChild
}
} else if lrFactor < -1 {
// right-left or right-right
if lrDifference(node: node.rightChild) < 0 {
// right-right
nodes[1] = node
nodes[2] = node.rightChild
nodes[0] = nodes[2]?.rightChild
subtrees[0] = nodes[1]?.leftChild
subtrees[1] = nodes[2]?.leftChild
subtrees[2] = nodes[0]?.leftChild
subtrees[3] = nodes[0]?.rightChild
} else {
// right-left
nodes[1] = node
nodes[0] = node.rightChild
nodes[2] = nodes[0]?.leftChild
subtrees[0] = nodes[1]?.leftChild
subtrees[1] = nodes[2]?.leftChild
subtrees[2] = nodes[2]?.rightChild
subtrees[3] = nodes[0]?.rightChild
}
} else {
// Don't need to balance 'node', go for parent
balance(node: node.parent)
return
}
// nodes[2] is always the head
if node.isRoot {
root = nodes[2]
root?.parent = nil
} else if node.isLeftChild {
nodeParent?.leftChild = nodes[2]
nodes[2]?.parent = nodeParent
} else if node.isRightChild {
nodeParent?.rightChild = nodes[2]
nodes[2]?.parent = nodeParent
}
nodes[2]?.leftChild = nodes[1]
nodes[1]?.parent = nodes[2]
nodes[2]?.rightChild = nodes[0]
nodes[0]?.parent = nodes[2]
nodes[1]?.leftChild = subtrees[0]
subtrees[0]?.parent = nodes[1]
nodes[1]?.rightChild = subtrees[1]
subtrees[1]?.parent = nodes[1]
nodes[0]?.leftChild = subtrees[2]
subtrees[2]?.parent = nodes[0]
nodes[0]?.rightChild = subtrees[3]
subtrees[3]?.parent = nodes[0]
updateHeightUpwards(node: nodes[1]) // Update height from left
updateHeightUpwards(node: nodes[0]) // Update height from right
balance(node: nodes[2]?.parent)
}
}
// MARK: - Displaying tree
extension AVLTree {
fileprivate func display(node: Node?, level: Int) {
if let node = node {
display(node: node.rightChild, level: level + 1)
print("")
if node.isRoot {
print("Root -> ", terminator: "")
}
for _ in 0..<level {
print(" ", terminator: "")
}
print("(\(node.key):\(node.height))", terminator: "")
display(node: node.leftChild, level: level + 1)
}
}
public func display(node: Node) {
display(node: node, level: 0)
print("")
}
}
// MARK: - Delete node
extension AVLTree {
public func delete(key: Key) {
if size == 1 {
root = nil
size -= 1
} else if let node = search(key: key, node: root) {
delete(node: node)
size -= 1
}
}
private func delete(node: Node) {
if node.isLeaf {
// Just remove and balance up
if let parent = node.parent {
guard node.isLeftChild || node.isRightChild else {
// just in case
fatalError("Error: tree is invalid.")
}
if node.isLeftChild {
parent.leftChild = nil
} else if node.isRightChild {
parent.rightChild = nil
}
balance(node: parent)
} else {
// at root
root = nil
}
} else {
// Handle stem cases
if let replacement = node.leftChild?.maximum() , replacement !== node {
node.key = replacement.key
node.payload = replacement.payload
delete(node: replacement)
} else if let replacement = node.rightChild?.minimum() , replacement !== node {
node.key = replacement.key
node.payload = replacement.payload
delete(node: replacement)
}
}
}
}
// MARK: - Debugging
extension TreeNode: CustomDebugStringConvertible {
public var debugDescription: String {
var s = "key: \(key), payload: \(payload), height: \(height)"
if let parent = parent {
s += ", parent: \(parent.key)"
}
if let left = leftChild {
s += ", left = [" + left.debugDescription + "]"
}
if let right = rightChild {
s += ", right = [" + right.debugDescription + "]"
}
return s
}
}
extension AVLTree: CustomDebugStringConvertible {
public var debugDescription: String {
if let root = root {
return root.debugDescription
} else {
return "[]"
}
}
}
extension TreeNode: CustomStringConvertible {
public var description: String {
var s = ""
if let left = leftChild {
s += "(\(left.description)) <- "
}
s += "\(key)"
if let right = rightChild {
s += " -> (\(right.description))"
}
return s
}
}
extension AVLTree: CustomStringConvertible {
public var description: String {
if let root = root {
return root.description
} else {
return "[]"
}
}
}
| gpl-3.0 | 4cdd2f2871ccaa8ca0f07d36c3ce4e94 | 26.041463 | 112 | 0.611437 | 3.98383 | false | false | false | false |
CoderST/DYZB | DYZB/DYZB/Class/Profile/View/CountryVCCell.swift | 1 | 2123 | //
// CountryVCCell.swift
// DYZB
//
// Created by xiudou on 2017/7/18.
// Copyright © 2017年 xiudo. All rights reserved.
//
import UIKit
class CountryVCCell: UICollectionViewCell {
fileprivate let titleLabel : UILabel = {
let titleLabel = UILabel()
// titleLabel.backgroundColor = UIColor.red
titleLabel.font = UIFont.systemFont(ofSize: 14)
return titleLabel
}()
fileprivate let subTitleLabel : UILabel = {
let subTitleLabel = UILabel()
// subTitleLabel.backgroundColor = UIColor.blue
subTitleLabel.font = UIFont.systemFont(ofSize: 14)
return subTitleLabel
}()
fileprivate let lineView : UIView = {
let lineView = UIView()
lineView.backgroundColor = UIColor(r: 239, g: 239, b: 239)
return lineView
}()
override init(frame: CGRect) {
super.init(frame: frame)
contentView.backgroundColor = .white
contentView.addSubview(titleLabel)
contentView.addSubview(subTitleLabel)
contentView.addSubview(lineView)
}
var countryModel : CountryModel?{
didSet{
guard let countryModel = countryModel else { return }
titleLabel.text = countryModel.country
subTitleLabel.text = countryModel.mobile_prefix
let titleSize = countryModel.country.sizeWithFont(titleLabel.font)
titleLabel.frame = CGRect(x: 20, y: 0, width: titleSize.width, height: frame.height)
let subTitleSize = countryModel.mobile_prefix.sizeWithFont(subTitleLabel.font)
subTitleLabel.frame = CGRect(x: frame.width - subTitleSize.width - 20, y: 0, width: subTitleSize.width, height: frame.height)
lineView.frame = CGRect(x: 0, y: frame.height - 1, width: frame.width, height: 1)
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| mit | a66ddf2604edc6da7ce0fef505513b95 | 28.444444 | 137 | 0.591509 | 4.953271 | false | false | false | false |
jasnig/ScrollPageView | ScrollViewController/遮盖+缩放+没有颜色渐变 效果/Vc4Controller.swift | 1 | 4246 | //
// Vc4Controller.swift
// ScrollViewController
//
// Created by jasnig on 16/4/8.
// Copyright © 2016年 ZeroJ. All rights reserved.
// github: https://github.com/jasnig
// 简书: http://www.jianshu.com/users/fb31a3d1ec30/latest_articles
//
// 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 Vc4Controller: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// 这个是必要的设置
automaticallyAdjustsScrollViewInsets = false
var style = SegmentStyle()
// 遮盖
style.showCover = true
// 缩放文字
style.scaleTitle = true
// 遮盖颜色
style.coverBackgroundColor = UIColor.lightGrayColor()
let titles = setChildVcs().map { $0.title! }
let scroll = ScrollPageView(frame: CGRect(x: 0, y: 64, width: view.bounds.size.width, height: view.bounds.size.height - 64), segmentStyle: style, titles: titles, childVcs: setChildVcs(), parentViewController: self)
view.addSubview(scroll)
}
func setChildVcs() -> [UIViewController] {
let vc1 = storyboard!.instantiateViewControllerWithIdentifier("test")
vc1.title = "国内头条"
let vc2 = UIViewController()
vc2.view.backgroundColor = UIColor.greenColor()
vc2.title = "国际要闻"
let vc3 = UIViewController()
vc3.view.backgroundColor = UIColor.redColor()
vc3.title = "趣事"
let vc4 = UIViewController()
vc4.view.backgroundColor = UIColor.yellowColor()
vc4.title = "囧图"
let vc5 = UIViewController()
vc5.view.backgroundColor = UIColor.lightGrayColor()
vc5.title = "明星八卦"
let vc6 = UIViewController()
vc6.view.backgroundColor = UIColor.brownColor()
vc6.title = "爱车"
let vc7 = UIViewController()
vc7.view.backgroundColor = UIColor.orangeColor()
vc7.title = "国防要事"
let vc8 = UIViewController()
vc8.view.backgroundColor = UIColor.blueColor()
vc8.title = "科技频道"
let vc9 = UIViewController()
vc9.view.backgroundColor = UIColor.brownColor()
vc9.title = "手机专页"
let vc10 = UIViewController()
vc10.view.backgroundColor = UIColor.orangeColor()
vc10.title = "风景图"
let vc11 = UIViewController()
vc11.view.backgroundColor = UIColor.blueColor()
vc11.title = "段子"
return [vc1, vc2, vc3,vc4, vc5, vc6, vc7, vc8, vc9, vc10, vc11]
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| mit | 0ee9a52aff71faf5ffae8d28dc49f30b | 33.731092 | 222 | 0.651343 | 4.359705 | false | false | false | false |
Turistforeningen/SjekkUT | ios/SjekkUt/network/CheckinRouter.swift | 1 | 2605 | //
// CheckinRouter.swift
// SjekkUt
//
// Created by Henrik Hartz on 14.03.2017.
// Copyright © 2017 Den Norske Turistforening. All rights reserved.
//
import Foundation
import Alamofire
enum CheckinRouter: URLRequestConvertible {
case Create(placeId: String, params: Parameters?)
case List(placeId: String)
case Update(placeId: String, checkinId: String, params: Parameters?)
func asURLRequest() throws -> URLRequest {
var method: Alamofire.HTTPMethod {
switch self {
case .Create:
return .post
case .List:
return .get
case .Update:
return .put
}
}
let params: Parameters? = {
switch self {
case .Create(_, let newParams):
return newParams
case .List:
return ["public": "true"]
case .Update(_, _, let updateParams):
return updateParams
}
}()
let url:URL? = {
// build up and return the URL for each endpoint
let relativePath:String?
switch self {
case .Create(let placeId, _):
relativePath = "\(placeId)/besok"
case .List(let placeId):
relativePath = "\(placeId)/logg"
case .Update(let placeId, let checkinId, _):
relativePath = "\(placeId)/besok/\(checkinId)"
}
var URL = (kSjekkUtUrl + "/steder/").URL()
if let relativePath = relativePath {
URL?.appendPathComponent(relativePath)
}
return URL
}()
let encoding:ParameterEncoding = {
switch self {
case .List:
return URLEncoding.default
default:
return JSONEncoding.default
}
}()
guard
let anUrl = url else {
throw NSError.init(domain: kSjekkUtErrorDomain, code: kSjekkUtErrorCodeGenericErrorMessage, userInfo: [NSLocalizedDescriptionKey: "failed to create URL"])
}
let theUrlRequest = URLRequest(url: anUrl)
var encodedRequest = try encoding.encode(theUrlRequest, with: params)
encodedRequest.httpMethod = method.rawValue
for (key, value) in SjekkUtApi.instance.authenticationHeaders {
encodedRequest.setValue(value, forHTTPHeaderField: key)
}
return encodedRequest
}
}
| mit | 0dad7818b1fa799afc43077f94f25fe2 | 29.635294 | 170 | 0.528802 | 5.176938 | false | false | false | false |
efa85/WeatherApp | WeatherApp/ViewModel/LocationsViewModel.swift | 1 | 1155 | //
// LocationsViewModel.swift
// WeatherApp
//
// Created by Emilio Fernandez on 24/11/14.
// Copyright (c) 2014 Emilio Fernandez. All rights reserved.
//
import Foundation
class LocationsViewModel {
private let locationsStore: LocationStore
private let locationViewModelProvider: (location: Location) -> (LocationViewModel)
init(locationsStore: LocationStore,
locationViewModelProvider: (location: Location) -> (LocationViewModel)) {
self.locationsStore = locationsStore
self.locationViewModelProvider = locationViewModelProvider
}
var numberOfLocations: Int {
get {
return self.locationsStore.fetchLocations().count
}
}
func locationViewModelForIndex(index: Int) -> LocationViewModel {
let locations = locationsStore.fetchLocations()
let location = locations[index]
return locationViewModelProvider(location: location)
}
func deleteLocationAtIndex(index: Int) {
let location = locationsStore.fetchLocations()[index]
locationsStore.deleteLocation(location)
}
}
| apache-2.0 | 0d99139bb9af04cabd407970ee4f81f9 | 26.5 | 86 | 0.673593 | 4.935897 | false | false | false | false |
mauryat/firefox-ios | Client/Frontend/Home/PanelDataObservers.swift | 1 | 3621 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Foundation
import Deferred
import Shared
public let ActivityStreamTopSiteCacheSize: Int32 = 16
private let log = Logger.browserLogger
protocol DataObserver {
var profile: Profile { get }
weak var delegate: DataObserverDelegate? { get set }
func refreshIfNeeded(forceHighlights highlights: Bool, forceTopSites topSites: Bool)
}
@objc protocol DataObserverDelegate: class {
func didInvalidateDataSources()
func willInvalidateDataSources()
}
open class PanelDataObservers {
var activityStream: DataObserver
init(profile: Profile) {
self.activityStream = ActivityStreamDataObserver(profile: profile)
}
}
class ActivityStreamDataObserver: DataObserver {
let profile: Profile
weak var delegate: DataObserverDelegate?
private var invalidationTime = OneMinuteInMilliseconds * 15
private var lastInvalidation: UInt64 = 0
fileprivate let events = [NotificationFirefoxAccountChanged, NotificationProfileDidFinishSyncing, NotificationPrivateDataClearedHistory]
init(profile: Profile) {
self.profile = profile
self.profile.history.setTopSitesCacheSize(ActivityStreamTopSiteCacheSize)
events.forEach { NotificationCenter.default.addObserver(self, selector: #selector(self.notificationReceived(_:)), name: $0, object: nil) }
}
deinit {
events.forEach { NotificationCenter.default.removeObserver(self, name: $0, object: nil) }
}
/*
refreshIfNeeded will refresh the underlying caches for both TopSites and Highlights.
By default this will only refresh the highlights if the last fetch is older than 15 mins
By default this will only refresh topSites if KeyTopSitesCacheIsValid is false
*/
func refreshIfNeeded(forceHighlights highlights: Bool, forceTopSites topSites: Bool) {
guard !profile.isShutdown else {
return
}
// Highlights are cached for 15 mins
let shouldInvalidateHighlights = highlights || (Timestamp.uptimeInMilliseconds() - lastInvalidation > invalidationTime)
// KeyTopSitesCacheIsValid is false when we want to invalidate. Thats why this logic is so backwards
let shouldInvalidateTopSites = topSites || !(profile.prefs.boolForKey(PrefsKeys.KeyTopSitesCacheIsValid) ?? false)
if !shouldInvalidateTopSites && !shouldInvalidateHighlights {
// There is nothing to refresh. Bye
return
}
self.delegate?.willInvalidateDataSources()
self.profile.recommendations.repopulate(invalidateTopSites: shouldInvalidateTopSites, invalidateHighlights: shouldInvalidateHighlights).uponQueue(.main) { _ in
if shouldInvalidateTopSites {
self.profile.prefs.setBool(true, forKey: PrefsKeys.KeyTopSitesCacheIsValid)
}
self.lastInvalidation = shouldInvalidateHighlights ? Timestamp.uptimeInMilliseconds() : self.lastInvalidation
self.delegate?.didInvalidateDataSources()
}
}
@objc func notificationReceived(_ notification: Notification) {
switch notification.name {
case NotificationProfileDidFinishSyncing, NotificationFirefoxAccountChanged, NotificationPrivateDataClearedHistory:
refreshIfNeeded(forceHighlights: true, forceTopSites: true)
default:
log.warning("Received unexpected notification \(notification.name)")
}
}
}
| mpl-2.0 | 9cdb2b9bc34d381d4244c1f5d13340d5 | 39.685393 | 167 | 0.728252 | 5.372404 | false | false | false | false |
scottkawai/sendgrid-swift | Sources/SendGrid/API/V3/Suppression/SuppressionListDeleter.swift | 1 | 3312 | import Foundation
/// The `SuppressionListDeleter` class is base class inherited by requests that
/// delete entries from a supression list. You should not use this class
/// directly.
public class SuppressionListDeleter<T: EmailEventRepresentable>: Request<SuppressionListDeleterParameters> {
// MARK: - Initializer
/// Private initializer to set all the required properties.
///
/// - Parameters:
/// - path: The path for the request's API endpoint.
/// - deleteAll: A `Bool` indicating if all the events on the suppression
/// list should be deleted.
/// - emails: An array of emails to delete from the suppression list.
internal init(path: String? = nil, deleteAll: Bool?, emails: [String]?) {
let params = SuppressionListDeleterParameters(deleteAll: deleteAll, emails: emails)
super.init(method: .DELETE, path: path ?? "/", parameters: params)
}
/// Initializes the request with an array of email addresses to delete
/// from the suppression list.
///
/// - Parameter emails: An array of emails to delete from the suppression
/// list.
public convenience init(emails: [String]) {
self.init(deleteAll: nil, emails: emails)
}
/// Initializes the request with an array of email addresses to delete
/// from the suppression list.
///
/// - Parameter emails: An array of emails to delete from the suppression
/// list.
public convenience init(emails: String...) {
self.init(emails: emails)
}
/// Initializes the request with an array of events that should
/// be removed from the suppression list.
///
/// - Parameter events: An array of events containing email addresses to
/// remove from the suppression list.
public convenience init(events: [T]) {
let emails = events.map { $0.email }
self.init(emails: emails)
}
/// Initializes the request with an array of events that should be removed
/// from the suppression list.
///
/// - Parameter events: An array of events containing email addresses to
/// remove from the suppression list.
public convenience init(events: T...) {
self.init(events: events)
}
}
/// The `SuppressionListDeleterParameters` struct houses all the parameters that
/// can be made for the suppression delete calls.
public struct SuppressionListDeleterParameters: Codable {
/// A `Bool` indicating if all the events on the suppression list should be
/// deleted.
public let deleteAll: Bool?
/// An array of emails to delete from the suppression list.
public let emails: [String]?
/// Initializes the struct.
///
/// - Parameters:
/// - deleteAll: A `Bool` indicating if all the events on the suppression
/// list should be deleted.
/// - emails: An array of emails to delete from the suppression list.
public init(deleteAll: Bool?, emails: [String]?) {
self.deleteAll = deleteAll
self.emails = emails
}
/// :nodoc:
public enum CodingKeys: String, CodingKey {
case deleteAll = "delete_all"
case emails
}
}
| mit | 3bbf399bdd3d36be834de0701b09112d | 37.964706 | 108 | 0.630435 | 4.813953 | false | false | false | false |
SlackKit/SKWebAPI | Sources/NetworkInterface.swift | 1 | 9335 | //
// NetworkInterface.swift
//
// Copyright © 2017 Peter Zignego. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#if os(Linux)
import Dispatch
#endif
import Foundation
import SKCore
public struct NetworkInterface {
private let apiUrl = "https://slack.com/api/"
private let session = URLSession(configuration: .default)
internal init() {}
internal func request(
_ endpoint: Endpoint,
parameters: [String: Any?],
successClosure: @escaping ([String: Any]) -> Void,
errorClosure: @escaping (SlackError) -> Void
) {
guard let url = requestURL(for: endpoint, parameters: parameters) else {
errorClosure(SlackError.clientNetworkError)
return
}
let request = URLRequest(url: url)
session.dataTask(with: request) {(data, response, publicError) in
do {
successClosure(try NetworkInterface.handleResponse(data, response: response, publicError: publicError))
} catch let error {
errorClosure(error as? SlackError ?? SlackError.unknownError)
}
}.resume()
}
//Adapted from https://gist.github.com/erica/baa8a187a5b4796dab27
internal func synchronusRequest(_ endpoint: Endpoint, parameters: [String: Any?]) -> [String: Any]? {
guard let url = requestURL(for: endpoint, parameters: parameters) else {
return nil
}
let request = URLRequest(url: url)
var data: Data? = nil
var response: URLResponse? = nil
var error: Error? = nil
let semaphore = DispatchSemaphore(value: 0)
session.dataTask(with: request) { (reqData, reqResponse, reqError) in
data = reqData
response = reqResponse
error = reqError
if data == nil, let error = error { print(error) }
semaphore.signal()
}.resume()
_ = semaphore.wait(timeout: DispatchTime.distantFuture)
return try? NetworkInterface.handleResponse(data, response: response, publicError: error)
}
internal func customRequest(
_ url: String,
data: Data,
success: @escaping (Bool) -> Void,
errorClosure: @escaping (SlackError) -> Void
) {
guard let string = url.removingPercentEncoding, let url = URL(string: string) else {
errorClosure(SlackError.clientNetworkError)
return
}
var request = URLRequest(url:url)
request.httpMethod = "POST"
let contentType = "application/json"
request.setValue(contentType, forHTTPHeaderField: "Content-Type")
request.httpBody = data
session.dataTask(with: request) {(_, _, publicError) in
if publicError == nil {
success(true)
} else {
errorClosure(SlackError.clientNetworkError)
}
}.resume()
}
internal func uploadRequest(
data: Data,
parameters: [String: Any?],
successClosure: @escaping ([String: Any]) -> Void, errorClosure: @escaping (SlackError) -> Void
) {
guard
let url = requestURL(for: .filesUpload, parameters: parameters),
let filename = parameters["filename"] as? String,
let filetype = parameters["filetype"] as? String
else {
errorClosure(SlackError.clientNetworkError)
return
}
var request = URLRequest(url:url)
request.httpMethod = "POST"
let boundaryConstant = randomBoundary()
let contentType = "multipart/form-data; boundary=" + boundaryConstant
request.setValue(contentType, forHTTPHeaderField: "Content-Type")
request.httpBody = requestBodyData(data: data, boundaryConstant: boundaryConstant, filename: filename, filetype: filetype)
session.dataTask(with: request) {(data, response, publicError) in
do {
successClosure(try NetworkInterface.handleResponse(data, response: response, publicError: publicError))
} catch let error {
errorClosure(error as? SlackError ?? SlackError.unknownError)
}
}.resume()
}
internal static func handleResponse(_ data: Data?, response: URLResponse?, publicError: Error?) throws -> [String: Any] {
guard let data = data, let response = response as? HTTPURLResponse else {
throw SlackError.clientNetworkError
}
do {
guard let json = try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any] else {
throw SlackError.clientJSONError
}
switch response.statusCode {
case 200:
if json["ok"] as? Bool == true {
return json
} else {
if let errorString = json["error"] as? String {
throw SlackError(rawValue: errorString) ?? .unknownError
} else {
throw SlackError.unknownError
}
}
case 429:
throw SlackError.tooManyRequests
default:
throw SlackError.clientNetworkError
}
} catch let error {
if let slackError = error as? SlackError {
throw slackError
} else {
throw SlackError.unknownError
}
}
}
private func requestURL(for endpoint: Endpoint, parameters: [String: Any?]) -> URL? {
var components = URLComponents(string: "\(apiUrl)\(endpoint.rawValue)")
if parameters.count > 0 {
components?.queryItems = filterNilParameters(parameters).map { URLQueryItem(name: $0.0, value: "\($0.1)") }
}
// As discussed http://www.openradar.me/24076063 and https://stackoverflow.com/a/37314144/407523, Apple considers
// a + and ? as valid characters in a URL query string, but Slack has recently started enforcing that they be
// encoded when included in a query string. As a result, we need to manually apply the encoding after Apple's
// default encoding is applied.
var encodedQuery = components?.percentEncodedQuery
encodedQuery = encodedQuery?.replacingOccurrences(of: ">", with: "%3E")
encodedQuery = encodedQuery?.replacingOccurrences(of: "<", with: "%3C")
encodedQuery = encodedQuery?.replacingOccurrences(of: "@", with: "%40")
encodedQuery = encodedQuery?.replacingOccurrences(of: "?", with: "%3F")
encodedQuery = encodedQuery?.replacingOccurrences(of: "+", with: "%2B")
components?.percentEncodedQuery = encodedQuery
return components?.url
}
private func requestBodyData(data: Data, boundaryConstant: String, filename: String, filetype: String) -> Data? {
let boundaryStart = "--\(boundaryConstant)\r\n"
let boundaryEnd = "--\(boundaryConstant)--\r\n"
let contentDispositionString = "Content-Disposition: form-data; name=\"file\"; filename=\"\(filename)\"\r\n"
let contentTypeString = "Content-Type: \(filetype)\r\n\r\n"
let dataEnd = "\r\n"
guard
let boundaryStartData = boundaryStart.data(using: .utf8),
let dispositionData = contentDispositionString.data(using: .utf8),
let contentTypeData = contentTypeString.data(using: .utf8),
let boundaryEndData = boundaryEnd.data(using: .utf8),
let dataEndData = dataEnd.data(using: .utf8)
else {
return nil
}
var requestBodyData = Data()
requestBodyData.append(contentsOf: boundaryStartData)
requestBodyData.append(contentsOf: dispositionData)
requestBodyData.append(contentsOf: contentTypeData)
requestBodyData.append(contentsOf: data)
requestBodyData.append(contentsOf: dataEndData)
requestBodyData.append(contentsOf: boundaryEndData)
return requestBodyData
}
private func randomBoundary() -> String {
#if os(Linux)
return "slackkit.boundary.\(Int(random()))\(Int(random()))"
#else
return "slackkit.boundary.\(arc4random())\(arc4random())"
#endif
}
}
| mit | efaf56053d02580b932437c1046af829 | 40.856502 | 130 | 0.625027 | 4.774425 | false | false | false | false |
ireland2011/Audible | Audible/Audible/View/PageCell.swift | 1 | 3887 | //
// PageCell.swift
// Audible
//
// Created by Genius on 17/4/2017.
// Copyright © 2017 Genius. All rights reserved.
//
import UIKit
import SnapKit
class PageCell: UICollectionViewCell {
var page: Page? {
didSet {
guard let page = page else {
return
}
var imageName = page.imageName
if UIDevice.current.orientation.isLandscape {
imageName += "_landscape"
}
imageView.image = UIImage(named: imageName)
let color = UIColor(white: 0.2, alpha: 1)
let attributedText = NSMutableAttributedString(string: page.title,
attributes: [
NSFontAttributeName: UIFont.systemFont(ofSize: 20, weight: UIFontWeightMedium),
NSForegroundColorAttributeName: color
])
attributedText.append(NSAttributedString(string: "\n\n\(page.message)",
attributes: [
NSFontAttributeName: UIFont.systemFont(ofSize: 14),
NSForegroundColorAttributeName: color
]
))
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.alignment = .center
let length = attributedText.string.characters.count
attributedText.addAttribute(NSParagraphStyleAttributeName, value: paragraphStyle, range: NSRange(location: 0, length: length))
textView.attributedText = attributedText
}
}
override init(frame: CGRect) {
super.init(frame: frame)
setupViews()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
let imageView: UIImageView = {
let iv = UIImageView()
iv.backgroundColor = .yellow
iv.contentMode = .scaleAspectFill
iv.image = UIImage(named: "page1")
iv.clipsToBounds = true
return iv
}()
let blackSeperatorView: UIView = {
let bsv = UIView()
bsv.backgroundColor = UIColor.init(white: 0.9, alpha: 1.0)
return bsv
}()
let textView: UITextView = {
let tx = UITextView()
tx.text = "Sample Text for now"
tx.isEditable = false
tx.contentInset = UIEdgeInsetsMake(24, 0, 0, 0)
return tx
}()
func setupViews() {
contentView.addSubview(imageView)
contentView.addSubview(textView)
contentView.addSubview(blackSeperatorView)
imageView.snp.makeConstraints { (make) in
make.top.equalToSuperview()
make.left.equalToSuperview()
make.right.equalToSuperview()
make.bottom.equalTo(textView.snp.top)
}
textView.snp.makeConstraints { (make) in
make.left.equalTo(contentView.snp.left).offset(16)
make.bottom.equalToSuperview()
make.right.equalTo(contentView.snp.right).offset(-16)
make.height.equalTo(contentView.snp.height).multipliedBy(0.3)
}
blackSeperatorView.snp.makeConstraints { (make) in
make.left.equalToSuperview()
make.right.equalToSuperview()
make.top.equalTo(textView.snp.top)
make.height.equalTo(1)
}
}
}
| mit | 4b19c18107916618e7baee96fdc6eece | 27.364964 | 147 | 0.501029 | 5.85241 | false | false | false | false |
universeiscool/MediaPickerController | MediaPickerController/PhotosViewController.swift | 1 | 4895 | //
// PhotosViewController.swift
// MediaPickerController
//
// Created by Malte Schonvogel on 23.11.15.
// Copyright © 2015 universeiscool UG (haftungsbeschränkt). All rights reserved.
//
import UIKit
import Photos
private let kReuseIdentifier = "PhotoCollectionViewCell"
public class PhotosViewController: MediaPickerCollectionViewController
{
override public var album: MediaPickerAlbum? {
didSet {
collectionView?.setContentOffset(CGPointZero, animated: false)
fetchResult = nil
guard let collection = album?.collection else { return }
mediaPickerController.selectAlbumButtonTitle = "\(album?.title ?? "") ▾"
let options = PHFetchOptions()
options.predicate = NSPredicate(format: "mediaType = %d", PHAssetMediaType.Image.rawValue)
options.sortDescriptors = [NSSortDescriptor(key: "creationDate", ascending: false)]
fetchResult = PHAsset.fetchAssetsInAssetCollection(collection, options: options)
self.collectionView?.reloadData()
}
}
var fetchResult:PHFetchResult?
override public func viewDidLoad()
{
super.viewDidLoad()
collectionView!.registerClass(PhotoCollectionViewCell.self, forCellWithReuseIdentifier: kReuseIdentifier)
}
public override func viewWillAppear(animated: Bool)
{
super.viewWillAppear(animated)
mediaPickerController.doneButtonView.enabled = !mediaPickerController.selectedAssets.isEmpty
if album != nil && fetchResult != nil {
collectionView?.reloadData()
}
}
// MARK: UICollectionViewDataSource
override public func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int
{
return 1
}
override public func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int
{
return fetchResult?.count ?? 0
}
override public func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell
{
let cell = collectionView.dequeueReusableCellWithReuseIdentifier(kReuseIdentifier, forIndexPath: indexPath) as! PhotoCollectionViewCell
if cell.tag != 0 {
cachingImageManager.cancelImageRequest(PHImageRequestID(cell.tag))
}
if let asset = fetchResult?[indexPath.row] as? PHAsset {
if mediaPickerController.selectedAssets.indexOf(asset) != nil {
cell.selected = true
collectionView.selectItemAtIndexPath(indexPath, animated: false, scrollPosition: UICollectionViewScrollPosition.None)
} else {
cell.selected = false
}
if mediaPickerController.prevSelectedAssetIdentifiers?.indexOf(asset.localIdentifier) != nil {
cell.enabled = false
}
cell.tag = Int(cachingImageManager.requestImageForAsset(asset, targetSize: imageSize, contentMode: imageContentMode, options: nil) { (result, _) in
cell.bind(result)
})
}
return cell
}
// MARK: UICollectionViewDelegate
override public func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath)
{
guard let asset = fetchResult?[indexPath.row] as? PHAsset else {
return
}
mediaPickerController.selectedAssets.append(asset)
let cell = collectionView.cellForItemAtIndexPath(indexPath) as? PhotoCollectionViewCell
cell?.setNeedsDisplay()
}
override public func collectionView(collectionView: UICollectionView, shouldSelectItemAtIndexPath indexPath: NSIndexPath) -> Bool
{
let cell = collectionView.cellForItemAtIndexPath(indexPath) as! PhotoCollectionViewCell
if(!cell.enabled){
return false
} else if mediaPickerController.selectedAssets.count == mediaPickerController.maximumSelect {
return false
}
return true
}
override public func collectionView(collectionView: UICollectionView, shouldDeselectItemAtIndexPath indexPath: NSIndexPath) -> Bool
{
return true
}
public override func collectionView(collectionView: UICollectionView, didDeselectItemAtIndexPath indexPath: NSIndexPath)
{
guard let asset = fetchResult?[indexPath.row] as? PHAsset else {
return
}
if let index = mediaPickerController.selectedAssets.indexOf(asset) {
mediaPickerController.selectedAssets.removeAtIndex(index)
}
let cell = collectionView.cellForItemAtIndexPath(indexPath) as? PhotoCollectionViewCell
cell?.setNeedsDisplay()
}
} | mit | 1ec66974fb67a1f18e2c431ee9da04bf | 36.630769 | 159 | 0.672664 | 6.15995 | false | false | false | false |
KuroBCN/FloatingHintTextfield | FloatingHintTextField/Classes/FloatingHintTextField.swift | 1 | 6569 | //
// FloatingHintTextField.swift
// floatingTextInput
//
// Created by Pereiro, Delfin on 28/12/15.
// Copyright © 2015 Pereiro, Delfin. All rights reserved.
//
import UIKit
let kAnimationTimeInterval : NSTimeInterval = 0.3
let kDefaultFloatingScale : CGFloat = 0.7
public class FloatingHintTextField: UITextField {
private var floatingLabel = CATextLayer()
public var floatingLabelColor : UIColor?
public var placeholderColor = UIColor.init(red: 0, green: 0, blue: 0.0980392, alpha: 0.22)
public var animationDuration = kAnimationTimeInterval
public var floatingLabelFont : UIFont? {
didSet{
scale = floatingLabelActiveFont().pointSize / self.font!.pointSize
floatingLabel.font = UIFont(name: self.floatingLabelFont!.fontName,
size: self.font!.pointSize)
self.setNeedsDisplay()
}
}
private var scale : CGFloat = kDefaultFloatingScale
private var topInset : CGFloat = 0
/// We can't get editing text frame from inside clearButtonRectForBounds method
/// without causing an infinite loop (editingRectForBounds and any other similar
/// methods call clearButtonRectForBounds under the hood) so we store it for
/// a proper clear button positioning
private var editingTextBounds = CGRectNull
/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
override func drawRect(rect: CGRect) {
// Drawing code
}
*/
override public var placeholder: String? {
didSet {
self.floatingLabel.string = placeholder
super.placeholder = nil
}
}
override public var frame: CGRect {
didSet {
super.frame = frame
self.commonInit()
}
}
public convenience init(){
self.init(frame: CGRectZero)
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.commonInit()
}
override public init(frame: CGRect) {
super.init(frame: frame)
self.commonInit()
}
// MARK: - Private methods
private func commonInit() {
// Get original placeholder color
var range = NSMakeRange(0, 0)
let color = super.attributedPlaceholder?.attribute(NSForegroundColorAttributeName, atIndex: 0, effectiveRange: &range)
if let color = color as? UIColor {
placeholderColor = color
}
// Set floating text string and removes real placeholder
placeholder = super.placeholder
// calculate top inset
if self.font != nil {
topInset = floor(super.editingRectForBounds(self.bounds).height-self.font!.lineHeight)
}
editingTextBounds = editingRectForBounds(self.bounds)
// Position floating label
floatingLabel.anchorPoint = CGPoint(x: 0, y: 0)
floatingLabel.frame = editingTextBounds
floatingLabel.contentsScale = UIScreen.mainScreen().scale
floatingLabel.font = floatingLabelActiveFont()
floatingLabel.fontSize = floatingLabelActiveFont().pointSize
floatingLabel.foregroundColor = placeholderColor.CGColor
self.layer.addSublayer(floatingLabel)
self.adjustsFontSizeToFitWidth = false
self.contentVerticalAlignment = UIControlContentVerticalAlignment.Top
}
private func floatingLabelActiveColor()->UIColor {
if let color = floatingLabelColor {
return color
}else if self.respondsToSelector(Selector("tintColor")) {
return self.tintColor
}
return UIColor.blueColor()
}
private func floatingLabelActiveFont()->UIFont {
if let font = floatingLabelFont {
return font
} else if let font = self.font {
return font
}
return UIFont.systemFontOfSize(12)
}
private func moveUpFloatingText() {
CATransaction.begin()
CATransaction.setValue(animationDuration, forKey: kCATransactionAnimationDuration)
let transformation = CATransform3DScale(CATransform3DIdentity, self.scale, self.scale, 1);
self.floatingLabel.transform = transformation
var frame2 = self.floatingLabel.frame
frame2.origin.y = 2 // top margin
self.floatingLabel.frame = frame2
self.floatingLabel.foregroundColor = self.floatingLabelActiveColor().CGColor
// self.floatingLabel.font = self.floatingLabelActiveFont()
CATransaction.commit()
}
private func moveDownFloatingText() {
var textFrame = textRectForBounds(self.frame)
textFrame.origin.x = textFrame.origin.x - self.frame.origin.x
textFrame.origin.y = textFrame.origin.y - self.frame.origin.y
CATransaction.begin()
CATransaction.setValue(animationDuration, forKey: kCATransactionAnimationDuration)
self.floatingLabel.transform = CATransform3DIdentity
// self.floatingLabel.font = UIFont.systemFontOfSize(15)
self.floatingLabel.foregroundColor = placeholderColor.CGColor
self.floatingLabel.frame = textFrame
CATransaction.commit()
}
func insetRectForBounds(rect : CGRect) -> CGRect {
var newRect = rect
newRect.origin.y += topInset
newRect.size.height -= topInset
return newRect
}
// MARK: - UITextField Methods
override public func editingRectForBounds(bounds: CGRect) -> CGRect {
var rect = super.editingRectForBounds(bounds)
rect = insetRectForBounds(rect)
return CGRectIntegral(rect)
}
override public func textRectForBounds(bounds: CGRect) -> CGRect {
var rect = super.textRectForBounds(bounds)
rect = insetRectForBounds(rect)
return CGRectIntegral(rect)
}
override public func clearButtonRectForBounds(bounds: CGRect) -> CGRect {
var rect = super.clearButtonRectForBounds(bounds)
let correction = (editingTextBounds.height-rect.height)/2.0
rect.origin.y = editingTextBounds.origin.y + correction
return CGRectIntegral(rect)
}
override public func layoutSubviews() {
super.layoutSubviews()
if self.text?.characters.count == 0 {
moveDownFloatingText()
} else {
moveUpFloatingText()
}
}
}
| mit | 3dbfd1a4e6678e541291e7b975311f52 | 33.568421 | 126 | 0.648752 | 5.171654 | false | false | false | false |
LoopKit/LoopKit | LoopKit/AnyCodableEquatable.swift | 1 | 1304 | //
// AnyCodableEquatable.swift
// LoopKit
//
// Created by Darin Krauss on 2/8/22.
// Copyright © 2022 LoopKit Authors. All rights reserved.
//
import Foundation
public struct AnyCodableEquatable: Codable, Equatable {
public enum Error: Swift.Error {
case unknownType
}
public let wrapped: Any
private let equals: (Self) -> Bool
public init<T: Codable & Equatable>(_ wrapped: T) {
self.wrapped = wrapped
self.equals = { $0.wrapped as? T == wrapped }
}
public init(from decoder: Decoder) throws {
let container = try decoder.singleValueContainer()
if let value = try? container.decode(String.self) {
self.init(value)
} else if let value = try? container.decode(Int.self) {
self.init(value)
} else if let value = try? container.decode(Double.self) {
self.init(value)
} else if let value = try? container.decode(Bool.self) {
self.init(value)
} else {
throw Error.unknownType
}
}
public func encode(to encoder: Encoder) throws {
try (wrapped as? Encodable)?.encode(to: encoder)
}
public static func ==(lhs: AnyCodableEquatable, rhs: AnyCodableEquatable) -> Bool {
return lhs.equals(rhs)
}
}
| mit | 37bb4e86292e55b7977882fbacd4d8b6 | 27.326087 | 87 | 0.610898 | 4.071875 | false | false | false | false |
maxoumime/emoji-data-ios | emojidataios/Classes/SkinVariationTypes.swift | 1 | 1399 | //
// SkinVariations.swift
// emoji-data-ios
//
// Created by Maxime Bertheau on 4/12/17.
// Copyright © 2017 Maxime Bertheau. All rights reserved.
//
import Foundation
enum SkinVariationTypes: String {
static let values: [SkinVariationTypes] = [.TYPE_1_2, .TYPE_3, .TYPE_4, .TYPE_5, .TYPE_6]
case TYPE_1_2 = "TYPE_1_2"
case TYPE_3 = "TYPE_3"
case TYPE_4 = "TYPE_4"
case TYPE_5 = "TYPE_5"
case TYPE_6 = "TYPE_6"
func getUnifiedValue() -> String {
switch self {
case .TYPE_1_2:
return "1F3FB"
case .TYPE_3:
return "1F3FC"
case .TYPE_4:
return "1F3FD"
case .TYPE_5:
return "1F3FE"
case .TYPE_6:
return "1F3FF"
}
}
func getAliasValue() -> String {
switch self {
case .TYPE_1_2:
return "skin-tone-2"
case .TYPE_3:
return "skin-tone-3"
case .TYPE_4:
return "skin-tone-4"
case .TYPE_5:
return "skin-tone-5"
case .TYPE_6:
return "skin-tone-6"
}
}
static func getFromUnified(_ unified: String) -> [SkinVariationTypes]? {
let splitUnified = unified.split(separator: "-").map(String.init)
return self.values.filter({ splitUnified.contains($0.getUnifiedValue()) })
}
static func getFromAlias(_ unified: String) -> SkinVariationTypes? {
return self.values.first(where: { $0.getAliasValue() == unified.lowercased() })
}
}
| mit | 27672d824c02bb199bfda57a22108201 | 21.548387 | 91 | 0.602289 | 3.052402 | false | false | false | false |
blackho1e/mjCamera | Classes/CameraViewController.swift | 1 | 3258 | import UIKit
import AVFoundation
import Photos
open class CameraViewController: UIViewController, CameraViewDelegate {
@IBOutlet weak var cameraView: CameraView!
var onCompletion: CameraViewControllerCompletion?
var albumName: String = ""
var cameraOutputQuality: CameraOutputQuality = .high
var saveToPhoneLibrary: Bool!
public init(albumName: String = "", cameraOutputQuality: CameraOutputQuality = .high,
saveToPhoneLibrary: Bool = true, completion: @escaping CameraViewControllerCompletion) {
super.init(nibName: nil, bundle: nil)
self.albumName = albumName
self.cameraOutputQuality = cameraOutputQuality
self.saveToPhoneLibrary = saveToPhoneLibrary
onCompletion = completion
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
deinit {
NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIDeviceOrientationDidChange, object: nil)
}
open override func loadView() {
super.loadView()
if let view = UINib(nibName: "CameraViewController", bundle: Bundle(for: self.classForCoder))
.instantiate(withOwner: self, options: nil).first as? UIView {
self.view = view
}
cameraView.albumName = self.albumName
cameraView.cameraOutputQuality = self.cameraOutputQuality
cameraView.saveToPhoneLibrary = self.saveToPhoneLibrary
}
open override var prefersStatusBarHidden: Bool {
get {
return true
}
}
open override var preferredInterfaceOrientationForPresentation: UIInterfaceOrientation {
get {
return .portrait
}
}
open override var shouldAutorotate: Bool {
get {
return false
}
}
open override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
get {
return .portrait
}
}
open override func viewDidLoad() {
super.viewDidLoad()
cameraView?.delegate = self
NotificationCenter.default.addObserver(self, selector: #selector(rotateCameraView(_:)),
name: NSNotification.Name.UIDeviceOrientationDidChange, object: nil)
}
open override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
UIDevice.current.beginGeneratingDeviceOrientationNotifications()
cameraView?.startSession()
}
open override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
UIDevice.current.endGeneratingDeviceOrientationNotifications()
cameraView?.stopSession()
}
func cameraViewCloseButtonTapped() {
self.onCompletion?(false, nil, nil)
}
func cameraViewShutterButtonTapped(image: UIImage?, asset: PHAsset?) {
self.onCompletion?(true, image, asset)
}
func cameraViewLastPhotoButtonTapped(image: UIImage?) {
self.onCompletion?(false, image, nil)
}
func rotateCameraView(_ notification: Notification) {
cameraView.rotatePreview()
}
}
| mit | 3847e75902a6601882c3a837062d9169 | 31.909091 | 124 | 0.655003 | 5.705779 | false | false | false | false |
beauhankins/rhok-thankbank-ios | ThankBank/Controllers/CheckInController.swift | 1 | 13120 | //
// CheckInController.swift
// ThankBank
//
// Created by Beau Hankins on 13/06/2015.
// Copyright (c) 2015 Beau Hankins. All rights reserved.
//
import Foundation
import UIKit
import AVFoundation
class CheckInController: UIViewController {
var image: UIImage?
let captureSession = AVCaptureSession()
var captureDevice: AVCaptureDevice?
let imageOutput = AVCaptureStillImageOutput()
lazy var captureButton: UIButton = {
let button = UIButton()
button.translatesAutoresizingMaskIntoConstraints = false
button.setBackgroundImage(UIImage(named: "camera"), forState: .Normal)
button.setBackgroundImage(UIImage(named: "camera-pressed"), forState: .Highlighted)
button.addTarget(self, action: "takePhoto", forControlEvents: .TouchUpInside)
return button
}()
lazy var backButton: UIButton = {
let button = UIButton()
button.translatesAutoresizingMaskIntoConstraints = false
button.setBackgroundImage(UIImage(named: "back"), forState: .Normal)
button.addTarget(self, action: "back", forControlEvents: .TouchUpInside)
return button
}()
lazy var approveButton: UIButton = {
let button = UIButton()
button.translatesAutoresizingMaskIntoConstraints = false
button.setBackgroundImage(UIImage(named: "confirm-camera"), forState: .Normal)
button.setBackgroundImage(UIImage(named: "confirm-camera-pressed"), forState: .Highlighted)
button.addTarget(self, action: "approvePhoto", forControlEvents: .TouchUpInside)
button.hidden = true
return button
}()
lazy var disapproveButton: UIButton = {
let button = UIButton()
button.translatesAutoresizingMaskIntoConstraints = false
button.setBackgroundImage(UIImage(named: "cancel-camera"), forState: .Normal)
button.setBackgroundImage(UIImage(named: "cancel-camera-pressed"), forState: .Highlighted)
button.addTarget(self, action: "disapprovePhoto", forControlEvents: .TouchUpInside)
button.hidden = true
return button
}()
lazy var hintLabel: UILabel = {
let label = UILabel()
label.translatesAutoresizingMaskIntoConstraints = false
label.text = "Take a photo as proof of your good deed"
label.textColor = Colors().White
label.font = Fonts().DefaultBold
label.textAlignment = .Center
return label
}()
lazy var topEdgeGradient: CAGradientLayer = {
let gradient = CAGradientLayer()
gradient.frame = CGRectMake(0, 0, UIScreen.mainScreen().bounds.width, 98)
gradient.colors = [UIColor(white: 0.0, alpha: 0.9).CGColor, UIColor.clearColor().CGColor]
gradient.locations = [0.0, 1.0]
return gradient
}()
lazy var bottomEdgeGradient: CAGradientLayer = {
let gradient = CAGradientLayer()
gradient.frame = CGRectMake(0, UIScreen.mainScreen().bounds.height - 98, UIScreen.mainScreen().bounds.width, 98)
gradient.colors = [UIColor.clearColor().CGColor, UIColor(white: 0.0, alpha: 0.9).CGColor]
gradient.locations = [0.0, 1.0]
return gradient
}()
lazy var edgeGradients: UIView = {
let view = UIView()
view.translatesAutoresizingMaskIntoConstraints = false
view.layer.addSublayer(self.topEdgeGradient)
view.layer.addSublayer(self.bottomEdgeGradient)
return view
}()
lazy var previewImage: UIImageView = {
let imageView = UIImageView()
imageView.translatesAutoresizingMaskIntoConstraints = false
imageView.contentMode = .ScaleAspectFill
imageView.autoresizingMask = [.FlexibleRightMargin, .FlexibleLeftMargin, .FlexibleBottomMargin, .FlexibleTopMargin, .FlexibleWidth, .FlexibleHeight]
return imageView
}()
lazy var videoPreviewLayer: AVCaptureVideoPreviewLayer = AVCaptureVideoPreviewLayer(session: self.captureSession)
override func viewDidLoad() {
super.viewDidLoad()
layoutInterface()
configureCaptureSession()
}
override func prefersStatusBarHidden() -> Bool {
return true
}
func layoutInterface() {
UIApplication.sharedApplication().setStatusBarHidden(true, withAnimation: .Slide)
view.backgroundColor = Colors().BackgroundDark
view.layer.contentsGravity = kCAGravityResizeAspectFill
view.layer.addSublayer(videoPreviewLayer)
view.addSubview(previewImage)
view.addSubview(edgeGradients)
view.addSubview(captureButton)
view.addSubview(backButton)
view.addSubview(approveButton)
view.addSubview(disapproveButton)
view.addSubview(hintLabel)
videoPreviewLayer.frame = view.layer.bounds
videoPreviewLayer.videoGravity = AVLayerVideoGravityResizeAspectFill
view.addConstraint(NSLayoutConstraint(item: previewImage, attribute: .Top, relatedBy: .Equal, toItem: view, attribute: .Top, multiplier: 1, constant: 0))
view.addConstraint(NSLayoutConstraint(item: previewImage, attribute: .CenterX, relatedBy: .Equal, toItem: view, attribute: .CenterX, multiplier: 1, constant: 0))
view.addConstraint(NSLayoutConstraint(item: previewImage, attribute: .Width, relatedBy: .Equal, toItem: view, attribute: .Width, multiplier: 1, constant: 0))
view.addConstraint(NSLayoutConstraint(item: previewImage, attribute: .Height, relatedBy: .Equal, toItem: view, attribute: .Height, multiplier: 1, constant: 0))
view.addConstraint(NSLayoutConstraint(item: edgeGradients, attribute: .Top, relatedBy: .Equal, toItem: view, attribute: .Top, multiplier: 1, constant: 0))
view.addConstraint(NSLayoutConstraint(item: edgeGradients, attribute: .CenterX, relatedBy: .Equal, toItem: view, attribute: .CenterX, multiplier: 1, constant: 0))
view.addConstraint(NSLayoutConstraint(item: edgeGradients, attribute: .Width, relatedBy: .Equal, toItem: view, attribute: .Width, multiplier: 1, constant: 0))
view.addConstraint(NSLayoutConstraint(item: edgeGradients, attribute: .Height, relatedBy: .Equal, toItem: view, attribute: .Height, multiplier: 1, constant: 0))
view.addConstraint(NSLayoutConstraint(item: captureButton, attribute: .CenterY, relatedBy: .Equal, toItem: view, attribute: .Bottom, multiplier: 1, constant: -49))
view.addConstraint(NSLayoutConstraint(item: captureButton, attribute: .CenterX, relatedBy: .Equal, toItem: view, attribute: .CenterX, multiplier: 1, constant: 0))
view.addConstraint(NSLayoutConstraint(item: captureButton, attribute: .Width, relatedBy: .Equal, toItem: .None, attribute: .NotAnAttribute, multiplier: 1, constant: 58))
view.addConstraint(NSLayoutConstraint(item: captureButton, attribute: .Height, relatedBy: .Equal, toItem: .None, attribute: .NotAnAttribute, multiplier: 1, constant: 58))
view.addConstraint(NSLayoutConstraint(item: backButton, attribute: .CenterY, relatedBy: .Equal, toItem: view, attribute: .Bottom, multiplier: 1, constant: -49))
view.addConstraint(NSLayoutConstraint(item: backButton, attribute: .Left, relatedBy: .Equal, toItem: view, attribute: .Left, multiplier: 1, constant: 25))
view.addConstraint(NSLayoutConstraint(item: backButton, attribute: .Width, relatedBy: .Equal, toItem: .None, attribute: .NotAnAttribute, multiplier: 1, constant: 21))
view.addConstraint(NSLayoutConstraint(item: backButton, attribute: .Height, relatedBy: .Equal, toItem: .None, attribute: .NotAnAttribute, multiplier: 1, constant: 17))
view.addConstraint(NSLayoutConstraint(item: approveButton, attribute: .CenterY, relatedBy: .Equal, toItem: view, attribute: .Bottom, multiplier: 1, constant: -49))
view.addConstraint(NSLayoutConstraint(item: approveButton, attribute: .CenterX, relatedBy: .Equal, toItem: view, attribute: .CenterX, multiplier: 1.5, constant: 0))
view.addConstraint(NSLayoutConstraint(item: approveButton, attribute: .Width, relatedBy: .Equal, toItem: .None, attribute: .NotAnAttribute, multiplier: 1, constant: 58))
view.addConstraint(NSLayoutConstraint(item: approveButton, attribute: .Height, relatedBy: .Equal, toItem: .None, attribute: .NotAnAttribute, multiplier: 1, constant: 58))
view.addConstraint(NSLayoutConstraint(item: disapproveButton, attribute: .CenterY, relatedBy: .Equal, toItem: view, attribute: .Bottom, multiplier: 1, constant: -49))
view.addConstraint(NSLayoutConstraint(item: disapproveButton, attribute: .CenterX, relatedBy: .Equal, toItem: view, attribute: .CenterX, multiplier: 0.5, constant: 0))
view.addConstraint(NSLayoutConstraint(item: disapproveButton, attribute: .Width, relatedBy: .Equal, toItem: .None, attribute: .NotAnAttribute, multiplier: 1, constant: 58))
view.addConstraint(NSLayoutConstraint(item: disapproveButton, attribute: .Height, relatedBy: .Equal, toItem: .None, attribute: .NotAnAttribute, multiplier: 1, constant: 58))
view.addConstraint(NSLayoutConstraint(item: hintLabel, attribute: .CenterY, relatedBy: .Equal, toItem: view, attribute: .Top, multiplier: 1, constant: 49))
view.addConstraint(NSLayoutConstraint(item: hintLabel, attribute: .CenterX, relatedBy: .Equal, toItem: view, attribute: .CenterX, multiplier: 1, constant: 0))
view.addConstraint(NSLayoutConstraint(item: hintLabel, attribute: .Width, relatedBy: .Equal, toItem: view, attribute: .Width, multiplier: 1, constant: 0))
}
// MARK: - AVCapture
func configureCaptureSession() {
captureSession.sessionPreset = AVCaptureSessionPresetPhoto
let devices = AVCaptureDevice.devices()
for device in devices {
if device.hasMediaType(AVMediaTypeVideo) {
if device.position == AVCaptureDevicePosition.Back {
captureDevice = device as? AVCaptureDevice
if captureDevice != nil {
beginSession()
}
}
}
}
}
func beginSession() {
do {
let deviceInput = try AVCaptureDeviceInput(device: captureDevice)
captureSession.addInput(deviceInput)
captureSession.startRunning()
imageOutput.outputSettings = [AVVideoCodecKey:AVVideoCodecJPEG]
if captureSession.canAddOutput(imageOutput) {
captureSession.addOutput(imageOutput)
}
} catch {
print(error)
}
}
func configureDevice() {
if let device = captureDevice {
do {
try device.lockForConfiguration()
device.focusMode = AVCaptureFocusMode.AutoFocus
device.unlockForConfiguration()
} catch {
print(error)
}
}
}
func focusTo(value : Float) {
if let device = captureDevice {
do {
try device.lockForConfiguration()
device.setFocusModeLockedWithLensPosition(value, completionHandler: { (time) -> Void in
print(value)
})
device.unlockForConfiguration()
} catch {
print(error)
}
}
}
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
if let touch: UITouch = touches.first {
let touchPercent = touch.locationInView(view).x / UIScreen.mainScreen().bounds.width
focusTo(Float(touchPercent))
}
super.touchesBegan(touches, withEvent:event)
}
override func touchesMoved(touches: Set<UITouch>, withEvent event: UIEvent?) {
if let touch: UITouch = touches.first {
let touchPercent = touch.locationInView(view).x / UIScreen.mainScreen().bounds.width
focusTo(Float(touchPercent))
}
super.touchesBegan(touches, withEvent:event)
}
// MARK - Take Photo
func takePhoto() {
print("Take Photo")
if let videoConnection = imageOutput.connectionWithMediaType(AVMediaTypeVideo) {
imageOutput.captureStillImageAsynchronouslyFromConnection(videoConnection) {
(imageDataSampleBuffer, error) -> Void in
let imageData = AVCaptureStillImageOutput.jpegStillImageNSDataRepresentation(imageDataSampleBuffer)
self.image = UIImage(data: imageData)
self.showPreview()
}
}
}
// MARK - Preview
func showPreview() {
print(image!)
videoPreviewLayer.hidden = true
previewImage.image = image!
hintLabel.text = "Use this photo as proof? "
captureButton.hidden = true
backButton.hidden = true
approveButton.hidden = false
disapproveButton.hidden = false
}
func hidePreview() {
videoPreviewLayer.hidden = false
previewImage.image = nil
hintLabel.text = "Take a photo as proof of your good deed"
captureButton.hidden = false
backButton.hidden = false
approveButton.hidden = true
disapproveButton.hidden = true
}
// MARK - Approval
func approvePhoto() {
saveDefaults()
let chooseRewardController = ChooseRewardController()
navigationController?.pushViewController(chooseRewardController, animated: true)
}
func disapprovePhoto() {
hidePreview()
}
// MARK: - NSUserDefaults
func saveDefaults() {
let defaults = NSUserDefaults.standardUserDefaults()
let imageData = UIImageJPEGRepresentation(image!, 1.0)
let encodedImageData = imageData!.base64EncodedDataWithOptions(.Encoding64CharacterLineLength)
defaults.setObject(encodedImageData, forKey: "checkin_image")
}
// MARK - Navigation
func back() {
navigationController?.popViewControllerAnimated(true)
}
} | mit | 46ff0f6e5fa0fa23db684dd1c49e058d | 41.462783 | 177 | 0.721037 | 4.734753 | false | false | false | false |
wasupwithuman/ScrapeME | ScrapeMESwiftly/ViewController.swift | 1 | 967 | //
// ViewController.swift
// ScrapeMESwiftly
//
// Created by Samuel Barthelemy on 5/25/16.
// Copyright © 2016 Samuel Barthelemy. All rights reserved.
//
import Cocoa
class ViewController: NSViewController {
@IBOutlet weak var website: NSTextField!
@IBOutlet var sitePagesResults: NSTextView!
@IBOutlet var emailAddressesResults: NSTextView!
@IBOutlet weak var statusLabel: NSTextField!
@IBAction func scrape(sender: NSButton) {
let scrapedWebsite = Domain(domain: website.stringValue)
statusLabel.stringValue = "Spidering and grabbing emails for \(website.stringValue)"
scrapedWebsite.delay(0.5) {
self.statusLabel.stringValue = scrapedWebsite.connectToDomain(nil)
scrapedWebsite.linkParser(scrapedWebsite.html)
self.sitePagesResults.string = scrapedWebsite.grabLinks()
self.emailAddressesResults.string = scrapedWebsite.spiderPages()
}
}
} | apache-2.0 | 9d4acb6b4f6d18f25e709044a112082f | 30.193548 | 92 | 0.704969 | 4.128205 | false | false | false | false |
takamashiro/XDYZB | XDYZB/XDYZB/Classes/Home/View/RecommendGameView.swift | 1 | 1981 | //
// RecommendGameView.swift
// XDYZB
//
// Created by takamashiro on 2016/9/30.
// Copyright © 2016年 com.takamashiro. All rights reserved.
//
import UIKit
private let kGameCellID = "kGameCellID"
private let kEdgeInsetMargin : CGFloat = 10
class RecommendGameView: UIView {
// MARK: 定义数据的属性
var groups : [BaseGameModel]? {
didSet {
// 刷新表格
collectionView.reloadData()
}
}
// MARK: 控件属性
@IBOutlet weak var collectionView: UICollectionView!
// MARK: 系统回调
override func awakeFromNib() {
super.awakeFromNib()
// 让控件不随着父控件的拉伸而拉伸
autoresizingMask = UIViewAutoresizing()
// 注册Cell
collectionView.register(UINib(nibName: "CollectionGameCell", bundle: nil), forCellWithReuseIdentifier: kGameCellID)
// 给collectionView添加内边距
collectionView.contentInset = UIEdgeInsets(top: 0, left: kEdgeInsetMargin, bottom: 0, right: kEdgeInsetMargin)
}
}
// MARK:- 提供快速创建的类方法
extension RecommendGameView {
class func recommendGameView() -> RecommendGameView {
return Bundle.main.loadNibNamed("RecommendGameView", owner: nil, options: nil)!.first as! RecommendGameView
}
}
// MARK:- 遵守UICollectionView的数据源协议
extension RecommendGameView : UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return groups?.count ?? 0
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: kGameCellID, for: indexPath) as! CollectionGameCell
cell.baseGame = groups![(indexPath as NSIndexPath).item]
return cell
}
}
| mit | 732998c7c22a4904d361848ec1f27577 | 27.151515 | 126 | 0.670075 | 5.263456 | false | false | false | false |
Ferrari-lee/firefox-ios | Client/Application/AuroraAppDelegate.swift | 26 | 6050 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Alamofire
import MessageUI
private let AuroraPropertyListURL = "https://people.mozilla.org/iosbuilds/FennecAurora.plist"
private let AuroraDownloadPageURL = "https://people.mozilla.org/iosbuilds/index.html"
private let AppUpdateTitle = NSLocalizedString("New version available", comment: "Prompt title for application update")
private let AppUpdateMessage = NSLocalizedString("There is a new version available of Firefox Aurora. Tap OK to go to the download page.", comment: "Prompt message for application update")
private let AppUpdateCancel = NSLocalizedString("Not Now", comment: "Label for button to cancel application update prompt")
private let AppUpdateOK = NSLocalizedString("OK", comment: "Label for OK button in the application update prompt")
class AuroraAppDelegate: AppDelegate {
private var naggedAboutAuroraUpdate = false
override func application(application: UIApplication, willFinishLaunchingWithOptions launchOptions: [NSObject : AnyObject]?) -> Bool {
super.application(application, willFinishLaunchingWithOptions: launchOptions)
checkForAuroraUpdate()
registerFeedbackNotification()
return true
}
override func applicationDidBecomeActive(application: UIApplication) {
if !naggedAboutAuroraUpdate {
checkForAuroraUpdate()
}
super.applicationDidBecomeActive(application)
}
func application(application: UIApplication, applicationWillTerminate app: UIApplication) {
unregisterFeedbackNotification()
}
func applicationWillResignActive(application: UIApplication) {
unregisterFeedbackNotification()
}
private func registerFeedbackNotification() {
NSNotificationCenter.defaultCenter().addObserverForName(
UIApplicationUserDidTakeScreenshotNotification,
object: nil,
queue: NSOperationQueue.mainQueue()) { (notification) -> Void in
if let window = self.window {
UIGraphicsBeginImageContext(window.bounds.size)
window.drawViewHierarchyInRect(window.bounds, afterScreenUpdates: true)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
self.sendFeedbackMailWithImage(image)
}
}
}
private func unregisterFeedbackNotification() {
NSNotificationCenter.defaultCenter().removeObserver(self,
name: UIApplicationUserDidTakeScreenshotNotification, object: nil)
}
}
extension AuroraAppDelegate: UIAlertViewDelegate {
private func checkForAuroraUpdate() {
if let localVersion = localVersion() {
fetchLatestAuroraVersion() { version in
if let remoteVersion = version {
if localVersion.compare(remoteVersion as String, options: NSStringCompareOptions.NumericSearch) == NSComparisonResult.OrderedAscending {
self.naggedAboutAuroraUpdate = true
let alert = UIAlertView(title: AppUpdateTitle, message: AppUpdateMessage, delegate: self, cancelButtonTitle: AppUpdateCancel, otherButtonTitles: AppUpdateOK)
alert.show()
}
}
}
}
}
private func localVersion() -> NSString? {
return NSBundle.mainBundle().objectForInfoDictionaryKey(String(kCFBundleVersionKey)) as? NSString
}
private func fetchLatestAuroraVersion(completionHandler: NSString? -> Void) {
Alamofire.request(.GET, AuroraPropertyListURL).responsePropertyList(options: NSPropertyListReadOptions(), completionHandler: { (_, _, object) -> Void in
if let plist = object.value as? NSDictionary {
if let items = plist["items"] as? NSArray {
if let item = items[0] as? NSDictionary {
if let metadata = item["metadata"] as? NSDictionary {
if let remoteVersion = metadata["bundle-version"] as? String {
completionHandler(remoteVersion)
return
}
}
}
}
}
completionHandler(nil)
})
}
func alertView(alertView: UIAlertView, clickedButtonAtIndex buttonIndex: Int) {
if buttonIndex == 1 {
UIApplication.sharedApplication().openURL(NSURL(string: AuroraDownloadPageURL)!)
}
}
}
extension AuroraAppDelegate: MFMailComposeViewControllerDelegate {
private func sendFeedbackMailWithImage(image: UIImage) {
if (MFMailComposeViewController.canSendMail()) {
if let buildNumber = NSBundle.mainBundle().objectForInfoDictionaryKey(String(kCFBundleVersionKey)) as? NSString {
let mailComposeViewController = MFMailComposeViewController()
mailComposeViewController.mailComposeDelegate = self
mailComposeViewController.setSubject("Feedback on iOS client version v\(appVersion) (\(buildNumber))")
mailComposeViewController.setToRecipients(["[email protected]"])
if let imageData = UIImagePNGRepresentation(image) {
mailComposeViewController.addAttachmentData(imageData, mimeType: "image/png", fileName: "feedback.png")
window?.rootViewController?.presentViewController(mailComposeViewController, animated: true, completion: nil)
}
}
}
}
func mailComposeController(mailComposeViewController: MFMailComposeViewController, didFinishWithResult result: MFMailComposeResult, error: NSError?) {
mailComposeViewController.dismissViewControllerAnimated(true, completion: nil)
}
}
| mpl-2.0 | 6320216e8752c253bad0d04e30999b03 | 45.899225 | 188 | 0.670083 | 6.31524 | false | false | false | false |
tokyovigilante/CesiumKit | CesiumKit/Core/PixelFormat.swift | 1 | 1777 | //
// PixelFormat.swift
// CesiumKit
//
// Created by Ryan Walklin on 20/07/14.
// Copyright (c) 2014 Test Toast. All rights reserved.
//
import OpenGLES
enum PixelFormat: Int {
/**
* 0x1902. A pixel format containing a depth value.
*
* @type {Number}
* @constant
*/
case DepthComponent = 0x1902,
/**
* 0x84F9. A pixel format containing a depth and stencil value, most often used with {@link PixelDatatype.UNSIGNED_INT_24_8_WEBGL}.
*
* @type {Number}
* @constant
*/
DepthStencil = 0x84F9,
/**
* 0x1906. A pixel format containing an alpha channel.
*
* @type {Number}
* @constant
*/
Alpha = 0x1906,
/**
* 0x1907. A pixel format containing red, green, and blue channels.
*
* @type {Number}
* @constant
*/
RGB = 0x1907,
/**
* 0x1908. A pixel format containing red, green, blue, and alpha channels.
*
* @type {Number}
* @constant
*/
RGBA = 0x1908,
/**
* 0x1909. A pixel format containing a luminance (intensity) channel.
*
* @type {Number}
* @constant
*/
Luminance = 0x1909,
/**
* 0x190A. A pixel format containing luminance (intensity) and alpha channels.
*
* @type {Number}
* @constant
* @default 0x190A
*/
LuminanceAlpha = 0x190A
func isColorFormat() -> Bool {
return self == PixelFormat.Alpha ||
self == PixelFormat.RGB ||
self == PixelFormat.RGBA ||
self == PixelFormat.Luminance ||
self == PixelFormat.LuminanceAlpha
}
func isDepthFormat() -> Bool {
return self == PixelFormat.DepthComponent ||
self == PixelFormat.DepthStencil
}
} | apache-2.0 | 4e72feae91715a17787f364dbedad604 | 20.950617 | 135 | 0.561058 | 3.764831 | false | false | false | false |
dekatotoro/FluxWithRxSwiftSample | FluxWithRxSwiftSample/Dispatchers/ErrorNotice/ErrorNoticeDispatcher.swift | 1 | 488 | //
// ErrorNoticeDispatcher.swift
// FluxWithRxSwiftSample
//
// Created by Yuji Hato on 2016/10/13.
// Copyright © 2016年 dekatotoro. All rights reserved.
//
struct ErrorNoticeDispatcher {
static let shared = ErrorNoticeDispatcher()
let addError = DispatchSubject<(ErrorNoticeType)>()
let removeError = DispatchSubject<ErrorNoticeType>()
let removeAll = DispatchSubject<Void>()
let next = DispatchSubject<Void>()
let hide = DispatchSubject<Void>()
}
| mit | 8a16fd4130f07cdc4d8dbae9ae2756b4 | 25.944444 | 56 | 0.713402 | 4.07563 | false | false | false | false |
ronaldbroens/jenkinsapp | JenkinsApp/DetailViewController.swift | 1 | 4592 | //
// DetailViewController.swift
// JenkinsApp
//
// Created by Ronald Broens on 07/02/15.
// Copyright (c) 2015 Ronald Broens. All rights reserved.
//
import UIKit
class DetailViewController: UIViewController, UITableViewDelegate {
@IBOutlet weak var detailDescriptionLabel: UILabel!
@IBOutlet weak var tv_builds: UITableView!
@IBOutlet weak var progressbar: UIProgressView!
var timer : NSTimer!
@IBAction func BtnBuildClick(sender: UIButton)
{
print("Must build the job with name: "+self.detailItem!.Name)
print("Must build the job with url: "+self.detailItem!.Url)
let jenkinsReader = JobsReader()
jenkinsReader.StartJobs(self.detailItem!.Url)
}
var detailItem: JenkinsJob? {
didSet {
// Update the view.
self.configureView()
}
}
func configureView() {
// Update the user interface for the detail item.
if let job = self.detailItem {
if let label = self.detailDescriptionLabel {
label.text = job.Name
}
if(self.timer != nil)
{
timer.invalidate()
timer = nil
}
self.timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: Selector("PullJobDetails"), userInfo: nil, repeats: true)
}
}
func PullJobDetails()
{
let jenkinsReader = JobsReader()
jenkinsReader.GetJobDetails(self.detailItem!.Url, detailhandler: self.JobDetailsLoaded)
}
func JobDetailsLoaded(details : JenkinsDetailInfo)
{
print("Details loaded")
let jenkinsReader = JobsReader()
jenkinsReader.GetBuildDetails(details.LastBuild.Url, detailhandler: self.JobBuildLoaded)
}
func JobBuildLoaded(details: JenkinsBuild)
{
// hack
var builds = Array<JenkinsBuild>()
builds.append(details)
self.tv_builds.dataSource = BuildsDatasource(builds: builds)
/*dispatch_async(dispatch_get_main_queue())
{
self.tv_builds.reloadData()
}*/
print("BuildInfo loaded");
let dateFormatter = NSDateFormatter()//3
let theDateFormat = NSDateFormatterStyle.ShortStyle //5
let theTimeFormat = NSDateFormatterStyle.MediumStyle//6
dateFormatter.dateStyle = theDateFormat//8
dateFormatter.timeStyle = theTimeFormat//9
print("Build started at: " + dateFormatter.stringFromDate(details.StartTime))//11
print("Expected finisch at: " + dateFormatter.stringFromDate(details.ExpectedEndTime))//11
if(!details.Building)
{
dispatch_async(dispatch_get_main_queue())
{
self.progressbar.hidden = true;
}
return
}
let timeDifg = NSDate().timeIntervalSinceDate(details.StartTime)
print("timedif: \(timeDifg)")
let totalTimeDone = Float(NSDate().timeIntervalSince1970 - details.StartTime.timeIntervalSince1970);
print("TotaltimeDOne \(totalTimeDone)")
let duration = Float(details.EstimatedDuration)
let percentage : Float = (totalTimeDone / duration)
print("Percentage = \(percentage)");
//percentage = Math.round(percentage * 100.0) / 100.0;
let calendar = NSCalendar.currentCalendar()
let components = calendar.components([.Hour, .Minute], fromDate: details.StartTime)
let hour = components.hour
let minutes = components.minute
print("Build starten on: " + String(hour) + ":" + String(minutes));
dispatch_async(dispatch_get_main_queue())
{
self.progressbar.hidden = false
self.progressbar.setProgress(percentage, animated: true)
}
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
self.configureView()
}
override func viewWillDisappear(animated: Bool) {
super.viewWillDisappear(animated)
if(self.timer != nil)
{
timer.invalidate()
timer = nil
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| apache-2.0 | ca5c964c38b63bc2135b8f9f91d0caaa | 28.625806 | 149 | 0.588632 | 5.046154 | false | false | false | false |
Zewo/Epoch | Sources/Media/JSON/JSONDecodingMedia.swift | 1 | 13058 | import Core
import Venice
extension JSON : DecodingMedia {
public init(from readable: Readable, deadline: Deadline) throws {
let parser = JSONParser()
let buffer = UnsafeMutableRawBufferPointer.allocate(count: 4096)
defer {
buffer.deallocate()
}
while true {
let read = try readable.read(buffer, deadline: deadline)
guard !read.isEmpty else {
break
}
guard let json = try parser.parse(read) else {
continue
}
self = json
return
}
self = try parser.finish()
}
public func keyCount() -> Int? {
if case let .object(object) = self {
return object.keys.count
}
if case let .array(array) = self {
return array.count
}
return nil
}
public func allKeys<Key>(keyedBy: Key.Type) -> [Key] where Key : CodingKey {
if case let .object(object) = self {
return object.keys.flatMap({ Key(stringValue: $0) })
}
if case let .array(array) = self {
return array.indices.flatMap({ Key(intValue: $0) })
}
return []
}
public func contains<Key>(_ key: Key) -> Bool where Key : CodingKey {
guard let map = try? decodeIfPresent(type(of: self), forKey: key) else {
return false
}
return map != nil
}
public func keyedContainer() throws -> DecodingMedia {
guard isObject else {
throw DecodingError.typeMismatch(type(of: self), DecodingError.Context())
}
return self
}
public func unkeyedContainer() throws -> DecodingMedia {
guard isArray else {
throw DecodingError.typeMismatch(type(of: self), DecodingError.Context())
}
return self
}
public func singleValueContainer() throws -> DecodingMedia {
if isObject {
throw DecodingError.typeMismatch(type(of: self), DecodingError.Context())
}
if isArray {
throw DecodingError.typeMismatch(type(of: self), DecodingError.Context())
}
return self
}
public func decode(_ type: DecodingMedia.Type, forKey key: CodingKey) throws -> DecodingMedia {
if let index = key.intValue {
guard case let .array(array) = self else {
throw DecodingError.typeMismatch(
[JSON].self,
DecodingError.Context(codingPath: [key])
)
}
guard array.indices.contains(index) else {
throw DecodingError.valueNotFound(
JSON.self,
DecodingError.Context(codingPath: [key])
)
}
return array[index]
} else {
guard case let .object(object) = self else {
throw DecodingError.typeMismatch(
[String: JSON].self,
DecodingError.Context(codingPath: [key])
)
}
guard let newValue = object[key.stringValue] else {
throw DecodingError.valueNotFound(
JSON.self,
DecodingError.Context(codingPath: [key])
)
}
return newValue
}
}
public func decodeIfPresent(
_ type: DecodingMedia.Type,
forKey key: CodingKey
) throws -> DecodingMedia? {
if let index = key.intValue {
guard case let .array(array) = self else {
throw DecodingError.typeMismatch(
[JSON].self,
DecodingError.Context(codingPath: [key])
)
}
guard array.indices.contains(index) else {
throw DecodingError.valueNotFound(
JSON.self,
DecodingError.Context(codingPath: [key])
)
}
return array[index]
} else {
guard case let .object(object) = self else {
throw DecodingError.typeMismatch(
[String: JSON].self,
DecodingError.Context(codingPath: [key])
)
}
guard let newValue = object[key.stringValue] else {
throw DecodingError.valueNotFound(
JSON.self,
DecodingError.Context(codingPath: [key])
)
}
return newValue
}
}
public func decodeNil() -> Bool {
return isNull
}
public func decode(_ type: Bool.Type) throws -> Bool {
if case .null = self {
throw DecodingError.valueNotFound(
Bool.self,
DecodingError.Context()
)
}
guard case let .bool(bool) = self else {
throw DecodingError.typeMismatch(
Bool.self,
DecodingError.Context()
)
}
return bool
}
public func decode(_ type: Int.Type) throws -> Int {
if case .null = self {
throw DecodingError.valueNotFound(
Int.self,
DecodingError.Context()
)
}
if case let .int(int) = self {
return int
}
if case let .double(double) = self, let int = Int(exactly: double) {
return int
}
throw DecodingError.typeMismatch(
Int.self,
DecodingError.Context()
)
}
public func decode(_ type: Int8.Type) throws -> Int8 {
if case .null = self {
throw DecodingError.valueNotFound(
Int8.self,
DecodingError.Context()
)
}
if case let .int(int) = self, let int8 = Int8(exactly: int) {
return int8
}
if case let .double(double) = self, let int8 = Int8(exactly: double) {
return int8
}
throw DecodingError.typeMismatch(
Int8.self,
DecodingError.Context()
)
}
public func decode(_ type: Int16.Type) throws -> Int16 {
if case .null = self {
throw DecodingError.valueNotFound(
Int16.self,
DecodingError.Context()
)
}
if case let .int(int) = self, let int16 = Int16(exactly: int) {
return int16
}
if case let .double(double) = self, let int16 = Int16(exactly: double) {
return int16
}
throw DecodingError.typeMismatch(
Int16.self,
DecodingError.Context()
)
}
public func decode(_ type: Int32.Type) throws -> Int32 {
if case .null = self {
throw DecodingError.valueNotFound(
Int32.self,
DecodingError.Context()
)
}
if case let .int(int) = self, let int32 = Int32(exactly: int) {
return int32
}
if case let .double(double) = self, let int32 = Int32(exactly: double) {
return int32
}
throw DecodingError.typeMismatch(
Int32.self,
DecodingError.Context()
)
}
public func decode(_ type: Int64.Type) throws -> Int64 {
if case .null = self {
throw DecodingError.valueNotFound(
Int64.self,
DecodingError.Context()
)
}
if case let .int(int) = self, let int64 = Int64(exactly: int) {
return int64
}
if case let .double(double) = self, let int64 = Int64(exactly: double) {
return int64
}
throw DecodingError.typeMismatch(
Int64.self,
DecodingError.Context()
)
}
public func decode(_ type: UInt.Type) throws -> UInt {
if case .null = self {
throw DecodingError.valueNotFound(
UInt.self,
DecodingError.Context()
)
}
if case let .int(int) = self, let uint = UInt(exactly: int) {
return uint
}
if case let .double(double) = self, let uint = UInt(exactly: double) {
return uint
}
throw DecodingError.typeMismatch(
UInt.self,
DecodingError.Context()
)
}
public func decode(_ type: UInt8.Type) throws -> UInt8 {
if case .null = self {
throw DecodingError.valueNotFound(
UInt8.self,
DecodingError.Context()
)
}
if case let .int(int) = self, let uint8 = UInt8(exactly: int) {
return uint8
}
if case let .double(double) = self, let uint8 = UInt8(exactly: double) {
return uint8
}
throw DecodingError.typeMismatch(
UInt8.self,
DecodingError.Context()
)
}
public func decode(_ type: UInt16.Type) throws -> UInt16 {
if case .null = self {
throw DecodingError.valueNotFound(
UInt16.self,
DecodingError.Context()
)
}
if case let .int(int) = self, let uint16 = UInt16(exactly: int) {
return uint16
}
if case let .double(double) = self, let uint16 = UInt16(exactly: double) {
return uint16
}
throw DecodingError.typeMismatch(
UInt16.self,
DecodingError.Context()
)
}
public func decode(_ type: UInt32.Type) throws -> UInt32 {
if case .null = self {
throw DecodingError.valueNotFound(
UInt32.self,
DecodingError.Context()
)
}
if case let .int(int) = self, let uint32 = UInt32(exactly: int) {
return uint32
}
if case let .double(double) = self, let uint32 = UInt32(exactly: double) {
return uint32
}
throw DecodingError.typeMismatch(
UInt32.self,
DecodingError.Context()
)
}
public func decode(_ type: UInt64.Type) throws -> UInt64 {
if case .null = self {
throw DecodingError.valueNotFound(
UInt64.self,
DecodingError.Context()
)
}
if case let .int(int) = self, let uint64 = UInt64(exactly: int) {
return uint64
}
if case let .double(double) = self, let uint64 = UInt64(exactly: double) {
return uint64
}
throw DecodingError.typeMismatch(
UInt64.self,
DecodingError.Context()
)
}
public func decode(_ type: Float.Type) throws -> Float {
if case .null = self {
throw DecodingError.valueNotFound(
Float.self,
DecodingError.Context()
)
}
if case let .int(int) = self, let float = Float(exactly: int) {
return float
}
if case let .double(double) = self, let float = Float(exactly: double) {
return float
}
throw DecodingError.typeMismatch(
Float.self,
DecodingError.Context()
)
}
public func decode(_ type: Double.Type) throws -> Double {
if case .null = self {
throw DecodingError.valueNotFound(
Double.self,
DecodingError.Context()
)
}
if case let .int(int) = self, let double = Double(exactly: int) {
return double
}
if case let .double(double) = self {
return double
}
throw DecodingError.typeMismatch(
Double.self,
DecodingError.Context()
)
}
public func decode(_ type: String.Type) throws -> String {
if case .null = self {
throw DecodingError.valueNotFound(
String.self,
DecodingError.Context()
)
}
guard case let .string(string) = self else {
throw DecodingError.typeMismatch(
String.self,
DecodingError.Context()
)
}
return string
}
}
| mit | 7e1c101e0d11a544a15ad5370a5a169b | 26.723992 | 99 | 0.476566 | 5.206539 | false | false | false | false |
salemoh/GoldenQuraniOS | GoldenQuranSwift/GoldenQuranSwift/FortyHadithViewController.swift | 1 | 2569 | //
// FortyHadithViewController.swift
// GoldenQuranSwift
//
// Created by Omar Fraiwan on 4/17/17.
// Copyright © 2017 Omar Fraiwan. All rights reserved.
//
import UIKit
class FortyHadithViewController: UIViewController {
@IBOutlet weak var tableView: UITableView!
var hadiths:[Hadith] = [Hadith]()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
hadiths = DBManager.shared.getHadithContent(withGroupId: 0)
self.tableView.estimatedRowHeight = 50
self.tableView.reloadData()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
if segue.identifier == "viewHadith" {
let indexPath = sender as! IndexPath
let navigationController = segue.destination as! UINavigationController
let rootViewController = navigationController.viewControllers[0] as! HadithViewerViewController
rootViewController.hadiths = self.hadiths
rootViewController.startViewerIndex = indexPath.row
}
}
}
//FortyHadithTableViewCell
extension FortyHadithViewController:UITableViewDelegate{
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return UITableViewAutomaticDimension
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
self.performSegue(withIdentifier: "viewHadith", sender: indexPath)
}
}
extension FortyHadithViewController:UITableViewDataSource{
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int{
return hadiths.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell{
let cell = tableView.dequeueReusableCell(withIdentifier: "FortyHadithTableViewCell") as! FortyHadithTableViewCell
let hadith = hadiths[indexPath.row]
cell.lblTitle.text = hadith.title
cell.setNeedsLayout()
return cell
}
}
| mit | 89418f5c8b0c2e4bc7c070f51fc7f6f9 | 30.317073 | 121 | 0.683411 | 5.146293 | false | false | false | false |
idapgroup/IDPDesign | Tests/iOS/Pods/Quick/Sources/Quick/ExampleGroup.swift | 93 | 2936 | import Foundation
/**
Example groups are logical groupings of examples, defined with
the `describe` and `context` functions. Example groups can share
setup and teardown code.
*/
final public class ExampleGroup: NSObject {
weak internal var parent: ExampleGroup?
internal let hooks = ExampleHooks()
internal var phase: HooksPhase = .nothingExecuted
private let internalDescription: String
private let flags: FilterFlags
private let isInternalRootExampleGroup: Bool
private var childGroups = [ExampleGroup]()
private var childExamples = [Example]()
internal init(description: String, flags: FilterFlags, isInternalRootExampleGroup: Bool = false) {
self.internalDescription = description
self.flags = flags
self.isInternalRootExampleGroup = isInternalRootExampleGroup
}
public override var description: String {
return internalDescription
}
/**
Returns a list of examples that belong to this example group,
or to any of its descendant example groups.
*/
public var examples: [Example] {
return childExamples + childGroups.flatMap { $0.examples }
}
internal var name: String? {
guard let parent = parent else {
return isInternalRootExampleGroup ? nil : description
}
guard let name = parent.name else { return description }
return "\(name), \(description)"
}
internal var filterFlags: FilterFlags {
var aggregateFlags = flags
walkUp { group in
for (key, value) in group.flags {
aggregateFlags[key] = value
}
}
return aggregateFlags
}
internal var befores: [BeforeExampleWithMetadataClosure] {
var closures = Array(hooks.befores.reversed())
walkUp { group in
closures.append(contentsOf: Array(group.hooks.befores.reversed()))
}
return Array(closures.reversed())
}
internal var afters: [AfterExampleWithMetadataClosure] {
var closures = hooks.afters
walkUp { group in
closures.append(contentsOf: group.hooks.afters)
}
return closures
}
internal func walkDownExamples(_ callback: (_ example: Example) -> Void) {
for example in childExamples {
callback(example)
}
for group in childGroups {
group.walkDownExamples(callback)
}
}
internal func appendExampleGroup(_ group: ExampleGroup) {
group.parent = self
childGroups.append(group)
}
internal func appendExample(_ example: Example) {
example.group = self
childExamples.append(example)
}
private func walkUp(_ callback: (_ group: ExampleGroup) -> Void) {
var group = self
while let parent = group.parent {
callback(parent)
group = parent
}
}
}
| bsd-3-clause | cd0bd5dd1781376b088fbd05f1e12d64 | 28.656566 | 102 | 0.634196 | 5.079585 | false | false | false | false |
ainopara/Stage1st-Reader | Stage1st/Scene/Notice/NoticeCell.swift | 1 | 6317 | //
// NoticeCell.swift
// Stage1st
//
// Created by Zheng Li on 2018/10/21.
// Copyright © 2018 Renaissance. All rights reserved.
//
import SnapKit
import Fuzi
import Kingfisher
class NoticeCell: UICollectionViewCell {
let avatarImageView = UIImageView()
let authorLabel = UILabel()
let titleLabel = UILabel()
let dateLabel = UILabel()
var isNew: Bool = false
override init(frame: CGRect) {
super.init(frame: frame)
selectedBackgroundView = UIView()
avatarImageView.contentMode = .scaleAspectFill
avatarImageView.clipsToBounds = true
avatarImageView.layer.borderWidth = 1.0
avatarImageView.layer.cornerRadius = 4.0
contentView.addSubview(avatarImageView)
contentView.addSubview(authorLabel)
contentView.addSubview(dateLabel)
titleLabel.numberOfLines = 2
contentView.addSubview(titleLabel)
avatarImageView.snp.makeConstraints { (make) in
make.leading.equalTo(contentView).offset(8.0)
make.top.equalTo(contentView).offset(10.0)
make.width.height.equalTo(60.0)
make.bottom.lessThanOrEqualTo(contentView).offset(-8.0)
}
authorLabel.snp.makeConstraints { (make) in
make.leading.equalTo(avatarImageView.snp.trailing).offset(8.0)
make.top.equalTo(contentView).inset(8.0)
}
dateLabel.setContentHuggingPriority(.defaultLow + 1.0, for: .horizontal)
dateLabel.snp.makeConstraints { (make) in
make.leading.equalTo(authorLabel.snp.trailing).offset(8.0)
make.trailing.equalTo(contentView).offset(-8.0)
make.top.equalTo(avatarImageView)
}
titleLabel.snp.makeConstraints { (make) in
make.top.equalTo(dateLabel.snp.bottom).offset(4.0)
make.leading.equalTo(authorLabel)
make.trailing.equalTo(contentView).offset(-8.0)
make.bottom.lessThanOrEqualTo(contentView).offset(-8.0)
}
NotificationCenter.default.reactive.notifications(forName: .APPaletteDidChange).producer
.map { _ in () }
.prefix(value: ())
.startWithValues { [weak self] (_) in
guard let strongSelf = self else { return }
let colorManager = AppEnvironment.current.colorManager
strongSelf.titleLabel.textColor = colorManager.colorForKey("notice.cell.title")
strongSelf.authorLabel.textColor = colorManager.colorForKey("notice.cell.author")
strongSelf.dateLabel.textColor = colorManager.colorForKey("notice.cell.date")
strongSelf.avatarImageView.layer.borderColor = colorManager.colorForKey("notice.cell.avatar.border").cgColor
strongSelf.updateBackgroundAppearance()
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func prepareForReuse() {
super.prepareForReuse()
avatarImageView.kf.cancelDownloadTask()
avatarImageView.image = nil
}
func configure(with viewModel: ViewModel) {
if let avatarURL = viewModel.user.avatarURL {
avatarImageView.kf.setImage(with: avatarURL)
}
titleLabel.text = viewModel.title
authorLabel.text = viewModel.user.name
dateLabel.text = viewModel.date.s1_gracefulDateTimeString()
self.isNew = viewModel.isNew
updateBackgroundAppearance()
}
func updateBackgroundAppearance() {
let colorManager = AppEnvironment.current.colorManager
if isNew {
selectedBackgroundView?.backgroundColor = colorManager.colorForKey("notice.cell.background.selected.new")
backgroundColor = colorManager.colorForKey("notice.cell.background.new")
} else {
selectedBackgroundView?.backgroundColor = colorManager.colorForKey("notice.cell.background.selected")
backgroundColor = colorManager.colorForKey("notice.cell.background")
}
}
override func preferredLayoutAttributesFitting(_ layoutAttributes: UICollectionViewLayoutAttributes) -> UICollectionViewLayoutAttributes {
let autoLayoutAttributes = super.preferredLayoutAttributesFitting(layoutAttributes)
// Specify you want _full width_
let targetSize = CGSize(width: layoutAttributes.frame.width, height: 0.0)
// Calculate the size (height) using Auto Layout
let autoLayoutSize = contentView.systemLayoutSizeFitting(
targetSize,
withHorizontalFittingPriority: .required,
verticalFittingPriority: .defaultLow
)
let autoLayoutFrame = CGRect(origin: autoLayoutAttributes.frame.origin, size: autoLayoutSize)
// Assign the new size to the layout attributes
autoLayoutAttributes.frame = autoLayoutFrame
return autoLayoutAttributes
}
}
extension NoticeCell {
struct ViewModel {
let title: String
let user: User
let date: Date
let path: String
let isNew: Bool
init(replyNotice: ReplyNotice) throws {
guard case .post = replyNotice.type else {
AppEnvironment.current.eventTracker.logEvent("Unknown Reply Type", attributes: [
"type": replyNotice.type.rawValue,
"rawData": try String(decoding: JSONEncoder().encode(replyNotice), as: UTF8.self)
])
throw "Unexpected notice type \(replyNotice.type.rawValue)"
}
let document = try HTMLDocument(string: replyNotice.note)
let result = document.xpath("//a")
guard let targetMessage = result.dropFirst().first else {
throw "Failed to extract node."
}
guard let link = targetMessage.attributes["href"] else {
throw "Failed to extract link."
}
let message = targetMessage.stringValue
self.title = message
self.path = link.aibo_stringByUnescapingFromHTML()
self.date = replyNotice.dateline
self.user = User(id: replyNotice.authorid, name: replyNotice.author ?? "")
self.isNew = replyNotice.new
}
}
}
| bsd-3-clause | 053416456ae44654f6d1a107ea560de5 | 36.152941 | 142 | 0.64677 | 5.069021 | false | false | false | false |
OSzhou/MyTestDemo | PerfectDemoProject(swift写服务端)/.build/checkouts/Perfect-HTTPServer.git--6671958091389663080/Sources/PerfectHTTPServer/HTTP11/HTTP11Request.swift | 1 | 14181 | //
// HTTP11Request.swift
// PerfectLib
//
// Created by Kyle Jessup on 2016-06-21.
// Copyright (C) 2016 PerfectlySoft, Inc.
//
//===----------------------------------------------------------------------===//
//
// This source file is part of the Perfect.org open source project
//
// Copyright (c) 2015 - 2016 PerfectlySoft Inc. and the Perfect project authors
// Licensed under Apache License v2.0
//
// See http://perfect.org/licensing.html for license information
//
//===----------------------------------------------------------------------===//
//
import PerfectNet
import PerfectThread
import PerfectLib
import PerfectHTTP
import PerfectCHTTPParser
private let httpMaxHeadersSize = 1024 * 8
private let characterCR: Character = "\r"
private let characterLF: Character = "\n"
private let characterCRLF: Character = "\r\n"
private let characterSP: Character = " "
private let characterHT: Character = "\t"
private let characterColon: Character = ":"
private let httpReadSize = 1024 * 8
private let httpReadTimeout = 5.0
let httpLF: UInt8 = 10
let httpCR: UInt8 = 13
private let httpSpace = UnicodeScalar(32)
private let httpQuestion = UnicodeScalar(63)
class HTTP11Request: HTTPRequest {
var method: HTTPMethod = .get
var path: String {
get {
var accum = ""
var lastSlashExplicit = false
for p in pathComponents {
if p == "/" {
accum += p
lastSlashExplicit = true
} else {
if !lastSlashExplicit {
accum += "/"
}
accum += p.stringByEncodingURL
lastSlashExplicit = false
}
}
return accum
}
set {
let components = newValue.filePathComponents.map { $0 == "/" ? "/" : $0.stringByDecodingURL ?? "" }
pathComponents = components
}
}
var pathComponents = [String]()
var queryString = ""
lazy var queryParams: [(String, String)] = {
return self.deFormURLEncoded(string: self.queryString)
}()
var protocolVersion = (1, 0)
var remoteAddress: (host: String, port: UInt16) {
guard let remote = connection.remoteAddress else {
return ("", 0)
}
return (remote.host, remote.port)
}
var serverAddress: (host: String, port: UInt16) {
guard let local = connection.localAddress else {
return ("", 0)
}
return (local.host, local.port)
}
var serverName = ""
var documentRoot = "./webroot"
var urlVariables = [String:String]()
var scratchPad = [String:Any]()
private var headerStore = Dictionary<HTTPRequestHeader.Name, [UInt8]>()
var headers: AnyIterator<(HTTPRequestHeader.Name, String)> {
var g = self.headerStore.makeIterator()
return AnyIterator<(HTTPRequestHeader.Name, String)> {
guard let n = g.next() else {
return nil
}
return (n.key, UTF8Encoding.encode(bytes: n.value))
}
}
lazy var postParams: [(String, String)] = {
if let mime = self.mimes {
return mime.bodySpecs.filter { $0.file == nil }.map { ($0.fieldName, $0.fieldValue) }
} else if let bodyString = self.postBodyString {
return self.deFormURLEncoded(string: bodyString)
}
return [(String, String)]()
}()
var postBodyBytes: [UInt8]? {
get {
if let _ = mimes {
return nil
}
return workingBuffer
}
set {
if let nv = newValue {
workingBuffer = nv
} else {
workingBuffer.removeAll()
}
}
}
var postBodyString: String? {
guard let bytes = postBodyBytes else {
return nil
}
if bytes.isEmpty {
return ""
}
return UTF8Encoding.encode(bytes: bytes)
}
var postFileUploads: [MimeReader.BodySpec]? {
guard let mimes = self.mimes else {
return nil
}
return mimes.bodySpecs
}
var connection: NetTCP
var workingBuffer = [UInt8]()
var workingBufferOffset = 0
var mimes: MimeReader?
var contentType: String? {
guard let v = self.headerStore[.contentType] else {
return nil
}
return UTF8Encoding.encode(bytes: v)
}
lazy var contentLength: Int = {
guard let cl = self.headerStore[.contentLength] else {
return 0
}
let conv = UTF8Encoding.encode(bytes: cl)
return Int(conv) ?? 0
}()
typealias StatusCallback = (HTTPResponseStatus) -> ()
var parser = http_parser()
var parserSettings = http_parser_settings()
enum State {
case none, messageBegin, messageComplete, headersComplete, headerField, headerValue, body, url
}
var state = State.none
var lastHeaderName: String?
static func getSelf(parser: UnsafeMutablePointer<http_parser>) -> HTTP11Request? {
guard let d = parser.pointee.data else { return nil }
return Unmanaged<HTTP11Request>.fromOpaque(d).takeUnretainedValue()
}
init(connection: NetTCP) {
self.connection = connection
parserSettings.on_message_begin = {
parser -> Int32 in
guard let parser = parser else { return 0 }
return Int32(HTTP11Request.getSelf(parser: parser)?.parserMessageBegin(parser) ?? 0)
}
parserSettings.on_message_complete = {
parser -> Int32 in
guard let parser = parser else { return 0 }
return Int32(HTTP11Request.getSelf(parser: parser)?.parserMessageComplete(parser) ?? 0)
}
parserSettings.on_headers_complete = {
parser -> Int32 in
guard let parser = parser else { return 0 }
return Int32(HTTP11Request.getSelf(parser: parser)?.parserHeadersComplete(parser) ?? 0)
}
parserSettings.on_header_field = {
(parser, chunk, length) -> Int32 in
guard let parser = parser else { return 0 }
return Int32(HTTP11Request.getSelf(parser: parser)?.parserHeaderField(parser, data: chunk, length: length) ?? 0)
}
parserSettings.on_header_value = {
(parser, chunk, length) -> Int32 in
guard let parser = parser else { return 0 }
return Int32(HTTP11Request.getSelf(parser: parser)?.parserHeaderValue(parser, data: chunk, length: length) ?? 0)
}
parserSettings.on_body = {
(parser, chunk, length) -> Int32 in
guard let parser = parser else { return 0 }
return Int32(HTTP11Request.getSelf(parser: parser)?.parserBody(parser, data: chunk, length: length) ?? 0)
}
parserSettings.on_url = {
(parser, chunk, length) -> Int32 in
guard let parser = parser else { return 0 }
return Int32(HTTP11Request.getSelf(parser: parser)?.parserURL(parser, data: chunk, length: length) ?? 0)
}
http_parser_init(&parser, HTTP_REQUEST)
self.parser.data = Unmanaged.passUnretained(self).toOpaque()
}
func parserMessageBegin(_ parser: UnsafePointer<http_parser>) -> Int {
self.enteringState(parser, .messageBegin, data: nil, length: 0)
return 0
}
func parserMessageComplete(_ parser: UnsafePointer<http_parser>) -> Int {
self.enteringState(parser, .messageComplete, data: nil, length: 0)
return 0
}
func parserHeadersComplete(_ parser: UnsafePointer<http_parser>) -> Int {
self.enteringState(parser, .headersComplete, data: nil, length: 0)
return 0
}
func parserURL(_ parser: UnsafePointer<http_parser>, data: UnsafePointer<Int8>?, length: Int) -> Int {
self.enteringState(parser, .url, data: data, length: length)
return 0
}
func parserHeaderField(_ parser: UnsafePointer<http_parser>, data: UnsafePointer<Int8>?, length: Int) -> Int {
self.enteringState(parser, .headerField, data: data, length: length)
return 0
}
func parserHeaderValue(_ parser: UnsafePointer<http_parser>, data: UnsafePointer<Int8>?, length: Int) -> Int {
self.enteringState(parser, .headerValue, data: data, length: length)
return 0
}
func parserBody(_ parser: UnsafePointer<http_parser>, data: UnsafePointer<Int8>?, length: Int) -> Int {
if self.state != .body {
self.leavingState(parser)
self.state = .body
}
if self.workingBuffer.count == 0 && self.mimes == nil {
if let contentType = self.contentType,
contentType.characters.starts(with: "multipart/form-data".characters) {
self.mimes = MimeReader(contentType)
}
}
data?.withMemoryRebound(to: UInt8.self, capacity: length) {
data in
for i in 0..<length {
self.workingBuffer.append(data[i])
}
}
if let mimes = self.mimes {
defer {
self.workingBuffer.removeAll()
}
mimes.addToBuffer(bytes: self.workingBuffer)
}
return 0
}
func enteringState(_ parser: UnsafePointer<http_parser>, _ state: State, data: UnsafePointer<Int8>?, length: Int) {
if self.state != state {
self.leavingState(parser)
self.state = state
}
data?.withMemoryRebound(to: UInt8.self, capacity: length) {
data in
for i in 0..<length {
self.workingBuffer.append(data[i])
}
}
}
// parse from workingBuffer contents
func parseURI() -> ([String], String) {
enum ParseURLState {
case slash, component, query
}
var state = ParseURLState.slash
var gen = workingBuffer.makeIterator()
var decoder = UTF8()
var pathComponents = ["/"]
var component = ""
var queryString = ""
let question = UnicodeScalar(63)
let slash = UnicodeScalar(47)
loopy:
repeat {
let res = decoder.decode(&gen)
switch res {
case .scalarValue(let uchar):
switch state {
case .slash:
if uchar == question {
state = .query
if pathComponents.count > 1 {
pathComponents.append("/")
}
} else if uchar != slash {
state = .component
component = String(Character(uchar))
}
case .component:
if uchar == question {
state = .query
pathComponents.append(component.stringByDecodingURL ?? "")
} else if uchar == slash {
state = .slash
pathComponents.append(component.stringByDecodingURL ?? "")
} else {
component.append(Character(uchar))
}
case .query:
queryString.append(Character(uchar))
}
case .emptyInput, .error:
switch state {
case .slash:
if pathComponents.count > 1 {
pathComponents.append("/")
}
case .component:
pathComponents.append(component.stringByDecodingURL ?? "")
case .query:
()
}
break loopy
}
} while true
return (pathComponents, queryString)
}
func leavingState(_ parser: UnsafePointer<http_parser>) {
switch state {
case .url:
(self.pathComponents, self.queryString) = parseURI()
workingBuffer.removeAll()
case .headersComplete:
let methodId = parser.pointee.method
if let methodName = http_method_str(http_method(rawValue: methodId)) {
self.method = HTTPMethod.from(string: String(validatingUTF8: methodName) ?? "GET")
}
protocolVersion = (Int(parser.pointee.http_major), Int(parser.pointee.http_minor))
workingBuffer.removeAll()
if let expect = header(.expect), expect.lowercased() == "100-continue" {
// TODO: Should let headers be passed to filters and let them
// determine if request should continue or not
_ = connection.writeFully(bytes: Array("HTTP/1.1 100 Continue\r\n\r\n".utf8))
}
case .headerField:
workingBuffer.append(0)
lastHeaderName = String(validatingUTF8: UnsafeMutableRawPointer(mutating: workingBuffer).assumingMemoryBound(to: Int8.self))
workingBuffer.removeAll()
case .headerValue:
if let name = self.lastHeaderName {
setHeader(named: name, value: self.workingBuffer)
}
lastHeaderName = nil
workingBuffer.removeAll()
case .body:
()
case .messageComplete:
()
case .messageBegin, .none:
()
}
}
func header(_ named: HTTPRequestHeader.Name) -> String? {
guard let v = headerStore[named] else {
return nil
}
return UTF8Encoding.encode(bytes: v)
}
func addHeader(_ named: HTTPRequestHeader.Name, value: String) {
guard let existing = headerStore[named] else {
self.headerStore[named] = [UInt8](value.utf8)
return
}
let valueBytes = [UInt8](value.utf8)
let newValue: [UInt8]
if named == .cookie {
newValue = existing + "; ".utf8 + valueBytes
} else {
newValue = existing + ", ".utf8 + valueBytes
}
self.headerStore[named] = newValue
}
func setHeader(_ named: HTTPRequestHeader.Name, value: String) {
headerStore[named] = [UInt8](value.utf8)
}
func setHeader(named: String, value: [UInt8]) {
headerStore[HTTPRequestHeader.Name.fromStandard(name: named)] = value
}
func readRequest(callback: @escaping StatusCallback) {
self.connection.readSomeBytes(count: httpReadSize) {
b in
if let b = b, b.count > 0 {
if self.didReadSomeBytes(b, callback: callback) {
if b.count == httpReadSize {
Threading.dispatch {
self.readRequest(callback: callback)
}
} else {
self.readRequest(callback: callback)
}
}
} else {
self.connection.readBytesFully(count: 1, timeoutSeconds: httpReadTimeout) {
b in
guard let b = b else {
return callback(.requestTimeout)
}
if self.didReadSomeBytes(b, callback: callback) {
self.readRequest(callback: callback)
}
}
}
}
}
// a true return value indicates that we should keep reading data
// false indicates that the request either was fully read and is being processed or that the request failed
// either way no further action should be taken
func didReadSomeBytes(_ b: [UInt8], callback: @escaping StatusCallback) -> Bool {
_ = UnsafePointer(b).withMemoryRebound(to: Int8.self, capacity: b.count) {
http_parser_execute(&parser, &parserSettings, $0, b.count)
}
let http_errno = parser.http_errno
guard HPE_HEADER_OVERFLOW.rawValue != http_errno else {
callback(.requestEntityTooLarge)
return false
}
guard http_errno == 0 else {
callback(.badRequest)
return false
}
if self.state == .messageComplete {
callback(.ok)
return false
}
return true
}
func putPostData(_ b: [UInt8]) {
if self.workingBuffer.count == 0 && self.mimes == nil {
if let contentType = self.contentType,
contentType.characters.starts(with: "multipart/form-data".characters) {
self.mimes = MimeReader(contentType)
}
}
if let mimes = self.mimes {
return mimes.addToBuffer(bytes: b)
} else {
self.workingBuffer.append(contentsOf: b)
}
}
func deFormURLEncoded(string: String) -> [(String, String)] {
return string.characters.split(separator: "&").map(String.init).flatMap {
let d = $0.characters.split(separator: "=", maxSplits: 1).flatMap { String($0).stringByDecodingURL }
if d.count == 2 { return (d[0], d[1]) }
if d.count == 1 { return (d[0], "") }
return nil
}
}
}
| apache-2.0 | e221d373fe1f19c1745b8e032494174e | 27.192843 | 127 | 0.666526 | 3.44199 | false | false | false | false |
UncleJoke/Spiral | Spiral/GameViewController.swift | 1 | 8842 | //
// GameViewController.swift
// Spiral
//
// Created by 杨萧玉 on 14-7-12.
// Copyright (c) 2014年 杨萧玉. All rights reserved.
//
import UIKit
import SpriteKit
import ReplayKit
public class GameViewController: UIViewController, RPPreviewViewControllerDelegate {
var longPress:UILongPressGestureRecognizer!
var tapWithOneFinger:UITapGestureRecognizer!
var tapWithTwoFinger:UITapGestureRecognizer!
var pan:UIPanGestureRecognizer!
// var swipeRight:UISwipeGestureRecognizer!
var pinch:UIPinchGestureRecognizer!
var screenEdgePanRight:UIScreenEdgePanGestureRecognizer!
var previewViewController:RPPreviewViewController?
override public func viewDidLoad() {
super.viewDidLoad()
// Configure the view.
let skView = self.view as! SKView
/* Sprite Kit applies additional optimizations to improve rendering performance */
skView.ignoresSiblingOrder = true
longPress = UILongPressGestureRecognizer(target: self, action: Selector("handleLongPressGesture:"))
tapWithOneFinger = UITapGestureRecognizer(target: self, action: Selector("handleTapWithOneFingerGesture:"))
tapWithTwoFinger = UITapGestureRecognizer(target: self, action: Selector("handleTapWithTwoFingerGesture:"))
tapWithTwoFinger.numberOfTouchesRequired = 2
pan = UIPanGestureRecognizer(target: self, action: Selector("handlePanGesture:"))
pan.maximumNumberOfTouches = 1
// swipeRight = UISwipeGestureRecognizer(target: self, action: Selector("handleSwipeGesture:"))
// swipeRight.direction = UISwipeGestureRecognizerDirection.Right
// swipeRight.numberOfTouchesRequired = 2
pinch = UIPinchGestureRecognizer(target: self, action: Selector("handlePinchGesture:"))
screenEdgePanRight = UIScreenEdgePanGestureRecognizer(target: self, action: Selector("handleEdgePanGesture:"))
screenEdgePanRight.edges = UIRectEdge.Left
// addGestureRecognizers()
let scene = MainScene(size: skView.bounds.size)
/* Set the scale mode to scale to fit the window */
scene.scaleMode = .AspectFill
skView.presentScene(scene)
}
override public func shouldAutorotate() -> Bool {
return true
}
override public func supportedInterfaceOrientations() -> UIInterfaceOrientationMask {
if UIDevice.currentDevice().userInterfaceIdiom == .Phone {
return UIInterfaceOrientationMask.AllButUpsideDown
} else {
return UIInterfaceOrientationMask.All
}
}
override public func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Release any cached data, images, etc that aren't in use.
}
override public func prefersStatusBarHidden() -> Bool {
return true
}
// MARK: - handle gestures
func handleLongPressGesture(recognizer:UILongPressGestureRecognizer) {
if recognizer.state == .Began {
((self.view as! SKView).scene as? GameScene)?.pause()
}
}
func handleTapWithOneFingerGesture(recognizer:UILongPressGestureRecognizer) {
if recognizer.state == .Ended {
((self.view as! SKView).scene as? GameScene)?.tap()
}
}
func handleTapWithTwoFingerGesture(recognizer:UILongPressGestureRecognizer) {
if recognizer.state == .Ended {
// ((self.view as! SKView).scene as? OrdinaryModeScene)?.createReaper()
}
}
func handlePanGesture(recognizer:UIPanGestureRecognizer) {
if recognizer.state == .Changed {
((self.view as! SKView).scene as? OrdinaryHelpScene)?.lightWithFinger(recognizer.locationInView(self.view))
((self.view as! SKView).scene as? ZenHelpScene)?.lightWithFinger(recognizer.locationInView(self.view))
}
else if recognizer.state == .Ended {
((self.view as! SKView).scene as? OrdinaryHelpScene)?.turnOffLight()
((self.view as! SKView).scene as? ZenHelpScene)?.turnOffLight()
}
}
func handleSwipeGesture(recognizer:UISwipeGestureRecognizer) {
if recognizer.direction == .Right {
((self.view as! SKView).scene as? OrdinaryHelpScene)?.back()
((self.view as! SKView).scene as? ZenHelpScene)?.back()
}
}
func handlePinchGesture(recognizer:UIPinchGestureRecognizer) {
if recognizer.state == .Began {
if recognizer.scale > 1 {
((self.view as! SKView).scene as? GameScene)?.createReaper()
}
else {
((self.view as! SKView).scene as? GameScene)?.allShapesJumpIn()
}
}
}
func handleEdgePanGesture(recognizer:UIPinchGestureRecognizer) {
if recognizer.state == .Ended {
let scene = (self.view as! SKView).scene
if let scene = scene as? OrdinaryHelpScene {
scene.back()
}
else if let scene = scene as? ZenHelpScene {
scene.back()
}
else if let scene = scene as? GameScene {
let skView = view as! SKView
Data.sharedData.display = nil
Data.sharedData.gameOver = true
Data.sharedData.reset()
scene.soundManager.stopBackGround()
stopRecord()
let scene = MainScene(size: skView.bounds.size)
let push = SKTransition.pushWithDirection(SKTransitionDirection.Right, duration: 1)
push.pausesIncomingScene = false
skView.presentScene(scene, transition: push)
removeGestureRecognizers()
}
}
}
// MARK: - add&remove gesture recognizers
func addGestureRecognizers() {
let skView = self.view as! SKView
skView.addGestureRecognizer(longPress)
skView.addGestureRecognizer(tapWithOneFinger)
skView.addGestureRecognizer(tapWithTwoFinger)
skView.addGestureRecognizer(pan)
// skView.addGestureRecognizer(swipeRight)
skView.addGestureRecognizer(pinch)
skView.addGestureRecognizer(screenEdgePanRight)
}
func removeGestureRecognizers() {
let skView = self.view as! SKView
skView.removeGestureRecognizer(longPress)
skView.removeGestureRecognizer(tapWithOneFinger)
skView.removeGestureRecognizer(tapWithTwoFinger)
skView.removeGestureRecognizer(pan)
// skView.removeGestureRecognizer(swipeRight)
skView.removeGestureRecognizer(pinch)
skView.removeGestureRecognizer(screenEdgePanRight)
}
// MARK: - record game
func startRecordWithHandler(handler:() -> Void) {
previewViewController = nil
guard Data.sharedData.autoRecord else {
handler()
return
}
RPScreenRecorder.sharedRecorder().startRecordingWithMicrophoneEnabled(false) { (error) -> Void in
if let rpError = error where rpError.domain == RPRecordingErrorDomain {
let alert = UIAlertController(title: "😌", message: "🚫🎥", preferredStyle: .Alert)
let action = UIAlertAction(title: "(⊙o⊙)", style: .Default, handler: { (action) -> Void in
handler()
})
alert.addAction(action)
self.presentViewController(alert, animated: true, completion: nil)
return
}
handler()
}
}
func stopRecord() {
RPScreenRecorder.sharedRecorder().stopRecordingWithHandler({ (previewViewController, ErrorType) -> Void in
self.previewViewController = previewViewController
previewViewController?.previewControllerDelegate = self
})
}
func discardRecordWithHandler(handler:() -> Void) {
RPScreenRecorder.sharedRecorder().discardRecordingWithHandler(handler)
}
func playRecord() {
guard let pvController = previewViewController else {
let alert = UIAlertController(title: "😌", message: "🙈🎥", preferredStyle: .Alert)
let action = UIAlertAction(title: "😭", style: .Default, handler: nil)
alert.addAction(action)
self.presentViewController(alert, animated: true, completion: nil)
return
}
pvController.modalPresentationStyle = UIModalPresentationStyle.FullScreen
presentViewController(pvController, animated: true, completion:nil)
}
// MARK: - RPPreviewViewControllerDelegate
public func previewControllerDidFinish(previewController: RPPreviewViewController) {
previewController.dismissViewControllerAnimated(true, completion: nil)
}
}
| mit | 8b8779fb078243b9050beea99b06c465 | 38.832579 | 119 | 0.648756 | 5.488155 | false | false | false | false |
fredrikcollden/LittleMaestro | GameScene.swift | 1 | 15527 | //
// GameScene.swift
// MaestroLevel
//
// Created by Fredrik Colldén on 2015-10-29.
// Copyright (c) 2015 Marie. All rights reserved.
//
import SpriteKit
protocol GameSceneDelegate {
func startSceneActions(action: String)
}
struct PhysicsCategory {
static let None : UInt32 = 0
static let All : UInt32 = UInt32.max
static let PieceDestination : UInt32 = 0b1
static let PuzzlePiece: UInt32 = 0b10
}
class GameScene: SKScene, SKPhysicsContactDelegate, PuzzlePieceDelegate, GuiButtonDelegate, LevelDelegate {
let backBtn = GuiButton(xScale: GameData.sharedInstance.deviceScale, yScale: GameData.sharedInstance.deviceScale, action: "goToMenu", labelText: "");
var gameSceneDelegate: GameSceneDelegate?
let maxNotes = CGFloat(22.0)
let maxNumNotes = CGFloat(32.0)
var gridPosition = CGPoint(x:100, y:700)
var pianoPosition = CGPoint(x:100, y:100)
var gridSize = CGPoint(x: 100, y: 100)
var pianoSize = CGPoint(x: 100, y: 100)
var deviceScale = GameData.sharedInstance.deviceScale
var allPieces: [PuzzlePiece] = []
var numberOfPieces:[Int] = []
var numberPutInPlace = 0
var allInPlace = false
var currentLevel: Int
var numberOfBars = 0
var currentBar = 0
var levelCompleted = false
var bgContainer: NightLevel?
var skipBar = false
var bars = [[PuzzlePieceDestination?]?](count: 0, repeatedValue: nil)
var melody2bars = [[PuzzlePiece?]?](count: 0, repeatedValue: nil)
var chordbars = [[Chord?]?](count: 0, repeatedValue: nil)
let birds = ["redbird-body"]
var uniqueNotes: [Int] = []
var noteBirdMapping: [Int: String] = [Int: String]()
var sceneSize:CGSize = CGSize()
let startZ: CGFloat = 3000
var timer = NSTimer()
var currentTick = 0
var playBackMelody: [PuzzlePieceDestination?]?
var playBackMelody2: [PuzzlePiece?]?
var playBackChord: [Chord?]?
var playLastTime = false
var tempo = CGFloat(120)
init(levelNo: Int, size: CGSize){
self.currentLevel = levelNo - 1
super.init(size: size)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func didMoveToView(view: SKView) {
sceneSize = view.frame.size
let gridHeight = GameData.sharedInstance.gridHeight
let gridWidth = GameData.sharedInstance.gridWidth
self.gridPosition = CGPoint(x:(sceneSize.width - gridWidth)/2, y:sceneSize.height - gridHeight) //ipad position
self.pianoPosition = CGPoint(x:100*GameData.sharedInstance.deviceScale, y:100*GameData.sharedInstance.deviceScale)//ipad position
self.gridSize = CGPoint(x: gridWidth/CGFloat(GameData.sharedInstance.noteNumMax), y: gridHeight/CGFloat(GameData.sharedInstance.noteMaxVis))
self.pianoSize = CGPoint(x: (sceneSize.width - 2 * pianoPosition.x)/maxNotes, y: 100)
self.numberOfBars = GameData.sharedInstance.levels[self.currentLevel].bars.count
bgContainer = NightLevel(numberOfBars: self.numberOfBars, sceneSize: sceneSize)
bgContainer!.levelDelegate = self
self.addChild(bgContainer!)
initBars()
backBtn.userInteractionEnabled = true
backBtn.anchorPoint = CGPoint(x: 0, y: 1)
backBtn.position = CGPoint(x: 5, y: self.frame.size.height - 5);
backBtn.zPosition = 100
backBtn.guiButtonDelegate = self
backBtn.color = SKColor(red: 0.0, green: 0.5, blue: 0.5, alpha: 1)
backBtn.colorBlendFactor = 0.4
self.addChild(backBtn)
physicsWorld.gravity = CGVectorMake(0, 0)
physicsWorld.contactDelegate = self
}
func initBars() {
let allBars = GameData.sharedInstance.levels[self.currentLevel].bars
let blacks = GameData.sharedInstance.blacks
//Analyze level a bit
for (_, bar) in allBars.enumerate() {
var minNote = 0
var maxNote = 0
let melody: [Int] = bar.melody
for (_, value) in melody.enumerate() {
if (value >= 0) {
if(value < minNote) {
minNote = value
}
if (value > maxNote){
maxNote = value
}
if (!uniqueNotes.contains(value)) {
uniqueNotes.append(value)
}
}
}
}
for (value) in uniqueNotes {
if (noteBirdMapping[value] == nil){
noteBirdMapping[value] = birds[noteBirdMapping.count % birds.count]
}
}
print(noteBirdMapping)
//Start generating puzzle pieces
for (barNum, bar) in allBars.enumerate() {
var numPieces = 0
let melody: [Int] = bar.melody
var puzzlePieceDestinations: [PuzzlePieceDestination?] = []
for (index, value) in melody.enumerate() {
if (value >= 0) {
var skipCount = 0
for (val) in blacks {
if (val < value) {
skipCount += 1
}
}
let birdBody = noteBirdMapping[value]!
let piece = PuzzlePiece(note: value, textureName: birdBody, zPos: startZ + (CGFloat(index*10+320*barNum)) , startPosition: CGPoint(x:(CGFloat(value)*pianoSize.x) + pianoPosition.x, y:pianoPosition.y), tintColor: SKColor(red: 0.0, green: 0.0, blue: 0.5, alpha: 1))
let pieceDest = PuzzlePieceDestination(depth: 10, note: value, textureName: birdBody)
pieceDest.position = CGPoint(x:(CGFloat(index)*gridSize.x) + (gridPosition.x + CGFloat(barNum) * frame.size.width), y:gridPosition.y+(CGFloat(value-skipCount)*gridSize.y)+gridSize.y/10)
let pHeight = 2*GameData.sharedInstance.noteHeight/piece.bird.birdBody.size.height
piece.setScale(pHeight)
pieceDest.setScale(pHeight)
piece.puzzlePieceDelegate = self
bgContainer?.addChild(piece)
allPieces.append(piece)
puzzlePieceDestinations.append(pieceDest)
bgContainer?.addChild(pieceDest)
numPieces += 1
} else {
puzzlePieceDestinations.append(nil)
}
}
var puzzlePieces: [PuzzlePiece?] = []
for (index, value) in bar.melody2.enumerate() {
if (value >= 0) {
var skipCount = 0
for (val) in blacks {
if (val < value) {
skipCount += 1
}
}
let piece = PuzzlePiece(note: value, textureName: "redbird-body", zPos: startZ + (CGFloat(index*10+320*barNum)) , startPosition: CGPoint(x:(CGFloat(index)*gridSize.x) + (gridPosition.x + CGFloat(barNum) * frame.size.width), y:gridPosition.y+(CGFloat(value-skipCount)*gridSize.y)+gridSize.y/10), tintColor: SKColor(red: 0.0, green: 0.0, blue: 0.5, alpha: 1))
let pHeight = 2*GameData.sharedInstance.noteHeight/piece.bird.birdBody.size.height
piece.setScale(pHeight)
bgContainer?.addChild(piece)
piece.puzzlePieceDelegate = self
puzzlePieces.append(piece)
} else {
puzzlePieces.append(nil)
}
}
self.melody2bars.append(puzzlePieces)
var chords: [Chord?] = []
for (_, value) in bar.chord.enumerate() {
if (value >= 0) {
let chord = Chord(note: CGFloat(value))
chord.setScale(0.1)
bgContainer?.addChild(chord)
chords.append(chord)
} else {
chords.append(nil)
}
}
self.chordbars.append(chords)
self.bars.append(puzzlePieceDestinations)
self.numberOfPieces.append(numPieces)
}
}
func birdsRunBar(deltaX: CGFloat) {
for piece in allPieces {
if (piece.isActive) {
piece.actionRunBar(deltaX)
}
}
}
func birdsFollow(to: CGPoint) {
for piece in allPieces {
piece.bird.actionLookAt(piece.position, to: to)
}
}
func birdsFollowStop() {
for piece in allPieces {
piece.bird.actionLookAtStop()
}
}
func birdsExcited() {
for piece in allPieces {
piece.bird.actionRun(100)
}
}
func birdsExcitedStop() {
for piece in allPieces {
piece.bird.actionRunStop()
}
}
func puzzlePiecePutInPlace(puzzlePiece:PuzzlePiece, place:PuzzlePieceDestination) {
if (puzzlePiece.note == place.note && place.isActive) {
print("did put in place")
puzzlePiece.snapDestination = place
birdsExcited()
}
}
func puzzlePiecePutOutPlace(puzzlePiece:PuzzlePiece, place:PuzzlePieceDestination) {
if (puzzlePiece.note == place.note) {
print("put out place")
if (puzzlePiece.snapDestination == place) {
puzzlePiece.snapDestination = nil
birdsExcitedStop()
}
}
}
func didBeginContact(contact: SKPhysicsContact) {
print("begin contact")
var firstBody: SKPhysicsBody
var secondBody: SKPhysicsBody
if contact.bodyA.categoryBitMask < contact.bodyB.categoryBitMask {
firstBody = contact.bodyA
secondBody = contact.bodyB
} else {
firstBody = contact.bodyB
secondBody = contact.bodyA
}
if ((firstBody.categoryBitMask & PhysicsCategory.PieceDestination != 0) &&
(secondBody.categoryBitMask & PhysicsCategory.PuzzlePiece != 0)) {
puzzlePiecePutInPlace(secondBody.node as! PuzzlePiece, place: firstBody.node as! PuzzlePieceDestination)
}
}
func didEndContact(contact: SKPhysicsContact) {
print("end contact")
var firstBody: SKPhysicsBody
var secondBody: SKPhysicsBody
if contact.bodyA.categoryBitMask < contact.bodyB.categoryBitMask {
firstBody = contact.bodyA
secondBody = contact.bodyB
} else {
firstBody = contact.bodyB
secondBody = contact.bodyA
}
if ((firstBody.categoryBitMask & PhysicsCategory.PieceDestination != 0) &&
(secondBody.categoryBitMask & PhysicsCategory.PuzzlePiece != 0)) {
puzzlePiecePutOutPlace(secondBody.node as! PuzzlePiece, place: firstBody.node as! PuzzlePieceDestination)
}
}
func addInPlace() {
self.numberPutInPlace += 1
print(numberOfPieces[self.currentBar])
if numberPutInPlace == numberOfPieces[self.currentBar] {
numberPutInPlace = 0
startPlayBack(self.currentBar)
}
}
func playAll(){
startPlayBack()
}
func startPlayBack(barNum: Int?=nil){
if (barNum == nil) {
print("play whole song")
self.playBackMelody = []
self.playBackMelody2 = []
self.playBackChord = []
for bar in self.bars {
self.playBackMelody?.appendContentsOf(bar!)
}
for bar in self.melody2bars {
self.playBackMelody2?.appendContentsOf(bar!)
}
for bar in self.chordbars {
self.playBackChord?.appendContentsOf(bar!)
}
self.playLastTime = true
bgContainer?.moveWhole(self.tempo)
} else {
self.playBackMelody = self.bars[barNum!]
self.playBackMelody2 = self.melody2bars[barNum!]
self.playBackChord = self.chordbars[barNum!]
print("play bar \(barNum)")
}
self.timer = NSTimer(timeInterval: Double(self.tempo/CGFloat(1200)), target: self, selector: #selector(GameScene.playBackTick), userInfo: nil, repeats: true)
NSRunLoop.currentRunLoop().addTimer(timer, forMode: NSRunLoopCommonModes)
}
func stopPlayBack(){
self.currentTick = 0;
timer.invalidate()
if self.playLastTime {
print("end level")
self.gameSceneDelegate?.startSceneActions("goToMenu")
}else if self.numberOfBars > (self.currentBar + 1) {
self.currentBar += 1
var countNext = 0;
for val in self.bars[self.currentBar]! {
if(val != nil){
countNext += 1;
}
}
if(countNext > 0) {
birdsRunBar(sceneSize.width)
bgContainer?.moveTo(self.currentBar, playWholeSong: false)
} else {
birdsRunBar(sceneSize.width)
bgContainer?.moveTo(self.currentBar, playWholeSong: false)
delay(4.0) {
self.startPlayBack(self.currentBar)
}
print(self.currentBar)
}
} else {
self.levelCompleted = true
bgContainer?.moveTo(0, playWholeSong: true)
print("level completed")
GameData.sharedInstance.levelCompleted(GameData.sharedInstance.levels[self.currentLevel].levelNo)
}
}
func playBackTick(){
if self.currentTick < self.playBackMelody2!.count {
if (self.playBackMelody2![self.currentTick] != nil) {
self.playBackMelody2![self.currentTick]!.playNote()
}
}
if self.currentTick < self.playBackChord!.count {
if (self.playBackChord![self.currentTick] != nil) {
self.playBackChord![self.currentTick]!.playNote()
}
}
if self.currentTick < self.playBackMelody!.count {
if (self.playBackMelody![self.currentTick] != nil) {
if self.playBackMelody![self.currentTick]!.connectedPuzzlePiece != nil {
self.playBackMelody![self.currentTick]!.connectedPuzzlePiece!.playNote()
}
}
self.currentTick += 1
} else {
stopPlayBack()
}
}
func guiButtonClick(action: String) {
self.gameSceneDelegate?.startSceneActions(action)
}
override func update(currentTime: CFTimeInterval) {
/* Called before each frame is rendered */
}
func delay(delay: Double, closure: ()->()) {
dispatch_after(
dispatch_time(
DISPATCH_TIME_NOW,
Int64(delay * Double(NSEC_PER_SEC))
),
dispatch_get_main_queue(),
closure
)
}
}
| lgpl-3.0 | a049a6cd6774c0581f9ec5ed051b5a27 | 35.446009 | 377 | 0.553265 | 4.543752 | false | false | false | false |
netyouli/WHC_Debuger | WHC_DebugerSwift/WHC_DebugerSwift/WHC_AutoLayoutKit/WHC_Frame.swift | 1 | 4220 | //
// WHC_ViewExtension.swift
// WHC_AutoLayoutKit(Swift)
// Created by WHC on 16/7/7.
// Copyright © 2016年 吴海超. All rights reserved.
// Github <https://github.com/netyouli/WHC_AutoLayoutKit>
//
// 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
public extension UIView {
public var whc_ScreenWidth: CGFloat {
return UIScreen.main.bounds.width
}
public var whc_ScreenHeight: CGFloat {
return UIScreen.main.bounds.height
}
public var whc_Width: CGFloat {
set {
var rect = self.frame
rect.size.width = newValue
self.frame = rect
}
get {
return self.frame.width
}
}
public var whc_Height: CGFloat {
set {
var rect = self.frame
rect.size.height = newValue
self.frame = rect
}
get {
return self.frame.height
}
}
public var whc_X: CGFloat {
set {
var rect = self.frame
rect.origin.x = newValue
self.frame = rect
}
get {
return self.frame.minX
}
}
public var whc_Y: CGFloat {
set {
var rect = self.frame
rect.origin.y = newValue
self.frame = rect
}
get {
return self.frame.minY
}
}
public var whc_MaxX: CGFloat {
set {
self.whc_Width = newValue - self.whc_X
}
get {
return self.frame.maxX
}
}
public var whc_MaxY: CGFloat {
set {
self.whc_Height = newValue - self.whc_Y
}
get {
return self.frame.maxY
}
}
public var whc_MidX: CGFloat {
set {
self.whc_Width = newValue * 2
}
get {
return self.frame.minX + self.frame.width / 2
}
}
public var whc_MidY: CGFloat {
set {
self.whc_Height = newValue * 2
}
get {
return self.frame.minY + self.frame.height / 2
}
}
public var whc_CenterX: CGFloat {
set {
var center = self.center
center.x = newValue
self.center = center
}
get {
return self.center.x
}
}
public var whc_CenterY: CGFloat {
set {
var center = self.center
center.y = newValue
self.center = center
}
get {
return self.center.y
}
}
public var whc_Xy: CGPoint {
set {
var rect = self.frame
rect.origin = newValue
self.frame = rect
}
get {
return self.frame.origin
}
}
public var whc_Size: CGSize {
set {
var rect = self.frame
rect.size = newValue
self.frame = rect
}
get {
return self.frame.size
}
}
}
| mit | b8616a028afc998ac935617f9eecadd8 | 22.926136 | 80 | 0.525528 | 4.489339 | false | false | false | false |
shingt/HarmonyKit | Sources/HarmonyKit.swift | 1 | 6493 | import Foundation
public struct HarmonyKit {
public typealias OctaveRange = Range<Int>
public typealias Tuning = [Tone: Float]
public static func tune(configuration: Configuration) -> [Note] {
switch configuration.temperament {
case .equal:
return tuneEqual(
pitch: configuration.pitch,
transpositionTone: configuration.transpositionTone,
octaveRange: configuration.octaveRange
)
case .pure(let pureType, let rootTone):
return tunePure(
pitch: configuration.pitch,
transpositionTone: configuration.transpositionTone,
octaveRange: configuration.octaveRange,
pureType: pureType,
rootTone: rootTone
)
}
}
private static let tones: [Tone] = [
.C, .Db, .D, .Eb, .E, .F, .Gb, .G, .Ab, .A, .Bb, .B
]
// https://en.wikipedia.org/wiki/Cent_(music)
private static let octaveCents: Float = 1200.0
private static let centOffsetsPureMajor: [Float] = [
0.0, -29.3, 3.9, 15.6, -13.7, -2.0,
-31.3, 2.0, -27.4, -15.6, 17.6, -11.7
].map { $0 / octaveCents }
private static let centOffsetsPureMinor: [Float] = [
0.0, 33.2, 3.9, 15.6, -13.7, -2.0,
31.3, 2.0, 13.7, -15.6, 17.6, -11.7
].map { $0 / octaveCents }
}
// Equal
private extension HarmonyKit {
static func tuneEqual(
pitch: Float,
transpositionTone: Tone,
octaveRange: OctaveRange
) -> [Note] {
let base = equalBase(pitch: pitch, transpositionTone: transpositionTone)
return expandTuning(base: base, octaveRange: octaveRange)
}
// "Base" means C1, D1, ... in:
// => http://ja.wikipedia.org/wiki/%E9%9F%B3%E5%90%8D%E3%83%BB%E9%9A%8E%E5%90%8D%E8%A1%A8%E8%A8%98
static func equalBase(pitch: Float, transpositionTone: Tone) -> Tuning {
// Frequencies when transpositionTone == C
var baseFrequencies: [Float] = [
frequency(pitch: pitch, order: 3.0) / 16.0, // C
frequency(pitch: pitch, order: 4.0) / 16.0, // Db
frequency(pitch: pitch, order: 5.0) / 16.0, // D
frequency(pitch: pitch, order: 6.0) / 16.0, // Eb
frequency(pitch: pitch, order: 7.0) / 16.0, // E
frequency(pitch: pitch, order: 8.0) / 16.0, // F
frequency(pitch: pitch, order: 9.0) / 16.0, // Gb
frequency(pitch: pitch, order: 10.0) / 16.0, // G
frequency(pitch: pitch, order: 11.0) / 16.0, // Ab
frequency(pitch: pitch, order: 0.0) / 8.0, // A
frequency(pitch: pitch, order: 1.0) / 8.0, // Bb
frequency(pitch: pitch, order: 2.0) / 8.0, // B
]
var transposedFrequencies: [Float] = []
for (i, tone) in tones.enumerated() {
if transpositionTone == tone {
for j in baseFrequencies[i..<baseFrequencies.count] {
transposedFrequencies.append(j)
}
for j in baseFrequencies[0..<i] {
transposedFrequencies.append(j)
}
break
}
baseFrequencies[i] *= 2.0
}
// Go up till Gb and go down after G
let GbIndex = 6
guard let transpositionToneIndex = tones.firstIndex(of: transpositionTone) else {
return [:]
}
if GbIndex < transpositionToneIndex {
transposedFrequencies = transposedFrequencies.map { $0 / 2.0 }
}
var tuning: Tuning = [:]
for (i, tone) in tones.enumerated() {
tuning[tone] = transposedFrequencies[i]
}
return tuning
}
static func frequency(pitch: Float, order: Float) -> Float {
return pitch * pow(2.0, order / 12.0)
}
static func expandTuning(base: Tuning, octaveRange: OctaveRange) -> [Note] {
var notes: [Note] = []
octaveRange.forEach { octave in
let notesInOctave = tune(base: base, octave: octave)
notes.append(contentsOf: notesInOctave)
}
return notes
}
// Generate 12 frequencies for spacified octave by integral multiplication
static func tune(base: Tuning, octave: Int) -> [Note] {
var notes: [Note] = []
for key in base.keys {
guard let baseFrequency = base[key] else { continue }
let frequency = Float(pow(2.0, Float(octave - 1))) * baseFrequency
notes.append(
.init(
tone: key,
octave: octave,
frequency: frequency
)
)
}
return notes
}
}
// Pure
private extension HarmonyKit {
static func tunePure(
pitch: Float,
transpositionTone: Tone,
octaveRange: OctaveRange,
pureType: Temperament.Pure,
rootTone: Tone
) -> [Note] {
let centOffets: [Float]
switch pureType {
case .major: centOffets = centOffsetsPureMajor
case .minor: centOffets = centOffsetsPureMinor
}
let base = pureBase(
pitch: pitch,
transpositionTone: transpositionTone,
rootTone: rootTone,
centOffsets: centOffets
)
return expandTuning(base: base, octaveRange: octaveRange)
}
static func pureBase(
pitch: Float,
transpositionTone: Tone,
rootTone: Tone,
centOffsets: [Float]
) -> Tuning {
let tones = arrangeTones(rootTone: rootTone)
let tuningBase = equalBase(pitch: pitch, transpositionTone: transpositionTone)
var tuning: Tuning = [:]
for (i, tone) in tones.enumerated() {
guard let baseFrequency = tuningBase[tone] else { continue }
let frequency = baseFrequency * pow(2.0, centOffsets[i])
tuning[tone] = frequency
}
return tuning
}
// Generate one-octave tones based on specified root tone
static func arrangeTones(rootTone: Tone) -> [Tone] {
guard var rootIndex = tones.firstIndex(of: rootTone) else { return [] }
var arrangedTones: [Tone] = []
tones.forEach { _ in
rootIndex = rootIndex == tones.count ? 0 : rootIndex
arrangedTones.append(tones[rootIndex])
rootIndex += 1
}
return arrangedTones
}
}
| mit | 4b18b9ba84a1f6b11914292a9190f979 | 33.354497 | 102 | 0.551209 | 3.808211 | false | false | false | false |
kunass2/BSSelectableView | SelectableView/Classes/MultiSelectableView.swift | 2 | 3648 | //
// MultiSelectableView.swift
// SelectableView
//
// Created by Bartłomiej Semańczyk on 06/22/2016.
// Copyright (c) 2016 Bartłomiej Semańczyk. All rights reserved.
//
@IBDesignable open class MultiSelectableView: SelectableView, UITableViewDataSource, UITableViewDelegate {
@IBInspectable open var lineHeight: CGFloat = 30
@IBInspectable open var margin: CGFloat = 0
@IBOutlet open var verticalTokenView: VerticalTokenView?
@IBOutlet open var horizontalTokenView: HorizontalTokenView?
@IBOutlet open var tokenViewHeightConstraint: NSLayoutConstraint?
open var selectedOptions = Set<SelectableOption>() {
didSet {
verticalTokenView?.reloadData()
horizontalTokenView?.reloadData()
tableView.reloadData()
updateContentOptionsHeight(for: filteredSortedOptions)
}
}
var sortedSelectedOptions: [SelectableOption] {
return selectedOptions.sorted { $0.index < $1.index }
}
private var filteredSortedOptions: [SelectableOption] {
return options.filter({ !selectedOptions.contains($0) }).sorted { $0.index < $1.index }
}
override var expanded: Bool {
didSet {
super.expanded = expanded
updateContentOptionsHeight(for: filteredSortedOptions)
}
}
//MARK: - Class Methods
//MARK: - Initialization
open override func awakeFromNib() {
super.awakeFromNib()
tableView.delegate = self
tableView.dataSource = self
verticalTokenView?.selectableView = self
horizontalTokenView?.selectableView = self
verticalTokenView?.reloadData()
horizontalTokenView?.reloadData()
}
//MARK: - Deinitialization
//MARK: - Actions
//MARK: - Open
open func deselect(option: SelectableOption) {
selectedOptions.remove(option)
}
open func select(option: SelectableOption) {
selectedOptions.insert(option)
delegate?.multiSelectableView?(self, didSelect: option)
}
//MARK: - Internal
func tokenView(for option: SelectableOption) -> UIView? {
return delegate?.multiSelectableView?(self, tokenViewFor: option)
}
//MARK: - Private
//MARK: - Overridden
//MARK: - UITableViewDataSource
open func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return filteredSortedOptions.count
}
open func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: SelectableTableViewCellIdentifier, for: indexPath) as! SelectableTableViewCell
let option = filteredSortedOptions[indexPath.row]
cell.titleLabel.text = option.title
cell.titleLabel.font = fontForOption
cell.titleLabel.textColor = titleColorForOption
cell.leftPaddingConstraint.constant = CGFloat(leftPaddingForOption)
cell.layoutMargins = .zero
cell.accessoryType = .none
cell.selectionStyle = .none
return cell
}
open func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return CGFloat(heightForOption)
}
//MARK: - UITableViewDelegate
open func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
select(option: filteredSortedOptions[indexPath.row])
}
}
| mit | 09008b7db5a277f14f4a2876a88986d0 | 29.366667 | 143 | 0.64764 | 5.235632 | false | false | false | false |
ChrisAU/Papyrus | Papyrus/ViewControllers/PreferencesViewController.swift | 2 | 1985 | //
// PreferencesViewController.swift
// Papyrus
//
// Created by Chris Nevin on 2/05/2016.
// Copyright © 2016 CJNevin. All rights reserved.
//
import UIKit
class PreferencesViewController : UITableViewController {
private let preferences: Preferences = .sharedInstance
var saveHandler: (() -> ())!
var dataSource: PreferencesDataSource!
override func viewDidLoad() {
super.viewDidLoad()
dataSource = PreferencesDataSource(preferences: preferences)
title = "Preferences"
tableView.dataSource = dataSource
tableView.delegate = dataSource
tableView.register(loadable: BoardCell.self)
tableView.register(loadable: SliderCell.self)
tableView.reloadData()
}
func save(_ sender: UIAlertAction) {
do {
try preferences.save()
saveHandler()
dismiss(animated: true, completion: nil)
} catch let err as PreferenceError {
if err == PreferenceError.insufficientPlayers {
let alert = UIAlertController(title: "Insufficient Players", message: "Please specify at least 2 players.", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "OK", style: .cancel, handler: nil))
present(alert, animated: true, completion: nil)
}
} catch {
assert(false)
}
}
@IBAction func done(_ sender: UIBarButtonItem) {
if preferences.hasChanges {
let alert = UIAlertController(title: "Save?", message: "Changes have been made, saving will discard your current game.", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil))
alert.addAction(UIAlertAction(title: "OK", style: .destructive, handler: save))
present(alert, animated: true, completion: nil)
} else {
dismiss(animated: true, completion: nil)
}
}
}
| mit | 2222d2eadc46d909fa8def17bc725c0a | 36.433962 | 156 | 0.63004 | 4.910891 | false | false | false | false |
AlexIzh/Griddle | CollectionPresenter/UI/CustomView/ItemsView/ItemsViewModels.swift | 1 | 1429 | //
// ItemsViewModels.swift
// CollectionPresenter
//
// Created by Alex on 22/03/16.
// Copyright © 2016 Moqod. All rights reserved.
//
import Foundation
import Griddle
import UIKit
struct ItemsViewMap: Map {
let registrationItems: [RegistrationItem] = []
func viewInfo(for model: Any, indexPath: Griddle.IndexPath) -> ViewInfo? {
return ViewInfo(identifier: "CellID", viewClass: ItemView.self)
}
}
class ItemsViewSourceFactory {
struct Model {
enum Shape: Int {
case circle
case rectangle
}
var title: String
var position: CGPoint = CGPoint(x: CGFloat(Float(arc4random()) / Float(UINT32_MAX)), y: CGFloat(Float(arc4random()) / Float(UINT32_MAX)))
var shape: Shape = .rectangle
var color: UIColor = Model.randomColor()
init(_ title: String) {
self.title = title
}
private static func randomColor() -> UIColor {
let random: () -> CGFloat = { CGFloat(arc4random() % 255) / 255.0 }
return UIColor(red: random(), green: random(), blue: random(), alpha: 1)
}
}
static func dataSource() -> ArraySource<ItemsViewSourceFactory.Model> {
return [Model("1"), Model("2"), Model("3"), Model("4"), Model("5")]
}
}
extension ItemsViewSourceFactory.Model: Equatable {}
func ==(lhs: ItemsViewSourceFactory.Model, rhs: ItemsViewSourceFactory.Model) -> Bool {
return lhs.title == rhs.title
}
| mit | 8294e511e7410de4da071dd1212eabf8 | 27 | 143 | 0.644258 | 3.901639 | false | false | false | false |
iRoxx/WordPress-iOS | WordPress/Classes/ViewRelated/Notifications/ReplyTextView/ReplyTextView.swift | 1 | 10592 | import Foundation
@objc public class ReplyTextView : UIView, UITextViewDelegate, SuggestableView
{
// MARK: - Initializers
public convenience init(width: CGFloat) {
let frame = CGRect(x: 0, y: 0, width: width, height: 0)
self.init(frame: frame)
}
public override init(frame: CGRect) {
super.init(frame: frame)
setupView()
}
public required init(coder: NSCoder) {
super.init(coder: coder)
setupView()
}
// MARK: - Public Properties
public weak var delegate: UITextViewDelegate?
public var onReply: ((String) -> ())?
public var text: String! {
didSet {
textView.text = text
refreshInterface()
}
}
public var placeholder: String! {
didSet {
placeholderLabel.text = placeholder
}
}
public var replyText: String! {
didSet {
replyButton.setTitle(replyText, forState: .Normal)
}
}
public var autocorrectionType: UITextAutocorrectionType = .Yes {
didSet {
textView.autocorrectionType = autocorrectionType
}
}
public var keyboardType: UIKeyboardType = .Default {
didSet {
textView.keyboardType = keyboardType
}
}
// MARK: - UITextViewDelegate Methods
public func textViewShouldBeginEditing(textView: UITextView!) -> Bool {
return delegate?.textViewShouldBeginEditing?(textView) ?? true
}
public func textViewDidBeginEditing(textView: UITextView!) {
delegate?.textViewDidBeginEditing?(textView)
}
public func textViewShouldEndEditing(textView: UITextView!) -> Bool {
return delegate?.textViewShouldEndEditing?(textView) ?? true
}
public func textViewDidEndEditing(textView: UITextView!) {
delegate?.textViewDidEndEditing?(textView)
}
public func textView(textView: UITextView!, shouldChangeTextInRange range: NSRange, replacementText text: String!) -> Bool {
let shouldChange = delegate?.textView?(textView, shouldChangeTextInRange: range, replacementText: text) ?? true
if shouldChange {
if let suggestionsDelegate = delegate as? SuggestionsTableViewDelegate {
if suggestionsDelegate.respondsToSelector(Selector("view:didTypeInWord:")) {
let textViewText: NSString = textView.text
let prerange = NSMakeRange(0, range.location)
let pretext: NSString = textViewText.substringWithRange(prerange) + text
let words = pretext.componentsSeparatedByCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet())
let lastWord: NSString = words.last as NSString
suggestionsDelegate.view?(textView, didTypeInWord: lastWord)
}
}
}
return shouldChange
}
public func textViewDidChange(textView: UITextView!) {
refreshInterface()
delegate?.textViewDidChange?(textView)
}
public func textView(textView: UITextView!, shouldInteractWithURL URL: NSURL!, inRange characterRange: NSRange) -> Bool {
return delegate?.textView?(textView, shouldInteractWithURL: URL, inRange: characterRange) ?? true
}
// MARK: - SuggestableView methods
public func replaceTextAtCaret(text: String!, withSuggestion suggestion: String!) {
let textToReplace: NSString = text;
var selectedRange: UITextRange = textView.selectedTextRange!
var newPosition: UITextPosition = textView.positionFromPosition(selectedRange.start, offset: -textToReplace.length)!
var newRange: UITextRange = textView.textRangeFromPosition(newPosition, toPosition: selectedRange.start)
textView.replaceRange(newRange, withText: suggestion)
}
// MARK: - IBActions
@IBAction private func btnReplyPressed() {
if let handler = onReply {
// Load the new text
let newText = textView.text
textView.resignFirstResponder()
// Cleanup + Shrink
text = String()
// Hit the handler
handler(newText)
}
}
// MARK: - Gestures Recognizers
public func backgroundWasTapped() {
becomeFirstResponder()
}
// MARK: - View Methods
public override func becomeFirstResponder() -> Bool {
return textView.becomeFirstResponder()
}
public override func resignFirstResponder() -> Bool {
endEditing(true)
return textView.resignFirstResponder()
}
public override func layoutSubviews() {
// Force invalidate constraints
invalidateIntrinsicContentSize()
super.layoutSubviews()
}
// MARK: - Autolayout Helpers
public override func intrinsicContentSize() -> CGSize {
// Make sure contentSize returns... the real content size
textView.layoutIfNeeded()
// Calculate the entire control's size
let topPadding = textView.constraintForAttribute(.Top) ?? textViewDefaultPadding
let bottomPadding = textView.constraintForAttribute(.Bottom) ?? textViewDefaultPadding
let contentHeight = textView.contentSize.height
let fullWidth = frame.width
let textHeight = floor(contentHeight + topPadding + bottomPadding)
var newHeight = min(max(textHeight, textViewMinHeight), textViewMaxHeight)
let intrinsicSize = CGSize(width: fullWidth, height: newHeight)
return intrinsicSize
}
// MARK: - Setup Helpers
private func setupView() {
self.frame.size.height = textViewMinHeight
// Load the nib + add its container view
bundle = NSBundle.mainBundle().loadNibNamed("ReplyTextView", owner: self, options: nil)
addSubview(containerView)
// Setup Layout
setTranslatesAutoresizingMaskIntoConstraints(false)
containerView.setTranslatesAutoresizingMaskIntoConstraints(false)
pinSubviewToAllEdges(containerView)
// Setup the TextView
textView.delegate = self
textView.scrollsToTop = false
textView.contentInset = UIEdgeInsetsZero
textView.textContainerInset = UIEdgeInsetsZero
textView.font = WPStyleGuide.Reply.textFont
textView.textColor = WPStyleGuide.Reply.textColor
textView.textContainer.lineFragmentPadding = 0
textView.layoutManager.allowsNonContiguousLayout = false
textView.accessibilityIdentifier = "ReplyText"
// Enable QuickType
textView.autocorrectionType = .Yes
// Placeholder
placeholderLabel.font = WPStyleGuide.Reply.textFont
placeholderLabel.textColor = WPStyleGuide.Reply.placeholderColor
// Reply
replyButton.enabled = false
replyButton.titleLabel?.font = WPStyleGuide.Reply.buttonFont
replyButton.setTitleColor(WPStyleGuide.Reply.disabledColor, forState: .Disabled)
replyButton.setTitleColor(WPStyleGuide.Reply.enabledColor, forState: .Normal)
// Background
layoutView.backgroundColor = WPStyleGuide.Reply.backgroundColor
// Recognizers
let recognizer = UITapGestureRecognizer(target: self, action: "backgroundWasTapped")
gestureRecognizers = [recognizer]
// iPhone's Width knows No Limits
if UIDevice.isPad() {
let maxWidthConstraint = NSLayoutConstraint(item: self,
attribute: .Width,
relatedBy: .LessThanOrEqual,
toItem: nil,
attribute: .NotAnAttribute,
multiplier: 1,
constant: WPTableViewFixedWidth)
addConstraint(maxWidthConstraint)
}
}
// MARK: - Refresh Helpers
private func refreshInterface() {
refreshPlaceholder()
refreshReplyButton()
refreshSizeIfNeeded()
refreshScrollPosition()
}
private func refreshSizeIfNeeded() {
var newSize = intrinsicContentSize()
let oldSize = frame.size
if newSize.height == oldSize.height {
return
}
invalidateIntrinsicContentSize()
}
private func refreshPlaceholder() {
placeholderLabel.hidden = !textView.text.isEmpty
}
private func refreshReplyButton() {
let whitespaceCharSet = NSCharacterSet.whitespaceAndNewlineCharacterSet()
replyButton.enabled = textView.text.stringByTrimmingCharactersInSet(whitespaceCharSet).isEmpty == false
}
private func refreshScrollPosition() {
// FIX: In iOS 8, scrollRectToVisible causes a weird flicker
if UIDevice.isOS8() {
// FIX: Force layout right away. This prevents the TextView from "Jumping"
textView.layoutIfNeeded()
textView.scrollRangeToVisible(textView.selectedRange)
} else {
let selectedRangeStart = textView.selectedTextRange?.start ?? UITextPosition()
var caretRect = textView.caretRectForPosition(selectedRangeStart)
caretRect = CGRectIntegral(caretRect)
textView.scrollRectToVisible(caretRect, animated: false)
}
}
// MARK: - Constants
private let textViewDefaultPadding: CGFloat = 12
private let textViewMaxHeight: CGFloat = 82 // Fits 3 lines onscreen
private let textViewMinHeight: CGFloat = 44
// MARK: - Private Properties
private var bundle: NSArray?
// MARK: - IBOutlets
@IBOutlet private var textView: UITextView!
@IBOutlet private var placeholderLabel: UILabel!
@IBOutlet private var replyButton: UIButton!
@IBOutlet private var layoutView: UIView!
@IBOutlet private var containerView: UIView!
}
| gpl-2.0 | dae0d2e010efb46fda9cfb1f1939b11d | 35.524138 | 128 | 0.606779 | 6.090857 | false | false | false | false |
dotty2883/AudioKit | Tests/Tests/AKGranularSynthesisTexture.swift | 14 | 2578 | //
// main.swift
// AudioKit
//
// Created by Nick Arner and Aurelius Prochazka on 12/27/14.
// Copyright (c) 2014 Aurelius Prochazka. All rights reserved.
//
import Foundation
let testDuration: NSTimeInterval = 10.0
class Instrument : AKInstrument {
override init() {
super.init()
let filename = "AKSoundFiles.bundle/Sounds/PianoBassDrumLoop.wav"
let soundfile = AKSoundFileTable(filename: filename, size:16384)
let hamming = AKTable(size: 512)
hamming.populateTableWithGenerator(AKWindowTableGenerator.hammingWindow())
let baseFrequency = AKConstant(expression: String(format: "44100 / %@", soundfile.length()))
let grainDensityLine = AKLine(firstPoint: 600.ak, secondPoint: 10.ak, durationBetweenPoints: 10.ak)
let grainDurationLine = AKLine(firstPoint: 0.4.ak, secondPoint: 0.1.ak, durationBetweenPoints: 10.ak)
let grainAmplitudeLine = AKLine(firstPoint: 0.2.ak, secondPoint: 0.5.ak, durationBetweenPoints: 10.ak)
let maximumFrequencyDeviationLine = AKLine(firstPoint: 0.ak, secondPoint: 0.1.ak, durationBetweenPoints: 10.ak)
let granularSynthesisTexture = AKGranularSynthesisTexture(
grainTable: soundfile,
windowTable: hamming
)
granularSynthesisTexture.grainFrequency = baseFrequency
granularSynthesisTexture.grainDensity = grainDensityLine
granularSynthesisTexture.averageGrainDuration = grainDurationLine
granularSynthesisTexture.maximumFrequencyDeviation = maximumFrequencyDeviationLine
granularSynthesisTexture.grainAmplitude = grainAmplitudeLine
enableParameterLog(
"Grain Density = ",
parameter: granularSynthesisTexture.grainDensity,
timeInterval:0.2
)
enableParameterLog(
"Average Grain Duration = ",
parameter: granularSynthesisTexture.averageGrainDuration,
timeInterval:0.2
)
enableParameterLog(
"Maximum Frequency Deviation = ",
parameter: granularSynthesisTexture.maximumFrequencyDeviation,
timeInterval:0.2
)
enableParameterLog(
"Grain Amplitude = ",
parameter: granularSynthesisTexture.grainAmplitude,
timeInterval:0.2
)
setAudioOutput(granularSynthesisTexture)
}
}
AKOrchestra.testForDuration(10)
let instrument = Instrument()
AKOrchestra.addInstrument(instrument)
instrument.play()
NSThread.sleepForTimeInterval(NSTimeInterval(testDuration))
| mit | 6cb75552e6e299239852d68dfe003230 | 32.480519 | 119 | 0.693561 | 4.579041 | false | false | false | false |
tkremenek/swift | test/Profiler/coverage_ternary.swift | 18 | 1324 | // RUN: %target-swift-frontend -Xllvm -sil-full-demangle -profile-generate -profile-coverage-mapping -emit-sorted-sil -emit-sil -module-name coverage_ternary %s | %FileCheck %s
// RUN: %target-swift-frontend -profile-generate -profile-coverage-mapping -emit-ir %s
// coverage_ternary.bar.init() -> coverage_ternary.bar
// CHECK-LABEL: sil hidden @$s16coverage_ternary3barCACycfc
// CHECK-NOT: return
// CHECK: builtin "int_instrprof_increment"
// rdar://problem/23256795 - Avoid crash if an if_expr has no parent
// CHECK: sil_coverage_map {{.*}}// variable initialization expression of coverage_ternary.bar.m1 : Swift.String
class bar {
var m1 = flag == 0 // CHECK: [[@LINE]]:12 -> [[@LINE+2]]:22 : 0
? "false" // CHECK: [[@LINE]]:16 -> [[@LINE]]:23 : 1
: "true"; // CHECK: [[@LINE]]:16 -> [[@LINE]]:22 : (0 - 1)
}
// Note: We didn't instantiate bar, but we still expect to see instrumentation
// for its *structors, and coverage mapping information for it.
var flag: Int = 0
// CHECK-LABEL: sil_coverage_map {{.*}}// coverage_ternary.foo
func foo(_ x : Int32) -> Int32 { // CHECK: [[@LINE]]:32 -> [[@LINE+4]]:2 : 0
return x == 3
? 9000 // CHECK: [[@LINE]]:16 -> [[@LINE]]:20 : 1
: 1234 // CHECK: [[@LINE]]:16 -> [[@LINE]]:20 : (0 - 1)
}
foo(1)
foo(2)
foo(3)
| apache-2.0 | 6a8b2a154502564a50663ef2ceaac56f | 41.709677 | 176 | 0.617069 | 3.301746 | false | false | false | false |
JohnCido/CKit | Sources/CKChart/CKChart.swift | 1 | 2099 | //
// CKChartBase.swift
// CKit
//
// Created by CHU on 2017/7/4.
//
//
import UIKit
open class CKChart: UIView {
@objc public var isInteractionEnabled = false
final public var delegate: CKChartDelegate?
@IBInspectable final public var vGuideColor: UIColor = .clear
@IBInspectable final public var hGuideColor: UIColor = .clear
@IBInspectable final public var xAxisColor: UIColor = .clear
@IBInspectable final public var yAxisColor: UIColor = .clear
@IBInspectable final public var xAxisDoubled: Bool = false
@IBInspectable final public var yAxisDoubled: Bool = false
@IBInspectable final public var xAxisNumber: Bool = true
@IBInspectable final public var yAxisNumber: Bool = true
@IBInspectable final public var xAxisReversed: Bool = false
final private var layers = [CKChartLayer]()
final private let axisLayer = CAShapeLayer()
final private let guideLayer = CAShapeLayer()
@objc final public var drawingBound: CGRect {
return bounds
}
final public var dataBound: CKChartDataBound {
let x = layers.map { $0.allX.min()! } + layers.map { $0.allX.max()! }
let y = layers.map { $0.allY.min()! } + layers.map { $0.allY.max()! }
return CKChartDataBound(x: x, y: y)
}
open override var bounds: CGRect {
didSet {
if bounds.width == oldValue.width && bounds.height == oldValue.height { return }
redraw()
}
}
open override func awakeFromNib() {
super.awakeFromNib()
}
@objc open func add(layer: CKChartLayer) {
layer.baseDelegate = self
layers.append(layer)
layer.addSublayer(layer)
}
fileprivate func resize(_ target: [CKChartLayer] = []) {
for l in target.count == 0 ? layers : target {
l.bounds = frame
}
}
}
extension CKChart: CKChartLayerDelegate {
@objc public func redraw(_ sender: CKChartLayer? = nil) {
resize()
}
}
public protocol CKChartDelegate {
func userDidSelect(dataPoint: CKChartPoint) -> Void
}
| mit | 5cc1fa2383a1de65f57ac213ea6da588 | 29.42029 | 92 | 0.641258 | 4.206413 | false | false | false | false |
kevinskyba/ReadyForCoffee | ReadyForCoffeeTestApp/MainViewModel.swift | 1 | 4091 | //
// MainViewModel.swift
// ReadyForCoffeeTestApp
//
// Created by Kevin Skyba on 14.08.15.
// Copyright (c) 2015 Kevin Skyba. All rights reserved.
//
import Foundation
import UIKit
import Bond
import MultipeerConnectivity
class MainViewModel: NSObject, MultipeerServiceDelegate {
//MARK: - Private Properties
private var service : MultipeerService? = nil
private let isActive = Dynamic<Bool>(true)
private let totalCoffees = Dynamic<Int>(0)
private let readyCoffees = Dynamic<Int>(0)
private var coffeeStatus = [MCPeerID: CoffeeStatus]()
//MARK: - Public Properties
let isReadyForCoffee = Dynamic<CoffeeStatus>(CoffeeStatus.NotReady)
//MARK: - Public Properties
let serviceID = Dynamic<String>("Default")
let status = Dynamic<String>("")
//MARK: - Init
override init() {
super.init()
//Setup MultipeerService
self.setupMultipeerService()
//Setup DataBinding
self.setupDataBinding()
}
//MARK: - Private Methods
var switchBond : Bond<CoffeeStatus>?
private func setupDataBinding() {
reduce(totalCoffees, readyCoffees) { (total, ready) -> String in
return String(ready) + " / " + String(total)
} ->> status
switchBond = Bond<CoffeeStatus> { value in
println(value.toString())
self.service!.sendBroadcastStatus(self.isReadyForCoffee.value)
self.readyCoffees.value = self.coffeeStatus.values.filter({ (element) -> Bool in return element == CoffeeStatus.Ready }).array.count + ((self.isReadyForCoffee.value == CoffeeStatus.Ready) ? 1 : 0)
}
isReadyForCoffee ->| switchBond!
//Update readyCoffees and totalCoffees value
self.totalCoffees.value = self.coffeeStatus.count + 1
self.readyCoffees.value = self.coffeeStatus.values.filter({ (element) -> Bool in return element == CoffeeStatus.Ready }).array.count + ((self.isReadyForCoffee.value == CoffeeStatus.Ready) ? 1 : 0)
}
private func setupMultipeerService() {
service = MultipeerService(displayName: UIDevice.currentDevice().name, serviceType: Commons.Settings.serviceNamePrefix + serviceID.value)
service!.delegate = self
}
//MARK: - MultipeerServiceDelegate
func multipeerService(service: MultipeerService, connectionStatusChanged status: String, forPeer peer: MCPeerID) {
if (status == "Disconnected") {
coffeeStatus.removeAtIndex(coffeeStatus.indexForKey(peer)!)
} else if (status == "Connected") {
coffeeStatus[peer] = CoffeeStatus.Unknown
service.sendStatusAskToPeer(peer)
}
//Update readyCoffees and totalCoffees value
totalCoffees.value = coffeeStatus.count + 1
readyCoffees.value = coffeeStatus.values.filter({ (element) -> Bool in return element == CoffeeStatus.Ready }).array.count + ((isReadyForCoffee.value == CoffeeStatus.Ready) ? 1 : 0)
}
func multipeerService(service: MultipeerService, readyStatusChanged status: CoffeeStatus, forPeer peer: MCPeerID) {
coffeeStatus[peer] = status
//Update readyCoffees and totalCoffees value
self.totalCoffees.value = self.coffeeStatus.count + 1
self.readyCoffees.value = self.coffeeStatus.values.filter({ (element) -> Bool in return element == CoffeeStatus.Ready }).array.count + ((self.isReadyForCoffee.value == CoffeeStatus.Ready) ? 1 : 0)
}
func multipeerService(service: MultipeerService, receivedReadyStatusQuestionFromPeer peer: MCPeerID) {
service.sendStatusToPeer(isReadyForCoffee.value, peer: peer)
//Update readyCoffees value
readyCoffees.value = coffeeStatus.values.filter({ (element) -> Bool in return element == CoffeeStatus.Ready }).array.count + ((isReadyForCoffee.value == CoffeeStatus.Ready) ? 1 : 0)
}
} | mit | 17e468dea88c88e6a383d58deeba03b5 | 41.625 | 208 | 0.647275 | 4.389485 | false | false | false | false |
wordpress-mobile/WordPress-iOS | WordPress/Classes/Services/SiteAssemblyService.swift | 1 | 6911 |
import Foundation
// MARK: - EnhancedSiteCreationService
/// Working implementation of a `SiteAssemblyService`.
///
final class EnhancedSiteCreationService: LocalCoreDataService, SiteAssemblyService {
// MARK: Properties
/// A service for interacting with WordPress accounts.
private let accountService: AccountService
/// A service for interacting with WordPress blogs.
private let blogService: BlogService
/// A facade for WPCOM services.
private let remoteService: WordPressComServiceRemote
/// The site creation request that's been enqueued.
private var creationRequest: SiteCreationRequest?
/// This handler is called with changes to the site assembly status.
private var statusChangeHandler: SiteAssemblyStatusChangedHandler?
/// The most recently created blog corresponding to the site creation request; `nil` otherwise.
private(set) var createdBlog: Blog?
// MARK: LocalCoreDataService
override init(managedObjectContext context: NSManagedObjectContext) {
self.accountService = AccountService(managedObjectContext: context)
self.blogService = BlogService(managedObjectContext: context)
let api: WordPressComRestApi
if let wpcomApi = (try? WPAccount.lookupDefaultWordPressComAccount(in: context))?.wordPressComRestApi {
api = wpcomApi
} else {
api = WordPressComRestApi.defaultApi(userAgent: WPUserAgent.wordPress())
}
self.remoteService = WordPressComServiceRemote(wordPressComRestApi: api)
super.init(managedObjectContext: context)
}
// MARK: SiteAssemblyService
private(set) var currentStatus: SiteAssemblyStatus = .idle {
didSet {
DispatchQueue.main.async { [weak self] in
guard let self = self else {
return
}
self.statusChangeHandler?(self.currentStatus)
}
}
}
/// This method serves as the entry point for creating an enhanced site. It consists of a few steps:
/// 1. The creation request is first validated.
/// 2. If a site passes validation, a new service invocation triggers creation.
/// 3. The details of the created Blog are persisted to the client.
///
/// Previously the site's theme & tagline were set post-creation. This is now handled on the server via Headstart.
///
/// - Parameters:
/// - creationRequest: the request with which to initiate site creation.
/// - changeHandler: this closure is invoked when site assembly status changes occur.
///
func createSite(creationRequest: SiteCreationRequest, changeHandler: SiteAssemblyStatusChangedHandler? = nil) {
self.creationRequest = creationRequest
self.statusChangeHandler = changeHandler
beginAssembly()
validatePendingRequest()
}
// MARK: Private behavior
private func beginAssembly() {
currentStatus = .inProgress
}
private func endFailedAssembly() {
currentStatus = .failed
}
private func endSuccessfulAssembly() {
// Here we designate the new site as the last used, so that it will be presented post-creation
if let siteUrl = createdBlog?.url {
RecentSitesService().touch(site: siteUrl)
StoreContainer.shared.statsWidgets.refreshStatsWidgetsSiteList()
}
currentStatus = .succeeded
}
private func performRemoteSiteCreation() {
guard let request = creationRequest else {
self.endFailedAssembly()
return
}
let validatedRequest = SiteCreationRequest(request: request)
remoteService.createWPComSite(request: validatedRequest) { result in
// Our result is of type SiteCreationResult, which can be either success or failure
switch result {
case .success(let response):
// A successful response includes a separate success field advising of the outcome of the call.
// In my testing, this has never been `false`, but we will be cautious.
guard response.success == true else {
DDLogError("The service response indicates that it failed.")
self.endFailedAssembly()
return
}
self.synchronize(createdSite: response.createdSite)
case .failure(let creationError):
DDLogError("\(creationError)")
self.endFailedAssembly()
}
}
}
private func synchronize(createdSite: CreatedSite) {
guard let defaultAccount = try? WPAccount.lookupDefaultWordPressComAccount(in: managedObjectContext) else {
endFailedAssembly()
return
}
let xmlRpcUrlString = createdSite.xmlrpcString
let blog: Blog
if let existingBlog = blogService.findBlog(withXmlrpc: xmlRpcUrlString, in: defaultAccount) {
blog = existingBlog
} else {
blog = blogService.createBlog(with: defaultAccount)
blog.xmlrpc = xmlRpcUrlString
}
// The response payload returns a number encoded as a JSON string
if let wpcomSiteIdentifier = Int(createdSite.identifier) {
blog.dotComID = NSNumber(value: wpcomSiteIdentifier)
}
blog.url = createdSite.urlString
blog.settings?.name = createdSite.title
// the original service required a separate call to update the tagline post-creation
blog.settings?.tagline = creationRequest?.tagline
defaultAccount.defaultBlog = blog
ContextManager.sharedInstance().save(managedObjectContext) { [weak self] in
guard let self = self else {
return
}
self.blogService.syncBlogAndAllMetadata(blog, completionHandler: {
self.accountService.updateUserDetails(for: defaultAccount,
success: {
self.createdBlog = blog
self.endSuccessfulAssembly()
},
failure: { error in self.endFailedAssembly() })
})
}
}
private func validatePendingRequest() {
guard let requestPendingValidation = creationRequest else {
endFailedAssembly()
return
}
remoteService.createWPComSite(request: requestPendingValidation) { result in
switch result {
case .success:
self.performRemoteSiteCreation()
case .failure(let validationError):
DDLogError("\(validationError)")
self.endFailedAssembly()
}
}
}
}
| gpl-2.0 | e132eb01b5cb04925a2efeda46341015 | 35.760638 | 118 | 0.625959 | 5.600486 | false | false | false | false |
apple/swift-nio | Tests/NIOWebSocketTests/WebSocketServerEndToEndTests+XCTest.swift | 1 | 2013 | //===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftNIO open source project
//
// Copyright (c) 2017-2021 Apple Inc. and the SwiftNIO project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of SwiftNIO project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
//
// WebSocketServerEndToEndTests+XCTest.swift
//
import XCTest
///
/// NOTE: This file was generated by generate_linux_tests.rb
///
/// Do NOT edit this file directly as it will be regenerated automatically when needed.
///
extension WebSocketServerEndToEndTests {
@available(*, deprecated, message: "not actually deprecated. Just deprecated to allow deprecated tests (which test deprecated functionality) without warnings")
static var allTests : [(String, (WebSocketServerEndToEndTests) -> () throws -> Void)] {
return [
("testBasicUpgradeDance", testBasicUpgradeDance),
("testUpgradeWithProtocolName", testUpgradeWithProtocolName),
("testCanRejectUpgrade", testCanRejectUpgrade),
("testCanDelayAcceptingUpgrade", testCanDelayAcceptingUpgrade),
("testRequiresVersion13", testRequiresVersion13),
("testRequiresVersionHeader", testRequiresVersionHeader),
("testRequiresKeyHeader", testRequiresKeyHeader),
("testUpgradeMayAddCustomHeaders", testUpgradeMayAddCustomHeaders),
("testMayRegisterMultipleWebSocketEndpoints", testMayRegisterMultipleWebSocketEndpoints),
("testSendAFewFrames", testSendAFewFrames),
("testMaxFrameSize", testMaxFrameSize),
("testAutomaticErrorHandling", testAutomaticErrorHandling),
("testNoAutomaticErrorHandling", testNoAutomaticErrorHandling),
]
}
}
| apache-2.0 | 955b88fe4f56875fbfb887737095b8a4 | 42.76087 | 162 | 0.641828 | 5.470109 | false | true | false | false |
cpageler93/RAML-Swift | Sources/BaseURI.swift | 1 | 1724 | //
// BaseURI.swift
// RAML
//
// Created by Christoph on 30.06.17.
//
import Foundation
import Yaml
public class BaseURI: HasAnnotations {
public var value: String
public var annotations: [Annotation]?
public init(value: String) {
self.value = value
self.annotations = []
}
internal init() {
value = ""
}
}
// MARK: BaseURI Parsing
internal extension RAML {
internal func parseBaseURI(_ input: ParseInput) throws -> BaseURI? {
guard let yaml = input.yaml else { return nil }
switch yaml {
case .string(let yamlString):
return try parseBaseURI(string: yamlString)
case .dictionary(let yamlDict):
return try parseBaseURI(dict: yamlDict)
default:
return nil
}
}
private func parseBaseURI(string: String) throws -> BaseURI {
return BaseURI(value: string)
}
private func parseBaseURI(dict: [Yaml: Yaml]) throws -> BaseURI {
guard let value = dict["value"]?.string else {
throw RAMLError.ramlParsingError(.missingValueFor(key: "value"))
}
let baseURI = BaseURI(value: value)
baseURI.annotations = try parseAnnotations(dict: dict)
return baseURI
}
}
// MARK: Default Values
public extension BaseURI {
public convenience init(initWithDefaultsBasedOn baseURI: BaseURI) {
self.init()
self.value = baseURI.value
self.annotations = baseURI.annotations?.map { $0.applyDefaults() }
}
public func applyDefaults() -> BaseURI {
return BaseURI(initWithDefaultsBasedOn: self)
}
}
| mit | 676c467f6413128a1a03aaad6403ed8b | 22.297297 | 77 | 0.592807 | 4.299252 | false | false | false | false |
whiteshadow-gr/HatForIOS | HAT/Objects/HAT Provider/HATProvider.swift | 1 | 7120 | /**
* Copyright (C) 2018 HAT Data Exchange Ltd
*
* SPDX-License-Identifier: MPL2
*
* This file is part of the Hub of All Things project (HAT).
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/
*/
import SwiftyJSON
// MARK: Struct
/// A struct representing the hat provider object
public struct HATProvider: HATObject, Comparable {
// MARK: - Comparable protocol
/// Returns a Boolean value indicating whether two values are equal.
///
/// Equality is the inverse of inequality. For any values `a` and `b`,
/// `a == b` implies that `a != b` is `false`.
///
/// - Parameters:
/// - lhs: A value to compare.
/// - rhs: Another value to compare.
public static func == (lhs: HATProvider, rhs: HATProvider) -> Bool {
return (lhs.sku == rhs.sku && lhs.name == rhs.name && lhs.description == rhs.description && lhs.details == rhs.details && lhs.imageURL == rhs.imageURL && lhs.price == rhs.price && lhs.availableHats == rhs.availableHats && lhs.purchasedHats == rhs.purchasedHats && lhs.ordering == rhs.ordering && lhs.features == rhs.features && lhs.hatProviderImage == rhs.hatProviderImage && lhs.category == rhs.category && lhs.kind == rhs.kind && lhs.paymentType == rhs.paymentType)
}
/// Returns a Boolean value indicating whether the value of the first
/// argument is less than that of the second argument.
///
/// This function is the only requirement of the `Comparable` protocol. The
/// remainder of the relational operator functions are implemented by the
/// standard library for any type that conforms to `Comparable`.
///
/// - Parameters:
/// - lhs: A value to compare.
/// - rhs: Another value to compare.
public static func < (lhs: HATProvider, rhs: HATProvider) -> Bool {
return lhs.ordering < rhs.ordering
}
// MARK: - Coding Keys
/**
The JSON fields used by the hat
The Fields are the following:
* `sku` in JSON is `sku`
* `name` in JSON is `name`
* `description` in JSON is `description`
* `details` in JSON is `details`
* `imageURL` in JSON is `illustration`
* `price` in JSON is `price`
* `availableHats` in JSON is `available`
* `purchasedHats` in JSON is `purchased`
* `ordering` in JSON is `ordering`
* `features` in JSON is `features`
* `category` in JSON is `category`
* `kind` in JSON is `kind`
* `paymentType` in JSON is `paymentType`
*/
private enum CodingKeys: String, CodingKey {
case sku = "sku"
case name = "name"
case description = "description"
case details = "details"
case imageURL = "illustration"
case price = "price"
case availableHats = "available"
case purchasedHats = "purchased"
case ordering = "ordering"
case features = "features"
case category = "category"
case kind = "kind"
case paymentType = "paymentType"
}
// MARK: - Variables
/// The hat provider's sku number
public var sku: String = ""
/// The hat provider's name
public var name: String = ""
/// The hat provider's description
public var description: String = ""
/// The hat provider's details
public var details: String = ""
/// The hat provider's illustration url
public var imageURL: String = ""
/// The hat provider's price
public var price: Int = 0
/// The hat provider's available hats remaining
public var availableHats: Int = 0
/// The hat provider's purchased hats so far
public var purchasedHats: Int = 0
/// The hat provider's ordering
public var ordering: Int = 0
/// The hat provider's hat features
public var features: [String] = []
/// The hat provider's image. used for caching the downloaded image
public var hatProviderImage: UIImage?
/// The hat provider's category information
public var category: HATProviderCategory = HATProviderCategory()
/// The hat provider's kind information
public var kind: HATProviderKind = HATProviderKind()
/// The hat provider's payment information
public var paymentType: HATProviderPayment = HATProviderPayment()
// MARK: Initialisers
/**
The default initialiser. Initialises everything to default values.
*/
public init() {
sku = ""
name = ""
description = ""
details = ""
imageURL = ""
price = 0
availableHats = 0
purchasedHats = 0
ordering = 0
features = []
hatProviderImage = nil
category = HATProviderCategory()
kind = HATProviderKind()
paymentType = HATProviderPayment()
}
/**
It initialises everything from the received JSON file from the HAT
- dictionary: The JSON file received
*/
public init(from dictionary: Dictionary<String, JSON>) {
self.init()
if let tempSKU: String = dictionary[CodingKeys.sku.rawValue]?.stringValue {
sku = tempSKU
}
if let tempName: String = dictionary[CodingKeys.name.rawValue]?.stringValue {
name = tempName
}
if let tempDescription: String = dictionary[CodingKeys.description.rawValue]?.stringValue {
description = tempDescription
}
if let tempDetails: String = dictionary[CodingKeys.details.rawValue]?.stringValue {
details = tempDetails
}
if let tempIllustration: String = dictionary[CodingKeys.imageURL.rawValue]?.stringValue {
imageURL = tempIllustration
}
if let tempPrice: Int = dictionary[CodingKeys.price.rawValue]?.intValue {
price = tempPrice
}
if let tempAvailable: Int = dictionary[CodingKeys.availableHats.rawValue]?.intValue {
availableHats = tempAvailable
}
if let tempPurchased: Int = dictionary[CodingKeys.purchasedHats.rawValue]?.intValue {
purchasedHats = tempPurchased
}
if let tempOrdering: Int = dictionary[CodingKeys.ordering.rawValue]?.intValue {
ordering = tempOrdering
}
if let tempFeatures: [JSON] = dictionary[CodingKeys.features.rawValue]?.arrayValue {
for item: JSON in tempFeatures {
features.append(item.stringValue)
}
}
if let tempKind: [String: JSON] = dictionary[CodingKeys.kind.rawValue]?.dictionaryValue {
kind = HATProviderKind(from: tempKind)
}
if let tempPaymentType: [String: JSON] = dictionary[CodingKeys.paymentType.rawValue]?.dictionaryValue {
paymentType = HATProviderPayment(from: tempPaymentType)
}
if let tempCategory: [String: JSON] = dictionary[CodingKeys.category.rawValue]?.dictionaryValue {
category = HATProviderCategory(from: tempCategory)
}
}
}
| mpl-2.0 | faf103104df2e47ebc47ffb3a0ed2331 | 31.81106 | 475 | 0.626124 | 4.537922 | false | false | false | false |
anzfactory/QiitaCollection | QiitaCollection/EntryDetailViewController.swift | 1 | 24412 | //
// EntryDetailViewController.swift
// QiitaCollection
//
// Created by ANZ on 2015/02/11.
// Copyright (c) 2015年 anz. All rights reserved.
//
import UIKit
class EntryDetailViewController: BaseViewController, NSUserActivityDelegate {
typealias ParseItem = (label: String, value: String)
// MARK: UI
@IBOutlet weak var webView: EntryDetailView!
// MARK: プロパティ
var displayEntry: EntryEntity? = nil {
willSet {
self.title = newValue?.title
}
didSet {
if let entry = self.displayEntry {
self.account.saveHistory(entry)
}
}
}
var displayEntryId: String? = nil
var useLocalFile: Bool = false
var navButtonHandOff: SelectedBarButton? = nil
var navButtonStock: SelectedBarButton? = nil
lazy var links: [ParseItem] = self.parseLink()
lazy var codes: [ParseItem] = self.parseCode()
let patternLink: String = "<a.*?href=\\\"([http|https].*?)\\\".*?>(.*?)</a>"
let patternCode: String = "\\`{3}(.*?)\\n((.|\\n)*?)\\`{3}"
var senderActivity: NSUserActivity? = nil
// MARK: ライフサイクル
override func viewDidLoad() {
super.viewDidLoad()
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
if !self.isBeingPresented() && !self.isMovingToParentViewController() {
return
}
// ローカルファイルじゃない かつ 認証済みなら
if !self.useLocalFile {
self.setupNavigationBar()
}
self.refresh()
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
// したに固定メニューボタンがあるんで、bottom padding をセットしておく
self.webView.scrollView.contentInset.bottom = 44.0
if let barbutton = self.navButtonStock {
barbutton.showGuide(GuideManager.GuideType.AddStock)
}
if let barbutton = self.navButtonHandOff {
barbutton.showGuide(GuideManager.GuideType.SyncBrowsing)
}
}
override func viewWillDisappear(animated: Bool) {
if let activity = self.senderActivity {
activity.invalidate()
}
super.viewWillDisappear(animated)
}
// MARK: メソッド
override func publicMenuItems() -> [PathMenuItem] {
// ローカルファイルから読みだしてる場合は、リロードだけ
if self.useLocalFile {
let menuItemReload: QCPathMenuItem = QCPathMenuItem(mainImage: UIImage(named: "menu_reload")!)
menuItemReload.action = {(sender: QCPathMenuItem) -> Void in
self.confirmReload()
return
}
return [menuItemReload]
}
let menuItemLink: QCPathMenuItem = QCPathMenuItem(mainImage: UIImage(named: "menu_link")!)
menuItemLink.action = {(sender: QCPathMenuItem) -> Void in
self.openLinks(sender)
return
}
let menuItemClip: QCPathMenuItem = QCPathMenuItem(mainImage: UIImage(named: "menu_clipboard")!)
menuItemClip.action = {(sender: QCPathMenuItem) -> Void in
self.copyCode(sender)
return
}
let menuItemPin: QCPathMenuItem = QCPathMenuItem(mainImage: UIImage(named: "menu_pin")!)
menuItemPin.action = {(sender: QCPathMenuItem) -> Void in
self.confirmPinEntry()
return
}
let menuItemShare: QCPathMenuItem = QCPathMenuItem(mainImage: UIImage(named: "menu_share")!)
menuItemShare.action = {(sender: QCPathMenuItem) -> Void in
self.shareEntry()
return
}
let menuPerson: QCPathMenuItem = QCPathMenuItem(mainImage: UIImage(named: "menu_person")!)
menuPerson.action = {(sender: QCPathMenuItem) -> Void in
self.moveUserDetail()
return
}
let menuDiscus: QCPathMenuItem = QCPathMenuItem(mainImage: UIImage(named: "menu_discus")!)
menuDiscus.action = {(sender: QCPathMenuItem) -> Void in
self.moveCommentList()
return
}
let menuTags: QCPathMenuItem = QCPathMenuItem(mainImage: UIImage(named: "menu_tag")!)
menuTags.action = {(sender: QCPathMenuItem) -> Void in
self.openTagList(sender)
return
}
let menuDownload: QCPathMenuItem = QCPathMenuItem(mainImage: UIImage(named: "menu_download")!)
menuDownload.action = {(sender: QCPathMenuItem) -> Void in
self.confirmDownload()
}
let menuStockers: QCPathMenuItem = QCPathMenuItem(mainImage: UIImage(named: "menu_star")!)
menuStockers.action = {(sender: QCPathMenuItem) -> Void in
self.moveStockers()
}
return [menuItemLink, menuItemClip, menuItemPin, menuDownload, menuItemShare, menuPerson, menuDiscus, menuTags, menuStockers]
}
func setupNavigationBar() {
var buttons: [SelectedBarButton] = [SelectedBarButton]()
if self.account is QiitaAccount {
// ストック
self.navButtonStock = SelectedBarButton(image: UIImage(named: "bar_item_bookmark"), style: UIBarButtonItemStyle.Plain, target: self, action: "confirmAddStock")
self.navButtonStock!.selectedColor = UIColor.tintSelectedBarButton()
buttons.append(self.navButtonStock!)
}
// macへのブラウジング同期
self.navButtonHandOff = SelectedBarButton(image: UIImage(named: "bar_item_desktop"), style: UIBarButtonItemStyle.Plain, target:self, action:"syncBrowsing")
buttons.append(self.navButtonHandOff!)
self.navigationItem.rightBarButtonItems = buttons
}
func refresh() {
if let entry = self.displayEntry {
self.displayEntryId = entry.id
self.loadLocalHtml()
self.getStockState(entry.id)
} else if let entryId = self.displayEntryId {
if self.useLocalFile {
// ローカルファイルから読み出す
self.account.loadLocalEntry(entryId, completion: { (isError, title, body) -> Void in
if isError {
Toast.show("投稿を取得できませんでした...", style: JFMinimalNotificationStytle.StyleWarning)
return
}
self.title = title
self.loadLocalHtml(self.title!, body: body)
})
} else {
// 投稿IDだけ渡されてる状況なので、とってくる
self.account.read(entryId, completion: { (entry) -> Void in
if entry == nil {
Toast.show("投稿を取得できませんでした...", style: JFMinimalNotificationStytle.StyleWarning)
return
}
self.displayEntry = entry
self.loadLocalHtml()
// 記事のストック状況を取得
self.getStockState(entryId)
})
}
} else {
fatalError("unknown entry....")
}
}
func loadLocalHtml() {
self.loadLocalHtml(self.displayEntry!.title, body:self.displayEntry!.htmlBody)
}
func loadLocalHtml(title: String, body:String) {
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), { () -> Void in
// テンプレート読み込み
let path: NSString = NSBundle.mainBundle().pathForResource("entry", ofType: "html")!
let template: NSString = NSString(contentsOfFile: path as String, encoding: NSUTF8StringEncoding, error: nil)!
dispatch_async(dispatch_get_main_queue(), { () -> Void in
// テンプレートに組み込んで表示
self.webView.loadHTMLString(NSString(format: template, title, body) as String, baseURL: nil)
})
})
}
func getStockState(entryId: String) {
if let qiitaAccount = self.account as? QiitaAccount {
qiitaAccount.isStocked(entryId, completion: { (stocked) -> Void in
self.navButtonStock?.selected = stocked
return
})
}
}
func syncBrowsing() {
if let entry = self.displayEntry {
if let activity = self.senderActivity {
} else {
self.senderActivity = NSUserActivity(activityType: QCKeys.UserActivity.TypeSendURLToMac.rawValue)
self.senderActivity?.delegate = self
self.senderActivity!.title = "QiitaCollection"
self.senderActivity!.becomeCurrent();
}
self.senderActivity!.webpageURL = NSURL(string: entry.urlString)
} else {
Toast.show("投稿データがないようです...", style: JFMinimalNotificationStytle.StyleWarning)
}
}
func confirmAddStock() {
var message: String = ""
if self.navButtonStock!.selected {
message = "この投稿のストックを解除しますか?"
} else {
message = "この投稿をストックしますか?"
}
let args = [
QCKeys.AlertView.Title.rawValue : "確認",
QCKeys.AlertView.Message.rawValue : message,
QCKeys.AlertView.NoTitle.rawValue : "Cancel",
QCKeys.AlertView.YesAction.rawValue: AlertViewSender(action: { () -> Void in
self.toggleStock()
}, title: "OK")
]
NSNotificationCenter.defaultCenter().postNotificationName(QCKeys.Notification.ShowAlertYesNo.rawValue, object: nil, userInfo: args)
}
func toggleStock() {
if let qiitaAccount = self.account as? QiitaAccount {
var message: String = ""
let completion = {(isError: Bool) -> Void in
if isError {
Toast.show("失敗しました…", style: JFMinimalNotificationStytle.StyleError)
return
}
// 処理後なんできめうちでもいいけど・・・ストック状態をとりなおしてみる
self.getStockState(self.displayEntryId!)
Toast.show(message, style: JFMinimalNotificationStytle.StyleSuccess)
return
}
if self.navButtonStock!.selected {
// 解除処理
message = "ストックを解除しました"
qiitaAccount.cancelStock(self.displayEntryId!, completion: completion)
} else {
// ストック処理
message = "ストックしました"
qiitaAccount.stock(self.displayEntryId!, completion: completion)
}
}
}
func shareEntry() {
if self.displayEntry == nil {
return
}
let args: [NSObject: AnyObject] = [
QCKeys.ActivityView.Message.rawValue: self.displayEntry!.title,
QCKeys.ActivityView.Link.rawValue : self.displayEntry!.urlString
]
NSNotificationCenter.defaultCenter().postNotificationName(QCKeys.Notification.ShowActivityView.rawValue, object: self, userInfo: args)
}
func openLinks(sender: QCPathMenuItem) {
if self.links.count == 0 {
Toast.show("開けるリンクがありません...", style: JFMinimalNotificationStytle.StyleWarning)
return
}
var linkTitles: [String] = [String]()
for item in self.links {
linkTitles.append(item.label + ":" + item.value)
}
let listVC: SimpleListViewController = self.storyboard?.instantiateViewControllerWithIdentifier("SimpleListVC") as! SimpleListViewController
listVC.title = "開くURLを選んで下さい"
listVC.items = linkTitles
listVC.swipableCell = false
listVC.tapCallback = {(vc: SimpleListViewController, index: Int) -> Void in
vc.dismissViewControllerAnimated(true, completion: { () -> Void in
let item: ParseItem = self.links[index]
self.openURL(item.value)
return
})
}
listVC.transitionSenderPoint = sender.superview?.convertPoint(sender.endPoint!, toView: self.view)
NSNotificationCenter.defaultCenter().postNotificationName(QCKeys.Notification.PresentedViewController.rawValue, object: listVC)
}
func copyCode(sender: QCPathMenuItem) {
if self.codes.count == 0 {
Toast.show("コードブロックがないようです...", style: JFMinimalNotificationStytle.StyleWarning)
return
}
var codeHeadlines: [String] = [String]()
for item in self.codes {
codeHeadlines.append(item.label)
}
let listVC: SimpleListViewController = self.storyboard?.instantiateViewControllerWithIdentifier("SimpleListVC") as! SimpleListViewController
listVC.title = "コピーするコードを選んでください"
listVC.items = codeHeadlines
listVC.swipableCell = false
listVC.tapCallback = {(vc: SimpleListViewController, index: Int) -> Void in
vc.dismissViewControllerAnimated(true, completion: { () -> Void in
let item: ParseItem = self.codes[index]
UIPasteboard.generalPasteboard().setValue(item.value, forPasteboardType: "public.utf8-plain-text")
Toast.show("クリップボードにコピーしました", style: JFMinimalNotificationStytle.StyleSuccess)
})
}
listVC.transitionSenderPoint = sender.superview!.convertPoint(sender.endPoint!, toView: self.view)
NSNotificationCenter.defaultCenter().postNotificationName(QCKeys.Notification.PresentedViewController.rawValue, object: listVC)
}
func parseLink() -> [ParseItem] {
if self.displayEntry == nil {
return [ParseItem]()
}
return self.parseHtml(self.displayEntry!.htmlBody, pattern:self.patternLink)
}
func parseCode() -> [ParseItem] {
if self.displayEntry == nil {
return [ParseItem]()
}
return self.parseHtml(self.displayEntry!.body, pattern:self.patternCode)
}
func parseHtml(body:String, pattern: String) -> [ParseItem] {
let nsBody: NSString = NSString(string: body)
var error: NSError?
let regex: NSRegularExpression? = NSRegularExpression(pattern: pattern, options: NSRegularExpressionOptions.CaseInsensitive, error: &error)
let mathes: [AnyObject]? = regex?.matchesInString(nsBody as String, options: NSMatchingOptions.allZeros, range: NSMakeRange(0, nsBody.length))
var targets: [ParseItem] = [ParseItem]()
let indexLabel: Int = pattern == self.patternLink ? 2 : 1
let indexValue: Int = pattern == self.patternLink ? 1 : 2
if let objects = mathes {
for obj in objects {
let result: NSTextCheckingResult = obj as! NSTextCheckingResult
var label: String = nsBody.substringWithRange(result.rangeAtIndex(indexLabel))
let value: String = nsBody.substringWithRange(result.rangeAtIndex(indexValue))
if (label.isEmpty) {
label = value.componentsSeparatedByString("\n")[0]
} else if (pattern == self.patternCode) {
let separateLabel = label.componentsSeparatedByString(":")
if (separateLabel.count == 2) {
label = separateLabel[1] + ":" + value.componentsSeparatedByString("\n")[0]
} else {
label = separateLabel[0] + ":" + value.componentsSeparatedByString("\n")[0]
}
}
let item: ParseItem = ParseItem(label:label, value:value)
targets.append(item)
}
}
return targets
}
func openURL(urlString: String) {
if let url = NSURL(string: urlString) {
let result = url.parse()
if let userId = result.userId {
// ユーザーVCを開く
let vc: UserDetailViewController = UIStoryboard(name: "Main", bundle: nil).instantiateViewControllerWithIdentifier("UserDetailVC") as! UserDetailViewController
vc.displayUserId = userId
NSNotificationCenter.defaultCenter().postNotificationName(QCKeys.Notification.PushViewController.rawValue, object: vc)
} else if let entryId = result.entryId {
// 投稿VCを開く
let vc: EntryDetailViewController = UIStoryboard(name: "Main", bundle: nil).instantiateViewControllerWithIdentifier("EntryDetailVC") as! EntryDetailViewController
vc.displayEntryId = entryId
NSNotificationCenter.defaultCenter().postNotificationName(QCKeys.Notification.PushViewController.rawValue, object: vc)
} else {
// ブラウザで開く
if UIApplication.sharedApplication().canOpenURL(url) {
UIApplication.sharedApplication().openURL(url)
} else {
Toast.show("開くことが出来るURLではないようです…", style: JFMinimalNotificationStytle.StyleWarning)
}
}
} else {
Toast.show("開くことが出来るURLではないようです…", style: JFMinimalNotificationStytle.StyleWarning)
return
}
}
func moveUserDetail() {
if self.displayEntry == nil {
return
}
let vc: UserDetailViewController = self.storyboard?.instantiateViewControllerWithIdentifier("UserDetailVC") as! UserDetailViewController
vc.displayUserId = self.displayEntry!.postUser.id
NSNotificationCenter.defaultCenter().postNotificationName(QCKeys.Notification.PushViewController.rawValue, object: vc)
}
func moveCommentList() {
if self.displayEntry == nil {
return
}
let vc: CommentListViewController = self.storyboard?.instantiateViewControllerWithIdentifier("CommentsVC") as! CommentListViewController
vc.displayEntryId = self.displayEntryId!
vc.displayEntryTitle = self.displayEntry?.title ?? ""
NSNotificationCenter.defaultCenter().postNotificationName(QCKeys.Notification.PushViewController.rawValue, object: vc)
}
func moveStockers() {
if self.displayEntry == nil {
return
}
let vc: UserListViewController = self.storyboard?.instantiateViewControllerWithIdentifier("UserListVC") as! UserListViewController
vc.listType = UserListViewController.UserListType.Stockers
vc.targetEntryId = self.displayEntryId
NSNotificationCenter.defaultCenter().postNotificationName(QCKeys.Notification.PushViewController.rawValue, object: vc)
}
func confirmPinEntry() {
if self.displayEntry == nil {
return
}
let action: AlertViewSender = AlertViewSender(action: { () -> Void in
self.account.pin(self.displayEntry!)
Toast.show("この投稿をpinしました", style: JFMinimalNotificationStytle.StyleSuccess)
return
}, title: "OK")
NSNotificationCenter.defaultCenter().postNotificationName(QCKeys.Notification.ShowAlertYesNo.rawValue, object: nil, userInfo: [
QCKeys.AlertView.Title.rawValue : "確認",
QCKeys.AlertView.Message.rawValue : "この投稿をpinしますか?",
QCKeys.AlertView.YesAction.rawValue: action,
QCKeys.AlertView.NoTitle.rawValue : "Cancel"
])
}
func confirmDownload() {
if self.displayEntry == nil {
return
}
let action: AlertViewSender = AlertViewSender(action: { () -> Void in
self.account.download(self.displayEntry!, completion: { (isError) -> Void in
if isError {
Toast.show("この投稿の保存に失敗しました", style: JFMinimalNotificationStytle.StyleError)
} else {
// ViewPager再構成指示
NSNotificationCenter.defaultCenter().postNotificationName(QCKeys.Notification.ReloadViewPager.rawValue, object: nil)
Toast.show("この投稿を保存しました", style: JFMinimalNotificationStytle.StyleSuccess)
}
})
return
}, title: "Save")
NSNotificationCenter.defaultCenter().postNotificationName(QCKeys.Notification.ShowAlertYesNo.rawValue, object: nil, userInfo: [
QCKeys.AlertView.Title.rawValue : "確認",
QCKeys.AlertView.Message.rawValue : "この投稿を保存しますか?保存するとオフラインでも閲覧できるようになります",
QCKeys.AlertView.YesAction.rawValue: action,
QCKeys.AlertView.NoTitle.rawValue : "Cancel"
])
}
func confirmReload() {
let action: AlertViewSender = AlertViewSender(action: {() -> Void in
self.useLocalFile = false
self.refresh()
NSNotificationCenter.defaultCenter().postNotificationName(QCKeys.Notification.ResetPublicMenuItems.rawValue, object: self)
}, title: "OK")
NSNotificationCenter.defaultCenter().postNotificationName(QCKeys.Notification.ShowAlertYesNo.rawValue, object: nil, userInfo: [
QCKeys.AlertView.Title.rawValue : "確認",
QCKeys.AlertView.Message.rawValue : "現在保存した投稿ファイルを表示しています。最新状態をネットから取得しなおしますか?",
QCKeys.AlertView.YesAction.rawValue: action,
QCKeys.AlertView.NoTitle.rawValue : "Cancel"
])
}
func openTagList(sender: QCPathMenuItem) {
if let entity = self.displayEntry {
let vc: SimpleListViewController = self.storyboard?.instantiateViewControllerWithIdentifier("SimpleListVC") as! SimpleListViewController
vc.items = entity.toTagList()
vc.title = "タグリスト"
vc.swipableCell = false
vc.tapCallback = {(vc: SimpleListViewController, index: Int) -> Void in
// タグで検索
let selectedTag: String = vc.items[index]
vc.dismissGridMenuAnimated(true, completion: { () -> Void in
let searchVC: EntryCollectionViewController = self.storyboard?.instantiateViewControllerWithIdentifier("EntryCollectionVC") as! EntryCollectionViewController
searchVC.title = "タグ:" + selectedTag
searchVC.query = "tag:" + selectedTag
NSNotificationCenter.defaultCenter().postNotificationName(QCKeys.Notification.PushViewController.rawValue, object: searchVC)
})
}
vc.transitionSenderPoint = sender.superview!.convertPoint(sender.endPoint!, toView: self.view)
NSNotificationCenter.defaultCenter().postNotificationName(QCKeys.Notification.PresentedViewController.rawValue, object: vc)
}
}
func userActivityWillSave(userActivity: NSUserActivity) {
dispatch_async(dispatch_get_main_queue(), {() -> Void in
Toast.show("閲覧中の投稿をHandoff対応デバイスとシンクロしました", style: JFMinimalNotificationStytle.StyleSuccess)
})
}
}
| mit | ee8adb377656d7bfceb36397dd8490e9 | 39.722807 | 178 | 0.595166 | 4.793887 | false | false | false | false |
yakirlee/Extersion | Helpers/PHAsset+Extension.swift | 1 | 1029 | //
// PHAsset+Extension.swift
// TSWeChat
//
// Created by Hilen on 2/25/16.
// Copyright © 2016 Hilen. All rights reserved.
//
import Foundation
import Photos
extension PHAsset {
func getUIImage() -> UIImage? {
let manager = PHImageManager.defaultManager()
let options = PHImageRequestOptions()
options.synchronous = true
options.networkAccessAllowed = true
options.version = .Current
options.deliveryMode = .HighQualityFormat
options.resizeMode = .Exact
var image: UIImage?
manager.requestImageForAsset(
self,
targetSize: CGSize(width: CGFloat(self.pixelWidth), height: CGFloat(self.pixelHeight)),
contentMode: .AspectFill,
options: options,
resultHandler: {(result, info)->Void in
if let theResult = result {
image = theResult
} else {
image = nil
}
})
return image
}
} | mit | 8b55c83a1e2b5eada89045b1776aa0cd | 26.078947 | 99 | 0.571984 | 5.165829 | false | false | false | false |
Yvent/QQMusic | QQMusic/QQMusic/HomeVC.swift | 1 | 3877 | //
// HomeVC.swift
// QQMusic
//
// Created by 周逸文 on 17/2/16.
// Copyright © 2017年 Devil. All rights reserved.
//
import UIKit
class HomeVC: UIViewController,ZYWBackViewDelegate {
private var topV: UIView!
private var ContentView: UIScrollView!
lazy var mineV: UIView = {
let VC = MineVC()
self.addChildViewController(VC)
return VC.view
}()
lazy var musicPavilionV: UIView = {
let VC = MusicPavilionVC()
self.addChildViewController(VC)
return VC.view
}()
lazy var discoverV: UIView = {
let VC = DiscoverVC()
self.addChildViewController(VC)
return VC.view
}()
override func viewDidLoad() {
super.viewDidLoad()
self.navigationController?.navigationBar.isHidden = true
self.view.backgroundColor = UIColor.white
initUI()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
private func initUI(){
topV = ZYW_BackView(yv_bc: NAVBC, any: self, title: "音乐库",centerlefttitle:"我的",centerrighttitle: "发现", lefttitle: "菜单", righttitle: "识曲")
ContentView = UIScrollView(yv_bc: UIColor.white, any: self, isP: true)
view.addSubview(ContentView)
ContentView.snp.makeConstraints { (make) in
make.left.right.bottom.equalTo(view)
make.top.equalTo(topV.snp.bottom)
}
ContentView.addSubviews([mineV,musicPavilionV,discoverV])
mineV.snp.makeConstraints { (make) in
make.left.equalTo(ContentView)
make.top.equalTo(ContentView)
make.height.equalTo(HomeSubviewHeight)
make.width.equalTo(ScreenWidth)
}
musicPavilionV.snp.makeConstraints { (make) in
make.left.equalTo(mineV.snp.right)
make.top.equalTo(ContentView)
make.height.equalTo(mineV)
make.width.equalTo(mineV)
}
discoverV.snp.makeConstraints { (make) in
make.left.equalTo(musicPavilionV.snp.right)
make.top.equalTo(ContentView)
make.height.equalTo(mineV)
make.width.equalTo(mineV)
}
}
///菜单
func zywdidleftitem() {
}
///识曲
func zywdidrightitem() {
}
}
extension HomeVC : UIScrollViewDelegate{
func scrollViewDidScroll(_ scrollView: UIScrollView) {
if scrollView.contentOffset.x > ScreenWidth * 2 {
scrollView.isScrollEnabled = false
}else if scrollView.contentOffset.x < 0 {
scrollView.isScrollEnabled = false
}else{
scrollView.isScrollEnabled = true
}
// if scrollView.contentOffset.x >= ScreenWidth {
//
// backgroundImgV.frame.origin.x = CGFloat(getX(Float(ScreenWidth * 2), minX: Float(ScreenWidth), maxBGX: -Float(ScreenWidth), minBGX: -Float(ScreenWidth/2), currentX: Float(scrollView.contentOffset.x)))
//
//
// }else if scrollView.contentOffset.x < ScreenWidth {
// backgroundImgV.frame.origin.x = CGFloat(getX(Float(ScreenWidth * 2), minX: Float(ScreenWidth), maxBGX: -Float(ScreenWidth), minBGX: -Float(ScreenWidth/2), currentX: Float(scrollView.contentOffset.x)))
//
// }
}
// func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
//
// let page = Int(scrollView.contentOffset.x / scrollView.frame.size.width)
// PageContrl.currentPage = page
// }
// func pageChanged(_ CP: Int) {
// //展现当前页面内容
// ContentView.contentOffset.x = ScreenWidth * CGFloat(CP)
// }
}
| mit | b47316b54c2f6a0dcba064609338ec9e | 30.327869 | 216 | 0.595761 | 4.237251 | false | false | false | false |
ConceptsInCode/PackageTracker | PackageTracker/PackageTracker/AppDelegate.swift | 1 | 1274 | //
// AppDelegate.swift
// PackageTracker
//
// Created by BJ on 4/26/15.
// Copyright (c) 2015 Concepts In Code. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, UISplitViewControllerDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
let splitViewController = window!.rootViewController as! UISplitViewController
let navController = splitViewController.viewControllers.last as! UINavigationController
navController.topViewController?.navigationItem.leftBarButtonItem = splitViewController.displayModeButtonItem()
splitViewController.delegate = self
return true
}
func splitViewController(splitViewController: UISplitViewController, collapseSecondaryViewController secondaryViewController:UIViewController, ontoPrimaryViewController primaryViewController:UIViewController) -> Bool {
guard let secondaryAsNavController = secondaryViewController as? UINavigationController else { return false }
guard let _ = secondaryAsNavController.topViewController as? ViewController else { return false }
return true
}
}
| mit | 9f61ece22c1d63241e83cf5acdb578c4 | 40.096774 | 222 | 0.776295 | 6.56701 | false | false | false | false |
arvedviehweger/swift | benchmark/single-source/PrefixWhile.swift | 1 | 6318 | //===--- PrefixWhile.swift ------------------------------------*- 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
//
//===----------------------------------------------------------------------===//
////////////////////////////////////////////////////////////////////////////////
// WARNING: This file is manually generated from .gyb template and should not
// be directly modified. Instead, make changes to PrefixWhile.swift.gyb and run
// scripts/generate_harness/generate_harness.py to regenerate this file.
////////////////////////////////////////////////////////////////////////////////
import TestsUtils
let sequenceCount = 4096
let prefixCount = sequenceCount - 1024
let sumCount = prefixCount * (prefixCount - 1) / 2
@inline(never)
public func run_PrefixWhileCountableRange(_ N: Int) {
let s = 0..<sequenceCount
for _ in 1...20*N {
var result = 0
for element in s.prefix(while: {$0 < prefixCount} ) {
result += element
}
CheckResults(result == sumCount,
"IncorrectResults in PrefixWhileCountableRange: \(result) != \(sumCount)")
}
}
@inline(never)
public func run_PrefixWhileSequence(_ N: Int) {
let s = sequence(first: 0) { $0 < sequenceCount - 1 ? $0 &+ 1 : nil }
for _ in 1...20*N {
var result = 0
for element in s.prefix(while: {$0 < prefixCount} ) {
result += element
}
CheckResults(result == sumCount,
"IncorrectResults in PrefixWhileSequence: \(result) != \(sumCount)")
}
}
@inline(never)
public func run_PrefixWhileAnySequence(_ N: Int) {
let s = AnySequence(sequence(first: 0) { $0 < sequenceCount - 1 ? $0 &+ 1 : nil })
for _ in 1...20*N {
var result = 0
for element in s.prefix(while: {$0 < prefixCount} ) {
result += element
}
CheckResults(result == sumCount,
"IncorrectResults in PrefixWhileAnySequence: \(result) != \(sumCount)")
}
}
@inline(never)
public func run_PrefixWhileAnySeqCntRange(_ N: Int) {
let s = AnySequence(0..<sequenceCount)
for _ in 1...20*N {
var result = 0
for element in s.prefix(while: {$0 < prefixCount} ) {
result += element
}
CheckResults(result == sumCount,
"IncorrectResults in PrefixWhileAnySeqCntRange: \(result) != \(sumCount)")
}
}
@inline(never)
public func run_PrefixWhileAnySeqCRangeIter(_ N: Int) {
let s = AnySequence((0..<sequenceCount).makeIterator())
for _ in 1...20*N {
var result = 0
for element in s.prefix(while: {$0 < prefixCount} ) {
result += element
}
CheckResults(result == sumCount,
"IncorrectResults in PrefixWhileAnySeqCRangeIter: \(result) != \(sumCount)")
}
}
@inline(never)
public func run_PrefixWhileAnyCollection(_ N: Int) {
let s = AnyCollection(0..<sequenceCount)
for _ in 1...20*N {
var result = 0
for element in s.prefix(while: {$0 < prefixCount} ) {
result += element
}
CheckResults(result == sumCount,
"IncorrectResults in PrefixWhileAnyCollection: \(result) != \(sumCount)")
}
}
@inline(never)
public func run_PrefixWhileArray(_ N: Int) {
let s = Array(0..<sequenceCount)
for _ in 1...20*N {
var result = 0
for element in s.prefix(while: {$0 < prefixCount} ) {
result += element
}
CheckResults(result == sumCount,
"IncorrectResults in PrefixWhileArray: \(result) != \(sumCount)")
}
}
@inline(never)
public func run_PrefixWhileCountableRangeLazy(_ N: Int) {
let s = (0..<sequenceCount).lazy
for _ in 1...20*N {
var result = 0
for element in s.prefix(while: {$0 < prefixCount} ) {
result += element
}
CheckResults(result == sumCount,
"IncorrectResults in PrefixWhileCountableRangeLazy: \(result) != \(sumCount)")
}
}
@inline(never)
public func run_PrefixWhileSequenceLazy(_ N: Int) {
let s = (sequence(first: 0) { $0 < sequenceCount - 1 ? $0 &+ 1 : nil }).lazy
for _ in 1...20*N {
var result = 0
for element in s.prefix(while: {$0 < prefixCount} ) {
result += element
}
CheckResults(result == sumCount,
"IncorrectResults in PrefixWhileSequenceLazy: \(result) != \(sumCount)")
}
}
@inline(never)
public func run_PrefixWhileAnySequenceLazy(_ N: Int) {
let s = (AnySequence(sequence(first: 0) { $0 < sequenceCount - 1 ? $0 &+ 1 : nil })).lazy
for _ in 1...20*N {
var result = 0
for element in s.prefix(while: {$0 < prefixCount} ) {
result += element
}
CheckResults(result == sumCount,
"IncorrectResults in PrefixWhileAnySequenceLazy: \(result) != \(sumCount)")
}
}
@inline(never)
public func run_PrefixWhileAnySeqCntRangeLazy(_ N: Int) {
let s = (AnySequence(0..<sequenceCount)).lazy
for _ in 1...20*N {
var result = 0
for element in s.prefix(while: {$0 < prefixCount} ) {
result += element
}
CheckResults(result == sumCount,
"IncorrectResults in PrefixWhileAnySeqCntRangeLazy: \(result) != \(sumCount)")
}
}
@inline(never)
public func run_PrefixWhileAnySeqCRangeIterLazy(_ N: Int) {
let s = (AnySequence((0..<sequenceCount).makeIterator())).lazy
for _ in 1...20*N {
var result = 0
for element in s.prefix(while: {$0 < prefixCount} ) {
result += element
}
CheckResults(result == sumCount,
"IncorrectResults in PrefixWhileAnySeqCRangeIterLazy: \(result) != \(sumCount)")
}
}
@inline(never)
public func run_PrefixWhileAnyCollectionLazy(_ N: Int) {
let s = (AnyCollection(0..<sequenceCount)).lazy
for _ in 1...20*N {
var result = 0
for element in s.prefix(while: {$0 < prefixCount} ) {
result += element
}
CheckResults(result == sumCount,
"IncorrectResults in PrefixWhileAnyCollectionLazy: \(result) != \(sumCount)")
}
}
@inline(never)
public func run_PrefixWhileArrayLazy(_ N: Int) {
let s = (Array(0..<sequenceCount)).lazy
for _ in 1...20*N {
var result = 0
for element in s.prefix(while: {$0 < prefixCount} ) {
result += element
}
CheckResults(result == sumCount,
"IncorrectResults in PrefixWhileArrayLazy: \(result) != \(sumCount)")
}
}
| apache-2.0 | df4a3c85e2456480eed56ebe6ea26547 | 31.90625 | 91 | 0.617601 | 3.857143 | false | false | false | false |
duming91/Hear-You | Hear You/Views/Cell/MyMusicCell.swift | 1 | 1019 | //
// MyMusicCell.swift
// Hear You
//
// Created by 董亚珣 on 16/5/27.
// Copyright © 2016年 snow. All rights reserved.
//
import UIKit
class MyMusicCell: UIView {
var backImage: UIImageView!
var title: UILabel!
override init(frame: CGRect) {
super.init(frame: frame)
let titleWidth : CGFloat = frame.width - 40
let titleHeight : CGFloat = 60
backImage = UIImageView(frame:frame)
backImage.backgroundColor = UIColor.clearColor()
title = UILabel()
title.frame = CGRectMake((frame.width - titleWidth) / 2, (frame.height - titleHeight) / 2, titleWidth, titleHeight)
title.textAlignment = .Center
title.font = UIFont.systemFontOfSize(35)
addSubview(backImage)
addSubview(title)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func awakeFromNib() {
super.awakeFromNib()
}
}
| gpl-3.0 | a5761d6752b0a3f04043b08c93200f22 | 24.25 | 123 | 0.610891 | 4.372294 | false | false | false | false |
xedin/swift | test/Driver/multi-threaded.swift | 2 | 5120 | // RUN: %empty-directory(%t)
// RUN: %target-swiftc_driver -driver-print-jobs -module-name=ThisModule -wmo -num-threads 4 %S/Inputs/main.swift %s -emit-module -o test.swiftmodule | %FileCheck -check-prefix=MODULE %s
// RUN: echo "{\"%/s\": {\"assembly\": \"/build/multi-threaded.s\"}, \"%/S/Inputs/main.swift\": {\"assembly\": \"/build/main.s\"}}" > %t/ofms.json
// RUN: %target-swiftc_driver -driver-print-jobs -module-name=ThisModule -wmo -num-threads 4 %/S/Inputs/main.swift %/s -output-file-map %t/ofms.json -S | %FileCheck -check-prefix=ASSEMBLY %s
// RUN: %target-swiftc_driver -driver-print-jobs -module-name=ThisModule -wmo -num-threads 4 %S/Inputs/main.swift %s -c | %FileCheck -check-prefix=OBJECT %s
// RUN: cd %t && %target-swiftc_driver -parseable-output -module-name=ThisModule -wmo -num-threads 4 %S/Inputs/main.swift %s -c 2> %t/parseable-output
// RUN: cat %t/parseable-output | %FileCheck -check-prefix=PARSEABLE %s
// RUN: cd %t && env TMPDIR=/tmp %swiftc_driver -driver-print-jobs -module-name=ThisModule -wmo -num-threads 4 %S/Inputs/main.swift %s -o a.out | %FileCheck -check-prefix=EXEC %s
// RUN: echo "{\"%/s\": {\"llvm-bc\": \"%/t/multi-threaded.bc\", \"object\": \"%/t/multi-threaded.o\"}, \"%/S/Inputs/main.swift\": {\"llvm-bc\": \"%/t/main.bc\", \"object\": \"%/t/main.o\"}}" > %t/ofmo.json
// RUN: %target-swiftc_driver -module-name=ThisModule -wmo -num-threads 4 %S/Inputs/main.swift %s -emit-dependencies -output-file-map %t/ofmo.json -c
// RUN: cat %t/*.d | %FileCheck -check-prefix=DEPENDENCIES %s
// Check if -embed-bitcode works
// RUN: %target-swiftc_driver -driver-print-jobs -module-name=ThisModule -embed-bitcode -wmo -num-threads 4 %/S/Inputs/main.swift %/s -output-file-map %t/ofmo.json -c | %FileCheck -check-prefix=BITCODE %s
// Check if -embed-bitcode works with -parseable-output
// RUN: %target-swiftc_driver -parseable-output -module-name=ThisModule -embed-bitcode -wmo -num-threads 4 %/S/Inputs/main.swift %/s -output-file-map %t/ofmo.json -c 2> %t/parseable2
// RUN: cat %t/parseable2 | %FileCheck -check-prefix=PARSEABLE2 %s
// Check if linking works with -parseable-output
// RUN: cd %t && %target-swiftc_driver -parseable-output -module-name=ThisModule -wmo -num-threads 4 %/S/Inputs/main.swift %/s -output-file-map %t/ofmo.json -o a.out 2> %t/parseable3
// RUN: cat %t/parseable3 | %FileCheck -check-prefix=PARSEABLE3 %s
// MODULE: -frontend
// MODULE-DAG: -num-threads 4
// MODULE-DAG: {{[^ ]*[/\\]}}Inputs{{/|\\\\}}main.swift{{"?}} {{[^ ]*[/\\]}}multi-threaded.swift
// MODULE-DAG: -o test.swiftmodule
// MODULE-NOT: {{ld|clang\+\+}}
// ASSEMBLY: -frontend
// ASSEMBLY-DAG: -num-threads 4
// ASSEMBLY-DAG: {{[^ ]*[/\\]}}Inputs{{/|\\\\}}main.swift{{"?}} {{[^ ]*[/\\]}}multi-threaded.swift
// ASSEMBLY-DAG: -o /build/main.s -o /build/multi-threaded.s
// ASSEMBLY-NOT: {{ld|clang\+\+}}
// OBJECT: -frontend
// OBJECT-DAG: -num-threads 4
// OBJECT-DAG: {{[^ ]*[/\\]}}Inputs{{/|\\\\}}main.swift{{"?}} {{[^ ]*[/\\]}}multi-threaded.swift
// OBJECT-DAG: -o main.o -o multi-threaded.o
// OBJECT-NOT: {{ld|clang\+\+}}
// BITCODE: -frontend
// BITCODE-DAG: -num-threads 4
// BITCODE-DAG: {{[^ ]*[/\\]}}Inputs{{/|\\\\}}main.swift{{"?}} {{[^ ]*[/\\]}}multi-threaded.swift
// BITCODE-DAG: -o {{.*[/\\]}}main.bc -o {{.*[/\\]}}multi-threaded.bc
// BITCODE-DAG: -frontend -c -primary-file {{.*[/\\]}}main.bc {{.*}} -o {{[^ ]*}}main.o
// BITCODE-DAG: -frontend -c -primary-file {{.*[/\\]}}multi-threaded.bc {{.*}} -o {{[^ ]*}}multi-threaded.o
// BITCODE-NOT: {{ld|clang\+\+}}
// PARSEABLE: "outputs": [
// PARSEABLE: "path": "main.o"
// PARSEABLE: "path": "multi-threaded.o"
// EXEC: -frontend
// EXEC-DAG: -num-threads 4
// EXEC-DAG: {{[^ ]*[/\\]}}Inputs{{/|\\\\}}main.swift{{"?}} {{[^ ]*[/\\]}}multi-threaded.swift
// EXEC-DAG: -o {{.*te?mp.*[/\\]}}main{{[^ ]*}}.o{{"?}} -o {{.*te?mp.*[/\\]}}multi-threaded{{[^ ]*}}.o
// EXEC: {{ld|clang\+\+}}
// EXEC: {{.*te?mp.*[/\\]}}main{{[^ ]*}}.o{{"?}} {{.*te?mp.*[/\\]}}multi-threaded{{[^ ]*}}.o
// DEPENDENCIES-DAG: {{.*}}multi-threaded.o : {{.*[/\\]}}multi-threaded.swift {{.*[/\\]}}Inputs{{[/\\]}}main.swift
// DEPENDENCIES-DAG: {{.*}}main.o : {{.*[/\\]}}multi-threaded.swift {{.*[/\\]}}Inputs{{[/\\]}}main.swift
// PARSEABLE2: "name": "compile"
// PARSEABLE2: "outputs": [
// PARSEABLE2: "path": "{{.*[/\\]}}main.bc"
// PARSEABLE2: "path": "{{.*[/\\]}}multi-threaded.bc"
// PARSEABLE2: "name": "backend"
// PARSEABLE2: "inputs": [
// PARSEABLE2: "{{.*[/\\]}}main.bc"
// PARSEABLE2: "outputs": [
// PARSEABLE2: "path": "{{.*[/\\]}}main.o"
// PARSEABLE2: "name": "backend"
// PARSEABLE2: "inputs": [
// PARSEABLE2: "{{.*[/\\]}}multi-threaded.bc"
// PARSEABLE2: "outputs": [
// PARSEABLE2: "path": "{{.*[/\\]}}multi-threaded.o"
// PARSEABLE3: "name": "compile"
// PARSEABLE3: "outputs": [
// PARSEABLE3: "path": "{{.*}}main.o"
// PARSEABLE3: "path": "{{.*}}multi-threaded.o"
// PARSEABLE3: "name": "link"
// PARSEABLE3: "inputs": [
// PARSEABLE3-NEXT: "{{.*}}main.o"
// PARSEABLE3-NEXT: "{{.*}}multi-threaded.o"
// PARSEABLE3: "outputs": [
// PARSEABLE3: "path": "a.out"
func libraryFunction() {}
| apache-2.0 | a38e15a6ebefdfde4837c88896318149 | 55.263736 | 206 | 0.601953 | 3.026005 | false | false | false | false |
roecrew/AudioKit | AudioKit/Common/Nodes/Generators/Physical Models/Plucked String/AKPluckedString.swift | 1 | 5155 | //
// AKPluckedString.swift
// AudioKit
//
// Created by Aurelius Prochazka, revision history on Github.
// Copyright (c) 2016 Aurelius Prochazka. All rights reserved.
//
import AVFoundation
/// Karplus-Strong plucked string instrument.
///
/// - Parameters:
/// - frequency: Variable frequency. Values less than the initial frequency will be doubled until it is greater than that.
/// - amplitude: Amplitude
/// - lowestFrequency: This frequency is used to allocate all the buffers needed for the delay. This should be the lowest frequency you plan on using.
///
public class AKPluckedString: AKNode, AKToggleable {
// MARK: - Properties
internal var internalAU: AKPluckedStringAudioUnit?
internal var token: AUParameterObserverToken?
private var frequencyParameter: AUParameter?
private var amplitudeParameter: AUParameter?
private var lowestFrequency: Double
/// Ramp Time represents the speed at which parameters are allowed to change
public var rampTime: Double = AKSettings.rampTime {
willSet {
if rampTime != newValue {
internalAU?.rampTime = newValue
internalAU?.setUpParameterRamp()
}
}
}
/// Variable frequency. Values less than the initial frequency will be doubled until it is greater than that.
public var frequency: Double = 110 {
willSet {
if frequency != newValue {
frequencyParameter?.setValue(Float(newValue), originator: token!)
}
}
}
/// Amplitude
public var amplitude: Double = 0.5 {
willSet {
if amplitude != newValue {
amplitudeParameter?.setValue(Float(newValue), originator: token!)
}
}
}
/// Tells whether the node is processing (ie. started, playing, or active)
public var isStarted: Bool {
return internalAU!.isPlaying()
}
// MARK: - Initialization
/// Initialize the pluck with defaults
override convenience init() {
self.init(frequency: 110)
}
/// Initialize this pluck node
///
/// - Parameters:
/// - frequency: Variable frequency. Values less than the initial frequency will be doubled until it is greater than that.
/// - amplitude: Amplitude
/// - lowestFrequency: This frequency is used to allocate all the buffers needed for the delay. This should be the lowest frequency you plan on using.
///
public init(
frequency: Double = 440,
amplitude: Double = 0.5,
lowestFrequency: Double = 110) {
self.frequency = frequency
self.amplitude = amplitude
self.lowestFrequency = lowestFrequency
var description = AudioComponentDescription()
description.componentType = kAudioUnitType_Generator
description.componentSubType = fourCC("pluk")
description.componentManufacturer = fourCC("AuKt")
description.componentFlags = 0
description.componentFlagsMask = 0
AUAudioUnit.registerSubclass(
AKPluckedStringAudioUnit.self,
asComponentDescription: description,
name: "Local AKPluckedString",
version: UInt32.max)
super.init()
AVAudioUnit.instantiateWithComponentDescription(description, options: []) {
avAudioUnit, error in
guard let avAudioUnitGenerator = avAudioUnit else { return }
self.avAudioNode = avAudioUnitGenerator
self.internalAU = avAudioUnitGenerator.AUAudioUnit as? AKPluckedStringAudioUnit
AudioKit.engine.attachNode(self.avAudioNode)
}
guard let tree = internalAU?.parameterTree else { return }
frequencyParameter = tree.valueForKey("frequency") as? AUParameter
amplitudeParameter = tree.valueForKey("amplitude") as? AUParameter
token = tree.tokenByAddingParameterObserver {
address, value in
dispatch_async(dispatch_get_main_queue()) {
if address == self.frequencyParameter!.address {
self.frequency = Double(value)
} else if address == self.amplitudeParameter!.address {
self.amplitude = Double(value)
}
}
}
internalAU?.frequency = Float(frequency)
internalAU?.amplitude = Float(amplitude)
}
/// Trigger the sound with an optional set of parameters
/// - frequency: Frequency in Hz
/// - amplitude amplitude: Volume
///
public func trigger(frequency frequency: Double, amplitude: Double = 1) {
self.frequency = frequency
self.amplitude = amplitude
self.internalAU!.start()
self.internalAU!.triggerFrequency(Float(frequency), amplitude: Float(amplitude))
}
/// Function to start, play, or activate the node, all do the same thing
public func start() {
self.internalAU!.start()
}
/// Function to stop or bypass the node, both are equivalent
public func stop() {
self.internalAU!.stop()
}
}
| mit | bde453db49aa2759978bdbaf4952218c | 32.914474 | 156 | 0.636081 | 5.353063 | false | false | false | false |
belkevich/DTModelStorage | DTModelStorageTests/XCTests/Specs/RuntimeHelperTestCase.swift | 1 | 6659 | //
// RuntimeHelperTestCase.swift
// DTModelStorageTests
//
// Created by Denys Telezhkin on 15.07.15.
// Copyright (c) 2015 Denys Telezhkin. All rights reserved.
//
import UIKit
import XCTest
import DTModelStorage
import Nimble
import CoreData
class SwiftCell:UITableViewCell{}
class ManagedClass: NSManagedObject {}
class RuntimeHelperTestCase: XCTestCase {
func testSummaryOfObjectiveCClasses()
{
let mirror = _reflect(UITableViewCell)
expect(RuntimeHelper.classNameFromReflection(mirror)) == "UITableViewCell"
expect(RuntimeHelper.classNameFromReflectionSummary(mirror.summary)) == "UITableViewCell"
}
func testSummaryOfSwiftCells()
{
let mirror = _reflect(SwiftCell)
expect(RuntimeHelper.classNameFromReflection(mirror)) == "SwiftCell"
expect(RuntimeHelper.classNameFromReflectionSummary(mirror.summary)) == "SwiftCell"
}
func testClassClusterUIColor()
{
expect(RuntimeHelper.classClusterReflectionFromMirrorType(_reflect(UIColor.self)).summary) == "UIColor"
expect(RuntimeHelper.classClusterReflectionFromMirrorType(RuntimeHelper.mirrorFromModel(UIColor())).summary) == "UIColor"
expect(RuntimeHelper.classClusterReflectionFromMirrorType(RuntimeHelper.mirrorFromModel(UIColor.cyanColor())).summary) == "UIColor"
expect(RuntimeHelper.classClusterReflectionFromMirrorType(RuntimeHelper.mirrorFromModel(UIColor(red: 0.5, green: 0.3, blue: 0.2, alpha: 0.8))).summary) == "UIColor"
}
func testClassClusterNSArray()
{
expect(RuntimeHelper.classClusterReflectionFromMirrorType(_reflect(NSArray.self)).summary) == "NSArray"
expect(RuntimeHelper.classClusterReflectionFromMirrorType(RuntimeHelper.mirrorFromModel(NSArray())).summary) == "NSArray"
expect(RuntimeHelper.classClusterReflectionFromMirrorType(RuntimeHelper.mirrorFromModel(NSMutableArray())).summary) == "NSArray"
expect(RuntimeHelper.classClusterReflectionFromMirrorType(RuntimeHelper.mirrorFromModel(NSArray(array: [1,""]))).summary) == "NSArray"
}
func testClassClusterNSDictionary()
{
expect(RuntimeHelper.classClusterReflectionFromMirrorType(_reflect(NSDictionary.self)).summary) == "NSDictionary"
expect(RuntimeHelper.classClusterReflectionFromMirrorType(RuntimeHelper.mirrorFromModel(NSDictionary())).summary) == "NSDictionary"
expect(RuntimeHelper.classClusterReflectionFromMirrorType(RuntimeHelper.mirrorFromModel(NSMutableDictionary())).summary) == "NSDictionary"
expect(RuntimeHelper.classClusterReflectionFromMirrorType(RuntimeHelper.mirrorFromModel(NSDictionary(dictionary: [1:"2"]))).summary) == "NSDictionary"
}
func testClassClusterNSNumber()
{
expect(RuntimeHelper.classClusterReflectionFromMirrorType(_reflect(NSNumber.self)).summary) == "NSNumber"
expect(RuntimeHelper.classClusterReflectionFromMirrorType(RuntimeHelper.mirrorFromModel(NSNumber(bool: true))).summary) == "NSNumber"
expect(RuntimeHelper.classClusterReflectionFromMirrorType(RuntimeHelper.mirrorFromModel(NSNumber(double: 45))).summary) == "NSNumber"
}
func testClassClusterNSSet()
{
expect(RuntimeHelper.classClusterReflectionFromMirrorType(_reflect(NSSet.self)).summary) == "NSSet"
expect(RuntimeHelper.classClusterReflectionFromMirrorType(RuntimeHelper.mirrorFromModel(NSSet())).summary) == "NSSet"
expect(RuntimeHelper.classClusterReflectionFromMirrorType(RuntimeHelper.mirrorFromModel(NSMutableSet(array: [1,2,3]))).summary) == "NSSet"
}
func testClassClusterNSOrderedSet()
{
expect(RuntimeHelper.classClusterReflectionFromMirrorType(_reflect(NSOrderedSet.self)).summary) == "NSOrderedSet"
expect(RuntimeHelper.classClusterReflectionFromMirrorType(RuntimeHelper.mirrorFromModel(NSOrderedSet())).summary) == "NSOrderedSet"
expect(RuntimeHelper.classClusterReflectionFromMirrorType(RuntimeHelper.mirrorFromModel(NSMutableOrderedSet(array: [1,2,3]))).summary) == "NSOrderedSet"
}
func testClassClusterNSDate()
{
expect(RuntimeHelper.classClusterReflectionFromMirrorType(_reflect(NSDate.self)).summary) == "NSDate"
expect(RuntimeHelper.classClusterReflectionFromMirrorType(RuntimeHelper.mirrorFromModel(NSDate())).summary) == "NSDate"
expect(RuntimeHelper.classClusterReflectionFromMirrorType(RuntimeHelper.mirrorFromModel(NSDate(timeIntervalSince1970: 500))).summary) == "NSDate"
}
func testClassClusterNSString()
{
expect(RuntimeHelper.classClusterReflectionFromMirrorType(_reflect(NSString.self)).summary) == "NSString"
expect(RuntimeHelper.classClusterReflectionFromMirrorType(RuntimeHelper.mirrorFromModel("" as NSString)).summary) == "NSString"
expect(RuntimeHelper.classClusterReflectionFromMirrorType(RuntimeHelper.mirrorFromModel(NSString(string: "foo"))).summary) == "NSString"
expect(RuntimeHelper.classClusterReflectionFromMirrorType(RuntimeHelper.mirrorFromModel(NSMutableString(string: "foo"))).summary) == "NSString"
}
func testSimpleModelIntrospection()
{
expect(RuntimeHelper.classClusterReflectionFromMirrorType(_reflect(Int.self)).summary) == "Swift.Int"
expect(RuntimeHelper.classClusterReflectionFromMirrorType(RuntimeHelper.mirrorFromModel(5)).summary) == "Swift.Int"
}
func testClassClusterNSAttributedString()
{
expect(RuntimeHelper.classClusterReflectionFromMirrorType(_reflect(NSAttributedString.self)).summary) == "NSAttributedString"
expect(RuntimeHelper.classClusterReflectionFromMirrorType(RuntimeHelper.mirrorFromModel(NSAttributedString())).summary) == "NSAttributedString"
expect(RuntimeHelper.classClusterReflectionFromMirrorType(RuntimeHelper.mirrorFromModel(NSAttributedString(string: "foo"))).summary) == "NSAttributedString"
expect(RuntimeHelper.classClusterReflectionFromMirrorType(RuntimeHelper.mirrorFromModel(NSMutableAttributedString(string: "foo"))).summary) == "NSAttributedString"
}
// func testRuntimeHelperCorrectlyGetsNSManagedObjectRepresentation()
// {
// expect(RuntimeHelper.classNameFromReflection(_reflect(ManagedClass))) == "ManagedClass"
// let context = NSManagedObjectContext()
// let entityDescription = NSEntityDescription.entityForName("Foo", inManagedObjectContext: context)
//
// let instance = NSManagedObject(entity: entityDescription!, insertIntoManagedObjectContext: nil)
//
// expect(RuntimeHelper.mirrorFromModel(instance).summary) == "ManagedClass"
// }
}
| mit | 8ca47d90effd634eaa0194037cef1a37 | 55.432203 | 172 | 0.760174 | 4.828861 | false | true | false | false |
ahmad-raza/QDStepsController | Example/QDStepsController/StepFourViewController.swift | 1 | 1432 | //
// DetailsViewController.swift
// CarCares
//
// Created by Ahmad Raza on 12/3/15.
// Copyright © 2015 Ahmad Raza. All rights reserved.
//
import UIKit
import QDStepsController
class StepFourViewController: QDStepViewController {
@IBOutlet weak var endButton: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
setStepNumber(3)
let image : UIImage = UIImage(named: "logo.png")!
let imageView = UIImageView(frame: CGRect(x: 0, y: 0, width: 40, height: 35))
imageView.contentMode = .ScaleAspectFit
imageView.image = image
self.navigationItem.titleView = imageView
endButton.layer.cornerRadius = 5.0
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
@IBAction func onNextClicked(sender: AnyObject) {
}
}
| mit | b50f15d904f7a823210ebf3bbd872cd5 | 26 | 106 | 0.654787 | 4.850847 | false | false | false | false |
bkmunar/firefox-ios | Client/Frontend/Widgets/Toolbar.swift | 1 | 2828 | import Foundation
import SnapKit
class Toolbar : UIView {
var drawTopBorder = false
var drawBottomBorder = false
var drawSeperators = false
override init(frame: CGRect) {
super.init(frame: frame)
self.backgroundColor = UIColor.clearColor()
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
private func drawLine(context: CGContextRef, start: CGPoint, end: CGPoint) {
CGContextSetStrokeColorWithColor(context, AppConstants.BorderColor.CGColor)
CGContextSetLineWidth(context, 1)
CGContextMoveToPoint(context, start.x, start.y)
CGContextAddLineToPoint(context, end.x, end.y)
CGContextStrokePath(context)
}
override func drawRect(rect: CGRect) {
let context = UIGraphicsGetCurrentContext()
if drawTopBorder {
drawLine(context, start: CGPoint(x: 0, y: 0), end: CGPoint(x: frame.width, y: 0))
}
if drawBottomBorder {
drawLine(context, start: CGPoint(x: 0, y: frame.height), end: CGPoint(x: frame.width, y: frame.height))
}
if drawSeperators {
var skippedFirst = false
for view in subviews {
if let view = view as? UIView {
if skippedFirst {
let frame = view.frame
drawLine(context,
start: CGPoint(x: frame.origin.x, y: frame.origin.y),
end: CGPoint(x: frame.origin.x, y: frame.origin.y + view.frame.height))
} else {
skippedFirst = true
}
}
}
}
}
func addButtons(buttons: UIButton...) {
for button in buttons {
button.setTitleColor(UIColor.blackColor(), forState: UIControlState.Normal)
button.setTitleColor(UIColor.grayColor(), forState: UIControlState.Disabled)
button.imageView?.contentMode = UIViewContentMode.ScaleAspectFit
addSubview(button)
}
}
override func updateConstraints() {
var prev: UIView? = nil
for view in self.subviews {
if let view = view as? UIView {
view.snp_remakeConstraints { make in
if let prev = prev {
make.left.equalTo(prev.snp_right)
} else {
make.left.equalTo(self)
}
prev = view
make.centerY.equalTo(self)
make.height.equalTo(AppConstants.ToolbarHeight)
make.width.equalTo(self).dividedBy(self.subviews.count)
}
}
}
super.updateConstraints()
}
} | mpl-2.0 | f0cb981f92ef5b3bdce1ded55df4765b | 33.5 | 115 | 0.548444 | 5.0681 | false | false | false | false |
practicalswift/swift | test/SILGen/keypaths_objc.swift | 4 | 3288 | // RUN: %target-swift-emit-silgen(mock-sdk: %clang-importer-sdk) -import-objc-header %S/Inputs/keypaths_objc.h %s | %FileCheck %s
// RUN: %target-swift-emit-ir(mock-sdk: %clang-importer-sdk) -import-objc-header %S/Inputs/keypaths_objc.h %s
// REQUIRES: objc_interop
import Foundation
struct NonObjC {
var x: Int
var y: NSObject
}
class Foo: NSObject {
@objc var int: Int { fatalError() }
@objc var bar: Bar { fatalError() }
var nonobjc: NonObjC { fatalError() }
@objc(thisIsADifferentName) var differentName: Bar { fatalError() }
@objc subscript(x: Int) -> Foo { return self }
@objc subscript(x: Bar) -> Foo { return self }
@objc dynamic var dyn: String { fatalError() }
}
class Bar: NSObject {
@objc var foo: Foo { fatalError() }
}
// CHECK-LABEL: sil hidden [ossa] @$s13keypaths_objc0B8KeypathsyyF
func objcKeypaths() {
// CHECK: keypath $WritableKeyPath<NonObjC, Int>, (root
_ = \NonObjC.x
// CHECK: keypath $WritableKeyPath<NonObjC, NSObject>, (root
_ = \NonObjC.y
// CHECK: keypath $KeyPath<Foo, Int>, (objc "int"
_ = \Foo.int
// CHECK: keypath $KeyPath<Foo, Bar>, (objc "bar"
_ = \Foo.bar
// CHECK: keypath $KeyPath<Foo, Foo>, (objc "bar.foo"
_ = \Foo.bar.foo
// CHECK: keypath $KeyPath<Foo, Bar>, (objc "bar.foo.bar"
_ = \Foo.bar.foo.bar
// CHECK: keypath $KeyPath<Foo, NonObjC>, (root
_ = \Foo.nonobjc
// CHECK: keypath $KeyPath<Foo, NSObject>, (root
_ = \Foo.bar.foo.nonobjc.y
// CHECK: keypath $KeyPath<Foo, Bar>, (objc "thisIsADifferentName"
_ = \Foo.differentName
}
// CHECK-LABEL: sil hidden [ossa] @$s13keypaths_objc0B18KeypathIdentifiersyyF
func objcKeypathIdentifiers() {
// CHECK: keypath $KeyPath<ObjCFoo, String>, (objc "objcProp"; {{.*}} id #ObjCFoo.objcProp!getter.1.foreign
_ = \ObjCFoo.objcProp
// CHECK: keypath $KeyPath<Foo, String>, (objc "dyn"; {{.*}} id #Foo.dyn!getter.1.foreign
_ = \Foo.dyn
// CHECK: keypath $KeyPath<Foo, Int>, (objc "int"; {{.*}} id #Foo.int!getter.1 :
_ = \Foo.int
}
struct X {}
extension NSObject {
var x: X { return X() }
@objc var objc: Int { return 0 }
@objc dynamic var dynamic: Int { return 0 }
}
// CHECK-LABEL: sil hidden [ossa] @{{.*}}nonobjcExtensionOfObjCClass
func nonobjcExtensionOfObjCClass() {
// Should be treated as a statically-dispatch property
// CHECK: keypath $KeyPath<NSObject, X>, ({{.*}} id @
_ = \NSObject.x
// CHECK: keypath $KeyPath<NSObject, Int>, ({{.*}} id #NSObject.objc!getter.1.foreign
_ = \NSObject.objc
// CHECK: keypath $KeyPath<NSObject, Int>, ({{.*}} id #NSObject.dynamic!getter.1.foreign
_ = \NSObject.dynamic
}
@objc protocol ObjCProto {
var objcRequirement: Int { get set }
}
// CHECK-LABEL: sil hidden [ossa] @{{.*}}ProtocolRequirement
func objcProtocolRequirement<T: ObjCProto>(_: T) {
// CHECK: keypath {{.*}} id #ObjCProto.objcRequirement!getter.1.foreign
_ = \T.objcRequirement
// CHECK: keypath {{.*}} id #ObjCProto.objcRequirement!getter.1.foreign
_ = \ObjCProto.objcRequirement
}
// CHECK-LABEL: sil hidden [ossa] @{{.*}}externalObjCProperty
func externalObjCProperty() {
// Pure ObjC-dispatched properties do not have external descriptors.
// CHECK: keypath $KeyPath<NSObject, String>,
// CHECK-NOT: external #NSObject.description
_ = \NSObject.description
}
| apache-2.0 | 29aaf4365eaf23889efef26e3a546ca7 | 32.55102 | 129 | 0.666058 | 3.37577 | false | false | false | false |
jhurliman/NeuralSwift | NeuralSwift/NeuralSwift/DataLoader/BinaryDataScanner.swift | 1 | 2523 | //
// BinaryDataScanner.swift
// Murphy
//
// Created by Dave Peck on 7/20/14.
// Copyright (c) 2014 Dave Peck. All rights reserved.
//
import Foundation
protocol BinaryReadable {
var littleEndian: Self { get }
var bigEndian: Self { get }
}
extension UInt8: BinaryReadable {
var littleEndian: UInt8 { return self }
var bigEndian: UInt8 { return self }
}
extension UInt16: BinaryReadable {}
extension UInt32: BinaryReadable {}
extension UInt64: BinaryReadable {}
class BinaryDataScanner {
let data: NSData
let littleEndian: Bool
let encoding: NSStringEncoding
var current: UnsafePointer<Void>
var remaining: Int
init(data: NSData, littleEndian: Bool, encoding: NSStringEncoding) {
self.data = data
self.littleEndian = littleEndian
self.encoding = encoding
self.current = self.data.bytes
self.remaining = self.data.length
}
func read<T: BinaryReadable>() -> T? {
if remaining < sizeof(T) {
return nil
}
let tCurrent = UnsafePointer<T>(current)
let v = tCurrent.memory
current = UnsafePointer<Void>(tCurrent.successor())
remaining -= sizeof(T)
return littleEndian ? v.littleEndian : v.bigEndian
}
/* convenience read funcs */
func readByte() -> UInt8? {
return read()
}
func read16() -> UInt16? {
return read()
}
func read32() -> UInt32? {
return read()
}
func read64() -> UInt64? {
return read()
}
func readNullTerminatedString() -> String? {
var string:String? = nil
var tCurrent = UnsafePointer<UInt8>(current)
var count: Int = 0
// scan
while (remaining > 0 && tCurrent.memory != 0) {
remaining -= 1
count += 1
tCurrent = tCurrent.successor()
}
// create string if available
if (remaining > 0 && tCurrent.memory == 0) {
if let nsString = NSString(bytes: current, length: count, encoding: encoding) {
string = nsString as String
current = UnsafePointer<()>(tCurrent.successor())
remaining -= 1
}
}
return string
}
func readData(length: Int) -> NSData? {
if length > remaining { return nil }
remaining -= length
return NSData(bytes: current, length: length)
}
}
| mit | 2c33866babe828c277e5e41e2aecf321 | 23.495146 | 91 | 0.564407 | 4.48135 | false | false | false | false |
googlearchive/science-journal-ios | ScienceJournal/UI/ClaimExperimentsView.swift | 1 | 7369 | /*
* 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 UIKit
import third_party_objective_c_material_components_ios_components_Buttons_Buttons
import third_party_objective_c_material_components_ios_components_Palettes_Palettes
import third_party_objective_c_material_components_ios_components_Typography_Typography
protocol ClaimExperimentsViewDelegate: class {
/// Tells the delegate the user pressed the claim experiments button.
func claimExperimentsViewDidPressClaimExperiments()
}
/// A view used to show a button that allows a user to claim experiments that don't belong to an
/// account.
class ClaimExperimentsView: UIView {
// MARK: - Properties
weak var delegate: ClaimExperimentsViewDelegate?
enum Metrics {
/// The height of the claim experiments view.
static let height: CGFloat = 180
/// The maximum width to use for the claim experiments view.
static let maxWidth: CGFloat = 400
fileprivate static let backgroundColor = UIColor.white
fileprivate static let shadowInsets = UIEdgeInsets(top: -2, left: -4, bottom: -6, right: -4)
fileprivate static let cornerRadius: CGFloat = 2
fileprivate static let imageViewDimension: CGFloat = 96
fileprivate static let contentOuterSideBuffer: CGFloat = 16
fileprivate static let imageViewTopBuffer: CGFloat = 16
fileprivate static let titleLabelTopBuffer: CGFloat = 32
fileprivate static let descriptionLabelTopBuffer: CGFloat = 16
fileprivate static let claimButtonSideBuffer: CGFloat = 8
fileprivate static let claimButtonTopBuffer: CGFloat = 16
}
private let imageView = UIImageView(image: UIImage(named: "claim_header"))
private let titleLabel = UILabel()
private let descriptionLabel = UILabel()
private let claimButton = MDCFlatButton()
private let shadow = UIImageView(image: UIImage(named: "shadow_layer_white"))
// MARK: - Public
override init(frame: CGRect) {
super.init(frame: frame)
configureView()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
configureView()
}
override func layoutSubviews() {
super.layoutSubviews()
// Shadow
shadow.frame =
CGRect(x: Metrics.shadowInsets.left,
y: Metrics.shadowInsets.top,
width: bounds.width - Metrics.shadowInsets.left - Metrics.shadowInsets.right,
height: bounds.height - Metrics.shadowInsets.top - Metrics.shadowInsets.bottom)
// Image view
imageView.frame = CGRect(x: Metrics.contentOuterSideBuffer,
y: Metrics.imageViewTopBuffer,
width: Metrics.imageViewDimension,
height: Metrics.imageViewDimension)
// Labels
let labelWidth = bounds.maxX - imageView.frame.maxX - Metrics.contentOuterSideBuffer * 2
// Title
titleLabel.frame = CGRect(x: imageView.frame.maxX + Metrics.contentOuterSideBuffer,
y: Metrics.titleLabelTopBuffer,
width: labelWidth,
height: 0)
titleLabel.sizeToFit()
// Description
descriptionLabel.frame = CGRect(x: titleLabel.frame.minX,
y: titleLabel.frame.maxY + Metrics.descriptionLabelTopBuffer,
width: labelWidth,
height: 0)
descriptionLabel.sizeToFit()
// Claim button
claimButton.sizeToFit()
claimButton.frame = CGRect(x: Metrics.claimButtonSideBuffer,
y: imageView.frame.maxY + Metrics.claimButtonTopBuffer,
width: claimButton.frame.width,
height: claimButton.frame.height)
[imageView, titleLabel, descriptionLabel, claimButton].forEach {
$0.adjustFrameForLayoutDirection()
}
}
override var intrinsicContentSize: CGSize {
return CGSize(width: UIView.noIntrinsicMetric, height: Metrics.height)
}
/// Sets the number of unclaimed experiments to display.
///
/// - Parameter number: The number of unclaimed experiments.
func setNumberOfUnclaimedExperiments(_ number: Int) {
if number == 1 {
descriptionLabel.text = String.claimExperimentsDescriptionWithCountOne
} else {
descriptionLabel.text = String(format: String.claimExperimentsDescriptionWithCount, number)
}
setNeedsLayout()
}
// MARK: - Private
private func configureView() {
backgroundColor = Metrics.backgroundColor
layer.cornerRadius = Metrics.cornerRadius
// Shadow
addSubview(shadow)
// Image view
addSubview(imageView)
// Title label
titleLabel.font = MDCTypography.body2Font()
titleLabel.numberOfLines = 2
titleLabel.text = String.claimExperimentsTitle
addSubview(titleLabel)
// Description label
descriptionLabel.font = MDCTypography.captionFont()
descriptionLabel.numberOfLines = 3
addSubview(descriptionLabel)
// Claim button
claimButton.addTarget(self,
action: #selector(claimButtonPressed),
for: .touchUpInside)
claimButton.setTitle(String.claimExperimentsButtonTitle, for: .normal)
claimButton.setTitleColor(MDCPalette.blue.tint500, for: .normal)
addSubview(claimButton)
}
// MARK: - User actions
@objc func claimButtonPressed() {
delegate?.claimExperimentsViewDidPressClaimExperiments()
}
}
/// The claim experiments view wrapped in a UICollectionReusableView, so it can be displayed as a
/// collection view header without being full width.
class ClaimExperimentsHeaderView: UICollectionReusableView {
// MARK: - Properties
/// The claim experiments view.
let claimExperimentsView = ClaimExperimentsView()
enum Metrics {
/// The height of the claim experiments header view.
static let height = ClaimExperimentsView.Metrics.height + topBuffer
fileprivate static let sideBuffer: CGFloat = 16
fileprivate static let topBuffer: CGFloat = 16
}
// MARK: - Public
override init(frame: CGRect) {
super.init(frame: frame)
configureView()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
configureView()
}
override func layoutSubviews() {
super.layoutSubviews()
let width = min(bounds.width - Metrics.sideBuffer * 2, ClaimExperimentsView.Metrics.maxWidth)
claimExperimentsView.frame = CGRect(x: ceil((bounds.width - width) / 2),
y: Metrics.topBuffer,
width: width,
height: ClaimExperimentsView.Metrics.height)
}
// MARK: - Private
private func configureView() {
addSubview(claimExperimentsView)
}
}
| apache-2.0 | e2cf0280f080628c4bb7cdcfec3eab78 | 32.495455 | 97 | 0.679604 | 4.841656 | false | false | false | false |
Tj3n/TVNExtensions | UIKit/UIActivityIndicatorView.swift | 1 | 3464 | //
// UIActivityIndicatorViewExtension.swift
// MerchantDashboard
//
// Created by Tien Nhat Vu on 6/10/16.
// Copyright © 2016 Tien Nhat Vu. All rights reserved.
//
import Foundation
import UIKit
extension UIActivityIndicatorView {
private static let tvnIndicatorTag = 38383
/// Show custom loader in view, keep the instance to stop the loading view
///
/// - Parameter view: view to show loader above
/// - Returns: A custom UIActivityIndicatorView
public class func showInView(_ view: UIView, withBackground: Bool = true) -> UIActivityIndicatorView {
let activityIndicator: UIActivityIndicatorView
if #available(iOS 13.0, *) {
activityIndicator = UIActivityIndicatorView(style: .large)
} else {
activityIndicator = UIActivityIndicatorView(style: withBackground ? .whiteLarge : .gray)
}
activityIndicator.backgroundColor = withBackground ? UIColor(white: 0.0, alpha: 0.4) : .clear
activityIndicator.layer.cornerRadius = 30.0
activityIndicator.startAnimating()
activityIndicator.center = CGPoint(x: view.bounds.size.width / 2, y: view.bounds.size.height / 2)
activityIndicator.translatesAutoresizingMaskIntoConstraints = false
activityIndicator.alpha = 0.0
activityIndicator.tag = Int.random(between: tvnIndicatorTag * 100, and: tvnIndicatorTag * 100 + 99)
view.addSubview(activityIndicator)
view.bringSubviewToFront(activityIndicator)
view.isUserInteractionEnabled = false
view.addConstraint(NSLayoutConstraint(item: activityIndicator, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1.0, constant: 100.0))
view.addConstraint(NSLayoutConstraint(item: activityIndicator, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1.0, constant: 100.0))
view.addConstraint(NSLayoutConstraint(item: activityIndicator, attribute: .centerX, relatedBy: .equal, toItem: view, attribute: .centerX, multiplier: 1.0, constant: 0.0))
view.addConstraint(NSLayoutConstraint(item: activityIndicator, attribute: .centerY, relatedBy: .equal, toItem: view, attribute: .centerY, multiplier: 1.0, constant: 0.0))
activityIndicator.transform = CGAffineTransform(scaleX: 0.7, y: 0.7)
UIView.animate(withDuration: 0.2, animations: {() -> Void in
activityIndicator.alpha = 1.0
activityIndicator.transform = CGAffineTransform(scaleX: 1.2, y: 1.2)
}, completion: {(finished: Bool) -> Void in
UIView.animate(withDuration: 0.1, animations: {() -> Void in
activityIndicator.transform = CGAffineTransform(scaleX: 1.0, y: 1.0)
})
})
return activityIndicator
}
public func end(completion: (() -> ())? = nil) {
guard self.tag / 100 == UIActivityIndicatorView.tvnIndicatorTag else { return }
self.superview?.isUserInteractionEnabled = true
let center: CGPoint = self.center
UIView.animate(withDuration: 0.2, animations: {() -> Void in
self.alpha = 0.0
self.transform = CGAffineTransform(scaleX: 0.7, y: 0.7)
self.center = center
}, completion: {(finished: Bool) -> Void in
self.removeFromSuperview()
completion?()
})
}
}
| mit | a8ebd141e94185f466316ab4f1b1a1b4 | 48.471429 | 185 | 0.661565 | 4.789765 | false | false | false | false |
vikmeup/MDCSwipeToChoose | Examples/SwiftLikedOrNope/SwiftLikedOrNope/ImageLabelView.swift | 1 | 2425 | //
// ImageLabelView.swift
// SwiftLikedOrNope
//
// Copyright (c) 2014 to present, Richard Burdish @rjburdish
//
// 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 ImagelabelView: UIView{
var imageView: UIImageView!
var label: UILabel!
override init(){
super.init()
imageView = UIImageView()
label = UILabel()
}
init(frame: CGRect, image: UIImage, text: NSString) {
super.init(frame: frame)
constructImageView(image)
constructLabel(text)
}
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
func constructImageView(image:UIImage) -> Void{
let topPadding:CGFloat = 10.0
let framex = CGRectMake(floor((CGRectGetWidth(self.bounds) - image.size.width)/2),
topPadding,
image.size.width,
image.size.height)
imageView = UIImageView(frame: framex)
imageView.image = image
addSubview(self.imageView)
}
func constructLabel(text:NSString) -> Void{
var height:CGFloat = 18.0
let frame2 = CGRectMake(0,
CGRectGetMaxY(self.imageView.frame),
CGRectGetWidth(self.bounds),
height);
self.label = UILabel(frame: frame2)
label.text = text
addSubview(label)
}
} | mit | 11e9860193180074ee2e7cbdfcd6311c | 32.232877 | 90 | 0.664742 | 4.541199 | false | false | false | false |
ppraveentr/MobileCore | Tests/CoreComponentsTests/TableViewControllerProtocolTests.swift | 1 | 3275 | //
// TableViewControllerProtocolTests.swift
// MobileCoreTests
//
// Created by Praveen P on 07/10/19.
// Copyright © 2019 Praveen Prabhakar. All rights reserved.
//
#if canImport(CoreComponents)
import CoreComponents
import CoreUtility
#endif
import XCTest
fileprivate final class MockTableViewHeader: UIView {
// Temp class extending Protocol for testing
}
fileprivate final class MockTableViewController: UIViewController, TableViewControllerProtocol {
// Temp class extending Protocol for testing
}
fileprivate final class MockCustomTableViewController: UIViewController, TableViewControllerProtocol {
var tableStyle: UITableView.Style = .grouped
var tableViewEdgeOffsets: UIEdgeInsets = .init(40, 40, 40, 40)
}
final class TableViewControllerProtocolTests: XCTestCase {
private var tableViewC: MockCustomTableViewController?
private var oldRootVC: UIViewController?
override func setUp() {
super.setUp()
oldRootVC = UIApplication.shared.keyWindow?.rootViewController
tableViewC = MockCustomTableViewController()
UIApplication.shared.keyWindow?.rootViewController = tableViewC
}
override func tearDown() {
super.tearDown()
UIApplication.shared.keyWindow?.rootViewController = oldRootVC
}
func testTableViewController() {
XCTAssertNotNil(tableViewC)
XCTAssertNotNil(tableViewC?.tableView)
XCTAssertEqual(tableViewC?.tableViewController, tableViewC?.tableViewController)
XCTAssertEqual(tableViewC?.tableStyle, UITableView.Style.grouped)
XCTAssertEqual(tableViewC?.tableViewEdgeOffsets, UIEdgeInsets(40, 40, 40, 40))
}
func testDefaultTableViewC() {
let defaultTableV = MockTableViewController()
XCTAssertNotNil(defaultTableV)
XCTAssertEqual(defaultTableV.tableStyle, UITableView.Style.plain)
XCTAssertEqual(defaultTableV.tableViewEdgeOffsets, UIEdgeInsets.zero)
}
func testSsetupTableController() {
let defaultTableV = MockTableViewController()
XCTAssertNotNil(defaultTableV.tableViewController)
let controller = defaultTableV.getCoreTableViewController()
defaultTableV.tableViewController = controller
XCTAssertEqual(defaultTableV.tableViewController, controller)
}
func testTableHeaderView() {
let headerView = MockTableViewHeader()
XCTAssertNotNil(headerView)
tableViewC?.tableView.setTableHeaderView(view: headerView)
let tableHeaderView = tableViewC?.tableView.tableHeaderView
XCTAssertNotNil(tableHeaderView)
}
func testTableFooterView() {
let footerView = MockTableViewHeader()
XCTAssertNotNil(footerView)
tableViewC?.tableView.setTableFooterView(view: footerView)
let tableFooterView = tableViewC?.tableView.tableFooterView
XCTAssertNotNil(tableFooterView)
}
func testTableHeaderFooterView() {
let defaultTableV = MockTableViewController()
let headerView = UIView()
defaultTableV.tableView.setTableHeaderView(view: headerView)
let tableHeaderView = defaultTableV.tableView.tableHeaderView
XCTAssertNotNil(tableHeaderView)
}
}
| mit | 04b5625c06e78d641eb27cba48347244 | 34.204301 | 102 | 0.73091 | 5.577513 | false | true | false | false |
scymen/sockettool | sockettool/sockettool/ViewController.swift | 1 | 8225 | //
// ViewController.swift
// sockettool
//
// Created by Abu on 16/7/3.
// Copyright © 2016年 sockettool. All rights reserved.
//
import Cocoa
import Foundation
import SocksCore
import Socks
class ViewController: NSViewController ,SocketDelegate{
let txt_cnn : String = "Connect"
let txt_listen : String = "Listen"
let txt_stop : String = "Stop"
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
if outlet_radio_clientmodel.state == 1 {
outlet_btn_ok.title = txt_cnn
}
showMsg(str:"Ready",clearFirstly: true)
outlet_tableview.delegate = self
outlet_tableview.dataSource = self
// outlet_tableview.target = self
// outlet_tableview.doubleAction = Selector(("tableViewDoubleClick"))
// let descriptorIP = SortDescriptor(key: "ip", ascending: true)
// let descriptorPort = SortDescriptor(key: "port", ascending: true)
// let descriptorStatus = SortDescriptor(key: "status", ascending: true)
//
// outlet_tableview.tableColumns[0].sortDescriptorPrototype = descriptorIP;
// outlet_tableview.tableColumns[1].sortDescriptorPrototype = descriptorPort;
// outlet_tableview.tableColumns[2].sortDescriptorPrototype = descriptorStatus;
th.socketDelegate = self
}
override var representedObject: AnyObject? {
didSet {
// Update the view, if already loaded.
}
}
@IBOutlet weak var outlet_tableview: NSTableView!
@IBOutlet weak var outlet_txt_port: NSTextField!
@IBOutlet weak var outlet_txt_ip: NSTextField!
@IBOutlet weak var outlet_radio_servermodel: NSButton!
@IBOutlet weak var outlet_radio_clientmodel: NSButton!
@IBOutlet weak var outlet_btn_ok: NSButton!
@IBOutlet weak var outlet_checkbox_hex: NSButton!
@IBOutlet weak var outlet_checkbox_echo: NSButton!
@IBOutlet weak var outlet_combo_echo_ms: NSComboBoxCell!
@IBOutlet weak var outlet_btn_send: NSButton!
@IBOutlet weak var outlet_btn_clear: NSButton!
@IBOutlet var outlet_textview: NSTextView!
@IBOutlet weak var outlet_txt_send: NSTextField!
// delegate
func action(conn: Connection ){
//http://stackoverflow.com/questions/37805885/how-to-create-dispatch-queue-in-swift-3
DispatchQueue.main.async {
// switch conn.status {
// case .close,.new,.connecting:
// self.outlet_tableview.reloadData()
// case .send,.receive:
//
// self.outlet_tableview.reloadData(forRowIndexes: <#T##IndexSet#>, columnIndexes: <#T##IndexSet#>)
// }
self.outlet_tableview.reloadData()
if self.outlet_checkbox_hex.state == 1 {
self.showMsg(str: "\(conn)")
} else {
self.showMsg(str: "\( conn.toStringWithASCIIs())")
}
}
}
// delegate
func action(msg:String) {
DispatchQueue.main.async {
self.showMsg(str: msg)
}
}
// delegate
func setButtonEnable(id:String,enable:Bool) {
if id == "btnOK" {
outlet_btn_ok.isEnabled = true
if enable {
// endable editing
outlet_txt_port.isEnabled = true
outlet_txt_ip.isEnabled = true
outlet_radio_clientmodel.isEnabled = true
outlet_radio_servermodel.isEnabled = true
if Paras.isClientMode {
outlet_btn_ok.title = txt_cnn
}else {
outlet_btn_ok.title = txt_listen
}
} else {
// disable editing
outlet_txt_port.isEnabled = false
outlet_txt_ip.isEnabled = false
outlet_radio_clientmodel.isEnabled = false
outlet_radio_servermodel.isEnabled = false
outlet_btn_ok.title = txt_stop
}
}
}
@IBAction func action_btn_send(_ sender: AnyObject) {
guard outlet_txt_send.stringValue.characters.count > 0 else { return }
if Paras.isClientMode {
th.send(b: getMsg2send())
} else {
let indexSet = outlet_tableview.selectedRowIndexes
if indexSet.count == 0 {
let de = th.socketList.first?.value.descriptor
th.send(descriptor: de! , b: getMsg2send())
} else {
var d :[Descriptor] = []
for i in indexSet.enumerated() {
let v = outlet_tableview.view(atColumn: 0, row: i.element, makeIfNecessary: false)
let cellview = v as! NSTableCellView
let ob = cellview.objectValue as! Int
d.append(Descriptor( ob))
}
print("-->> index set = \(indexSet) , descriptor = \(d)")
th.send(descriptor:d, b: getMsg2send())
}
}
}
func getMsg2send() -> [UInt8] {
var b:[UInt8] = []
if outlet_checkbox_hex.state == 1 {
let hex = outlet_txt_send.stringValue.replacingOccurrences(of: " ", with: "")
if hex.isHex() {
b = try! hex.hex2Byte()
} else {
showMsg(str: "Not a hex string")
}
} else {
b = outlet_txt_send.stringValue.toBytes()
}
return b
}
func showMsg(str:String,clearFirstly:Bool = false,newLine:Bool = true) {
let a : String = clearFirstly ? "":self.outlet_textview.string!
self.outlet_textview.string = a + "[\(Date().toString(fmt: "HH:mm:ss.SSS"))] \(str)"
+ (newLine ? "\r" :"")
}
@IBAction func action_btn_clear(_ sender: AnyObject) {
showMsg(str: "Clear",clearFirstly: true)
}
@IBAction func action_radSelected(_ sender: AnyObject) {
let btn = sender as! NSButton
if btn == outlet_radio_clientmodel {
outlet_btn_ok.title = txt_cnn
}else {
outlet_btn_ok.title = txt_listen
}
}
var th : MySocket = MySocket()
@IBAction func action_btnOK(_ sender: AnyObject) {
if !th.isWorking {
Paras.IP = outlet_txt_ip.stringValue
Paras.port = outlet_txt_port.stringValue
if outlet_radio_clientmodel.state == NSOnState {
Paras.isClientMode = true
} else {
Paras.isClientMode = false
}
if !Paras.validate(){
let a = NSAlert()
a.messageText = "Error"
a.informativeText = "IP or Port invalidated"
a.addButton(withTitle: "OK")
// a.addButton(withTitle: "Cancel")
a.alertStyle = NSAlertStyle.warning
a.beginSheetModal(for: self.view.window!, completionHandler: { (modalResponse) -> Void in
if modalResponse == NSAlertFirstButtonReturn {
NSLog(a.informativeText)
}
})
return
}
// disable editing
setButtonEnable(id: "btnOK", enable: false)
outlet_btn_ok.isEnabled = false
th.start2Work()
} else { //stop working
th.stopWorking()
setButtonEnable(id: "btnOK", enable: true)
}
}
}
| lgpl-3.0 | 6ce3dd9e65e60a3dd486db426e415c7f | 30.381679 | 126 | 0.506324 | 4.791375 | false | false | false | false |
austinzheng/swift-compiler-crashes | crashes-duplicates/07808-swift-constraints-constraintsystem-opengeneric.swift | 11 | 317 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
class B<T, U, g = c<T where T: d = c<I : A? {
class B<T : T.e : T: NSObject {
func b<T where T where T>
func g<T.B == [Void>
var b = ")
var b = g<T
| mit | 2be050741d0c29f6b9cd6cd92d87be53 | 30.7 | 87 | 0.659306 | 2.935185 | false | true | false | false |
trill-lang/trill | Sources/Sema/SemaError.swift | 2 | 7308 | ///
/// SemaError.swift
///
/// Copyright 2016-2017 the Trill project authors.
/// Licensed under the MIT License.
///
/// Full license text available at https://github.com/trill-lang/trill
///
import AST
import Foundation
enum SemaError: Error, CustomStringConvertible {
case unknownFunction(name: Identifier)
case unknownType(type: DataType)
case unknownProtocol(name: Identifier)
case callNonFunction(type: DataType?)
case unknownProperty(typeDecl: TypeDecl, expr: PropertyRefExpr)
case unknownVariableName(name: Identifier)
case invalidOperands(op: BuiltinOperator, invalid: DataType)
case cannotSubscript(type: DataType)
case cannotCoerce(type: DataType, toType: DataType)
case varArgsInNonForeignDecl
case foreignFunctionWithBody(name: Identifier)
case nonForeignFunctionWithoutBody(name: Identifier)
case foreignVarWithRHS(name: Identifier)
case dereferenceNonPointer(type: DataType)
case cannotSwitch(type: DataType)
case nonPointerNil(type: DataType)
case notAllPathsReturn(type: DataType)
case noViableOverload(name: Identifier, args: [Argument])
case candidates([FuncDecl])
case ambiguousReference(name: Identifier)
case addressOfRValue
case breakNotAllowed
case continueNotAllowed
case caseMustBeConstant
case isCheckAlways(fails: Bool)
case fieldOfFunctionType(type: DataType)
case duplicateMethod(name: Identifier, type: DataType)
case duplicateField(name: Identifier, type: DataType)
case referenceSelfInProp(name: Identifier)
case poundFunctionOutsideFunction
case assignToConstant(name: Identifier?)
case deinitOnStruct(name: Identifier)
case incompleteTypeAccess(type: DataType, operation: String)
case indexIntoNonTuple
case outOfBoundsTupleField(field: Int, max: Int)
case nonMatchingArrayType(DataType, DataType)
case ambiguousType
case operatorsMustHaveTwoArgs(op: BuiltinOperator)
case cannotOverloadOperator(op: BuiltinOperator, type: String)
case typeDoesNotConform(DataType, protocol: DataType)
case missingImplementation(FuncDecl)
case pointerPropertyAccess(lhs: DataType, property: Identifier)
case tuplePropertyAccess(lhs: DataType, property: Identifier)
case stdlibRequired(String)
var description: String {
switch self {
case .unknownFunction(let name):
return "unknown function '\(name)'"
case .unknownType(let type):
return "unknown type '\(type)'"
case .unknownProtocol(let name):
return "unknown protocol '\(name)'"
case .unknownVariableName(let name):
return "unknown variable '\(name)'"
case .unknownProperty(let typeDecl, let expr):
return "unknown property '\(expr.name)' in type '\(typeDecl.type)'"
case .invalidOperands(let op, let invalid):
return "invalid argument for operator '\(op)' (got '\(invalid)')"
case .cannotSubscript(let type):
return "cannot subscript value of type '\(type)'"
case .cannotCoerce(let type, let toType):
return "cannot coerce '\(type)' to '\(toType)'"
case .cannotSwitch(let type):
return "cannot switch over values of type '\(type)'"
case .foreignFunctionWithBody(let name):
return "foreign function '\(name)' cannot have a body"
case .nonForeignFunctionWithoutBody(let name):
return "function '\(name)' must have a body"
case .foreignVarWithRHS(let name):
return "foreign var '\(name)' cannot have a value"
case .varArgsInNonForeignDecl:
return "varargs in non-foreign declarations are not yet supported"
case .nonPointerNil(let type):
return "cannot set non-pointer type '\(type)' to nil"
case .dereferenceNonPointer(let type):
return "cannot dereference a value of non-pointer type '\(type)'"
case .addressOfRValue:
return "cannot get address of an r-value"
case .breakNotAllowed:
return "'break' not allowed outside loop"
case .continueNotAllowed:
return "'continue' not allowed outside loop"
case .notAllPathsReturn(let type):
return "missing return in a function expected to return \(type)"
case .noViableOverload(let name, let args):
var s = "could not find a viable overload for \(name) with arguments of type ("
s += args.map {
var d = ""
if let label = $0.label {
d += "\(label): "
}
d += "\($0.val.type)"
return d
}.joined(separator: ", ")
s += ")"
return s
case .candidates(let functions):
var s = "found candidates with these arguments: "
s += functions.map { $0.formattedParameterList }.joined(separator: ", ")
return s
case .ambiguousReference(let name):
return "ambiguous reference to '\(name)'"
case .callNonFunction(let type):
return "cannot call non-function type '" + (type.map { String(describing: $0) } ?? "<<error type>>") + "'"
case .fieldOfFunctionType(let type):
return "cannot find field on function of type \(type)"
case .duplicateMethod(let name, let type):
return "invalid redeclaration of method '\(name)' on type '\(type)'"
case .duplicateField(let name, let type):
return "invalid redeclaration of field '\(name)' on type '\(type)'"
case .referenceSelfInProp(let name):
return "type '\(name)' cannot have a property that references itself"
case .poundFunctionOutsideFunction:
return "'#function' is only valid inside function scope"
case .deinitOnStruct(let name):
return "cannot have a deinitializer in non-indirect type '\(name)'"
case .assignToConstant(let name):
let val: String
if let n = name {
val = "'\(n)'"
} else {
val = "expression"
}
return "cannot mutate \(val); expression is a 'let' constant"
case .indexIntoNonTuple:
return "cannot index into non-tuple expression"
case .outOfBoundsTupleField(let field, let max):
return "cannot access field \(field) in tuple with \(max) fields"
case .incompleteTypeAccess(let type, let operation):
return "cannot \(operation) incomplete type '\(type)'"
case .nonMatchingArrayType(let arrayType, let elementType):
return "element type '\(elementType)' does not match array type '\(arrayType)'"
case .ambiguousType:
return "type is ambiguous without more context"
case .caseMustBeConstant:
return "case statement expressions must be constants"
case .isCheckAlways(let fails):
return "'is' check always \(fails ? "fails" : "succeeds")"
case .operatorsMustHaveTwoArgs(let op):
return "definition for operator '\(op)' must have two arguments"
case .cannotOverloadOperator(let op, let type):
return "cannot overload \(type) operator '\(op)'"
case .typeDoesNotConform(let typeName, let `protocol`):
return "'\(typeName)' does not conform to protocol '\(`protocol`)'"
case .missingImplementation(let decl):
return "missing implementation for '\(decl.formattedName)'"
case .pointerPropertyAccess(let lhs, let property):
return "cannot access property \(property) of pointer type \(lhs)"
case .tuplePropertyAccess(let lhs, let property):
return "cannot access property \(property) on tuple type \(lhs)"
case .stdlibRequired(let message):
return "the stdlib must be present to \(message)"
}
}
}
| mit | fb945db8b1ab6d6fee3d4255cba3267a | 42.242604 | 112 | 0.699781 | 4.370813 | false | false | false | false |
CoderSLZeng/SLWeiBo | SLWeiBo/SLWeiBo/Classes/Compose/View/ComposeTitleView.swift | 1 | 1577 | //
// ComposeTitleView.swift
// SLWeiBo
//
// Created by Anthony on 17/3/16.
// Copyright © 2017年 SLZeng. All rights reserved.
//
import UIKit
//import SnapKit
class ComposeTitleView: UIView {
// MARK:- 懒加载属性
fileprivate lazy var titleLabel : UILabel = UILabel()
fileprivate lazy var screenNameLabel : UILabel = UILabel()
// MARK:- 构造函数
override init(frame: CGRect) {
super.init(frame: frame)
setupUI()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
// MARK:- 设置UI界面
extension ComposeTitleView {
fileprivate func setupUI() {
// 1.将子控件添加到view中
addSubview(titleLabel)
addSubview(screenNameLabel)
// 2.设置frame
// titleLabel.snp_makeConstraints { (make) -> Void in
// make.centerX.equalTo(self)
// make.top.equalTo(self)
// }
// screenNameLabel.snp_makeConstraints { (make) -> Void in
// make.centerX.equalTo(titleLabel.snp_centerX)
// make.top.equalTo(titleLabel.snp_bottom).offset(3)
// }
// 3.设置空间的属性
titleLabel.font = UIFont.systemFont(ofSize: 16)
screenNameLabel.font = UIFont.systemFont(ofSize: 14)
screenNameLabel.textColor = UIColor.lightGray
// 4.设置文字内容
titleLabel.text = "发微博"
screenNameLabel.text = UserAccountViewModel.shareIntance.account?.screen_name
}
}
| mit | 7362900516d7967ad9fb8dbcdd475554 | 25.714286 | 85 | 0.60762 | 4.274286 | false | false | false | false |
audiokit/AudioKit | Sources/AudioKit/Nodes/Mixing/Fader.swift | 1 | 4629 | // Copyright AudioKit. All Rights Reserved. Revision History at http://github.com/AudioKit/AudioKit/
import AVFoundation
import CAudioKit
/// Stereo Fader.
public class Fader: Node, AudioUnitContainer, Toggleable {
/// Unique four-letter identifier "fder"
public static let ComponentDescription = AudioComponentDescription(effect: "fder")
/// Internal type of audio unit for this node
public typealias AudioUnitType = InternalAU
/// Internal audio unit
public private(set) var internalAU: AudioUnitType?
// MARK: - Parameters
/// Amplification Factor, from 0 ... 4
open var gain: AUValue = 1 {
willSet {
leftGain = newValue
rightGain = newValue
}
}
/// Allow gain to be any non-negative number
public static let gainRange: ClosedRange<AUValue> = 0.0 ... Float.greatestFiniteMagnitude
/// Specification details for left gain
public static let leftGainDef = NodeParameterDef(
identifier: "leftGain",
name: "Left Gain",
address: akGetParameterAddress("FaderParameterLeftGain"),
range: Fader.gainRange,
unit: .linearGain,
flags: .default)
/// Left Channel Amplification Factor
@Parameter public var leftGain: AUValue
/// Specification details for right gain
public static let rightGainDef = NodeParameterDef(
identifier: "rightGain",
name: "Right Gain",
address: akGetParameterAddress("FaderParameterRightGain"),
range: Fader.gainRange,
unit: .linearGain,
flags: .default)
/// Right Channel Amplification Factor
@Parameter public var rightGain: AUValue
/// Amplification Factor in db
public var dB: AUValue {
set { gain = pow(10.0, newValue / 20.0) }
get { return 20.0 * log10(gain) }
}
/// Whether or not to flip left and right channels
public static let flipStereoDef = NodeParameterDef(
identifier: "flipStereo",
name: "Flip Stereo",
address: akGetParameterAddress("FaderParameterFlipStereo"),
range: 0.0 ... 1.0,
unit: .boolean,
flags: .default)
/// Flip left and right signal
@Parameter public var flipStereo: Bool
/// Specification for whether to mix the stereo signal down to mono
public static let mixToMonoDef = NodeParameterDef(
identifier: "mixToMono",
name: "Mix To Mono",
address: akGetParameterAddress("FaderParameterMixToMono"),
range: 0.0 ... 1.0,
unit: .boolean,
flags: .default)
/// Make the output on left and right both be the same combination of incoming left and mixed equally
@Parameter public var mixToMono: Bool
// MARK: - Audio Unit
/// Internal audio unit for fader
public class InternalAU: AudioUnitBase {
/// Get an array of the parameter definitions
/// - Returns: Array of parameter definitions
public override func getParameterDefs() -> [NodeParameterDef] {
[Fader.leftGainDef,
Fader.rightGainDef,
Fader.flipStereoDef,
Fader.mixToMonoDef]
}
/// Create the DSP Refence for this node
/// - Returns: DSP Reference
public override func createDSP() -> DSPRef {
akCreateDSP("FaderDSP")
}
}
// MARK: - Initialization
/// Initialize this fader node
///
/// - Parameters:
/// - input: Node whose output will be amplified
/// - gain: Amplification factor (Default: 1, Minimum: 0)
///
public init(_ input: Node, gain: AUValue = 1) {
super.init(avAudioNode: AVAudioNode())
instantiateAudioUnit { avAudioUnit in
self.avAudioUnit = avAudioUnit
self.avAudioNode = avAudioUnit
self.internalAU = avAudioUnit.auAudioUnit as? AudioUnitType
self.leftGain = gain
self.rightGain = gain
self.flipStereo = false
self.mixToMono = false
}
connections.append(input)
}
deinit {
// Log("* { Fader }")
}
// MARK: - Automation
/// Gain automation helper
/// - Parameters:
/// - events: List of events
/// - startTime: start time
public func automateGain(events: [AutomationEvent], startTime: AVAudioTime? = nil) {
$leftGain.automate(events: events, startTime: startTime)
$rightGain.automate(events: events, startTime: startTime)
}
/// Stop automation
public func stopAutomation() {
$leftGain.stopAutomation()
$rightGain.stopAutomation()
}
}
| mit | d8e579a263556c1be02d21c2c5416d9f | 30.067114 | 105 | 0.628213 | 4.733129 | false | false | false | false |
ChristianKienle/highway | Sources/HighwayCore/Highways/_Highway.swift | 1 | 6825 | import Foundation
import Terminal
import Arguments
infix operator ==>
public enum PrivateHighway {
public static let listPublicHighwaysAsJSON = "listPublicHighwaysAsJSON"
}
public typealias HighwayBody = (Invocation) throws -> Any?
open class _Highway<T: HighwayTypeProtocol> {
// MARK: - Types
public typealias ErrorHandler = (Error) -> ()
public typealias EmptyHandler = () throws -> ()
public typealias UnrecognizedCommandHandler = (_ arguments: Arguments) throws -> ()
// MARK: - Init
public init(_ highwayType: T.Type) throws {
setupHighways()
}
// MARK: - Properties
private var _highways = OrderedDictionary<String, Raw<T>>()
public var descriptions: [HighwayDescription] {
return _highways.values.map { $0.description }
}
public var onError: ErrorHandler?
public var onEmptyCommand: EmptyHandler?
public var onUnrecognizedCommand: UnrecognizedCommandHandler?
public var verbose = false
// MARK: - Subclasses
open func setupHighways() {
}
// MARK: - Adding Highway
public subscript(type: T) -> Raw<T> {
return _highways[type.name, default: Raw(type)]
}
// MARK: Getting Results
public func result<ObjectType>(for highway: T) throws -> ObjectType {
guard let value = _highways[highway.name]?.result as? ObjectType else {
throw "No result or type mismatch for \(ObjectType.self)"
}
return value
}
// MARK: Executing
private func _handle(highway: Raw<T>, with arguments: Arguments) throws {
let dependencies: [Raw<T>] = try highway.dependencies.map { dependency in
guard let result = _highways[dependency] else {
throw "\(highway.name) depends on \(dependency) but no such highway is registered."
}
return result
}
try dependencies.forEach {
try self._handle(highway: $0, with: arguments)
}
do {
let invocation = Invocation(highway: highway.name, arguments: arguments)
try highway.invoke(with: invocation) // Execute and sets the result
} catch {
_reportError(error)
throw error
}
}
/// Calls the error handler with the given error.
/// If no error handler is set the error is logged.
///
/// - Parameter error: An error to be passed to the error handler
private func _reportError(_ error: Error) {
guard let errorHandler = onError else {
Terminal.shared.log("ERROR: \(error.localizedDescription)")
return
}
errorHandler(error)
}
private func _handleEmptyCommandOrReportError() {
guard let emptyHandler = onEmptyCommand else {
_reportError("No empty handler set.")
return
}
do {
try emptyHandler()
} catch {
_reportError(error)
}
}
private func _handleUnrecognizedCommandOrReportError(arguments: Arguments) {
guard let unrecognizedHandler = onUnrecognizedCommand else {
_reportError("Unrecognized command detected. No highway matching \(arguments) found and no unrecognized command handler set.")
return
}
do {
try unrecognizedHandler(arguments)
} catch {
_reportError(error)
}
}
public func go(_ invocationProvider: InvocationProvider = CommandLineInvocationProvider()) {
let invocation = invocationProvider.invocation()
verbose = invocation.verbose
// Empty?
if invocation.representsEmptyInvocation {
_handleEmptyCommandOrReportError()
return
}
// Private
if invocation.highway == PrivateHighway.listPublicHighwaysAsJSON {
try? _listPublicHighwaysAsJSON()
return
}
// Remaining highways
let highwayName = invocation.highway
guard let highway = _highways[highwayName] else {
_handleUnrecognizedCommandOrReportError(arguments: invocation.arguments)
return
}
do {
try _handle(highway: highway, with: invocation.arguments)
} catch {
// Do not rethrow or report the error because _handle did that already
}
}
private func _listPublicHighwaysAsJSON() throws {
let text = try descriptions.jsonString()
Swift.print(text, separator: "", terminator: "\n")
fflush(stdout)
}
public class Raw<T: HighwayTypeProtocol> {
// MARK: - Types
typealias HighwayBody = (Invocation) throws -> Any?
// MARK: - Properties
private let type: T
public var name: String { return type.name }
public var dependencies = [String]()
var body: HighwayBody?
public var result: Any?
public var description: HighwayDescription {
var result = HighwayDescription(name: type.name, usage: type.usage)
result.examples = type.examples
return result
}
// MARK: - Init
init(_ highway: T) {
self.type = highway
}
// MARK: - Setting Bodies
public static func ==> (lhs: Raw, rhs: @escaping () throws -> ()) { lhs.execute(rhs) }
public static func ==> (lhs: Raw, rhs: @escaping () throws -> (Any)) { lhs.execute(rhs) }
public static func ==> (lhs: Raw, rhs: @escaping (Invocation) throws -> (Any?)) { lhs.execute(rhs) }
public static func ==> (lhs: Raw, rhs: @escaping (Invocation) throws -> ()) { lhs.execute(rhs) }
// MARK: - Cast Bodies
public func execute(_ newBody: @escaping () throws -> ()) {
body = { _ in try newBody() }
}
public func execute(_ newBody: @escaping (_ invocation: Invocation) throws -> ()) {
body = {
try newBody($0)
return ()
}
}
public func execute(_ newBody: @escaping (_ invocation: Invocation) throws -> (Any?)) {
body = { try newBody($0) }
}
public func execute(_ newBody: @escaping () throws -> (Any?)) {
body = { _ in try newBody() }
}
// MARK: - Set Dependencies
public func depends(on highways: T...) -> Raw<T> {
_setDependencies(highways)
return self
}
private func _setDependencies(_ highways: [T]) {
dependencies = highways.map { $0.name }
}
// MARK: - Invoke the Highway
func invoke(with invocation: Invocation) throws {
result = try body?(invocation)
}
}
}
| mit | de10fef90f87417e86830905d24df0ae | 32.455882 | 138 | 0.577875 | 4.796205 | false | false | false | false |
steelwheels/Coconut | CoconutData/Source/Value/CNValue.swift | 1 | 10726 | /*
* @file CNValue.swift
* @brief Define CNValue class
* @par Copyright
* Copyright (C) 2017-2021 Steel Wheels Project
*/
#if os(iOS)
import UIKit
#endif
import Foundation
public enum CNValue {
case boolValue(_ val: Bool)
case numberValue(_ val: NSNumber)
case stringValue(_ val: String)
case enumValue(_ val: CNEnum)
case dictionaryValue(_ val: Dictionary<String, CNValue>)
case arrayValue(_ val: Array<CNValue>)
case setValue(_ val: Array<CNValue>) // Sorted in ascending order
case objectValue(_ val: AnyObject)
//case functionValue(_ val: (_ params: Array<CNValue>) -> CNValue)
public var valueType: CNValueType {
get {
let result: CNValueType
switch self {
case .boolValue(_): result = .boolType
case .numberValue(_): result = .numberType
case .stringValue(_): result = .stringType
case .dictionaryValue(_): result = .dictionaryType(.anyType)
case .arrayValue(_): result = .arrayType(.anyType)
case .setValue(_): result = .setType(.anyType)
case .objectValue(let obj):
let name = String(describing: type(of: obj))
result = .objectType(name)
case .enumValue(let eobj):
if let etype = eobj.enumType {
result = .enumType(etype)
} else {
CNLog(logLevel: .error, message: "Failed to get enum type (Can not happen)", atFunction: #function, inFile: #file)
result = .anyType
}
}
return result
}
}
public static var null: CNValue { get {
return CNValue.objectValue(NSNull())
}}
public func toBool() -> Bool? {
let result: Bool?
switch self {
case .boolValue(let val): result = val
default: result = nil
}
return result
}
public func toNumber() -> NSNumber? {
let result: NSNumber?
switch self {
case .numberValue(let obj): result = obj
default: result = nil
}
return result
}
public func toString() -> String? {
let result: String?
switch self {
case .stringValue(let obj): result = obj
default: result = nil
}
return result
}
public func toEnum() -> CNEnum? {
let result: CNEnum?
switch self {
case .enumValue(let eval): result = eval
case .dictionaryValue(let dict): result = CNEnum.fromValue(value: dict)
default: result = nil
}
return result
}
public func toDictionary() -> Dictionary<String, CNValue>? {
let result: Dictionary<String, CNValue>?
switch self {
case .dictionaryValue(let obj): result = obj
default: result = nil
}
return result
}
public func toArray() -> Array<CNValue>? {
let result: Array<CNValue>?
switch self {
case .arrayValue(let obj): result = obj
default: result = nil
}
return result
}
public func toSet() -> Array<CNValue>? {
let result: Array<CNValue>?
switch self {
case .setValue(let obj): result = obj
default: result = nil
}
return result
}
public func toObject() -> AnyObject? {
let result: AnyObject?
switch self {
case .objectValue(let obj): result = obj
default: result = nil
}
return result
}
public func boolProperty(identifier ident: String) -> Bool? {
if let elm = valueProperty(identifier: ident){
return elm.toBool()
} else {
return nil
}
}
public func numberProperty(identifier ident: String) -> NSNumber? {
if let elm = valueProperty(identifier: ident){
return elm.toNumber()
} else {
return nil
}
}
public func stringProperty(identifier ident: String) -> String? {
if let elm = valueProperty(identifier: ident){
return elm.toString()
} else {
return nil
}
}
public func dictionaryProperty(identifier ident: String) -> Dictionary<String, CNValue>? {
if let elm = valueProperty(identifier: ident){
return elm.toDictionary()
} else {
return nil
}
}
public func arrayProperty(identifier ident: String) -> Array<CNValue>? {
if let elm = valueProperty(identifier: ident){
return elm.toArray()
} else {
return nil
}
}
public func setProperty(identifier ident: String) -> Array<CNValue>? {
if let elm = valueProperty(identifier: ident){
return elm.toSet()
} else {
return nil
}
}
public func objectProperty(identifier ident: String) -> AnyObject? {
if let elm = valueProperty(identifier: ident){
return elm.toObject()
} else {
return nil
}
}
public func valueProperty(identifier ident: String) -> CNValue? {
let result: CNValue?
switch self {
case .dictionaryValue(let dict):
result = dict[ident]
default:
result = nil
}
return result
}
private func propertyCount() -> Int? {
let result: Int?
switch self {
case .dictionaryValue(let dict):
result = dict.count
default:
result = nil
}
return result
}
public var description: String { get {
let result: String
switch self {
case .boolValue(let val):
result = val ? "true" : "false"
case .numberValue(let val):
result = val.stringValue
case .stringValue(let val):
result = val
case .enumValue(let val):
result = val.memberName
case .dictionaryValue(let val):
var line = "["
var is1st = true
let keys = val.keys.sorted()
for key in keys {
if is1st { is1st = false } else { line += ", " }
if let elm = val[key] {
line += key + ":" + elm.description
} else {
CNLog(logLevel: .error, message: "Can not happen", atFunction: #function, inFile: #file)
}
}
line += "]"
result = line
case .arrayValue(let val):
var line = "["
var is1st = true
for elm in val {
if is1st { is1st = false } else { line += ", " }
line += elm.description
}
line += "]"
result = line
case .setValue(let val):
result = val.description
case .objectValue(let val):
let classname = String(describing: type(of: val))
result = "instanceOf(\(classname))"
}
return result
}}
public func toScript() -> CNText {
let result: CNText
switch self {
case .boolValue(_), .numberValue(_), .objectValue(_):
// Use description
result = CNTextLine(string: self.description)
case .stringValue(let val):
let txt = CNStringUtil.insertEscapeForQuote(source: val)
result = CNTextLine(string: "\"" + txt + "\"")
case .enumValue(let val):
let txt = "\(val.typeName).\(val.memberName)"
result = CNTextLine(string: txt)
case .dictionaryValue(let val):
result = dictionaryToScript(dictionary: val)
case .arrayValue(let val):
result = arrayToScript(array: val)
case .setValue(let val):
result = setToScript(set: val)
}
return result
}
private func arrayToScript(array arr: Array<CNValue>) -> CNTextSection {
let sect = CNTextSection()
sect.header = "[" ; sect.footer = "]" ; sect.separator = ","
for elm in arr {
sect.add(text: elm.toScript())
}
return sect
}
private func setToScript(set vals: Array<CNValue>) -> CNTextSection {
let dict: Dictionary<String, CNValue> = [
"class": .stringValue(CNValueSet.ClassName),
"values": .arrayValue(vals)
]
return dictionaryToScript(dictionary: dict)
}
private func dictionaryToScript(dictionary dict: Dictionary<String, CNValue>) -> CNTextSection {
let sect = CNTextSection()
sect.header = "{" ; sect.footer = "}" ; sect.separator = ","
let keys = dict.keys.sorted()
for key in keys {
if let val = dict[key] {
let newtxt = val.toScript()
let labtxt = CNLabeledText(label: "\(key): ", text: newtxt)
sect.add(text: labtxt)
}
}
return sect
}
public static func className(forValue dict: Dictionary<String, CNValue>) -> String? {
guard let val = dict["class"] else {
return nil
}
switch val {
case .stringValue(let str):
return str
default:
return nil
}
}
public static func hasClassName(inValue dict: Dictionary<String, CNValue>, className expname: String) -> Bool {
if let name = CNValue.className(forValue: dict) {
return expname == name
} else {
return false
}
}
public static func setClassName(toValue dict: inout Dictionary<String, CNValue>, className name: String){
dict["class"] = .stringValue(name)
}
public static func removeClassName(fromValue dict: inout Dictionary<String, CNValue>){
dict["class"] = nil
}
private static func stringFromDate(date: Date) -> String {
let formatter: DateFormatter = DateFormatter()
formatter.calendar = Calendar(identifier: .gregorian)
formatter.dateFormat = "yyyy/MM/dd HH:mm:ss Z"
return formatter.string(from: date)
}
private static func dateFromString(string: String) -> Date? {
let formatter: DateFormatter = DateFormatter()
formatter.calendar = Calendar(identifier: .gregorian)
formatter.dateFormat = "yyyy/MM/dd HH:mm:ss Z"
return formatter.date(from: string)
}
public func toAny() -> Any {
let result: Any
switch self {
case .boolValue(let val):
result = val
case .numberValue(let val):
result = val
case .stringValue(let val):
result = val
case .enumValue(let val):
result = val.toValue()
case .objectValue(let val):
result = val
case .dictionaryValue(let dict):
var newdict: Dictionary<String, Any> = [:]
for (key, elm) in dict {
newdict[key] = elm.toAny()
}
result = newdict
case .arrayValue(let arr):
var newarr: Array<Any> = []
for elm in arr {
newarr.append(elm.toAny())
}
result = newarr
case .setValue(let arr):
var newarr: Array<Any> = []
for elm in arr {
newarr.append(elm.toAny())
}
result = newarr
}
return result
}
public static func anyToValue(object obj: Any) -> CNValue {
var result: CNValue
if let _ = obj as? NSNull {
result = CNValue.null
} else if let val = obj as? NSNumber {
result = .numberValue(val)
} else if let val = obj as? String {
result = .stringValue(val)
} else if let val = obj as? Dictionary<String, Any> {
var newdict: Dictionary<String, CNValue> = [:]
for (key, elm) in val {
let child = anyToValue(object: elm)
newdict[key] = child
}
if let val = dictionaryToValue(dictionary: newdict){
result = val
} else {
result = .dictionaryValue(newdict)
}
} else if let val = obj as? Array<Any> {
var newarr: Array<CNValue> = []
for elm in val {
let child = anyToValue(object: elm)
newarr.append(child)
}
result = .arrayValue(newarr)
} else {
result = .objectValue(obj as AnyObject)
}
return result
}
public static func dictionaryToValue(dictionary dict: Dictionary<String, CNValue>) -> CNValue? {
var result: CNValue? = nil
if let clsval = dict["class"] {
if let clsname = clsval.toString() {
switch clsname {
case CNEnum.ClassName:
if let eval = CNEnum.fromValue(value: dict) {
result = .enumValue(eval)
}
case CNValueSet.ClassName:
if let val = CNValueSet.fromValue(value: dict) {
result = val
}
default:
break
}
}
}
return result
}
}
| lgpl-2.1 | 216cd902f5c7972ba0b99a99dd10e399 | 24.002331 | 119 | 0.65551 | 3.221021 | false | false | false | false |
featherweightlabs/FeatherweightRouter | Tests/CachedPresenterTests.swift | 1 | 870 | import XCTest
@testable import FeatherweightRouter
class CachedPresenterTests: XCTestCase {
typealias TestPresenter = Presenter<ViewController>
class ViewController {
init() {}
}
func testCreation() {
var callCount = 0
let presenter: TestPresenter = cachedPresenter { () -> ViewController in
callCount += 1
return ViewController()
}
XCTAssertEqual(callCount, 0)
var x: ViewController! = presenter.presentable
XCTAssertEqual(callCount, 1)
var y: ViewController! = presenter.presentable
XCTAssertEqual(callCount, 1)
XCTAssert(x === y)
x = nil
y = nil
x = presenter.presentable
XCTAssertEqual(callCount, 2)
y = presenter.presentable
XCTAssertEqual(callCount, 2)
XCTAssert(x === y)
}
}
| apache-2.0 | 55a2810ad8a05a83328108178e564806 | 23.166667 | 80 | 0.610345 | 5.209581 | false | true | false | false |
6ag/WeiboSwift-mvvm | WeiboSwift/Classes/Utils/Extensions/UIImageViewWebImage.swift | 1 | 1600 | //
// UIImageViewWebImage.swift
// WeiboSwift
//
// Created by zhoujianfeng on 2017/1/21.
// Copyright © 2017年 周剑峰. All rights reserved.
//
import SDWebImage
extension UIImageView {
/// 设置图像
///
/// - Parameters:
/// - urlString: 图片url
/// - placeholderImage: 占位图像
func setImage(urlString: String?, placeholderImage: UIImage?) {
guard let urlString = urlString,
let url = URL(string: urlString) else {
image = placeholderImage
return
}
sd_setImage(with: url, placeholderImage: placeholderImage, options: []) { [weak self] (image, _, _, _) in
// 重绘图片 - 解决图片拉伸引起的性能问题
self?.image = image?.redrawImage(size: self?.bounds.size)
}
}
/// 设置圆形头像
///
/// - Parameters:
/// - urlString: 图片url
/// - placeholderImage: 占位图
func setAvatarImage(urlString: String?, placeholderImage: UIImage?) {
guard let urlString = urlString,
let url = URL(string: urlString) else {
image = placeholderImage
return
}
sd_setImage(with: url, placeholderImage: placeholderImage, options: []) { [weak self] (image, _, _, _) in
// 重绘图片 - 解决图片拉伸引起的性能问题
self?.image = image?.redrawOvalImage(size: self?.bounds.size, bgColor: self?.superview?.backgroundColor ?? UIColor.white)
}
}
}
| mit | 0277ca1b59fad6577cdf8f976f13633e | 27.480769 | 133 | 0.548278 | 4.368732 | false | false | false | false |
codwam/NPB | Demos/NPBDemo/NPB/UIViewController+NPB.swift | 1 | 4649 | //
// UIViewController+NPB.swift
// NPBDemo
//
// Created by 李辉 on 2017/4/13.
// Copyright © 2017年 codwam. All rights reserved.
//
import UIKit
extension UIViewController {
fileprivate struct AssociatedKeys {
static var npb_wantsNavigationBarVisible: Bool?
static var npb_navigationBarBackgroundAlpha: CGFloat?
static var npb_navigationBarTintColor: UIColor?
}
/// Adjust navigation bar hidden state for view controller in anytime you want. If have not set, this property will not work.
@IBInspectable var npb_wantsNavigationBarVisible: Bool? {
get {
guard let npb_wantsNavigationBarVisible = objc_getAssociatedObject(self, &AssociatedKeys.npb_wantsNavigationBarVisible) as? Bool else {
return nil
}
return npb_wantsNavigationBarVisible
}
set {
objc_setAssociatedObject(self, &AssociatedKeys.npb_wantsNavigationBarVisible, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
if let newValue = newValue {
self.navigationController?.setNavigationBarHidden(!newValue, animated: true)
}
}
}
/// Worked on each view controller's push or pop, set the alpha value if you want to apply specific bar alpha to the view controller. If you have not set this property then the value will be the current navigation bar background alpha dynamically.
@IBInspectable var npb_navigationBarBackgroundAlpha: CGFloat {
get {
guard let navigationController = self.navigationController else {
return 1
}
return npb_navigationBarBackgroundAlpha(with: navigationController)
}
set {
self.navigationController?.npb_navigationBarBackgroundAlpha = newValue
objc_setAssociatedObject(self, &AssociatedKeys.npb_navigationBarBackgroundAlpha, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
/// Worked on each view controller's push or pop, set the color value if you want to apply specific bar tint color to the view controller. If you have not set this property then the value will be the current navigation bar barTintColor dynamically. Set it to "nil", when you expect a system default color.
@IBInspectable var npb_navigationBarTintColor: UIColor? {
get {
guard let navigationController = self.navigationController else {
return nil
}
return npb_navigationBarTintColor(with: navigationController)
}
set {
self.npb_navigationBarTintColorSetterBeenCalled = true
self.navigationController?.npb_navigationBarTintColor = newValue
objc_setAssociatedObject(self, &AssociatedKeys.npb_navigationBarTintColor, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
/// Hide or show the navigation bar background.
@IBInspectable var npb_navigationBarBackgroundHidden: Bool {
get {
return self.npb_navigationBarBackgroundAlpha - 0.0 <= 0.0001
}
set {
self.npb_navigationBarBackgroundAlpha = newValue ? 0 : 1
}
}
/// Hide or show the navigation bar background. If animated, it will transition vertically using UINavigationControllerHideShowBarDuration.
func npb_setNavigationBarBackgroundHidden(_ hidden: Bool, animated: Bool) {
UIView.animate(withDuration: TimeInterval(animated ? UINavigationControllerHideShowBarDuration : 0)) {
self.npb_navigationBarBackgroundHidden = hidden
}
}
/// Return the gives view controller's previous view controller in the navigation stack.
var npb_previousViewController: UIViewController? {
guard let navigationController = self.navigationController else {
return nil
}
return navigationController.npb_previousViewController(for: self)
}
// MARK: - KVC
// 如果没有重写这个方法,会报警告⚠️
// Failed to set (npb_wantsNavigationBarVisible) user defined inspected property on (NPBDemo.JZViewController): [<NPBDemo.JZViewController 0x7f88a0416980> setValue:forUndefinedKey:]: this class is not key value coding-compliant for the key npb_wantsNavigationBarVisible.
open override func setValue(_ value: Any?, forUndefinedKey key: String) {
if key == "npb_wantsNavigationBarVisible" {
self.npb_wantsNavigationBarVisible = value as? Bool
} else {
super.setValue(value, forUndefinedKey: key)
}
}
}
| mit | 60e16c3df177d322ea3791851990c08b | 43.307692 | 309 | 0.676649 | 5.125695 | false | false | false | false |
MAARK/Charts | ChartsDemo-iOS/Swift/Demos/ScatterChartViewController.swift | 2 | 4077 | //
// ScatterChartViewController.swift
// ChartsDemo-iOS
//
// Created by Jacob Christie on 2017-07-09.
// Copyright © 2017 jc. All rights reserved.
//
import UIKit
import Charts
class ScatterChartViewController: DemoBaseViewController {
@IBOutlet var chartView: ScatterChartView!
@IBOutlet var sliderX: UISlider!
@IBOutlet var sliderY: UISlider!
@IBOutlet var sliderTextX: UITextField!
@IBOutlet var sliderTextY: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
self.title = "Scatter Chart"
self.options = [.toggleValues,
.toggleHighlight,
.animateX,
.animateY,
.animateXY,
.saveToGallery,
.togglePinchZoom,
.toggleAutoScaleMinMax,
.toggleData]
chartView.delegate = self
chartView.chartDescription?.enabled = false
chartView.dragEnabled = true
chartView.setScaleEnabled(true)
chartView.maxVisibleCount = 200
chartView.pinchZoomEnabled = true
let l = chartView.legend
l.horizontalAlignment = .right
l.verticalAlignment = .top
l.orientation = .vertical
l.drawInside = false
l.font = .systemFont(ofSize: 10, weight: .light)
l.xOffset = 5
let leftAxis = chartView.leftAxis
leftAxis.labelFont = .systemFont(ofSize: 10, weight: .light)
leftAxis.axisMinimum = 0
chartView.rightAxis.enabled = false
let xAxis = chartView.xAxis
xAxis.labelFont = .systemFont(ofSize: 10, weight: .light)
sliderX.value = 45
sliderY.value = 100
slidersValueChanged(nil)
}
override func updateChartData() {
if self.shouldHideData {
chartView.data = nil
return
}
self.setDataCount(Int(sliderX.value + 1), range: UInt32(sliderY.value))
}
func setDataCount(_ count: Int, range: UInt32) {
let values1 = (0..<count).map { (i) -> ChartDataEntry in
let val = Double(arc4random_uniform(range) + 3)
return ChartDataEntry(x: Double(i), y: val)
}
let values2 = (0..<count).map { (i) -> ChartDataEntry in
let val = Double(arc4random_uniform(range) + 3)
return ChartDataEntry(x: Double(i) + 0.33, y: val)
}
let values3 = (0..<count).map { (i) -> ChartDataEntry in
let val = Double(arc4random_uniform(range) + 3)
return ChartDataEntry(x: Double(i) + 0.66, y: val)
}
let set1 = ScatterChartDataSet(entries: values1, label: "DS 1")
set1.setScatterShape(.square)
set1.setColor(ChartColorTemplates.colorful()[0])
set1.scatterShapeSize = 8
let set2 = ScatterChartDataSet(entries: values2, label: "DS 2")
set2.setScatterShape(.circle)
set2.scatterShapeHoleColor = ChartColorTemplates.colorful()[3]
set2.scatterShapeHoleRadius = 3.5
set2.setColor(ChartColorTemplates.colorful()[1])
set2.scatterShapeSize = 8
let set3 = ScatterChartDataSet(entries: values3, label: "DS 3")
set3.setScatterShape(.cross)
set3.setColor(ChartColorTemplates.colorful()[2])
set3.scatterShapeSize = 8
let data = ScatterChartData(dataSets: [set1, set2, set3])
data.setValueFont(.systemFont(ofSize: 7, weight: .light))
chartView.data = data
}
override func optionTapped(_ option: Option) {
super.handleOption(option, forChartView: chartView)
}
@IBAction func slidersValueChanged(_ sender: Any?) {
sliderTextX.text = "\(Int(sliderX.value))"
sliderTextY.text = "\(Int(sliderY.value))"
self.updateChartData()
}
}
| apache-2.0 | 35d177c30afc49db9a0384a25f500dfa | 31.870968 | 79 | 0.580962 | 4.73403 | false | false | false | false |
tarrgor/LctvSwift | Sources/LctvApi+Functions.swift | 1 | 14205 | //
// LctvApi+Functions.swift
// Pods
//
//
//
import Foundation
import SwiftyJSON
extension LctvApi {
/**
Retrieve a pageable list of coding categories from livecoding.tv.
Result is given into the success() handler as a `LctvResultContainer`.
- parameter page: Optional parameter to specify a concrete page to retrieve (defaults to 0).
- parameter success: A handler function which is executed in case of success.
- parameter failure: A handler function for handling errors.
*/
public func getCodingCategories(page page: Int? = 0, success: (LctvResultContainer<LctvCodingCategory>) -> (), failure: (String, JSON?) -> ()) {
get(ApiUrl.CodingCategories.url, page: page ?? 0, success: {
json in
let result = LctvResultContainer<LctvCodingCategory>(json: json)
success(result)
},
failure: { message, json in
failure(message, json)
})
}
/**
Retrieve a coding category by its name from livecoding.tv.
Result is given into the success() handler as a `LctvCodingCategory`.
- parameter name: The name to be searched for.
- parameter success: A handler function which is executed in case of success.
- parameter failure: A handler function for handling errors.
*/
public func getCodingCategoryByName(name: String, success: (LctvCodingCategory) -> (), failure: (String, JSON?) -> ()) {
let url = ApiUrl.CodingCategories.url + "\(name)/"
get(url, success: {
json in
let result = LctvCodingCategory(json: json)
success(result)
},
failure: { message, json in
failure(message, json)
})
}
/**
Retrieve a pageable list of livestreams from livecoding.tv.
Result is given into the success() handler as a `LctvResultContainer`.
- parameter page: Optional parameter to specify a concrete page to retrieve (defaults to 0).
- parameter success: A handler function which is executed in case of success.
- parameter failure: A handler function for handling errors.
*/
public func getLivestreams(page page: Int? = 0, success: (LctvResultContainer<LctvLivestream>) -> (), failure: (String, JSON?) -> ()) {
get(ApiUrl.Livestreams.url, page: page ?? 0, success: {
json in
let result = LctvResultContainer<LctvLivestream>(json: json)
success(result)
},
failure: { message, json in
failure(message, json)
})
}
/**
Retrieve a pageable list of livestreams which are currently on air from livecoding.tv.
Result is given into the success() handler as a `LctvResultContainer`.
- parameter page: Optional parameter to specify a concrete page to retrieve (defaults to 0).
- parameter success: A handler function which is executed in case of success.
- parameter failure: A handler function for handling errors.
*/
public func getLivestreamsOnAir(page page: Int? = 0, success: (LctvResultContainer<LctvLivestream>) -> (), failure: (String, JSON?) -> ()) {
get(ApiUrl.LivestreamsOnAir.url, page: page ?? 0, success: {
json in
let result = LctvResultContainer<LctvLivestream>(json: json)
success(result)
},
failure: { message, json in
failure(message, json)
})
}
/**
Retrieve the livestream of the specified user from livecoding.tv.
Result is given into the success() handler as a `LctvLivestream`.
- parameter userSlug: The nickname of the user.
- parameter success: A handler function which is executed in case of success.
- parameter failure: A handler function for handling errors.
*/
public func getLivestreamByUserSlug(userSlug: String, success: (LctvLivestream) -> (), failure: (String, JSON?) -> ()) {
let url = ApiUrl.Livestreams.url + "\(userSlug)/"
get(url, success: {
json in
let result = LctvLivestream(json: json)
success(result)
},
failure: { message, json in
failure(message, json)
})
}
/**
Retrieve a pageable list of languages from livecoding.tv.
Result is given into the success() handler as a `LctvResultContainer`.
- parameter page: Optional parameter to specify a concrete page to retrieve (defaults to 0).
- parameter success: A handler function which is executed in case of success.
- parameter failure: A handler function for handling errors.
*/
public func getLanguages(page page: Int? = 0, success: (LctvResultContainer<LctvLanguage>) -> (), failure: (String, JSON?) -> ()) {
get(ApiUrl.Languages.url, page: page ?? 0, success: {
json in
let result = LctvResultContainer<LctvLanguage>(json: json)
success(result)
},
failure: { message, json in
failure(message, json)
})
}
public func getLanguageByName(name: String, success: (LctvLanguage) -> (), failure: (String, JSON?) -> ()) {
let url = ApiUrl.Languages.url + "\(name)/"
get(url, success: {
json in
let result = LctvLanguage(json: json)
success(result)
},
failure: { message, json in
failure(message, json)
})
}
public func getCurrentUser(success success: (LctvUser) -> (), failure: (String, JSON?) -> ()) {
get(ApiUrl.CurrentUser.url, success: {
json in
let result = LctvUser(json: json)
success(result)
},
failure: { message, json in
failure(message, json)
})
}
public func getCurrentUserFollowers(success success: (LctvArrayContainer<LctvUser>) -> (), failure: (String, JSON?) -> ()) {
get(ApiUrl.Followers.url, success: {
json in
let result = LctvArrayContainer<LctvUser>(json: json)
success(result)
},
failure: { message, json in
failure(message, json)
})
}
public func getCurrentUserFollows(success success: (LctvArrayContainer<LctvUser>) -> (), failure: (String, JSON?) -> ()) {
get(ApiUrl.Follows.url, success: {
json in
let result = LctvArrayContainer<LctvUser>(json: json)
success(result)
},
failure: { message, json in
failure(message, json)
})
}
public func getUserChatAccount(success success: (LctvXmppAccount) -> (), failure: (String, JSON?) -> ()) {
get(ApiUrl.ChatAccount.url, success: {
json in
let result = LctvXmppAccount(json: json)
success(result)
},
failure: { message, json in
failure(message, json)
})
}
public func getViewingKey(success success: (LctvUser) -> (), failure: (String, JSON?) -> ()) {
get(ApiUrl.ViewingKey.url, success: {
json in
let result = LctvUser(json: json)
success(result)
},
failure: { message, json in
failure(message, json)
})
}
/**
Retrieve a pageable list of current user's videos from livecoding.tv.
Result is given into the success() handler as a `LctvResultContainer`.
- parameter page: Optional parameter to specify a concrete page to retrieve (defaults to 0).
- parameter success: A handler function which is executed in case of success.
- parameter failure: A handler function for handling errors.
*/
public func getUserVideos(page page: Int? = 0, success: (LctvResultContainer<LctvVideo>) -> (), failure: (String, JSON?) -> ()) {
get(ApiUrl.UserVideos.url, page: page ?? 0, success: {
json in
let result = LctvResultContainer<LctvVideo>(json: json)
success(result)
},
failure: { message, json in
failure(message, json)
})
}
/**
Retrieve a pageable list of current user's videos from livecoding.tv.
Result is given into the success() handler as a `LctvResultContainer`.
- parameter page: Optional parameter to specify a concrete page to retrieve (defaults to 0).
- parameter success: A handler function which is executed in case of success.
- parameter failure: A handler function for handling errors.
*/
public func getUserLatestVideos(page page: Int? = 0, success: (LctvResultContainer<LctvVideo>) -> (), failure: (String, JSON?) -> ()) {
get(ApiUrl.UserLatestVideos.url, page: page ?? 0, success: {
json in
let result = LctvResultContainer<LctvVideo>(json: json)
success(result)
},
failure: { message, json in
failure(message, json)
})
}
/**
Retrieve a pageable list of channels from livecoding.tv.
Result is given into the success() handler as a `LctvResultContainer`.
- parameter page: Optional parameter to specify a concrete page to retrieve (defaults to 0).
- parameter success: A handler function which is executed in case of success.
- parameter failure: A handler function for handling errors.
*/
public func getUserChannel(page page: Int? = 0, success: (LctvResultContainer<LctvUserChannel>) -> (), failure: (String, JSON?) -> ()) {
get(ApiUrl.UserChannel.url, page: page ?? 0, success: {
json in
let result = LctvResultContainer<LctvUserChannel>(json: json)
success(result)
},
failure: { message, json in
failure(message, json)
})
}
/**
Retrieve a pageable list of channels currently on air from livecoding.tv.
Result is given into the success() handler as a `LctvResultContainer`.
- parameter page: Optional parameter to specify a concrete page to retrieve (defaults to 0).
- parameter success: A handler function which is executed in case of success.
- parameter failure: A handler function for handling errors.
*/
public func getUserChannelOnAir(page page: Int? = 0, success: (LctvResultContainer<LctvUserChannel>) -> (), failure: (String, JSON?) -> ()) {
get(ApiUrl.UserChannelOnAir.url, page: page ?? 0, success: {
json in
let result = LctvResultContainer<LctvUserChannel>(json: json)
success(result)
},
failure: { message, json in
failure(message, json)
})
}
public func getUserProfileBySlug(slug: String, success: (LctvUser) -> (), failure: (String, JSON?) -> ()) {
let url = "\(ApiUrl.UserProfile.url)\(slug)/"
get(url, success: {
json in
let result = LctvUser(json: json)
success(result)
},
failure: { message, json in
failure(message, json)
})
}
/**
Retrieve a pageable list of scheduled broadcasts from livecoding.tv.
Result is given into the success() handler as a `LctvResultContainer`.
- parameter page: Optional parameter to specify a concrete page to retrieve (defaults to 0).
- parameter success: A handler function which is executed in case of success.
- parameter failure: A handler function for handling errors.
*/
public func getScheduledBroadcasts(page page: Int? = 0, success: (LctvResultContainer<LctvScheduledBroadcast>) -> (), failure: (String, JSON?) -> ()) {
get(ApiUrl.ScheduledBroadcasts.url, page: page ?? 0, success: {
json in
let result = LctvResultContainer<LctvScheduledBroadcast>(json: json)
success(result)
},
failure: { message, json in
failure(message, json)
})
}
public func getScheduledBroadcastById(id: Int, success: (LctvScheduledBroadcast) -> (), failure: (String, JSON?) -> ()) {
let url = "\(ApiUrl.ScheduledBroadcasts.url)\(id)/"
get(url, success: {
json in
let result = LctvScheduledBroadcast(json: json)
success(result)
},
failure: { message, json in
failure(message, json)
})
}
/**
Retrieve a pageable list of videos from livecoding.tv.
Result is given into the success() handler as a `LctvResultContainer`.
- parameter page: Optional parameter to specify a concrete page to retrieve (defaults to 0).
- parameter success: A handler function which is executed in case of success.
- parameter failure: A handler function for handling errors.
*/
public func getVideos(page page: Int? = 0, success: (LctvResultContainer<LctvVideo>) -> (), failure: (String, JSON?) -> ()) {
get(ApiUrl.Videos.url, page: page ?? 0, success: {
json in
let result = LctvResultContainer<LctvVideo>(json: json)
success(result)
},
failure: { message, json in
failure(message, json)
})
}
public func getVideoBySlug(slug: String, success: (LctvVideo) -> (), failure: (String, JSON?) -> ()) {
let url = "\(ApiUrl.Videos.url)\(slug)/"
get(url, success: {
json in
let result = LctvVideo(json: json)
success(result)
},
failure: { message, json in
failure(message, json)
})
}
/**
With a given `LctvResultContainer` this method will retrieve the next page if it exists.
The success handler will receive a new `LctvResultContainer` with the next elements. You
can configure the page size by using the `pageSize` property of the `LctvApi` instance.
- parameter result: The current `LctvResultContainer`.
- parameter success: A handler function which is executed in case of success.
- parameter failure: A handler function for handling errors.
*/
public func nextPage<T: JSONInitializable>(result: LctvResultContainer<T>, success: (LctvResultContainer<T>) -> (), failure: (String, JSON?) -> ()) {
if let next = result.next {
get(next, success: {
json in
let result = LctvResultContainer<T>(json: json)
success(result)
}, failure: { message, json in
failure(message, json)
})
}
}
/**
With a given `LctvResultContainer` this method will retrieve the previous page if it exists.
The success handler will receive a new `LctvResultContainer` with the previous elements. You
can configure the page size by using the `pageSize` property of the `LctvApi` instance.
- parameter result: The current `LctvResultContainer`.
- parameter success: A handler function which is executed in case of success.
- parameter failure: A handler function for handling errors.
*/
public func previousPage<T: JSONInitializable>(result: LctvResultContainer<T>, success: (LctvResultContainer<T>) -> (), failure: (String, JSON?) -> ()) {
if let prev = result.previous {
get(prev, success: {
json in
let result = LctvResultContainer<T>(json: json)
success(result)
}, failure: { message, json in
failure(message, json)
})
}
}
}
| mit | 8619e4e117d2f3270b093dc3b7901209 | 34.871212 | 155 | 0.66202 | 3.930548 | false | false | false | false |
borglab/SwiftFusion | Sources/SwiftFusionBenchmarks/Patch.swift | 1 | 2041 | // Copyright 2020 The SwiftFusion Authors. 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.
/// Benchmarks Pose2SLAM solutions.
import _Differentiation
import Benchmark
import SwiftFusion
import TensorFlow
let patchBenchmark = BenchmarkSuite(name: "Patch") { suite in
suite.benchmark(
"PatchForward",
settings: Iterations(1), TimeUnit(.ms)
) {
let rows = 100
let cols = 100
let image = Tensor<Double>(randomNormal: [500, 500, 1])
_ = image.patch(at: OrientedBoundingBox(center: Pose2(100, 100, 0.5), rows: rows, cols: cols))
}
suite.benchmark(
"PatchJacobian",
settings: Iterations(1), TimeUnit(.ms)
) {
let rows = 28
let cols = 62
let latentDimension = 5
let image = Tensor<Double>(randomNormal: [500, 500])
let W = Tensor<Double>(randomNormal: [rows * cols, latentDimension])
let mu = Tensor<Double>(randomNormal: [rows, cols])
func errorVector(_ center: Pose2, _ latent: Vector5) -> Tensor<Double> {
let bbox = OrientedBoundingBox(center: center, rows: rows, cols: cols)
let generated = mu + matmul(W, latent.flatTensor.expandingShape(at: 1)).reshaped(to: [rows, cols])
return generated - image.patch(at: bbox)
}
let (value, pb) = valueWithPullback(at: Pose2(100, 100, 0.5), Vector5.zero, in: errorVector)
for i in 0..<rows {
for j in 0..<cols {
var basisVector = Tensor<Double>(zeros: [rows, cols])
basisVector[i, j] = Tensor(1)
_ = pb(basisVector)
}
}
}
}
| apache-2.0 | f1f8d3c7fc7630a805b6b53235a9bb78 | 32.459016 | 104 | 0.675159 | 3.786642 | false | false | false | false |
gaurav1981/Swiftz | SwiftzTests/MaybeSpec.swift | 1 | 3788 | //
// MaybeSpec.swift
// swiftz
//
// Created by Robert Widmann on 1/19/15.
// Copyright (c) 2015 TypeLift. All rights reserved.
//
import XCTest
import Swiftz
import SwiftCheck
struct MaybeOf<A : Arbitrary> : Arbitrary, Printable {
let getMaybe : Maybe<A>
init(_ maybe : Maybe<A>) {
self.getMaybe = maybe
}
var description : String {
return "\(self.getMaybe)"
}
private static func create(opt : Maybe<A>) -> MaybeOf<A> {
return MaybeOf(opt)
}
static func arbitrary() -> Gen<MaybeOf<A>> {
return Gen.frequency([
(1, Gen.pure(MaybeOf(Maybe<A>.none()))),
(3, liftM({ MaybeOf(Maybe<A>.just($0)) })(m1: A.arbitrary()))
])
}
static func shrink(bl : MaybeOf<A>) -> [MaybeOf<A>] {
if bl.getMaybe.isJust() {
return [MaybeOf(Maybe<A>.none())] + A.shrink(bl.getMaybe.fromJust()).map({ MaybeOf(Maybe<A>.just($0)) })
}
return []
}
}
func == <T : protocol<Arbitrary, Equatable>>(lhs : MaybeOf<T>, rhs : MaybeOf<T>) -> Bool {
return lhs.getMaybe == rhs.getMaybe
}
func != <T : protocol<Arbitrary, Equatable>>(lhs : MaybeOf<T>, rhs : MaybeOf<T>) -> Bool {
return !(lhs == rhs)
}
class MaybeSpec : XCTestCase {
func testProperties() {
property["Maybes of Equatable elements obey reflexivity"] = forAll { (l : MaybeOf<Int>) in
return l == l
}
property["Maybes of Equatable elements obey symmetry"] = forAll { (x : MaybeOf<Int>, y : MaybeOf<Int>) in
return (x == y) == (y == x)
}
property["Maybes of Equatable elements obey transitivity"] = forAll { (x : MaybeOf<Int>, y : MaybeOf<Int>, z : MaybeOf<Int>) in
return (x == y) && (y == z) ==> (x == z)
}
property["Maybes of Equatable elements obey negation"] = forAll { (x : MaybeOf<Int>, y : MaybeOf<Int>) in
return (x != y) == !(x == y)
}
property["Maybes of Comparable elements obey reflexivity"] = forAll { (l : MaybeOf<Int>) in
return l == l
}
property["Maybe obeys the Functor identity law"] = forAll { (x : MaybeOf<Int>) in
return (x.getMaybe.fmap(identity)) == identity(x.getMaybe)
}
property["Maybe obeys the Functor composition law"] = forAll { (f : ArrowOf<Int, Int>, g : ArrowOf<Int, Int>, x : MaybeOf<Int>) in
return ((f.getArrow • g.getArrow) <^> x.getMaybe) == (x.getMaybe.fmap(g.getArrow).fmap(f.getArrow))
}
property["Maybe obeys the Applicative identity law"] = forAll { (x : MaybeOf<Int>) in
return (Maybe.pure(identity) <*> x.getMaybe) == x.getMaybe
}
property["Maybe obeys the first Applicative composition law"] = forAll { (fl : MaybeOf<ArrowOf<Int8, Int8>>, gl : MaybeOf<ArrowOf<Int8, Int8>>, x : MaybeOf<Int8>) in
let f = fl.getMaybe.fmap({ $0.getArrow })
let g = gl.getMaybe.fmap({ $0.getArrow })
return (curry(•) <^> f <*> g <*> x.getMaybe) == (f <*> (g <*> x.getMaybe))
}
property["Maybe obeys the second Applicative composition law"] = forAll { (fl : MaybeOf<ArrowOf<Int8, Int8>>, gl : MaybeOf<ArrowOf<Int8, Int8>>, x : MaybeOf<Int8>) in
let f = fl.getMaybe.fmap({ $0.getArrow })
let g = gl.getMaybe.fmap({ $0.getArrow })
return (Maybe.pure(curry(•)) <*> f <*> g <*> x.getMaybe) == (f <*> (g <*> x.getMaybe))
}
property["Maybe obeys the Monad left identity law"] = forAll { (a : Int, fa : ArrowOf<Int, MaybeOf<Int>>) in
let f = { $0.getMaybe } • fa.getArrow
return (Maybe.pure(a) >>- f) == f(a)
}
property["Maybe obeys the Monad right identity law"] = forAll { (m : MaybeOf<Int>) in
return (m.getMaybe >>- Maybe.pure) == m.getMaybe
}
property["Maybe obeys the Monad associativity law"] = forAll { (fa : ArrowOf<Int, MaybeOf<Int>>, ga : ArrowOf<Int, MaybeOf<Int>>, m : MaybeOf<Int>) in
let f = { $0.getMaybe } • fa.getArrow
let g = { $0.getMaybe } • ga.getArrow
return ((m.getMaybe >>- f) >>- g) == (m.getMaybe >>- { x in f(x) >>- g })
}
}
}
| bsd-3-clause | 4db653e26f3927a41655f8ab0e42ea32 | 32.714286 | 168 | 0.621028 | 2.952306 | false | false | false | false |
StanZabroda/Hydra | Hydra/AnimatedMenuButton.swift | 1 | 5529 | // Copyright (c) 2014 evolved.io (http://evolved.io)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
import QuartzCore
import UIKit
public class AnimatedMenuButton : UIButton {
let top: CAShapeLayer = CAShapeLayer()
let middle: CAShapeLayer = CAShapeLayer()
let bottom: CAShapeLayer = CAShapeLayer()
// MARK: - Constants
let animationDuration: CFTimeInterval = 8.0
let shortStroke: CGPath = {
let path = CGPathCreateMutable()
CGPathMoveToPoint(path, nil, 2, 2)
CGPathAddLineToPoint(path, nil, 30 - 2 * 2, 2)
return path
}()
// MARK: - Initializers
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override init(frame: CGRect) {
super.init(frame:frame)
self.top.path = shortStroke;
self.middle.path = shortStroke;
self.bottom.path = shortStroke;
for layer in [ self.top, self.middle, self.bottom ] {
layer.fillColor = nil
layer.strokeColor = UIColor.grayColor().CGColor
layer.lineWidth = 4
layer.miterLimit = 2
layer.lineCap = kCALineCapRound
layer.masksToBounds = true
let strokingPath = CGPathCreateCopyByStrokingPath(layer.path, nil, 4, .Round, .Miter, 4)
layer.bounds = CGPathGetPathBoundingBox(strokingPath)
layer.actions = [
"opacity": NSNull(),
"transform": NSNull()
]
self.layer.addSublayer(layer)
}
self.top.anchorPoint = CGPoint(x: 1, y: 0.5)
self.top.position = CGPoint(x: 30 - 1, y: 5)
self.middle.position = CGPoint(x: 15, y: 15)
self.bottom.anchorPoint = CGPoint(x: 1, y: 0.5)
self.bottom.position = CGPoint(x: 30 - 1, y: 25)
}
// MARK: - Animations
public func animateWithPercentVisible(percentVisible:CGFloat, drawerSide: DrawerSide) {
if drawerSide == DrawerSide.Left {
self.top.anchorPoint = CGPoint(x: 1, y: 0.5)
self.top.position = CGPoint(x: 30 - 1, y: 5)
self.middle.position = CGPoint(x: 15, y: 15)
self.bottom.anchorPoint = CGPoint(x: 1, y: 0.5)
self.bottom.position = CGPoint(x: 30 - 1, y: 25)
} else if drawerSide == DrawerSide.Right {
self.top.anchorPoint = CGPoint(x: 0, y: 0.5)
self.top.position = CGPoint(x: 1, y: 5)
self.middle.position = CGPoint(x: 15, y: 15)
self.bottom.anchorPoint = CGPoint(x: 0, y: 0.5)
self.bottom.position = CGPoint(x: 1, y: 25)
}
let middleTransform = CABasicAnimation(keyPath: "opacity")
middleTransform.duration = animationDuration
let topTransform = CABasicAnimation(keyPath: "transform")
topTransform.timingFunction = CAMediaTimingFunction(controlPoints: 0.5, -0.8, 0.5, 1.85)
topTransform.duration = animationDuration
topTransform.fillMode = kCAFillModeBackwards
let bottomTransform = topTransform.copy() as! CABasicAnimation
middleTransform.toValue = 1 - percentVisible
let translation = CATransform3DMakeTranslation(-4 * percentVisible, 0, 0)
let sideInverter: CGFloat = drawerSide == DrawerSide.Left ? -1 : 1
topTransform.toValue = NSValue(CATransform3D: CATransform3DRotate(translation, 1.0 * sideInverter * ((CGFloat)(45.0 * M_PI / 180.0) * percentVisible), 0, 0, 1))
bottomTransform.toValue = NSValue(CATransform3D: CATransform3DRotate(translation, (-1.0 * sideInverter * (CGFloat)(45.0 * M_PI / 180.0) * percentVisible), 0, 0, 1))
topTransform.beginTime = CACurrentMediaTime()
bottomTransform.beginTime = CACurrentMediaTime()
self.top.addAnimation(topTransform, forKey: topTransform.keyPath)
self.middle.addAnimation(middleTransform, forKey: middleTransform.keyPath)
self.bottom.addAnimation(bottomTransform, forKey: bottomTransform.keyPath)
self.top.setValue(topTransform.toValue, forKey: topTransform.keyPath!)
self.middle.setValue(middleTransform.toValue, forKey: middleTransform.keyPath!)
self.bottom.setValue(bottomTransform.toValue, forKey: bottomTransform.keyPath!)
}
} | mit | ef54c4e2a01f3480a8be960cdf6b03e2 | 40.893939 | 172 | 0.637728 | 4.458871 | false | false | false | false |
mike4aday/SwiftlySalesforce | Sources/SwiftlySalesforce/HTTP.swift | 1 | 567 | import Foundation
public struct HTTP {
struct Method {
static let get = "GET"
static let delete = "DELETE"
static let post = "POST"
static let patch = "PATCH"
static let head = "HEAD"
static let put = "PUT"
}
struct MIMEType {
static let json = "application/json;charset=UTF-8"
static let formUrlEncoded = "application/x-www-form-urlencoded;charset=utf-8"
}
struct Header {
static let accept = "Accept"
static let contentType = "Content-Type"
}
}
| mit | 706952cf9e37c0d89d74e90172573e94 | 23.652174 | 85 | 0.578483 | 4.2 | false | false | false | false |
hugoantunes/tsuru | misc/git-hooks/pre-receive.swift | 1 | 2111 | #!/bin/bash -el
# This script generates a git archive from the provided commit, uploads it to
# Swift, sends the URL to Tsuru and then delete the archive in from the
# container.
#
# It depends on the "swift" command line (it can be installed with pip).
#
# It also depends on the following environment variables:
#
# - AUTH_PARAMS: the parameters used in authentication (for example:
# "-A https://yourswift.com -K yourkey -U youruser")
# - CDN_URL: the URL of the CDN that serves content from your container (for
# example: something.cf5.rackcdn.com).
# - CONTAINER_NAME: name of the container where the script will store the
# archives
# - TSURU_HOST: URL to the Tsuru API (for example: http://yourtsuru:8080)
# - TSURU_TOKEN: the token to communicate with the API (generated with `tsr
# token`, in the server).
while read oldrev newrev refname
do
set +e
echo $refname | grep -q /master$
status=$?
set -e
if [ $status = 0 ]
then
COMMIT=${newrev}
fi
done
if [ -z ${COMMIT} ]
then
echo "ERROR: please push to master"
exit 3
fi
APP_DIR=${PWD##*/}
APP_NAME=${APP_DIR/.git/}
UUID=`python -c 'import uuid; print uuid.uuid4().hex'`
ARCHIVE_FILE_NAME=${APP_NAME}_${COMMIT}_${UUID}.tar.gz
git archive --format=tar.gz -o /tmp/$ARCHIVE_FILE_NAME $COMMIT
swift -q $AUTH_PARAMS upload $CONTAINER_NAME /tmp/$ARCHIVE_FILE_NAME --object-name $ARCHIVE_FILE_NAME
swift -q $AUTH_PARAMS post -r ".r:*" $CONTAINER_NAME
rm /tmp/$ARCHIVE_FILE_NAME
if [ -z "${CDN_URL}" ]
then
ARCHIVE_URL=`swift $AUTH_PARAMS stat -v $CONTAINER_NAME $ARCHIVE_FILE_NAME | grep URL | awk -F': ' '{print $2}'`
else
ARCHIVE_URL=${CDN_URL}/${ARCHIVE_FILE_NAME}
fi
URL="${TSURU_HOST}/apps/${APP_NAME}/repository/clone"
curl -H "Authorization: bearer ${TSURU_TOKEN}" -d "archive-url=${ARCHIVE_URL}&commit=${COMMIT}&user=${TSURU_USER}" -s -N $URL | tee /tmp/deploy-${APP_NAME}.log
swift -q $AUTH_PARAMS delete $CONTAINER_NAME $ARCHIVE_FILE_NAME
tail -1 /tmp/deploy-${APP_NAME}.log | grep -q "^OK$"
| bsd-3-clause | 987b57e11b011fa75a14b5e982cb1099 | 36.696429 | 159 | 0.650403 | 3.127407 | false | false | false | false |
stefanilie/swift-playground | Variables-types.playground/Contents.swift | 1 | 633 | //: Playground - noun: a place where people can play
import UIKit
var strHelloWorld = "Hello, ciorba" //String
strHelloWorld + " eu sunt miezu";
var numA = 1.5 //Double
var numB: Float = 1.5 //Float
var numC = 3 //Int
var sum = 5+1
var product = 5*5
var divisor = 20/5
var remainder = 22%5
var sub = 44-22
var crazyResult = sum * product + (divisor * remainder + sub)
var newStr = "Hey " + "how are you"
var firstName = "Jon"
var lastName = "Smith"
var fullName = "\(firstName) \(lastName)"
var price = "Price: $\(numA)"
price = "Banana"
let total = 5.1 //Constant
var totalPrice: Double
totalPrice = 1.56
print(totalPrice) | mit | 6a28204db127b17c458b727d18725a1f | 18.212121 | 61 | 0.671406 | 3.028708 | false | false | false | false |
huangboju/QMUI.swift | QMUI.swift/Demo/Modules/Demos/UIKit/QDFontViewController.swift | 1 | 3002 | //
// QDFontViewController.swift
// QMUI.swift
//
// Created by qd-hxt on 2018/4/24.
// Copyright © 2018年 伯驹 黄. All rights reserved.
//
import UIKit
class QDFontViewController: QDCommonGroupListViewController {
override func initDataSource() {
super.initDataSource()
let od1 = QMUIOrderedDictionary(
dictionaryLiteral:
("UIFontMake", ""),
("UIFontItalicMake", ""),
("UIFontBoldMake", ""),
("UIFontLightMake", ""))
let od2 = QMUIOrderedDictionary(
dictionaryLiteral:
("UIDynamicFontMake", ""),
("UIDynamicFontBoldMake", ""),
("UIDynamicFontLightMake", ""))
dataSource = QMUIOrderedDictionary(
dictionaryLiteral:
("默认", od1), ("动态字体", od2))
}
override func setNavigationItems(_ isInEditMode: Bool, animated: Bool) {
super.setNavigationItems(isInEditMode, animated: animated)
title = "UIFont+QMUI"
}
override func contentSizeCategoryDidChanged(_ notification: Notification) {
super.contentSizeCategoryDidChanged(notification)
// QMUICommonTableViewController 默认会在这个方法里响应动态字体大小变化,并自动调用 [self.tableView reloadData],所以使用者只需要保证在 cellForRow 里更新动态字体大小即可,不需要手动监听动态字体的变化。
}
// MARK: QMUITableViewDataSource, QMUITableViewDelegate
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = super.tableView(tableView, cellForRowAt: indexPath)
cell.accessoryType = .none
cell.selectionStyle = .none
let key = keyName(at: indexPath)
var font: UIFont?
let pointSize: CGFloat = 15
if key == "UIFontMake" {
font = UIFontMake(pointSize)
} else if key == "UIFontItalicMake" {
font = UIFontItalicMake(pointSize)
} else if key == "UIFontBoldMake" {
font = UIFontBoldMake(pointSize)
} else if key == "UIFontLightMake" {
font = UIFontLightMake(pointSize)
} else if key == "UIDynamicFontMake" {
font = UIDynamicFontMake(pointSize)
} else if key == "UIDynamicFontBoldMake" {
font = UIDynamicFontBoldMake(pointSize)
} else if key == "UIDynamicFontLightMake" {
font = UIDynamicFontLightMake(pointSize)
}
cell.textLabel?.font = font
return cell
}
func tableView(_ tableView: UITableView, titleForFooterInSection section: Int) -> String? {
if section == 1 {
let path = IS_SIMULATOR ? "设置-通用-辅助功能-Larger Text" : "设置-显示与亮度-文字大小"
return "请到“\(path)”里修改文字大小再观察当前界面的变化"
}
return nil
}
}
| mit | 10a773ff271f30809cd16bb40e61edd9 | 34.101266 | 145 | 0.608366 | 4.644891 | false | false | false | false |
noppoMan/aws-sdk-swift | Sources/Soto/Services/CostandUsageReportService/CostandUsageReportService_API.swift | 1 | 5236 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Soto for AWS open source project
//
// Copyright (c) 2017-2020 the Soto project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of Soto project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
// THIS FILE IS AUTOMATICALLY GENERATED by https://github.com/soto-project/soto/tree/main/CodeGenerator. DO NOT EDIT.
@_exported import SotoCore
/*
Client object for interacting with AWS CostandUsageReportService service.
The AWS Cost and Usage Report API enables you to programmatically create, query, and delete AWS Cost and Usage report definitions. AWS Cost and Usage reports track the monthly AWS costs and usage associated with your AWS account. The report contains line items for each unique combination of AWS product, usage type, and operation that your AWS account uses. You can configure the AWS Cost and Usage report to show only the data that you want, using the AWS Cost and Usage API. Service Endpoint The AWS Cost and Usage Report API provides the following endpoint: cur.us-east-1.amazonaws.com
*/
public struct CostandUsageReportService: AWSService {
// MARK: Member variables
public let client: AWSClient
public let config: AWSServiceConfig
// MARK: Initialization
/// Initialize the CostandUsageReportService client
/// - parameters:
/// - client: AWSClient used to process requests
/// - region: Region of server you want to communicate with. This will override the partition parameter.
/// - partition: AWS partition where service resides, standard (.aws), china (.awscn), government (.awsusgov).
/// - endpoint: Custom endpoint URL to use instead of standard AWS servers
/// - timeout: Timeout value for HTTP requests
public init(
client: AWSClient,
region: SotoCore.Region? = nil,
partition: AWSPartition = .aws,
endpoint: String? = nil,
timeout: TimeAmount? = nil,
byteBufferAllocator: ByteBufferAllocator = ByteBufferAllocator(),
options: AWSServiceConfig.Options = []
) {
self.client = client
self.config = AWSServiceConfig(
region: region,
partition: region?.partition ?? partition,
amzTarget: "AWSOrigamiServiceGatewayService",
service: "cur",
serviceProtocol: .json(version: "1.1"),
apiVersion: "2017-01-06",
endpoint: endpoint,
errorType: CostandUsageReportServiceErrorType.self,
timeout: timeout,
byteBufferAllocator: byteBufferAllocator,
options: options
)
}
// MARK: API Calls
/// Deletes the specified report.
public func deleteReportDefinition(_ input: DeleteReportDefinitionRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<DeleteReportDefinitionResponse> {
return self.client.execute(operation: "DeleteReportDefinition", path: "/", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Lists the AWS Cost and Usage reports available to this account.
public func describeReportDefinitions(_ input: DescribeReportDefinitionsRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<DescribeReportDefinitionsResponse> {
return self.client.execute(operation: "DescribeReportDefinitions", path: "/", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Allows you to programatically update your report preferences.
public func modifyReportDefinition(_ input: ModifyReportDefinitionRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<ModifyReportDefinitionResponse> {
return self.client.execute(operation: "ModifyReportDefinition", path: "/", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Creates a new report using the description that you provide.
public func putReportDefinition(_ input: PutReportDefinitionRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<PutReportDefinitionResponse> {
return self.client.execute(operation: "PutReportDefinition", path: "/", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
}
extension CostandUsageReportService {
/// Initializer required by `AWSService.with(middlewares:timeout:byteBufferAllocator:options)`. You are not able to use this initializer directly as there are no public
/// initializers for `AWSServiceConfig.Patch`. Please use `AWSService.with(middlewares:timeout:byteBufferAllocator:options)` instead.
public init(from: CostandUsageReportService, patch: AWSServiceConfig.Patch) {
self.client = from.client
self.config = from.config.with(patch: patch)
}
}
| apache-2.0 | e67cd8bd4a91ae055c449060ad6780e6 | 54.702128 | 592 | 0.699389 | 5.020134 | false | true | false | false |
jamy0801/LGWeChatKit | LGWeChatKit/LGChatKit/friend/LGFriendListCell.swift | 1 | 2966 | //
// LGFriendListCecll.swift
// LGChatViewController
//
// Created by jamy on 10/20/15.
// Copyright © 2015 jamy. All rights reserved.
//
import UIKit
class LGFriendListCell: LGConversionListBaseCell {
let iconView: UIImageView!
let userNameLabel: UILabel!
let phoneLabel: UILabel!
let messageListCellHeight = 44
let imageHeight = 40
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
iconView = UIImageView(frame: CGRectMake(5, CGFloat(messageListCellHeight - imageHeight) / 2, CGFloat(imageHeight), CGFloat(imageHeight)))
iconView.layer.cornerRadius = 5.0
iconView.layer.masksToBounds = true
userNameLabel = UILabel()
userNameLabel.textAlignment = .Left
userNameLabel.font = UIFont.systemFontOfSize(14.0)
phoneLabel = UILabel()
phoneLabel.textAlignment = .Left
phoneLabel.font = UIFont.systemFontOfSize(13.0)
phoneLabel.textColor = UIColor.lightGrayColor()
super.init(style: style, reuseIdentifier: reuseIdentifier)
contentView.addSubview(iconView)
contentView.addSubview(userNameLabel)
contentView.addSubview(phoneLabel)
userNameLabel.translatesAutoresizingMaskIntoConstraints = false
phoneLabel.translatesAutoresizingMaskIntoConstraints = false
contentView.addConstraint(NSLayoutConstraint(item: userNameLabel, attribute: .Left, relatedBy: .Equal, toItem: contentView, attribute: .Left, multiplier: 1, constant: CGFloat(messageListCellHeight + 8)))
contentView.addConstraint(NSLayoutConstraint(item: userNameLabel, attribute: .Top, relatedBy: .Equal, toItem: contentView, attribute: .Top, multiplier: 1, constant: 5))
contentView.addConstraint(NSLayoutConstraint(item: phoneLabel, attribute: .Left, relatedBy: .Equal, toItem: userNameLabel, attribute: .Left, multiplier: 1, constant: 0))
contentView.addConstraint(NSLayoutConstraint(item: phoneLabel, attribute: .Top, relatedBy: .Equal, toItem: userNameLabel, attribute: .Bottom, multiplier: 1, constant: 5))
contentView.addConstraint(NSLayoutConstraint(item: phoneLabel, attribute: .Right, relatedBy: .Equal, toItem: contentView, attribute: .Right, multiplier: 1, constant: -70))
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
var viewModel: contactCellModel? {
didSet {
viewModel?.iconName.observe {
[unowned self] in
self.iconView.image = UIImage(named: $0)
}
viewModel?.name.observe {
[unowned self] in
self.userNameLabel.text = $0
}
viewModel?.phone.observe {
[unowned self] in
self.phoneLabel.text = $0
}
}
}
}
| mit | 063e6b7b2f2f749a388957f16db74e1a | 38.533333 | 211 | 0.655987 | 5.17452 | false | false | false | false |
netguru/inbbbox-ios | Inbbbox/Source Files/Model/Protocols/BucketType.swift | 1 | 1318 | //
// BucketType.swift
// Inbbbox
//
// Created by Lukasz Wolanczyk on 2/18/16.
// Copyright © 2016 Netguru Sp. z o.o. All rights reserved.
//
import Foundation
/// Interface for Bucket and ManagedBucket.
protocol BucketType {
/// Unique identifier.
var identifier: String { get }
/// Name of the Bucket.
var name: String { get }
/// Description of the Bucket.
var attributedDescription: NSAttributedString? { get }
/// Number of shots contained in this Bucket.
var shotsCount: UInt { get }
/// Date when Bucket was created.
var createdAt: Date { get }
/// Owner of this Bucket.
///
/// - returns: User.
var owner: UserType { get }
}
func == (lhs: BucketType, rhs: BucketType) -> Bool {
return lhs.identifier == rhs.identifier
}
func == (lhs: [BucketType], rhs: [BucketType]) -> Bool {
guard lhs.count == rhs.count else { return false }
var indexingGenerators = (left: lhs.makeIterator(), right: rhs.makeIterator())
var isEqual = true
while let leftElement = indexingGenerators.left.next(),
let rightElement = indexingGenerators.right.next(), isEqual {
isEqual = leftElement == rightElement
}
return isEqual
}
func != (lhs: [BucketType], rhs: [BucketType]) -> Bool {
return !(lhs == rhs)
}
| gpl-3.0 | 197693e3527b4fc874709ead60ac4ff5 | 22.517857 | 82 | 0.634776 | 3.919643 | false | false | false | false |
wawandco/away | Example/Pods/Quick/Quick/ExampleGroup.swift | 1 | 2966 | /**
Example groups are logical groupings of examples, defined with
the `describe` and `context` functions. Example groups can share
setup and teardown code.
*/
final public class ExampleGroup {
weak internal var parent: ExampleGroup?
internal let hooks = ExampleHooks()
private let description: String
private let flags: FilterFlags
private let isInternalRootExampleGroup: Bool
private var childGroups = [ExampleGroup]()
private var childExamples = [Example]()
internal init(description: String, flags: FilterFlags, isInternalRootExampleGroup: Bool = false) {
self.description = description
self.flags = flags
self.isInternalRootExampleGroup = isInternalRootExampleGroup
}
/**
Returns a list of examples that belong to this example group,
or to any of its descendant example groups.
*/
public var examples: [Example] {
var examples = childExamples
for group in childGroups {
examples.appendContentsOf(group.examples)
}
return examples
}
internal var name: String? {
if let parent = parent {
switch(parent.name) {
case .Some(let name): return "\(name), \(description)"
case .None: return description
}
} else {
return isInternalRootExampleGroup ? nil : description
}
}
internal var filterFlags: FilterFlags {
var aggregateFlags = flags
walkUp() { (group: ExampleGroup) -> () in
for (key, value) in group.flags {
aggregateFlags[key] = value
}
}
return aggregateFlags
}
internal var befores: [BeforeExampleWithMetadataClosure] {
var closures = Array(hooks.befores.reverse())
walkUp() { (group: ExampleGroup) -> () in
closures.appendContentsOf(Array(group.hooks.befores.reverse()))
}
return Array(closures.reverse())
}
internal var afters: [AfterExampleWithMetadataClosure] {
var closures = hooks.afters
walkUp() { (group: ExampleGroup) -> () in
closures.appendContentsOf(group.hooks.afters)
}
return closures
}
internal func walkDownExamples(callback: (example: Example) -> ()) {
for example in childExamples {
callback(example: example)
}
for group in childGroups {
group.walkDownExamples(callback)
}
}
internal func appendExampleGroup(group: ExampleGroup) {
group.parent = self
childGroups.append(group)
}
internal func appendExample(example: Example) {
example.group = self
childExamples.append(example)
}
private func walkUp(callback: (group: ExampleGroup) -> ()) {
var group = self
while let parent = group.parent {
callback(group: parent)
group = parent
}
}
}
| mit | 463b5a359f6f1b53d60b64bc3c63612e | 29.57732 | 102 | 0.613284 | 5.027119 | false | false | false | false |
cpuu/OTT | OTT/Peripheral/PeripheralManagerServiceCharacteristicEditValueViewController.swift | 1 | 2275 | //
// PeripheralManagerServiceCharacteristicEditValueViewController.swift
// BlueCap
//
// Created by Troy Stribling on 8/20/14.
// Copyright (c) 2014 Troy Stribling. The MIT License (MIT).
//
import UIKit
import BlueCapKit
class PeripheralManagerServiceCharacteristicEditValueViewController: UIViewController, UITextViewDelegate {
@IBOutlet var valueTextField: UITextField!
var characteristic: BCMutableCharacteristic?
var valueName: String?
var peripheralManagerViewController: PeripheralManagerViewController?
required init?(coder aDecoder:NSCoder) {
super.init(coder:aDecoder)
}
override func viewDidLoad() {
super.viewDidLoad()
if let valueName = self.valueName {
self.navigationItem.title = valueName
if let value = self.characteristic?.stringValue?[valueName] {
self.valueTextField.text = value
}
}
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(PeripheralManagerServiceCharacteristicEditValueViewController.didEnterBackground), name: UIApplicationDidEnterBackgroundNotification, object: nil)
}
override func viewWillDisappear(animated: Bool) {
super.viewWillDisappear(animated)
NSNotificationCenter.defaultCenter().removeObserver(self)
}
func didEnterBackground() {
BCLogger.debug()
if let peripheralManagerViewController = self.peripheralManagerViewController {
self.navigationController?.popToViewController(peripheralManagerViewController, animated:false)
}
}
// UITextFieldDelegate
func textFieldShouldReturn(textField: UITextField!) -> Bool {
if let newValue = self.valueTextField.text,
valueName = self.valueName,
characteristic = self.characteristic where !valueName.isEmpty {
if var values = characteristic.stringValue {
values[valueName] = newValue
characteristic.updateValueWithString(values)
self.navigationController?.popViewControllerAnimated(true)
}
}
return true
}
} | mit | 15fa396fc27461aec8ef5dbc28b2fec7 | 34.015385 | 229 | 0.693626 | 5.774112 | false | false | false | false |
february29/Learning | swift/Fch_Contact/Pods/RxCocoa/RxCocoa/Common/DelegateProxy.swift | 8 | 11539 | //
// DelegateProxy.swift
// RxCocoa
//
// Created by Krunoslav Zaher on 6/14/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
#if !os(Linux)
#if !RX_NO_MODULE
import RxSwift
#if SWIFT_PACKAGE && !os(Linux)
import RxCocoaRuntime
#endif
#endif
/// Base class for `DelegateProxyType` protocol.
///
/// This implementation is not thread safe and can be used only from one thread (Main thread).
open class DelegateProxy<P: AnyObject, D: AnyObject>: _RXDelegateProxy {
public typealias ParentObject = P
public typealias Delegate = D
private var _sentMessageForSelector = [Selector: MessageDispatcher]()
private var _methodInvokedForSelector = [Selector: MessageDispatcher]()
/// Parent object associated with delegate proxy.
private weak private(set) var _parentObject: ParentObject?
fileprivate let _currentDelegateFor: (ParentObject) -> Delegate?
fileprivate let _setCurrentDelegateTo: (Delegate?, ParentObject) -> ()
/// Initializes new instance.
///
/// - parameter parentObject: Optional parent object that owns `DelegateProxy` as associated object.
public init<Proxy: DelegateProxyType>(parentObject: ParentObject, delegateProxy: Proxy.Type)
where Proxy: DelegateProxy<ParentObject, Delegate>, Proxy.ParentObject == ParentObject, Proxy.Delegate == Delegate {
self._parentObject = parentObject
self._currentDelegateFor = delegateProxy.currentDelegate(for:)
self._setCurrentDelegateTo = delegateProxy.setCurrentDelegate(_:to:)
MainScheduler.ensureExecutingOnScheduler()
#if TRACE_RESOURCES
_ = Resources.incrementTotal()
#endif
super.init()
}
/**
Returns observable sequence of invocations of delegate methods. Elements are sent *before method is invoked*.
Only methods that have `void` return value can be observed using this method because
those methods are used as a notification mechanism. It doesn't matter if they are optional
or not. Observing is performed by installing a hidden associated `PublishSubject` that is
used to dispatch messages to observers.
Delegate methods that have non `void` return value can't be observed directly using this method
because:
* those methods are not intended to be used as a notification mechanism, but as a behavior customization mechanism
* there is no sensible automatic way to determine a default return value
In case observing of delegate methods that have return type is required, it can be done by
manually installing a `PublishSubject` or `BehaviorSubject` and implementing delegate method.
e.g.
// delegate proxy part (RxScrollViewDelegateProxy)
let internalSubject = PublishSubject<CGPoint>
public func requiredDelegateMethod(scrollView: UIScrollView, arg1: CGPoint) -> Bool {
internalSubject.on(.next(arg1))
return self._forwardToDelegate?.requiredDelegateMethod?(scrollView, arg1: arg1) ?? defaultReturnValue
}
....
// reactive property implementation in a real class (`UIScrollView`)
public var property: Observable<CGPoint> {
let proxy = RxScrollViewDelegateProxy.proxy(for: base)
return proxy.internalSubject.asObservable()
}
**In case calling this method prints "Delegate proxy is already implementing `\(selector)`,
a more performant way of registering might exist.", that means that manual observing method
is required analog to the example above because delegate method has already been implemented.**
- parameter selector: Selector used to filter observed invocations of delegate methods.
- returns: Observable sequence of arguments passed to `selector` method.
*/
open func sentMessage(_ selector: Selector) -> Observable<[Any]> {
MainScheduler.ensureExecutingOnScheduler()
checkSelectorIsObservable(selector)
let subject = _sentMessageForSelector[selector]
if let subject = subject {
return subject.asObservable()
}
else {
let subject = MessageDispatcher(delegateProxy: self)
_sentMessageForSelector[selector] = subject
return subject.asObservable()
}
}
/**
Returns observable sequence of invoked delegate methods. Elements are sent *after method is invoked*.
Only methods that have `void` return value can be observed using this method because
those methods are used as a notification mechanism. It doesn't matter if they are optional
or not. Observing is performed by installing a hidden associated `PublishSubject` that is
used to dispatch messages to observers.
Delegate methods that have non `void` return value can't be observed directly using this method
because:
* those methods are not intended to be used as a notification mechanism, but as a behavior customization mechanism
* there is no sensible automatic way to determine a default return value
In case observing of delegate methods that have return type is required, it can be done by
manually installing a `PublishSubject` or `BehaviorSubject` and implementing delegate method.
e.g.
// delegate proxy part (RxScrollViewDelegateProxy)
let internalSubject = PublishSubject<CGPoint>
public func requiredDelegateMethod(scrollView: UIScrollView, arg1: CGPoint) -> Bool {
internalSubject.on(.next(arg1))
return self._forwardToDelegate?.requiredDelegateMethod?(scrollView, arg1: arg1) ?? defaultReturnValue
}
....
// reactive property implementation in a real class (`UIScrollView`)
public var property: Observable<CGPoint> {
let proxy = RxScrollViewDelegateProxy.proxy(for: base)
return proxy.internalSubject.asObservable()
}
**In case calling this method prints "Delegate proxy is already implementing `\(selector)`,
a more performant way of registering might exist.", that means that manual observing method
is required analog to the example above because delegate method has already been implemented.**
- parameter selector: Selector used to filter observed invocations of delegate methods.
- returns: Observable sequence of arguments passed to `selector` method.
*/
open func methodInvoked(_ selector: Selector) -> Observable<[Any]> {
MainScheduler.ensureExecutingOnScheduler()
checkSelectorIsObservable(selector)
let subject = _methodInvokedForSelector[selector]
if let subject = subject {
return subject.asObservable()
}
else {
let subject = MessageDispatcher(delegateProxy: self)
_methodInvokedForSelector[selector] = subject
return subject.asObservable()
}
}
private func checkSelectorIsObservable(_ selector: Selector) {
MainScheduler.ensureExecutingOnScheduler()
if hasWiredImplementation(for: selector) {
print("Delegate proxy is already implementing `\(selector)`, a more performant way of registering might exist.")
return
}
guard ((self.forwardToDelegate() as? NSObject)?.responds(to: selector) ?? false) || voidDelegateMethodsContain(selector) else {
rxFatalError("This class doesn't respond to selector \(selector)")
}
}
// proxy
open override func _sentMessage(_ selector: Selector, withArguments arguments: [Any]) {
_sentMessageForSelector[selector]?.on(.next(arguments))
}
open override func _methodInvoked(_ selector: Selector, withArguments arguments: [Any]) {
_methodInvokedForSelector[selector]?.on(.next(arguments))
}
/// Returns reference of normal delegate that receives all forwarded messages
/// through `self`.
///
/// - returns: Value of reference if set or nil.
open func forwardToDelegate() -> Delegate? {
return castOptionalOrFatalError(self._forwardToDelegate)
}
/// Sets reference of normal delegate that receives all forwarded messages
/// through `self`.
///
/// - parameter forwardToDelegate: Reference of delegate that receives all messages through `self`.
/// - parameter retainDelegate: Should `self` retain `forwardToDelegate`.
open func setForwardToDelegate(_ delegate: Delegate?, retainDelegate: Bool) {
#if DEBUG // 4.0 all configurations
MainScheduler.ensureExecutingOnScheduler()
#endif
self._setForwardToDelegate(delegate, retainDelegate: retainDelegate)
self.reset()
}
private func hasObservers(selector: Selector) -> Bool {
return (_sentMessageForSelector[selector]?.hasObservers ?? false)
|| (_methodInvokedForSelector[selector]?.hasObservers ?? false)
}
override open func responds(to aSelector: Selector!) -> Bool {
return super.responds(to: aSelector)
|| (self._forwardToDelegate?.responds(to: aSelector) ?? false)
|| (self.voidDelegateMethodsContain(aSelector) && self.hasObservers(selector: aSelector))
}
fileprivate func reset() {
guard let parentObject = self._parentObject else { return }
let maybeCurrentDelegate = _currentDelegateFor(parentObject)
if maybeCurrentDelegate === self {
_setCurrentDelegateTo(nil, parentObject)
_setCurrentDelegateTo(castOrFatalError(self), parentObject)
}
}
deinit {
for v in _sentMessageForSelector.values {
v.on(.completed)
}
for v in _methodInvokedForSelector.values {
v.on(.completed)
}
#if TRACE_RESOURCES
_ = Resources.decrementTotal()
#endif
}
}
fileprivate let mainScheduler = MainScheduler()
fileprivate final class MessageDispatcher {
private let dispatcher: PublishSubject<[Any]>
private let result: Observable<[Any]>
init<P, D>(delegateProxy _delegateProxy: DelegateProxy<P, D>) {
weak var weakDelegateProxy = _delegateProxy
let dispatcher = PublishSubject<[Any]>()
self.dispatcher = dispatcher
self.result = dispatcher
.do(onSubscribed: { weakDelegateProxy?.reset() }, onDispose: { weakDelegateProxy?.reset() })
.share()
.subscribeOn(mainScheduler)
}
var on: (Event<[Any]>) -> () {
return self.dispatcher.on
}
var hasObservers: Bool {
return self.dispatcher.hasObservers
}
func asObservable() -> Observable<[Any]> {
return self.result
}
}
#endif
| mit | 062bdb244146d419c401edb25f0ca275 | 40.503597 | 139 | 0.635639 | 5.815524 | false | false | false | false |
jianweihehe/JWDouYuZB | JWDouYuZB/JWDouYuZB/Classes/Room/Controller/RoomShowViewController.swift | 1 | 1071 | //
// RoomShowViewController.swift
// JWDouYuZB
//
// Created by [email protected] on 2017/1/16.
// Copyright © 2017年 简伟. All rights reserved.
//
import UIKit
class RoomShowViewController: UIViewController {
fileprivate lazy var dismissButton:UIButton = {
let dismissButton = UIButton(type: UIButtonType.custom)
dismissButton.frame = CGRect(x: JWScreenWidth - 100, y: 60, width: 80, height: 40)
dismissButton.setTitle("返回", for: .normal)
dismissButton.backgroundColor = UIColor.cyan
dismissButton.addTarget(self, action: #selector(dissmissButtonClick), for: .touchUpInside)
return dismissButton
}()
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = UIColor.red
setupUI()
}
@objc private func dissmissButtonClick() {
self.dismiss(animated: true, completion: nil)
}
}
// MARK: - 设置UI界面
extension RoomShowViewController{
func setupUI() {
view.addSubview(dismissButton)
}
}
| mit | 73545cdac255a7d82feda3a10f79caa2 | 22.909091 | 98 | 0.653992 | 4.495726 | false | false | false | false |
twobitlabs/Nimble | Tests/NimbleTests/Matchers/AllPassTest.swift | 16 | 4069 | import XCTest
import Nimble
/// Add operators to `Optional` for conforming `Comparable` that removed in Swift 3.0
extension Optional where Wrapped: Comparable {
static func < (lhs: Optional, rhs: Optional) -> Bool {
switch (lhs, rhs) {
case let (l?, r?):
return l < r
case (nil, _?):
return true
default:
return false
}
}
static func > (lhs: Optional, rhs: Optional) -> Bool {
switch (lhs, rhs) {
case let (l?, r?):
return l > r
default:
return rhs < lhs
}
}
static func <= (lhs: Optional, rhs: Optional) -> Bool {
switch (lhs, rhs) {
case let (l?, r?):
return l <= r
default:
return !(rhs < lhs)
}
}
static func >= (lhs: Optional, rhs: Optional) -> Bool {
switch (lhs, rhs) {
case let (l?, r?):
return l >= r
default:
return !(lhs < rhs)
}
}
}
final class AllPassTest: XCTestCase, XCTestCaseProvider {
func testAllPassArray() {
expect([1, 2, 3, 4]).to(allPass({$0 < 5}))
expect([1, 2, 3, 4]).toNot(allPass({$0 > 5}))
failsWithErrorMessage(
"expected to all pass a condition, but failed first at element <3> in <[1, 2, 3, 4]>") {
expect([1, 2, 3, 4]).to(allPass({$0 < 3}))
}
failsWithErrorMessage("expected to not all pass a condition") {
expect([1, 2, 3, 4]).toNot(allPass({$0 < 5}))
}
failsWithErrorMessage(
"expected to all be something, but failed first at element <3> in <[1, 2, 3, 4]>") {
expect([1, 2, 3, 4]).to(allPass("be something", {$0 < 3}))
}
failsWithErrorMessage("expected to not all be something") {
expect([1, 2, 3, 4]).toNot(allPass("be something", {$0 < 5}))
}
}
func testAllPassMatcher() {
expect([1, 2, 3, 4]).to(allPass(beLessThan(5)))
expect([1, 2, 3, 4]).toNot(allPass(beGreaterThan(5)))
failsWithErrorMessage(
"expected to all be less than <3>, but failed first at element <3> in <[1, 2, 3, 4]>") {
expect([1, 2, 3, 4]).to(allPass(beLessThan(3)))
}
failsWithErrorMessage("expected to not all be less than <5>") {
expect([1, 2, 3, 4]).toNot(allPass(beLessThan(5)))
}
}
func testAllPassCollectionsWithOptionalsDontWork() {
failsWithErrorMessage("expected to all be nil, but failed first at element <nil> in <[nil, nil, nil]>") {
expect([nil, nil, nil] as [Int?]).to(allPass(beNil()))
}
failsWithErrorMessage("expected to all pass a condition, but failed first at element <nil> in <[nil, nil, nil]>") {
expect([nil, nil, nil] as [Int?]).to(allPass({$0 == nil}))
}
}
func testAllPassCollectionsWithOptionalsUnwrappingOneOptionalLayer() {
expect([nil, nil, nil] as [Int?]).to(allPass({$0! == nil}))
expect([nil, 1, nil] as [Int?]).toNot(allPass({$0! == nil}))
expect([1, 1, 1] as [Int?]).to(allPass({$0! == 1}))
expect([1, 1, nil] as [Int?]).toNot(allPass({$0! == 1}))
expect([1, 2, 3] as [Int?]).to(allPass({$0! < 4}))
expect([1, 2, 3] as [Int?]).toNot(allPass({$0! < 3}))
expect([1, 2, nil] as [Int?]).to(allPass({$0! < 3}))
}
func testAllPassSet() {
expect(Set([1, 2, 3, 4])).to(allPass({$0 < 5}))
expect(Set([1, 2, 3, 4])).toNot(allPass({$0 > 5}))
failsWithErrorMessage("expected to not all pass a condition") {
expect(Set([1, 2, 3, 4])).toNot(allPass({$0 < 5}))
}
failsWithErrorMessage("expected to not all be something") {
expect(Set([1, 2, 3, 4])).toNot(allPass("be something", {$0 < 5}))
}
}
func testAllPassWithNilAsExpectedValue() {
failsWithErrorMessageForNil("expected to all pass") {
expect(nil as [Int]?).to(allPass(beLessThan(5)))
}
}
}
| apache-2.0 | 682d336dbbd75c35bcbb6b216b6b862d | 34.382609 | 123 | 0.521504 | 3.795709 | false | true | false | false |
daehn/Counted-Set | CountedSetTests/HashHelper.swift | 1 | 1534 | //
// The MIT License (MIT)
// Copyright 2016 Silvan Dähn
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
// of the Software, and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
// PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
// CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE
// OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
class HashHelper: Hashable, Equatable {
fileprivate let _hashValue: Int
fileprivate let name: String
init(hashValue: Int, name: String) {
_hashValue = hashValue
self.name = name
}
var hashValue: Int {
return _hashValue
}
}
func ==(lhs: HashHelper, rhs: HashHelper) -> Bool {
return lhs._hashValue == rhs._hashValue && lhs.name == rhs.name
}
| mit | ae84b401668bcf0121538dcd63b56c7b | 35.5 | 87 | 0.724723 | 4.456395 | false | false | false | false |
merlos/iOS-Open-GPX-Tracker | OpenGpxTracker/AboutViewController.swift | 1 | 3197 | //
// InfoWKViewController.swift
// OpenGpxTracker
//
// Created by merlos on 24/09/14.
//
// Localized by nitricware on 19/08/19.
//
import UIKit
import WebKit
///
/// Controller to display the About page.
///
/// Internally it is a WKWebView that displays the resource file about.html.
///
class AboutViewController: UIViewController {
/// Embedded web browser
var webView: WKWebView?
/// Initializer. Only calls super
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
/// Initializer. Only calls super
override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
}
///
/// Configures the view. Performs the following actions:
///
/// 1. Sets the title to About
/// 2. Adds "Done" button
/// 3. Adds the webview that loads about.html from the bundle.
///
override func viewDidLoad() {
super.viewDidLoad()
self.title = NSLocalizedString("ABOUT", comment: "no comment")
//Add the done button
let shareItem = UIBarButtonItem(title: NSLocalizedString("DONE", comment: "no comment"),
style: UIBarButtonItem.Style.plain, target: self,
action: #selector(AboutViewController.closeViewController))
self.navigationItem.rightBarButtonItems = [shareItem]
//Add the Webview
self.webView = WKWebView(frame: self.view.frame, configuration: WKWebViewConfiguration())
self.webView?.navigationDelegate = self
let path = Bundle.main.path(forResource: "about", ofType: "html")
let text = try? String(contentsOfFile: path!, encoding: String.Encoding.utf8)
webView?.loadHTMLString(text!, baseURL: nil)
webView?.autoresizingMask = [.flexibleWidth, .flexibleHeight]
self.view.addSubview(webView!)
}
/// Closes this view controller. Triggered by pressing the "Done" button in navigation bar.
@objc func closeViewController() {
self.dismiss(animated: true, completion: { () -> Void in
})
}
}
/// Handles all navigation related stuff for the web view
extension AboutViewController: WKNavigationDelegate {
/// Opens Safari when user clicks a link in the About page.
func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction,
decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
print("AboutViewController: decidePolicyForNavigationAction")
if navigationAction.navigationType == .linkActivated {
if #available(iOS 10, *) {
UIApplication.shared.open(navigationAction.request.url!)
}
else {
UIApplication.shared.openURL(navigationAction.request.url!)
}
print("AboutViewController: external link sent to Safari")
decisionHandler(.cancel)
return
}
decisionHandler(.allow)
}
}
| gpl-3.0 | cc8c010b212fc0eb8d0c40b1c61de1f0 | 31.958763 | 99 | 0.620582 | 5.232406 | false | false | false | false |
kevintavog/WatchThis | Source/WatchThis/Preferences.swift | 1 | 2128 | //
//
import Foundation
import RangicCore
class Preferences : BasePreferences
{
static let SlideshowFileExtension = "watchthisslideshow"
static fileprivate let SlideshowFolderKey = "SlideshowFolder"
static fileprivate let LastEditedFilenameKey = "LastEditedFilename"
static fileprivate let VideoPlayerVolumeKey = "VideoPlayerVolume"
static fileprivate let BaseLocationLookupKey = "BaseLocationLookup"
static fileprivate let FindAPhotoHost = "FindAPhotoHost"
static func setMissingDefaults()
{
let appSupportFolder = FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask).first!
lastEditedFilename = NSString.path(withComponents: [appSupportFolder.path, "WatchThis", "LastEdited"])
lastEditedFilename = (lastEditedFilename as NSString).appendingPathExtension(SlideshowFileExtension)!
let picturesFolder = FileManager.default.urls(for: .picturesDirectory, in: .userDomainMask).first!
slideshowFolder = NSString.path(withComponents: [picturesFolder.path, "WatchThis Slideshows"])
setDefaultValue("http://open.mapquestapi.com", key: BaseLocationLookupKey)
setDefaultValue("http://web.local:5000", key: FindAPhotoHost)
}
static var baseLocationLookup: String
{
get { return stringForKey(BaseLocationLookupKey) }
set { super.setValue(newValue, key: BaseLocationLookupKey) }
}
static var slideshowFolder: String
{
get { return stringForKey(SlideshowFolderKey) }
set { super.setValue(newValue, key: SlideshowFolderKey) }
}
static var lastEditedFilename: String
{
get { return stringForKey(LastEditedFilenameKey) }
set { super.setValue(newValue, key: LastEditedFilenameKey) }
}
static var videoPlayerVolume: Float
{
get { return floatForKey(VideoPlayerVolumeKey) }
set { setValue(newValue, key: VideoPlayerVolumeKey) }
}
static var findAPhotoHost: String
{
get { return stringForKey(FindAPhotoHost) }
set { super.setValue(newValue, key: FindAPhotoHost) }
}
}
| mit | 6fc49c6b08d8981ef8c33a691ca631f9 | 34.466667 | 118 | 0.717105 | 4.636166 | false | false | false | false |
Pluto-Y/SwiftyEcharts | SwiftyEcharts/Models/Title.swift | 1 | 6956 | //
// Title.swift
// SwiftyEcharts
//
// Created by Pluto Y on 30/11/2016.
// Copyright © 2016 com.pluto-y. All rights reserved.
//
/// 标题组件,包含主标题和副标题。
/// 在 ECharts 2.x 中单个 ECharts 实例最多只能拥有一个标题组件。但是在 ECharts 3 中可以存在任意多个标题组件,这在需要标题进行排版,或者单个实例中的多个图表都需要标题时会比较有用。
public final class Title: Borderable, Displayable, Textful, Zable {
/// 是否显示标题组件
public var show: Bool?
/// 主标题文本,支持使用 \n 换。
public var text: String?
/// 主标题文本超链接
public var link: String?
/// 指定窗口打开主标题超链接。
public var target: Target?
/// 主标题文字样式
public var textStyle: TextStyle?
/// 标题文本水平对齐
public var textAlign: Align?
/// 标题文本垂直对齐
public var textBaseline: VerticalAlign?
/// 副标题文本,支持使用 \n 换行
public var subtext: String?
/// 副标题文本超链接
public var sublink: String?
/// 指定窗口打开副标题超链接
public var subtarget: Target?
/// 副标题文字样式
public var subtextStyle: TextStyle?
/// 标题内边距
public var padding: Padding?
/// 主副标题之间的间距
public var itemGap: Float?
/// 所有图形的`zlevel`值
public var zlevel: Float?
/// 组件的所有图形的z值。控制图形的前后顺序。z值小的图形会被z值大的图形覆盖。
/// z相比zlevel优先级更低,而且不会创建新的 Canvas
public var z: Float?
/// grid 组件离容器左侧的距离。
public var left: Position?
/// grid 组件离容器上侧的距离。
public var top: Position?
/// grid 组件离容器右侧的距离。
public var right: Position?
/// grid 组件离容器下侧的距离。
public var bottom: Position?
/// 标题背景色,默认透明。
public var backgroundColor: Color?
/// 标题的边框颜色。支持的颜色格式同 backgroundColor。
public var borderColor: Color?
/// 标题的边框线宽。
public var borderWidth: Float?
/// 图形阴影的模糊大小。该属性配合 shadowColor,shadowOffsetX, shadowOffsetY 一起设置图形的阴影效果
/// 注意:此配置项生效的前提是,设置了 show: true 以及值不为 tranparent 的背景色 backgroundColor。
public var shadowBlur: Float?
/// 阴影颜色
/// 注意:此配置项生效的前提是,设置了 show: true。
public var shadowColor: Color?
/// 阴影水平方向上的偏移距离。
/// 注意:此配置项生效的前提是,设置了 show: true。
public var shadowOffsetX: Float?
/// 阴影水平方向上的偏移距离。
/// 注意:此配置项生效的前提是,设置了 show: true。
public var shadowOffsetY: Float?
public init() { }
}
extension Title: Enumable {
public enum Enums {
case show(Bool), text(String), link(String), target(Target), textStyle(TextStyle), textAlign(Align), textBaseline(VerticalAlign), subtext(String), sublink(String), subtarget(Target), subtextStyle(TextStyle), padding(Padding), itemGap(Float), zlevel(Float), z(Float), left(Position), x(Position), top(Position), y(Position), right(Position), bottom(Position), backgroundColor(Color), borderColor(Color), borderWidth(Float), shadowBlur(Float), shadowColor(Color), shadowOffsetX(Float), shadowOffsetY(Float)
}
public typealias ContentEnum = Enums
public convenience init(_ elements: Enums...) {
self.init()
for ele in elements {
switch ele {
case let .show(show):
self.show = show
case let .text(text):
self.text = text
case let .link(link):
self.link = link
case let .target(target):
self.target = target
case let .textStyle(textStyle):
self.textStyle = textStyle
case let .textAlign(align):
self.textAlign = align
case let .textBaseline(baseline):
self.textBaseline = baseline
case let .subtext(text):
self.subtext = text
case let .sublink(sublink):
self.sublink = sublink
case let .subtarget(target):
self.subtarget = target
case let .subtextStyle(textStyle):
self.subtextStyle = textStyle
case let .padding(padding):
self.padding = padding
case let .itemGap(itemGap):
self.itemGap = itemGap
case let .zlevel(zlevel):
self.zlevel = zlevel
case let .z(z):
self.z = z
case let .left(left):
self.left = left
case let .x(left):
self.left = left
case let .y(top):
self.top = top
case let .top(top):
self.top = top
case let .right(right):
self.right = right
case let .bottom(bottom):
self.bottom = bottom
case let .backgroundColor(backgroundColor):
self.backgroundColor = backgroundColor
case let .borderColor(color):
self.borderColor = color
case let .borderWidth(width):
self.borderWidth = width
case let .shadowBlur(blur):
self.shadowBlur = blur
case let .shadowColor(color):
self.shadowColor = color
case let .shadowOffsetX(x):
self.shadowOffsetX = x
case let .shadowOffsetY(y):
self.shadowOffsetY = y
}
}
}
}
extension Title: Mappable {
public func mapping(_ map: Mapper) {
map["show"] = show
map["text"] = text
map["link"] = link
map["target"] = target
map["textStyle"] = textStyle
map["textAlign"] = textAlign
map["textBaseline"] = textBaseline
map["subtext"] = subtext
map["sublink"] = sublink
map["subtarget"] = subtarget
map["subtextStyle"] = subtextStyle
map["padding"] = padding
map["itemGap"] = itemGap
map["zlevel"] = zlevel
map["z"] = z
map["left"] = left
map["top"] = top
map["right"] = right
map["bottom"] = bottom
map["backgroundColor"] = backgroundColor
map["borderColor"] = borderColor
map["borderWidth"] = borderWidth
map["shadowBlur"] = shadowBlur
map["shadowColor"] = shadowColor
map["shadowOffsetX"] = shadowOffsetX
map["shadowOffsetY"] = shadowOffsetY
}
}
| mit | 3159017e2116ab029d1289e1a7fc7494 | 33.488506 | 512 | 0.576404 | 4.127235 | false | false | false | false |
tjw/swift | test/SILGen/existential_metatypes.swift | 2 | 2942 | // RUN: %target-swift-frontend -emit-silgen -parse-stdlib -enable-sil-ownership %s | %FileCheck %s
struct Value {}
protocol P {
init()
static func staticMethod() -> Self
static var value: Value { get }
}
struct S: P {
init() {}
static func staticMethod() -> S { return S() }
static var value: Value { return Value() }
}
// CHECK-LABEL: sil hidden @$S21existential_metatypes0A8MetatypeyyAA1P_pF
// CHECK: bb0([[X:%.*]] : @trivial $*P):
func existentialMetatype(_ x: P) {
// CHECK: [[TYPE1:%.*]] = existential_metatype $@thick P.Type, [[X]]
let type1 = type(of: x)
// CHECK: [[INSTANCE1:%.*]] = alloc_stack $P
// CHECK: [[OPEN_TYPE1:%.*]] = open_existential_metatype [[TYPE1]]
// CHECK: [[INSTANCE1_VALUE:%.*]] = init_existential_addr [[INSTANCE1]] : $*P
// CHECK: [[INIT:%.*]] = witness_method {{.*}} #P.init!allocator
// CHECK: apply [[INIT]]<{{.*}}>([[INSTANCE1_VALUE]], [[OPEN_TYPE1]])
let instance1 = type1.init()
// CHECK: [[S:%.*]] = metatype $@thick S.Type
// CHECK: [[TYPE2:%.*]] = init_existential_metatype [[S]] : $@thick S.Type, $@thick P.Type
let type2: P.Type = S.self
// CHECK: [[INSTANCE2:%.*]] = alloc_stack $P
// CHECK: [[OPEN_TYPE2:%.*]] = open_existential_metatype [[TYPE2]]
// CHECK: [[INSTANCE2_VALUE:%.*]] = init_existential_addr [[INSTANCE2]] : $*P
// CHECK: [[STATIC_METHOD:%.*]] = witness_method {{.*}} #P.staticMethod
// CHECK: apply [[STATIC_METHOD]]<{{.*}}>([[INSTANCE2_VALUE]], [[OPEN_TYPE2]])
let instance2 = type2.staticMethod()
}
protocol PP: P {}
protocol Q {}
// CHECK-LABEL: sil hidden @$S21existential_metatypes0A15MetatypeUpcast1yAA1P_pXpAA2PP_pXpF
// CHECK: [[OPENED:%.*]] = open_existential_metatype %0
// CHECK: [[NEW:%.*]] = init_existential_metatype [[OPENED]]
// CHECK: return [[NEW]]
func existentialMetatypeUpcast1(_ x: PP.Type) -> P.Type {
return x
}
// CHECK-LABEL: sil hidden @$S21existential_metatypes0A15MetatypeUpcast2yAA1P_pXpAaC_AA1QpXpF
// CHECK: [[OPENED:%.*]] = open_existential_metatype %0
// CHECK: [[NEW:%.*]] = init_existential_metatype [[OPENED]]
// CHECK: return [[NEW]]
func existentialMetatypeUpcast2(_ x: (P & Q).Type) -> P.Type {
return x
}
// rdar://32288618
// CHECK-LABEL: sil hidden @$S21existential_metatypes0A19MetatypeVarPropertyAA5ValueVyF : $@convention(thin) () -> Value
func existentialMetatypeVarProperty() -> Value {
// CHECK: [[BOX:%.*]] = alloc_box ${ var @thick P.Type }
// CHECK: [[ADDR:%.*]] = project_box [[BOX]] : ${ var @thick P.Type }, 0
// CHECK: [[T0:%.*]] = metatype $@thick S.Type
// CHECK: [[T1:%.*]] = init_existential_metatype [[T0]]
// CHECK: store [[T1]] to [trivial] [[ADDR]] :
// CHECK: [[T0:%.*]] = begin_access [read] [unknown] [[ADDR]] :
// CHECK: [[T1:%.*]] = load [trivial] [[T0]]
// CHECK: open_existential_metatype [[T1]] :
var type: P.Type = S.self
return type.value
}
| apache-2.0 | 78ccd469cb5c1edf2c6f0824f838e5c4 | 39.861111 | 120 | 0.600612 | 3.346985 | false | false | false | false |
CPRTeam/CCIP-iOS | OPass/OPassEventCell.swift | 1 | 1693 | //
// OPassEventCell.swift
// OPass
//
// Created by 腹黒い茶 on 2019/3/3.
// 2019 OPass.
//
import Foundation
import UIKit
import FoldingCell
class OPassEventCell: FoldingCell {
var EventId: String = ""
@IBOutlet weak var EventLogo: UIImageView!
@IBOutlet weak var EventName: UILabel!
override func awakeFromNib() {
self.foregroundView.layer.cornerRadius = 10
self.foregroundView.backgroundColor = Constants.appConfigColor.colorConfig("EventSwitcherButtonColor")
self.backgroundColor = UIColor.clear
self.layer.shadowColor = UIColor.black.cgColor
self.layer.shadowRadius = 4.0
self.layer.shadowOpacity = 0.3
self.layer.shadowOffset = CGSize(width: 1, height: 1)
self.layer.masksToBounds = false
self.EventLogo.layer.shadowColor = UIColor.black.cgColor
self.EventLogo.layer.shadowRadius = 4.0
self.EventLogo.layer.shadowOpacity = 0.3
self.EventLogo.layer.shadowOffset = CGSize(width: 1, height: 1)
self.EventLogo.layer.masksToBounds = false
self.EventName.textColor = Constants.appConfigColor.colorConfig("EventSwitcherTextColor")
self.EventName.layer.shadowColor = UIColor.black.cgColor
self.EventName.layer.shadowRadius = 4.0
self.EventName.layer.shadowOpacity = 0.3
self.EventName.layer.shadowOffset = CGSize(width: 1, height: 1)
self.EventName.layer.masksToBounds = false
super.awakeFromNib()
}
override func animationDuration(_ itemIndex: NSInteger, type _: FoldingCell.AnimationType) -> TimeInterval {
let durations = [0.26, 0.2, 0.2]
return durations[itemIndex]
}
}
| gpl-3.0 | 1d37a84a23c84992c30838f5619479bf | 33.387755 | 112 | 0.692582 | 4.27665 | false | true | false | false |
apple/swift | test/IRGen/prespecialized-metadata/class-fileprivate-inmodule-1argument-1distinct_use_generic_class.swift | 14 | 10743 | // RUN: %swift -prespecialize-generic-metadata -target %module-target-future -emit-ir %s | %FileCheck %s -DINT=i%target-ptrsize -DALIGNMENT=%target-alignment --check-prefix=CHECK --check-prefix=CHECK-%target-vendor
// REQUIRES: VENDOR=apple || OS=linux-gnu
// UNSUPPORTED: CPU=i386 && OS=ios
// UNSUPPORTED: CPU=armv7 && OS=ios
// UNSUPPORTED: CPU=armv7s && OS=ios
// CHECK: @"$s4main3Box[[UNIQUE_ID_1:[A-Za-z0-9_]+]]LLCySiGMf" =
// CHECK: @"$s4main5Value[[UNIQUE_ID_1]]LLCyAA3BoxACLLCySiGGMf" = linkonce_odr hidden
// CHECK-apple-SAME: global
// CHECK-unknown-SAME: constant
// CHECK-SAME: <{
// CHECK-SAME: void (
// CHECK-SAME: %T4main5Value[[UNIQUE_ID_1]]LLC*
// CHECK-SAME: )*,
// CHECK-SAME: i8**,
// : [[INT]],
// CHECK-apple-SAME: %objc_class*,
// CHECK-unknown-SAME: %swift.type*,
// CHECK-apple-SAME: %swift.opaque*,
// CHECK-apple-SAME: %swift.opaque*,
// CHECK-apple-SAME: [[INT]],
// CHECK-SAME: i32,
// CHECK-SAME: i32,
// CHECK-SAME: i32,
// CHECK-SAME: i16,
// CHECK-SAME: i16,
// CHECK-SAME: i32,
// CHECK-SAME: i32,
// CHECK-SAME: %swift.type_descriptor*,
// CHECK-SAME: i8*,
// CHECK-SAME: %swift.type*,
// CHECK-SAME: [[INT]],
// CHECK-SAME: %T4main5Value[[UNIQUE_ID_1]]LLC* (
// CHECK-SAME: %swift.opaque*,
// CHECK-SAME: %swift.type*
// CHECK-SAME: )*
// CHECK-SAME: }> <{
// CHECK-SAME: void (
// CHECK-SAME: %T4main5Value[[UNIQUE_ID_1]]LLC*
// CHECK-SAME: $s4main5Value[[UNIQUE_ID_1]]LLCfD
// CHECK-SAME: $sBoWV
// CHECK-apple-SAME: $s4main5Value[[UNIQUE_ID_1]]LLCyAA3BoxACLLCySiGGMM
// CHECK-unknown-SAME: [[INT]] 0,
// CHECK-apple-SAME: OBJC_CLASS_$__TtCs12_SwiftObject
// CHECK-unknown-SAME: %swift.type* null,
// CHECK-apple-SAME: %swift.opaque* @_objc_empty_cache,
// CHECK-apple-SAME: %swift.opaque* null,
// CHECK-apple-SAME: [[INT]] add (
// CHECK-apple-SAME: [[INT]] ptrtoint (
// CHECK-apple-SAME: {
// CHECK-apple-SAME: i32,
// CHECK-apple-SAME: i32,
// CHECK-apple-SAME: i32,
// : i32,
// CHECK-apple-SAME: i8*,
// CHECK-apple-SAME: i8*,
// CHECK-apple-SAME: i8*,
// CHECK-apple-SAME: i8*,
// CHECK-apple-SAME: {
// CHECK-apple-SAME: i32,
// CHECK-apple-SAME: i32,
// CHECK-apple-SAME: [
// CHECK-apple-SAME: 1 x {
// CHECK-apple-SAME: [[INT]]*,
// CHECK-apple-SAME: i8*,
// CHECK-apple-SAME: i8*,
// CHECK-apple-SAME: i32,
// CHECK-apple-SAME: i32
// CHECK-apple-SAME: }
// CHECK-apple-SAME: ]
// CHECK-apple-SAME: }*,
// CHECK-apple-SAME: i8*,
// CHECK-apple-SAME: i8*
// CHECK-apple-SAME: }* @"_DATA_$s4main5Value[[UNIQUE_ID_1]]LLCyAA3BoxACLLCySiGGMf" to [[INT]]
// CHECK-apple-SAME: ),
// CHECK-apple-SAME: [[INT]] 2
// CHECK-apple-SAME: ),
// CHECK-SAME: i32 26,
// CHECK-SAME: i32 0,
// CHECK-SAME: i32 {{(24|12)}},
// CHECK-SAME: i16 {{(7|3)}},
// CHECK-SAME: i16 0,
// CHECK-apple-SAME: i32 {{(120|72)}},
// CHECK-unknown-SAME: i32 96,
// CHECK-SAME: i32 {{(16|8)}},
// : %swift.type_descriptor* bitcast (
// : <{
// : i32,
// : i32,
// : i32,
// : i32,
// : i32,
// : i32,
// : i32,
// : i32,
// : i32,
// : i32,
// : i32,
// : i32,
// : i32,
// : i16,
// : i16,
// : i16,
// : i16,
// : i8,
// : i8,
// : i8,
// : i8,
// : i32,
// : i32,
// : %swift.method_descriptor
// : }>* @"$s4main5Value[[UNIQUE_ID_1]]LLCMn" to %swift.type_descriptor*
// : ),
// CHECK-SAME: i8* null,
// CHECK-SAME: %swift.type* getelementptr inbounds (
// CHECK-SAME: %swift.full_heapmetadata,
// CHECK-SAME: %swift.full_heapmetadata* bitcast (
// CHECK-SAME: <{
// CHECK-SAME: void (
// CHECK-SAME: %T4main3Box[[UNIQUE_ID_1:[a-zA-Z0-9_]+]]LLC*
// CHECK-SAME: )*,
// CHECK-SAME: i8**,
// : [[INT]],
// CHECK-apple-SAME: %objc_class*,
// CHECK-unknown-SAME: %swift.type*,
// CHECK-apple-SAME: %swift.opaque*,
// CHECK-apple-SAME: %swift.opaque*,
// CHECK-apple-SAME: [[INT]],
// CHECK-SAME: i32,
// CHECK-SAME: i32,
// CHECK-SAME: i32,
// CHECK-SAME: i16,
// CHECK-SAME: i16,
// CHECK-SAME: i32,
// CHECK-SAME: i32,
// CHECK-SAME: %swift.type_descriptor*,
// CHECK-SAME: i8*,
// CHECK-SAME: %swift.type*,
// CHECK-SAME: [[INT]],
// CHECK-SAME: %T4main3Box[[UNIQUE_ID_1]]LLC* (
// CHECK-SAME: %swift.opaque*,
// CHECK-SAME: %swift.type*
// CHECK-SAME: )*
// CHECK-SAME: }>* @"$s4main3Box[[UNIQUE_ID_1]]LLCySiGMf" to %swift.full_heapmetadata*
// CHECK-SAME: ),
// CHECK-SAME: i32 0,
// CHECK-SAME: i32 2
// CHECK-SAME: ),
// CHECK-SAME: [[INT]] {{(16|8)}},
// CHECK-SAME: %T4main5Value[[UNIQUE_ID_1]]LLC* (
// CHECK-SAME: %swift.opaque*,
// CHECK-SAME: %swift.type*
// CHECK-SAME: $s4main5Value[[UNIQUE_ID_1]]LLC5firstADyxGx_tcfC
// CHECK-SAME: }>,
// CHECK-SAME: align [[ALIGNMENT]]
fileprivate class Value<First> {
let first_Value: First
init(first: First) {
self.first_Value = first
}
}
fileprivate class Box<Value> {
let value: Value
init(value: Value) {
self.value = value
}
}
@inline(never)
func consume<T>(_ t: T) {
withExtendedLifetime(t) { t in
}
}
// CHECK: define hidden swiftcc void @"$s4main4doityyF"() #{{[0-9]+}} {
// CHECK: [[METADATA_RESPONSE:%[0-9]+]] = call swiftcc %swift.metadata_response @"$s4main5Value[[UNIQUE_ID_4:[0-9A-Z_]+]]LLCyAA3BoxACLLCySiGGMb"([[INT]] 0)
// CHECK: [[METADATA:%[0-9]+]] = extractvalue %swift.metadata_response [[METADATA_RESPONSE]], 0
// CHECK: call swiftcc void @"$s4main7consumeyyxlF"(
// CHECK-SAME: %swift.opaque* noalias nocapture {{%[0-9]+}},
// CHECK-SAME: %swift.type* [[METADATA]])
// CHECK: }
func doit() {
consume( Value(first: Box(value: 13)) )
}
doit()
// CHECK: define internal swiftcc %swift.metadata_response @"$s4main5Value[[UNIQUE_ID_1]]LLCMa"([[INT]] [[METADATA_REQUEST:%[0-9]+]], %swift.type* %1) #{{[0-9]+}} {
// CHECK: entry:
// CHECK: [[ERASED_TYPE:%[0-9]+]] = bitcast %swift.type* %1 to i8*
// CHECK: {{%[0-9]+}} = call swiftcc %swift.metadata_response @__swift_instantiateCanonicalPrespecializedGenericMetadata(
// CHECK: [[INT]] [[METADATA_REQUEST]],
// CHECK: i8* [[ERASED_TYPE]],
// CHECK: i8* undef,
// CHECK: i8* undef,
// CHECK: %swift.type_descriptor* bitcast (
// : <{ i32, i32, i32, i32, i32, i32, i32, i32, i32, i32, i32, i32, i32, i16, i16, i16, i16, i8, i8, i8, i8, i32, i32, %swift.method_descriptor }>*
// CHECK: $s4main5Value[[UNIQUE_ID_1]]LLCMn
// CHECK: to %swift.type_descriptor*
// CHECK: )
// CHECK: ) #{{[0-9]+}}
// CHECK: ret %swift.metadata_response {{%[0-9]+}}
// CHECK: }
// CHECK: ; Function Attrs: noinline nounwind readnone
// CHECK: define linkonce_odr hidden swiftcc %swift.metadata_response @"$s4main5Value[[UNIQUE_ID_1]]LLCyAA3BoxACLLCySiGGMb"([[INT]] {{%[0-9]+}}) {{#[0-9]+}} {
// CHECK: entry:
// CHECK-unknown: ret
// CHECK-apple: [[INITIALIZED_CLASS:%[0-9]+]] = call %objc_class* @objc_opt_self(
// : %objc_class* bitcast (
// : %swift.type* getelementptr inbounds (
// : %swift.full_heapmetadata,
// : %swift.full_heapmetadata* bitcast (
// : <{
// : void (
// : %T4main5Value33_9100AE3EFBE408E03C856CED54B18B61LLC*
// : )*,
// : i8**,
// : [[INT]],
// : %objc_class*,
// : %swift.opaque*,
// : %swift.opaque*,
// : [[INT]],
// : i32,
// : i32,
// : i32,
// : i16,
// : i16,
// : i32,
// : i32,
// : %swift.type_descriptor*,
// : i8*,
// : %swift.type*,
// : [[INT]],
// : %T4main5Value33_9100AE3EFBE408E03C856CED54B18B61LLC* (
// : %swift.opaque*,
// : %swift.type*
// : )*
// CHECK-SAME: @"$s4main5Value[[UNIQUE_ID_1]]LLCyAA3BoxACLLCySiGGMf"
// : to %swift.full_heapmetadata*
// : ),
// : i32 0,
// : i32 2
// : ) to %objc_class*
// : )
// : )
// CHECK-apple: [[INITIALIZED_METADATA:%[0-9]+]] = bitcast %objc_class* [[INITIALIZED_CLASS]] to %swift.type*
// CHECK-apple: [[PARTIAL_METADATA_RESPONSE:%[0-9]+]] = insertvalue %swift.metadata_response undef, %swift.type* [[INITIALIZED_METADATA]], 0
// CHECK-apple: [[METADATA_RESPONSE:%[0-9]+]] = insertvalue %swift.metadata_response [[PARTIAL_METADATA_RESPONSE]], [[INT]] 0, 1
// CHECK-apple: ret %swift.metadata_response [[METADATA_RESPONSE]]
// CHECK: }
| apache-2.0 | 47557c6dd2148c1a009df4ce1a922118 | 40.801556 | 214 | 0.448664 | 3.203041 | false | false | false | false |
noppoMan/aws-sdk-swift | Sources/Soto/Services/Pricing/Pricing_Error.swift | 1 | 2645 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Soto for AWS open source project
//
// Copyright (c) 2017-2020 the Soto project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of Soto project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
// THIS FILE IS AUTOMATICALLY GENERATED by https://github.com/soto-project/soto/tree/main/CodeGenerator. DO NOT EDIT.
import SotoCore
/// Error enum for Pricing
public struct PricingErrorType: AWSErrorType {
enum Code: String {
case expiredNextTokenException = "ExpiredNextTokenException"
case internalErrorException = "InternalErrorException"
case invalidNextTokenException = "InvalidNextTokenException"
case invalidParameterException = "InvalidParameterException"
case notFoundException = "NotFoundException"
}
private let error: Code
public let context: AWSErrorContext?
/// initialize Pricing
public init?(errorCode: String, context: AWSErrorContext) {
guard let error = Code(rawValue: errorCode) else { return nil }
self.error = error
self.context = context
}
internal init(_ error: Code) {
self.error = error
self.context = nil
}
/// return error code string
public var errorCode: String { self.error.rawValue }
/// The pagination token expired. Try again without a pagination token.
public static var expiredNextTokenException: Self { .init(.expiredNextTokenException) }
/// An error on the server occurred during the processing of your request. Try again later.
public static var internalErrorException: Self { .init(.internalErrorException) }
/// The pagination token is invalid. Try again without a pagination token.
public static var invalidNextTokenException: Self { .init(.invalidNextTokenException) }
/// One or more parameters had an invalid value.
public static var invalidParameterException: Self { .init(.invalidParameterException) }
/// The requested resource can't be found.
public static var notFoundException: Self { .init(.notFoundException) }
}
extension PricingErrorType: Equatable {
public static func == (lhs: PricingErrorType, rhs: PricingErrorType) -> Bool {
lhs.error == rhs.error
}
}
extension PricingErrorType: CustomStringConvertible {
public var description: String {
return "\(self.error.rawValue): \(self.message ?? "")"
}
}
| apache-2.0 | 214a9b440055a81604268848d1a3c64b | 37.333333 | 117 | 0.670699 | 5.057361 | false | false | false | false |
Brightify/DataMapper | Source/Core/SupportedType.swift | 1 | 3005 | //
// SupportedType.swift
// DataMapper
//
// Created by Filip Dolnik on 20.10.16.
// Copyright © 2016 Brightify. All rights reserved.
//
import Foundation
public final class SupportedType: CustomStringConvertible {
public enum RawType {
case null
case string
case bool
case int
case double
case array
case dictionary
case intOrDouble
}
public private(set) var raw: Any?
public private(set) var type: RawType
public var description: String {
return String(describing: raw)
}
public init(raw: Any?, type: RawType) {
self.raw = raw
self.type = type
}
public func addToDictionary(key: String, value: SupportedType) {
var mutableDictionary: [String: SupportedType]
if let dictionary = dictionary {
mutableDictionary = dictionary
} else {
mutableDictionary = [:]
type = .dictionary
}
mutableDictionary[key] = value
raw = mutableDictionary
}
}
extension SupportedType {
public var isNull: Bool {
return raw == nil
}
public var string: String? {
return raw as? String
}
public var bool: Bool? {
return raw as? Bool
}
public var int: Int? {
return raw as? Int
}
public var double: Double? {
if type == .intOrDouble, let int = int {
return Double(int)
} else {
return raw as? Double
}
}
public var array: [SupportedType]? {
return raw as? [SupportedType]
}
public var dictionary: [String: SupportedType]? {
return raw as? [String: SupportedType]
}
}
extension SupportedType {
public static func raw(_ raw: Any?, type: RawType) -> SupportedType {
return SupportedType(raw: raw, type: type)
}
public static var null: SupportedType {
return SupportedType(raw: nil, type: .null)
}
public static func string(_ value: String) -> SupportedType {
return SupportedType(raw: value, type: .string)
}
public static func bool(_ value: Bool) -> SupportedType {
return SupportedType(raw: value, type: .bool)
}
public static func int(_ value: Int) -> SupportedType {
return SupportedType(raw: value, type: .int)
}
public static func double(_ value: Double) -> SupportedType {
return SupportedType(raw: value, type: .double)
}
public static func array(_ value: [SupportedType]) -> SupportedType {
return SupportedType(raw: value, type: .array)
}
public static func dictionary(_ value: [String: SupportedType]) -> SupportedType {
return SupportedType(raw: value, type: .dictionary)
}
public static func intOrDouble(_ value: Int) -> SupportedType {
return SupportedType(raw: value, type: .intOrDouble)
}
}
| mit | 69ffb20d090092a21c55056fdeea9794 | 23.622951 | 86 | 0.586218 | 4.753165 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.