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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
michaelgwelch/swift-parsing | Parsing/Parsing/Operators.swift | 1 | 1778 | //
// Operators.swift
// tibasic
//
// Created by Michael Welch on 7/22/15.
// Copyright © 2015 Michael Welch. All rights reserved.
//
/*
Haskell Precdence
. 9 r (function composition)
* 7 l
+ 6 l
*> 4 l
<* 4 l
<*> 4 l
<$> 4 l
== 4 none
<|> 3 l
&& 3 r
|| 2 r
>> 1 l
>>= 1 l
$ 0 r
*/
import Foundation
// §
precedencegroup ApplicationPrecedence {
higherThan: AssignmentPrecedence, TernaryPrecedence
associativity: right
}
precedencegroup MonadicBindPrecedence {
higherThan: ApplicationPrecedence
associativity: left
}
precedencegroup AlternativePrecedence {
higherThan: MonadicBindPrecedence
associativity: left
}
precedencegroup ApplicativePrecedence {
higherThan: AlternativePrecedence
associativity: left
}
precedencegroup FunctionCompositionPrecedence {
higherThan: ApplicativePrecedence
associativity: right
}
// Like Haskell . (compose)
infix operator • : FunctionCompositionPrecedence
// Like Haskell fmap, <$>
infix operator <§> : ApplicativePrecedence
// Like Haskell Applicative <*>
infix operator <*> : ApplicativePrecedence //{ associativity left precedence 120 }
// Haskell Applicative <*
infix operator <* : ApplicativePrecedence //{ associativity left precedence 120 }
// Haskell Applictive *>
//infix operator *> { associativity left precedence 120 }
infix operator *> : ApplicativePrecedence
// Like Haskell Alternative <|>
infix operator <|> : AlternativePrecedence
// Like Haskell >>=, bind
infix operator |>>= : MonadicBindPrecedence
// Like Haskell >> (sequence and throw away the value on the left)
infix operator |>> : MonadicBindPrecedence
// Like Haskell $
infix operator § : ApplicationPrecedence
// repeatMany
postfix operator *
postfix operator +
| mit | af5f56064d3a261fc009af64e580ff20 | 16.544554 | 82 | 0.71219 | 4.463476 | false | false | false | false |
lanjing99/iOSByTutorials | iOS Apprentice V4/Tutorial 2 Checklists/Checklists/Checklists/AllListsViewController.swift | 1 | 8195 | //
// AllListsViewController.swift
// Checklists
//
// Created by lanjing on 11/11/15.
// Copyright © 2015 lanjing. All rights reserved.
//
import UIKit
class AllListsViewController: UITableViewController, ListDetailViewControllerDelegate {
var lists : [Checklist]
required init?(coder aDecoder: NSCoder) {
lists = [Checklist]()
super.init(coder: aDecoder)
configData()
}
override func viewDidLoad() {
super.viewDidLoad()
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view delegate
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
performSegueWithIdentifier("ShowChecklist", sender: checklistAtIndex(indexPath))
}
override func tableView(tableView: UITableView, accessoryButtonTappedForRowWithIndexPath indexPath: NSIndexPath) {
performSegueWithIdentifier("EditChecklist", sender: checklistAtIndex(indexPath))
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return lists.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
// let cell = tableView.dequeueReusableCellWithIdentifier("reuseIdentifier", forIndexPath: indexPath)
// Configure the cell...
var cell = tableView.dequeueReusableCellWithIdentifier("cell")
if cell == nil {
cell = UITableViewCell(style: .Default, reuseIdentifier: "cell")
cell?.accessoryType = .DetailDisclosureButton
}
let checklist = checklistAtIndex(indexPath)!
cell!.textLabel?.text = checklist.name
return cell!
}
/*
// Override to support conditional editing of the table view.
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the specified item to be editable.
return true
}
*/
/*
// Override to support editing the table view.
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == .Delete {
// Delete the row from the data source
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
} else if editingStyle == .Insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
*/
/*
// Override to support rearranging the table view.
override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) {
}
*/
/*
// Override to support conditional rearranging of the table view.
override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the item to be re-orderable.
return true
}
*/
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
if(segue.identifier == "ShowChecklist"){
let checklist = sender as? Checklist
let viewController = segue.destinationViewController as! ChecklistsTableViewController
viewController.checklist = checklist
}else if segue.identifier == "AddChecklist" {
let navigationController = segue.destinationViewController as! UINavigationController
let controller = navigationController.topViewController as! ListDetailViewController
controller.delegate = self
controller.checklistToEdit = nil
}else if segue.identifier == "EditChecklist" {
let navigationController = segue.destinationViewController as! UINavigationController
let controller = navigationController.topViewController as! ListDetailViewController
controller.delegate = self
controller.checklistToEdit = sender as? Checklist
}
}
//MARK: - Private Methods
func checklistAtIndex(indexPath:NSIndexPath) -> Checklist?{
if indexPath.row < 0 || indexPath.row >= lists.count {
return nil
}
return lists[indexPath.row]
}
//MARK: - private methods
private func configData(){
var list = Checklist(name: "Birthdays")
lists.append(list)
list = Checklist(name: "Groceries")
lists.append(list)
list = Checklist(name: "Cool Apps")
lists.append(list)
list = Checklist(name: "To Do")
lists.append(list)
for list in lists {
let item = ChecklistItem()
item.text = "item for \(list.name)"
list.items.append(item)
}
}
func documentDirectory()->String{
let paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)
return paths[0]
}
func dataFilePath() -> String{
return (documentDirectory() as NSString).stringByAppendingPathComponent("Checklist.plist")
}
func saveChecklistItem(){
let data = NSMutableData()
let archiver = NSKeyedArchiver(forWritingWithMutableData: data)
archiver.encodeObject(lists, forKey: "lists")
archiver.finishEncoding()
data.writeToFile(dataFilePath(), atomically: true)
}
func loadChecklistItems(){
let path = dataFilePath()
// if NSFileManager.defaultManager().fileExistsAtPath(path){
if let data = NSData(contentsOfFile: path){
let unarchiver = NSKeyedUnarchiver(forReadingWithData: data)
lists = unarchiver.decodeObjectForKey("lists") as! [Checklist]
unarchiver.finishDecoding()
}
// }的
}
// MARK: - ListDetailViewController delegate
func listDetailViewControllerDidCancel(controller: ListDetailViewController) {
dismissViewControllerAnimated(true, completion: nil)
}
func listDetailViewController(controller: ListDetailViewController, didFinishAddingChecklist item: Checklist) {
let index = lists.count
let indexPath = NSIndexPath(forRow: index, inSection: 0)
lists.append(item)
tableView.insertRowsAtIndexPaths([indexPath], withRowAnimation: .Automatic)
dismissViewControllerAnimated(true, completion: nil)
}
func listDetailViewController(controller: ListDetailViewController, didFinishEditingChecklist item: Checklist) {
let index = lists.indexOf(item)
let indexPath = NSIndexPath(forRow: index!, inSection: 0)
tableView.reloadRowsAtIndexPaths([indexPath], withRowAnimation: .Automatic)
dismissViewControllerAnimated(true, completion: nil)
}
@IBAction func addChecklist(sender: AnyObject) {
performSegueWithIdentifier("AddChecklist", sender: nil)
}
}
| mit | fdb399b39d5e39403ab33f16ee8af72a | 34.158798 | 157 | 0.665894 | 5.830605 | false | false | false | false |
gang462234887/TestKitchen_1606 | TestKitchen/TestKitchen/classes/common/MainTabBarController.swift | 1 | 6544 | //
// MainTabBarController.swift
// TestKitchen
//
// Created by qianfeng on 16/8/15.
// Copyright © 2016年 qianfeng. All rights reserved.
//
import UIKit
class MainTabBarController: UITabBarController {
private var bgView:UIView?
//json对应的数组
private var array:Array<Dictionary<String,String>>?{
get{
let path = NSBundle.mainBundle().pathForResource("Ctrl.json", ofType: nil)
var myArray:Array<Dictionary<String,String>>? = nil
if let filePath = path{
let data = NSData(contentsOfFile: filePath)
do{
let jsonValue = try NSJSONSerialization.JSONObjectWithData(data!, options: .MutableContainers)
if jsonValue.isKindOfClass(NSArray.self){
myArray = jsonValue as? Array<Dictionary<String,String>>
}
}catch{
print(error)
return nil
}
}
return myArray
}
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
createViewControllers()
}
//创建视图控制器
func createViewControllers(){
var ctrlNames = [String]()
var imageNames = [String]()
var titleNames = [String]()
if let tmpArray = self.array{
for dict in tmpArray{
let name = dict["ctrlName"]
let titleName = dict["titleName"]
let imageName = dict["imageName"]
ctrlNames.append(name!)
titleNames.append(titleName!)
imageNames.append(imageName!)
}
}else{
ctrlNames = ["CookBookViewController","CommunityViewController","MallViewController","FoodClassViewController","ProfileViewController"]
//home_normal@2x home_select@2x community_normal@2x community_select@2x shop_normal@2x shop_select@2x shike_normal@2x shike_select@2x mine_normal@2x mine_select@2x
titleNames = ["食材","社区","商城","食课","我的"]
imageNames = ["home","community","shop","shike","mine"]
}
var vCtrlArray = Array<UINavigationController>()
for i in 0..<ctrlNames.count{
let ctrlName = "TestKitchen." + ctrlNames[i]
let cls = NSClassFromString(ctrlName) as! UIViewController.Type
let ctrl = cls.init()
let navCtrl = UINavigationController(rootViewController: ctrl)
vCtrlArray.append(navCtrl)
}
self.viewControllers = vCtrlArray
//自定制tabbar
self.createCustomTabbar(titleNames, imageNames: imageNames)
}
//自定制tabbar
func createCustomTabbar(titleNames:[String],imageNames:[String]){
self.bgView = UIView.createView()
self.bgView?.backgroundColor = UIColor.whiteColor()
self.bgView?.layer.borderWidth = 1
self.bgView?.layer.borderColor = UIColor.grayColor().CGColor
self.view.addSubview(self.bgView!)
self.bgView?.snp_makeConstraints(closure: {
[weak self]
(make) in
make.left.right.equalTo(self!.view)
make.bottom.equalTo((self?.view)!)
make.top.equalTo((self?.view.snp_bottom)!).offset(-49)
let width = kScreenWidth/5.0
for i in 0..<imageNames.count{
let imageName = imageNames[i]
let titleName = titleNames[i]
let bgImageName = imageName+"_normal"
let selectBgImageName = imageName+"_select"
let btn = UIButton.createBtn(nil, bgImageName: bgImageName, selectBgImageName: selectBgImageName, target: self, action: #selector(self!.clickBtn(_:)))
btn.tag = 300+i
self?.bgView?.addSubview(btn)
btn.snp_makeConstraints(closure: {
[weak self]
(make) in
make.top.bottom.equalTo((self?.bgView)!)
make.width.equalTo(width)
make.left.equalTo(width*CGFloat(i))
})
let label = UILabel.createLabel(titleName, font: UIFont.systemFontOfSize(8), textAlignment: .Center, textColor: UIColor.grayColor())
label.tag = 400
btn.addSubview(label)
label.snp_makeConstraints(closure: { (make) in
make.left.right.equalTo(btn)
make.top.equalTo(btn).offset(32)
make.height.equalTo(12)
})
if i == 0{
btn.selected = true
label.textColor = UIColor.orangeColor()
}
}
})
}
func clickBtn(curBtn:UIButton){
//1.取消之前选中按钮的状态
let lastBtnView = self.view.viewWithTag(300+selectedIndex)
if let tmpBtn = lastBtnView{
let lastBtn = tmpBtn as! UIButton
let lastView = tmpBtn.viewWithTag(400)
if let tmpLabel = lastView{
let lastLbael = tmpLabel as! UILabel
lastBtn.selected = false
lastLbael.textColor = UIColor.grayColor()
}
}
//2.设置当前选中按钮的状态
let curLabelView = curBtn.viewWithTag(400)
if let tmpLabel = curLabelView{
let curLabel = tmpLabel as! UILabel
curBtn.selected = true
curLabel.textColor = UIColor.orangeColor()
}
//选中视图控制器
selectedIndex = curBtn.tag - 300
}
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 | e23b04bf7bc3308dfa16c6c68a6d5e4a | 33.929348 | 179 | 0.542399 | 5.15397 | false | false | false | false |
KeithPiTsui/Pavers | Pavers/Sources/CryptoSwift/SHA3.swift | 2 | 10535 | //
// SHA3.swift
// CryptoSwift
//
// Copyright (C) 2014-2017 Marcin Krzyżanowski <[email protected]>
// This software is provided 'as-is', without any express or implied warranty.
//
// In no event will the authors be held liable for any damages arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions:
//
// - The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation is required.
// - Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
// - This notice may not be removed or altered from any source or binary distribution.
//
// http://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.202.pdf
// http://keccak.noekeon.org/specs_summary.html
//
#if os(Linux) || os(Android) || os(FreeBSD)
import Glibc
#else
import Darwin
#endif
public final class SHA3: DigestType {
let round_constants: Array<UInt64> = [
0x0000000000000001, 0x0000000000008082, 0x800000000000808a, 0x8000000080008000,
0x000000000000808b, 0x0000000080000001, 0x8000000080008081, 0x8000000000008009,
0x000000000000008a, 0x0000000000000088, 0x0000000080008009, 0x000000008000000a,
0x000000008000808b, 0x800000000000008b, 0x8000000000008089, 0x8000000000008003,
0x8000000000008002, 0x8000000000000080, 0x000000000000800a, 0x800000008000000a,
0x8000000080008081, 0x8000000000008080, 0x0000000080000001, 0x8000000080008008,
]
public let blockSize: Int
public let digestLength: Int
public let markByte: UInt8
fileprivate var accumulated = Array<UInt8>()
fileprivate var processedBytesTotalCount: Int = 0
fileprivate var accumulatedHash: Array<UInt64>
public enum Variant {
case sha224, sha256, sha384, sha512, keccak224, keccak256, keccak384, keccak512
var digestLength: Int {
return 100 - (blockSize / 2)
}
var blockSize: Int {
return (1600 - outputLength * 2) / 8
}
var markByte: UInt8 {
switch self {
case .sha224, .sha256, .sha384, .sha512:
return 0x06 // 0x1F for SHAKE
case .keccak224, .keccak256, .keccak384, .keccak512:
return 0x01
}
}
public var outputLength: Int {
switch self {
case .sha224, .keccak224:
return 224
case .sha256, .keccak256:
return 256
case .sha384, .keccak384:
return 384
case .sha512, .keccak512:
return 512
}
}
}
public init(variant: SHA3.Variant) {
blockSize = variant.blockSize
digestLength = variant.digestLength
markByte = variant.markByte
accumulatedHash = Array<UInt64>(repeating: 0, count: digestLength)
}
public func calculate(for bytes: Array<UInt8>) -> Array<UInt8> {
do {
return try update(withBytes: bytes.slice, isLast: true)
} catch {
return []
}
}
/// 1. For all pairs (x,z) such that 0≤x<5 and 0≤z<w, let
/// C[x,z]=A[x, 0,z] ⊕ A[x, 1,z] ⊕ A[x, 2,z] ⊕ A[x, 3,z] ⊕ A[x, 4,z].
/// 2. For all pairs (x, z) such that 0≤x<5 and 0≤z<w let
/// D[x,z]=C[(x1) mod 5, z] ⊕ C[(x+1) mod 5, (z –1) mod w].
/// 3. For all triples (x, y, z) such that 0≤x<5, 0≤y<5, and 0≤z<w, let
/// A′[x, y,z] = A[x, y,z] ⊕ D[x,z].
private func θ(_ a: inout Array<UInt64>) {
let c = UnsafeMutablePointer<UInt64>.allocate(capacity: 5)
c.initialize(to: 0, count: 5)
defer {
c.deinitialize(count: 5)
c.deallocate(capacity: 5)
}
let d = UnsafeMutablePointer<UInt64>.allocate(capacity: 5)
d.initialize(to: 0, count: 5)
defer {
d.deinitialize(count: 5)
d.deallocate(capacity: 5)
}
for i in 0..<5 {
c[i] = a[i] ^ a[i &+ 5] ^ a[i &+ 10] ^ a[i &+ 15] ^ a[i &+ 20]
}
d[0] = rotateLeft(c[1], by: 1) ^ c[4]
d[1] = rotateLeft(c[2], by: 1) ^ c[0]
d[2] = rotateLeft(c[3], by: 1) ^ c[1]
d[3] = rotateLeft(c[4], by: 1) ^ c[2]
d[4] = rotateLeft(c[0], by: 1) ^ c[3]
for i in 0..<5 {
a[i] ^= d[i]
a[i &+ 5] ^= d[i]
a[i &+ 10] ^= d[i]
a[i &+ 15] ^= d[i]
a[i &+ 20] ^= d[i]
}
}
/// A′[x, y, z]=A[(x &+ 3y) mod 5, x, z]
private func π(_ a: inout Array<UInt64>) {
let a1 = a[1]
a[1] = a[6]
a[6] = a[9]
a[9] = a[22]
a[22] = a[14]
a[14] = a[20]
a[20] = a[2]
a[2] = a[12]
a[12] = a[13]
a[13] = a[19]
a[19] = a[23]
a[23] = a[15]
a[15] = a[4]
a[4] = a[24]
a[24] = a[21]
a[21] = a[8]
a[8] = a[16]
a[16] = a[5]
a[5] = a[3]
a[3] = a[18]
a[18] = a[17]
a[17] = a[11]
a[11] = a[7]
a[7] = a[10]
a[10] = a1
}
/// For all triples (x, y, z) such that 0≤x<5, 0≤y<5, and 0≤z<w, let
/// A′[x, y,z] = A[x, y,z] ⊕ ((A[(x+1) mod 5, y, z] ⊕ 1) ⋅ A[(x+2) mod 5, y, z])
private func χ(_ a: inout Array<UInt64>) {
for i in stride(from: 0, to: 25, by: 5) {
let a0 = a[0 &+ i]
let a1 = a[1 &+ i]
a[0 &+ i] ^= ~a1 & a[2 &+ i]
a[1 &+ i] ^= ~a[2 &+ i] & a[3 &+ i]
a[2 &+ i] ^= ~a[3 &+ i] & a[4 &+ i]
a[3 &+ i] ^= ~a[4 &+ i] & a0
a[4 &+ i] ^= ~a0 & a1
}
}
private func ι(_ a: inout Array<UInt64>, round: Int) {
a[0] ^= round_constants[round]
}
fileprivate func process(block chunk: ArraySlice<UInt64>, currentHash hh: inout Array<UInt64>) {
// expand
hh[0] ^= chunk[0].littleEndian
hh[1] ^= chunk[1].littleEndian
hh[2] ^= chunk[2].littleEndian
hh[3] ^= chunk[3].littleEndian
hh[4] ^= chunk[4].littleEndian
hh[5] ^= chunk[5].littleEndian
hh[6] ^= chunk[6].littleEndian
hh[7] ^= chunk[7].littleEndian
hh[8] ^= chunk[8].littleEndian
if blockSize > 72 { // 72 / 8, sha-512
hh[9] ^= chunk[9].littleEndian
hh[10] ^= chunk[10].littleEndian
hh[11] ^= chunk[11].littleEndian
hh[12] ^= chunk[12].littleEndian
if blockSize > 104 { // 104 / 8, sha-384
hh[13] ^= chunk[13].littleEndian
hh[14] ^= chunk[14].littleEndian
hh[15] ^= chunk[15].littleEndian
hh[16] ^= chunk[16].littleEndian
if blockSize > 136 { // 136 / 8, sha-256
hh[17] ^= chunk[17].littleEndian
// FULL_SHA3_FAMILY_SUPPORT
if blockSize > 144 { // 144 / 8, sha-224
hh[18] ^= chunk[18].littleEndian
hh[19] ^= chunk[19].littleEndian
hh[20] ^= chunk[20].littleEndian
hh[21] ^= chunk[21].littleEndian
hh[22] ^= chunk[22].littleEndian
hh[23] ^= chunk[23].littleEndian
hh[24] ^= chunk[24].littleEndian
}
}
}
}
// Keccak-f
for round in 0..<24 {
θ(&hh)
hh[1] = rotateLeft(hh[1], by: 1)
hh[2] = rotateLeft(hh[2], by: 62)
hh[3] = rotateLeft(hh[3], by: 28)
hh[4] = rotateLeft(hh[4], by: 27)
hh[5] = rotateLeft(hh[5], by: 36)
hh[6] = rotateLeft(hh[6], by: 44)
hh[7] = rotateLeft(hh[7], by: 6)
hh[8] = rotateLeft(hh[8], by: 55)
hh[9] = rotateLeft(hh[9], by: 20)
hh[10] = rotateLeft(hh[10], by: 3)
hh[11] = rotateLeft(hh[11], by: 10)
hh[12] = rotateLeft(hh[12], by: 43)
hh[13] = rotateLeft(hh[13], by: 25)
hh[14] = rotateLeft(hh[14], by: 39)
hh[15] = rotateLeft(hh[15], by: 41)
hh[16] = rotateLeft(hh[16], by: 45)
hh[17] = rotateLeft(hh[17], by: 15)
hh[18] = rotateLeft(hh[18], by: 21)
hh[19] = rotateLeft(hh[19], by: 8)
hh[20] = rotateLeft(hh[20], by: 18)
hh[21] = rotateLeft(hh[21], by: 2)
hh[22] = rotateLeft(hh[22], by: 61)
hh[23] = rotateLeft(hh[23], by: 56)
hh[24] = rotateLeft(hh[24], by: 14)
π(&hh)
χ(&hh)
ι(&hh, round: round)
}
}
}
extension SHA3: Updatable {
public func update(withBytes bytes: ArraySlice<UInt8>, isLast: Bool = false) throws -> Array<UInt8> {
accumulated += bytes
if isLast {
// Add padding
let markByteIndex = processedBytesTotalCount &+ accumulated.count
if accumulated.count == 0 || accumulated.count % blockSize != 0 {
let r = blockSize * 8
let q = (r / 8) - (accumulated.count % (r / 8))
accumulated += Array<UInt8>(repeating: 0, count: q)
}
accumulated[markByteIndex] |= markByte
accumulated[self.accumulated.count - 1] |= 0x80
}
var processedBytes = 0
for chunk in accumulated.batched(by: blockSize) {
if isLast || (accumulated.count - processedBytes) >= blockSize {
process(block: chunk.toUInt64Array().slice, currentHash: &accumulatedHash)
processedBytes += chunk.count
}
}
accumulated.removeFirst(processedBytes)
processedBytesTotalCount += processedBytes
// TODO: verify performance, reduce vs for..in
let result = accumulatedHash.reduce(Array<UInt8>()) { (result, value) -> Array<UInt8> in
return result + value.bigEndian.bytes()
}
// reset hash value for instance
if isLast {
accumulatedHash = Array<UInt64>(repeating: 0, count: digestLength)
}
return Array(result[0..<self.digestLength])
}
}
| mit | 0c4fddc9039bff9476c94c0d81b64e24 | 34.883562 | 217 | 0.51422 | 3.432034 | false | false | false | false |
XCEssentials/UniFlow | Sources/8_SemanticIndicators/FeatureStatus.swift | 1 | 2276 | /*
MIT License
Copyright (c) 2016 Maxim Khatskevich ([email protected])
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
import Combine
//---
public
struct FeatureStatus
{
public
enum StatusIndicator: String, Equatable, Codable
{
case ok = "🟢"
case busy = "🟠"
case failure = "🔴"
case missing = "⚠️"
}
//---
public
let title: String
public
let subtitle: String
public
let state: SomeStateBase?
public
let indicator: StatusIndicator
public
init(missing feature: SomeFeature.Type)
{
self.title = feature.displayName
self.subtitle = "<missing>"
self.state = nil
self.indicator = .missing
}
public
init(with state: SomeStateBase)
{
self.title = type(of: state).feature.displayName
self.subtitle = .init(describing: type(of: state).self)
self.state = state
switch state
{
case is FailureIndicator:
self.indicator = .failure
case is BusyIndicator:
self.indicator = .busy
default:
self.indicator = .ok
}
}
}
| mit | da3803a5da59fe592278d989d3b6b232 | 25.623529 | 79 | 0.644719 | 4.877155 | false | false | false | false |
idapgroup/IDPDesign | Tests/iOS/Pods/Quick/Sources/Quick/NSString+C99ExtendedIdentifier.swift | 15 | 1546 | #if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
import Foundation
extension NSString {
private static var invalidCharacters: CharacterSet = {
var invalidCharacters = CharacterSet()
let invalidCharacterSets: [CharacterSet] = [
.whitespacesAndNewlines,
.illegalCharacters,
.controlCharacters,
.punctuationCharacters,
.nonBaseCharacters,
.symbols
]
for invalidSet in invalidCharacterSets {
invalidCharacters.formUnion(invalidSet)
}
return invalidCharacters
}()
/// This API is not meant to be used outside Quick, so will be unavaialbe in
/// a next major version.
@objc(qck_c99ExtendedIdentifier)
public var c99ExtendedIdentifier: String {
let validComponents = components(separatedBy: NSString.invalidCharacters)
let result = validComponents.joined(separator: "_")
return result.isEmpty ? "_" : result
}
}
/// Extension methods or properties for NSObject subclasses are invisible from
/// the Objective-C runtime on static linking unless the consumers add `-ObjC`
/// linker flag, so let's make a wrapper class to mitigate that situation.
///
/// See: https://github.com/Quick/Quick/issues/785 and https://github.com/Quick/Quick/pull/803
@objc
class QCKObjCStringUtils: NSObject {
override private init() {}
@objc
static func c99ExtendedIdentifier(from string: String) -> String {
return string.c99ExtendedIdentifier
}
}
#endif
| bsd-3-clause | 8b1e7c44ba305ea27eb51020ffc31ebe | 30.55102 | 94 | 0.66947 | 4.801242 | false | false | false | false |
kosicki123/eidolon | Kiosk/Bid Fulfillment/RegistrationEmailViewController.swift | 1 | 1338 | import UIKit
class RegistrationEmailViewController: UIViewController, RegistrationSubController, UITextFieldDelegate {
@IBOutlet var emailTextField: TextField!
@IBOutlet var confirmButton: ActionButton!
let finishedSignal = RACSubject()
override func viewDidLoad() {
super.viewDidLoad()
if let bidDetails = self.navigationController?.fulfillmentNav().bidDetails {
emailTextField.text = bidDetails.newUser.email
RAC(bidDetails, "newUser.email") <~ emailTextField.rac_textSignal()
let emailIsValidSignal = RACObserve(bidDetails.newUser, "email").map(stringIsEmailAddress)
RAC(confirmButton, "enabled") <~ emailIsValidSignal
}
emailTextField.returnKeySignal().subscribeNext({ [weak self] (_) -> Void in
self?.finishedSignal.sendCompleted()
return
})
emailTextField.becomeFirstResponder()
}
@IBAction func confirmTapped(sender: AnyObject) {
finishedSignal.sendCompleted()
}
func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
// Allow delete
if (countElements(string) == 0) { return true }
// the API doesn't accept spaces
return string != " "
}
}
| mit | f3de7b1519480d0b1793ee7ea5dd4dc9 | 30.857143 | 132 | 0.668909 | 5.598326 | false | false | false | false |
RocketChat/Rocket.Chat.iOS | Rocket.Chat/Extensions/UITextField/UITextFieldActivityIndicator.swift | 1 | 1468 | //
// UITextFieldActivityIndicator.swift
// Rocket.Chat
//
// Created by Matheus Cardoso on 6/14/18.
// Copyright © 2018 Rocket.Chat. All rights reserved.
//
import UIKit
extension UITextField {
var activityIndicator: UIActivityIndicatorView? {
if let activityIndicator = subviews.compactMap({ $0 as? UIActivityIndicatorView }).first {
return activityIndicator
} else {
let activityIndicator = UIActivityIndicatorView(style: .gray)
addSubview(activityIndicator)
activityIndicator.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
activityIndicator.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -10),
activityIndicator.centerYAnchor.constraint(equalTo: centerYAnchor, constant: 0),
activityIndicator.widthAnchor.constraint(equalToConstant: activityIndicator.frame.width),
activityIndicator.heightAnchor.constraint(equalToConstant: activityIndicator.frame.height)
])
return activityIndicator
}
}
func startIndicatingActivity() {
activityIndicator?.startAnimating()
activityIndicator?.isHidden = false
clearButton?.isHidden = true
}
func stopIndicatingActivity() {
activityIndicator?.stopAnimating()
activityIndicator?.isHidden = true
clearButton?.isHidden = false
}
}
| mit | 0eb032d23341449014b7eb138a42c578 | 32.340909 | 106 | 0.680982 | 6.1125 | false | false | false | false |
ayushgoel/SAHistoryNavigationViewController | SAHistoryNavigationViewControllerSample/SAHistoryNavigationViewControllerSample/TimelineView/DetailViewController.swift | 3 | 1503 | //
// DetailViewController.swift
// SAHistoryNavigationViewControllerSample
//
// Created by 鈴木大貴 on 2015/04/01.
// Copyright (c) 2015年 鈴木大貴. All rights reserved.
//
import UIKit
import QuartzCore
class DetailViewController: UIViewController {
@IBOutlet weak var iconButton: UIButton!
@IBOutlet weak var usernameLabel: UILabel!
@IBOutlet weak var textView: UITextView!
var iconImage: UIImage?
var text: String?
var username: String?
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
iconButton.layer.cornerRadius = 10
iconButton.layer.masksToBounds = true
setIconImage(iconImage)
usernameLabel.text = username
textView.text = text
title = username
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
private func setIconImage(image: UIImage?) {
if let image = image {
iconButton.setImage(image, forState: .Normal)
}
}
@IBAction func didTapIconButton(sender: UIButton) {
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let viewController = storyboard.instantiateViewControllerWithIdentifier("TimelineViewController")
navigationController?.pushViewController(viewController, animated: true)
}
}
| mit | 2de76afb5dd8c4df0b046a811c8f9fee | 27.711538 | 105 | 0.667113 | 5.078231 | false | false | false | false |
julienbodet/wikipedia-ios | Wikipedia/Code/WMFTableOfContentsPresentationController.swift | 1 | 11325 | import UIKit
// MARK: - Delegate
@objc public protocol WMFTableOfContentsPresentationControllerTapDelegate {
func tableOfContentsPresentationControllerDidTapBackground(_ controller: WMFTableOfContentsPresentationController)
}
open class WMFTableOfContentsPresentationController: UIPresentationController, Themeable {
var theme = Theme.standard
var displaySide = WMFTableOfContentsDisplaySide.left
var displayMode = WMFTableOfContentsDisplayMode.modal
// MARK: - init
public required init(presentedViewController: UIViewController, presentingViewController: UIViewController?, tapDelegate: WMFTableOfContentsPresentationControllerTapDelegate) {
self.tapDelegate = tapDelegate
super.init(presentedViewController: presentedViewController, presenting: presentedViewController)
}
weak open var tapDelegate: WMFTableOfContentsPresentationControllerTapDelegate?
open var minimumVisibleBackgroundWidth: CGFloat = 60.0
open var maximumTableOfContentsWidth: CGFloat = 300.0
open var statusBarEstimatedHeight: CGFloat {
if #available(iOS 11.0, *) {
return max(UIApplication.shared.statusBarFrame.size.height, presentedView?.safeAreaInsets.top ?? 0)
} else {
return UIApplication.shared.statusBarFrame.size.height
}
}
// MARK: - Views
lazy var statusBarBackground: UIView = {
let view = UIView(frame: CGRect.zero)
view.autoresizingMask = .flexibleWidth
view.layer.shadowOpacity = 0.8
view.layer.shadowOffset = CGSize(width: 0, height: 5)
view.clipsToBounds = false
return view
}()
lazy var closeButton:UIButton = {
let button = UIButton(frame: CGRect.zero)
button.setImage(UIImage(named: "close"), for: .normal)
button.addTarget(self, action: #selector(WMFTableOfContentsPresentationController.didTap(_:)), for: .touchUpInside)
button.accessibilityHint = WMFLocalizedString("table-of-contents-close-accessibility-hint", value:"Close", comment:"Accessibility hint for closing table of contents\n{{Identical|Close}}")
button.accessibilityLabel = WMFLocalizedString("table-of-contents-close-accessibility-label", value:"Close Table of contents", comment:"Accessibility label for closing table of contents")
button.translatesAutoresizingMaskIntoConstraints = false
return button
}()
var closeButtonTrailingConstraint: NSLayoutConstraint?
var closeButtonLeadingConstraint: NSLayoutConstraint?
var closeButtonTopConstraint: NSLayoutConstraint?
var closeButtonBottomConstraint: NSLayoutConstraint?
lazy var backgroundView :UIVisualEffectView = {
let view = UIVisualEffectView(frame: CGRect.zero)
view.autoresizingMask = .flexibleWidth
view.effect = UIBlurEffect(style: .light)
view.alpha = 0.0
let tap = UITapGestureRecognizer.init()
tap.addTarget(self, action: #selector(WMFTableOfContentsPresentationController.didTap(_:)))
view.addGestureRecognizer(tap)
view.contentView.addSubview(self.statusBarBackground)
let closeButtonDimension: CGFloat = 44
let widthConstraint = self.closeButton.widthAnchor.constraint(equalToConstant: closeButtonDimension)
let heightConstraint = self.closeButton.heightAnchor.constraint(equalToConstant: closeButtonDimension)
let leadingConstraint = view.contentView.layoutMarginsGuide.leadingAnchor.constraint(equalTo: self.closeButton.leadingAnchor, constant: 0)
let trailingConstraint = view.contentView.layoutMarginsGuide.trailingAnchor.constraint(equalTo: self.closeButton.trailingAnchor, constant: 0)
let topConstraint = view.contentView.layoutMarginsGuide.topAnchor.constraint(equalTo: self.closeButton.topAnchor, constant: 0)
let bottomConstraint = view.contentView.layoutMarginsGuide.bottomAnchor.constraint(equalTo: self.closeButton.bottomAnchor, constant: 0)
trailingConstraint.isActive = false
bottomConstraint.isActive = false
closeButtonLeadingConstraint = leadingConstraint
closeButtonTrailingConstraint = trailingConstraint
closeButtonTopConstraint = topConstraint
closeButtonBottomConstraint = bottomConstraint
self.closeButton.frame = CGRect(x: 0, y: 0, width: closeButtonDimension, height: closeButtonDimension)
self.closeButton.addConstraints([widthConstraint, heightConstraint])
view.contentView.addSubview(self.closeButton)
view.contentView.addConstraints([leadingConstraint, trailingConstraint, topConstraint, bottomConstraint])
return view
}()
func updateStatusBarBackgroundFrame() {
self.statusBarBackground.frame = CGRect(x: self.backgroundView.bounds.minX, y: self.backgroundView.bounds.minY, width: self.backgroundView.bounds.width, height: self.frameOfPresentedViewInContainerView.origin.y)
}
func updateButtonConstraints() {
switch self.displaySide {
case .right:
fallthrough
case .left:
closeButtonLeadingConstraint?.isActive = false
closeButtonBottomConstraint?.isActive = false
closeButtonTrailingConstraint?.isActive = true
closeButtonTopConstraint?.isActive = true
break
case .center:
fallthrough
default:
closeButtonTrailingConstraint?.isActive = false
closeButtonTopConstraint?.isActive = false
closeButtonLeadingConstraint?.isActive = true
closeButtonBottomConstraint?.isActive = true
}
return ()
}
@objc func didTap(_ tap: UITapGestureRecognizer) {
self.tapDelegate?.tableOfContentsPresentationControllerDidTapBackground(self)
}
// MARK: - Accessibility
func togglePresentingViewControllerAccessibility(_ accessible: Bool) {
self.presentingViewController.view.accessibilityElementsHidden = !accessible
}
// MARK: - UIPresentationController
override open func presentationTransitionWillBegin() {
guard let containerView = self.containerView, let presentedView = self.presentedView else {
return
}
// Add the dimming view and the presented view to the heirarchy
self.backgroundView.frame = containerView.bounds
updateStatusBarBackgroundFrame()
containerView.addSubview(self.backgroundView)
if(self.traitCollection.verticalSizeClass == .compact){
self.statusBarBackground.isHidden = true
}
updateButtonConstraints()
containerView.addSubview(presentedView)
// Hide the presenting view controller for accessibility
self.togglePresentingViewControllerAccessibility(false)
apply(theme: theme)
// Fade in the dimming view alongside the transition
if let transitionCoordinator = self.presentingViewController.transitionCoordinator {
transitionCoordinator.animate(alongsideTransition: {(context: UIViewControllerTransitionCoordinatorContext!) -> Void in
self.backgroundView.alpha = 1.0
}, completion:nil)
}
}
override open func presentationTransitionDidEnd(_ completed: Bool) {
if !completed {
self.backgroundView.removeFromSuperview()
}
}
override open func dismissalTransitionWillBegin() {
if let transitionCoordinator = self.presentingViewController.transitionCoordinator {
transitionCoordinator.animate(alongsideTransition: {(context: UIViewControllerTransitionCoordinatorContext!) -> Void in
self.backgroundView.alpha = 0.0
}, completion:nil)
}
}
override open func dismissalTransitionDidEnd(_ completed: Bool) {
if completed {
self.backgroundView.removeFromSuperview()
self.togglePresentingViewControllerAccessibility(true)
self.presentedView?.layer.cornerRadius = 0
self.presentedView?.layer.borderWidth = 0
self.presentedView?.layer.shadowOpacity = 0
self.presentedView?.clipsToBounds = true
}
}
override open var frameOfPresentedViewInContainerView : CGRect {
var frame = self.containerView!.bounds
var bgWidth = self.minimumVisibleBackgroundWidth
var tocWidth = frame.size.width - bgWidth
if(tocWidth > self.maximumTableOfContentsWidth){
tocWidth = self.maximumTableOfContentsWidth
bgWidth = frame.size.width - tocWidth
}
frame.origin.y = self.statusBarEstimatedHeight + 0.5
frame.size.height -= frame.origin.y
switch displaySide {
case .center:
frame.origin.y += 10
frame.origin.x += 0.5*bgWidth
frame.size.height -= 80
break
case .right:
frame.origin.x += bgWidth
break
default:
break
}
frame.size.width = tocWidth
return frame
}
override open func viewWillTransition(to size: CGSize, with transitionCoordinator: UIViewControllerTransitionCoordinator) {
super.viewWillTransition(to: size, with: transitionCoordinator)
transitionCoordinator.animate(alongsideTransition: {(context: UIViewControllerTransitionCoordinatorContext!) -> Void in
self.backgroundView.frame = self.containerView!.bounds
let frame = self.frameOfPresentedViewInContainerView
self.presentedView!.frame = frame
self.updateStatusBarBackgroundFrame()
self.updateButtonConstraints()
}, completion:nil)
}
public func apply(theme: Theme) {
self.theme = theme
guard self.containerView != nil else {
return
}
switch displaySide {
case .center:
self.presentedView?.layer.cornerRadius = 10
self.presentedView?.clipsToBounds = true
self.presentedView?.layer.borderColor = theme.colors.border.cgColor
self.presentedView?.layer.borderWidth = 1.0
self.closeButton.setImage(UIImage(named: "toc-close-blue"), for: .normal)
self.closeButton.tintColor = theme.colors.link
self.statusBarBackground.isHidden = true
break
default:
//Add shadow to the presented view
self.presentedView?.layer.shadowOpacity = 0.8
self.presentedView?.layer.shadowColor = theme.colors.shadow.cgColor
self.presentedView?.layer.shadowOffset = CGSize(width: 3, height: 5)
self.presentedView?.clipsToBounds = false
self.closeButton.setImage(UIImage(named: "close"), for: .normal)
self.statusBarBackground.isHidden = false
}
self.backgroundView.effect = UIBlurEffect(style: theme.blurEffectStyle)
self.statusBarBackground.backgroundColor = theme.colors.paperBackground
self.statusBarBackground.layer.shadowColor = theme.colors.shadow.cgColor
self.closeButton.tintColor = theme.colors.primaryText
}
}
| mit | ab82219a951eeba5ffe577bfd1e51916 | 40.944444 | 219 | 0.689272 | 6.062634 | false | false | false | false |
PhillipEnglish/TIY-Assignments | DudeWheresMyCar/Forecaster/CityTableViewController.swift | 1 | 6142 | //
// CityTableViewController.swift
// Forecaster
//
// Created by Phillip English on 10/29/15.
// Copyright © 2015 The Iron Yard. All rights reserved.
//
import UIKit
let kCitiesKey = "cities"
protocol modalZipCodeViewControllerDelegate
{
func zipCodeWasChosen(zipCode: String)
}
protocol CityAPIControllerProtocol
{
func didReceiveMapsAPIResults(results: NSArray)
}
class CityTableViewController: UITableViewController, modalZipCodeViewControllerDelegate, CityAPIControllerProtocol
{
var cities = [City]()
var cityAPI: CityAPIController!
override func viewDidLoad() {
super.viewDidLoad()
title = "Forecaster"
//zipCodeWasChosen("32801")
//Coloring
navigationController?.navigationBar.barTintColor = UIColor.purpleColor()
//self.tableView.backgroundColor = UIColor.lightGrayColor()
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
//TableCell Coloring
override func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
cell.backgroundColor = UIColor.clearColor()
}
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return cities.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("CityCell", forIndexPath: indexPath) as! CityWeatherTableViewCell
let aCity = cities[indexPath.row]
cell.cityLabel?.text = aCity.cityName
// Configure the cell...
//cell.textLabel!.text = "Orlando"
//cell.detailTextLabel?.text = "79 Degrees"
return cell
}
// MARK: - API Controller Protocols
func didReceiveMapsAPIResults(results: NSArray)
{
dispatch_async(dispatch_get_main_queue(), {
let aCity = City.cityWithJSON(results)
self.cities.append(aCity)
self.tableView.reloadData()
})
}
// MARK: - Loction Delegate
func zipCodeWasChosen(zipCode: String)
{
print(zipCode)
UIApplication.sharedApplication().networkActivityIndicatorVisible = true
self.cityAPI = CityAPIController(cityDelegate: self)
cityAPI.searchGoogleForCity(zipCode)
//tableView.reloadData()
//navigationController?.dismissViewControllerAnimated(true, completion: nil)
let zipCodeArray = [zipCode]
for zipCode in zipCodeArray
{
cityAPI.searchGoogleForCity(zipCode)
}
self.tableView.reloadData()
print (zipCodeArray)
}
/*
// Override to support conditional editing of the table view.
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the specified item to be editable.
return true
}
*/
/*
// Override to support editing the table view.
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == .Delete {
// Delete the row from the data source
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
} else if editingStyle == .Insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
*/
/*
// Override to support rearranging the table view.
override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) {
}
*/
/*
// Override to support conditional rearranging of the table view.
override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the item to be re-orderable.
return true
}
*/
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
// MARK: -MISC
func loadCityData()
{
if let data = NSUserDefaults.standardUserDefaults().objectForKey(kCitiesKey) as? NSData
{
if let savedCities = NSKeyedUnarchiver.unarchiveObjectWithData(data) as? [City]
{
cities = savedCities
tableView.reloadData()
}
}
}
func saveCityData() //this is how we persist data to the disk
{
let cityData = NSKeyedArchiver.archivedDataWithRootObject(cities!) // you can only archive data like this if every object in the array has nscoding enabled in it. This is why we implemented nscoding in our city class
NSUserDefaults.standardUserDefaults().setObject(cityData, forKey: kCitiesKey)
}
}
| cc0-1.0 | 20c171ad8c22fb973b117577a5f2d355 | 30.984375 | 224 | 0.657873 | 5.502688 | false | false | false | false |
SaberVicky/LoveStory | LoveStory/Tool/Chat/LSChatManager.swift | 1 | 1632 | //
// LSChatManager.swift
// LoveStory
//
// Created by songlong on 2017/1/22.
// Copyright © 2017年 com.Saber. All rights reserved.
//
import UIKit
import HyphenateLite
class LSChatManager: NSObject {
public class func chatRegister(account: String) -> Bool {
let error = EMClient.shared().register(withUsername: account, password: HuanXinPassword)
if error == nil {
LSPrint("注册环信成功")
return true
} else {
LSPrint("注册环信失败")
return false
}
}
public class func chatInit() {
let option = EMOptions.init(appkey: "1143170105178612#lovestory")
option?.apnsCertName = "lovestoryTest"
let error = EMClient.shared().initializeSDK(with: option)
if error == nil {
LSPrint("环信初始化成功")
} else {
LSPrint("环信初始化失败")
}
}
public class func chatLogin() {
let user = LSUser.currentUser()
let error = EMClient.shared().login(withUsername: user?.user_account, password: HuanXinPassword)
if error == nil {
LSPrint("登录成功")
EMClient.shared().setApnsNickname(user?.user_name)
EMClient.shared().pushOptions.displayStyle = EMPushDisplayStyle(rawValue: 1)
if EMClient.shared().updatePushOptionsToServer() != nil {
LSPrint("更换推送样式失败")
} else {
LSPrint("更换推送样式成功")
}
} else {
LSPrint("登录失败")
}
}
}
| mit | 6fe39bf0195206f6ee175f71e582ac5c | 27.314815 | 104 | 0.564421 | 4.247222 | false | false | false | false |
LoveZYForever/HXWeiboPhotoPicker | Pods/HXPHPicker/Sources/HXPHPicker/Editor/Controller/Video/VideoEditorViewController+ToolView.swift | 1 | 15958 | //
// VideoEditorViewController+ToolView.swift
// HXPHPicker
//
// Created by Slience on 2021/8/6.
//
import UIKit
import AVKit
// MARK: EditorToolViewDelegate
extension VideoEditorViewController: EditorToolViewDelegate {
/// 导出视频
/// - Parameter toolView: 底部工具视频
func toolView(didFinishButtonClick toolView: EditorToolView) {
videoView.deselectedSticker()
let timeRang: CMTimeRange
if let startTime = videoView.playerView.playStartTime,
let endTime = videoView.playerView.playEndTime {
if endTime.seconds - startTime.seconds > config.cropTime.maximumVideoCroppingTime {
let seconds = Double(config.cropTime.maximumVideoCroppingTime)
timeRang = CMTimeRange(
start: startTime,
duration: CMTime(
seconds: seconds,
preferredTimescale: endTime.timescale
)
)
}else {
timeRang = CMTimeRange(start: startTime, end: endTime)
}
}else {
timeRang = .zero
}
let hasAudio: Bool
if backgroundMusicPath != nil || videoVolume < 1 || !hasOriginalSound {
hasAudio = true
}else {
hasAudio = false
}
let hasCropSize: Bool
if videoView.canReset() ||
videoView.imageResizerView.hasCropping ||
videoView.canUndoDraw ||
videoView.hasFilter ||
videoView.hasSticker ||
videoView.imageResizerView.videoFilter != nil {
hasCropSize = true
}else {
hasCropSize = false
}
if hasAudio || timeRang != .zero || hasCropSize {
exportLoadingView = ProgressHUD.showProgress(
addedTo: view,
text: "正在处理...".localized,
animated: true
)
exportVideoURL(
timeRang: timeRang,
hasCropSize: hasCropSize,
cropSizeData: videoView.getVideoCropData()
)
return
}
delegate?.videoEditorViewController(didFinishWithUnedited: self)
finishHandler?(self, nil)
backAction()
}
func exportVideoURL(
timeRang: CMTimeRange,
hasCropSize: Bool,
cropSizeData: VideoEditorCropSizeData
) {
avAsset.loadValuesAsynchronously(
forKeys: ["tracks"]
) { [weak self] in
guard let self = self else { return }
DispatchQueue.global().async {
if self.avAsset.statusOfValue(forKey: "tracks", error: nil) != .loaded {
self.showErrorHUD()
return
}
var audioURL: URL?
if let musicPath = self.backgroundMusicPath {
audioURL = URL(fileURLWithPath: musicPath)
}
self.exportSession = PhotoTools.exportEditVideo(
for: self.avAsset,
outputURL: self.config.videoExportURL,
timeRang: timeRang,
cropSizeData: cropSizeData,
audioURL: audioURL,
audioVolume: self.backgroundMusicVolume,
originalAudioVolume: self.hasOriginalSound ? self.videoVolume : 0,
exportPreset: self.config.exportPreset,
videoQuality: self.config.videoQuality
) { [weak self] videoURL, error in
if let videoURL = videoURL {
ProgressHUD.hide(forView: self?.view, animated: true)
self?.editFinishCallBack(videoURL)
self?.backAction()
}else {
self?.showErrorHUD()
}
}
DispatchQueue.main.async {
Timer.scheduledTimer(withTimeInterval: 0.1, repeats: true) { [weak self] timer in
guard let self = self,
let session = self.exportSession else {
timer.invalidate()
return
}
let progress = session.progress
self.exportLoadingView?.progress = CGFloat(progress)
if progress >= 1 ||
session.status == .completed ||
session.status == .failed ||
session.status == .cancelled {
timer.invalidate()
}
}
}
}
}
}
func showErrorHUD() {
ProgressHUD.hide(forView: view, animated: true)
ProgressHUD.showWarning(addedTo: view, text: "处理失败".localized, animated: true, delayHide: 1.5)
}
func editFinishCallBack(_ videoURL: URL) {
if let currentCropOffset = currentCropOffset {
rotateBeforeStorageData = cropView.getRotateBeforeData(
offsetX: currentCropOffset.x,
validX: currentValidRect.minX,
validWidth: currentValidRect.width
)
}
rotateBeforeData = cropView.getRotateBeforeData()
var cropData: VideoCropData?
if let startTime = videoView.playerView.playStartTime,
let endTime = videoView.playerView.playEndTime,
let rotateBeforeStorageData = rotateBeforeStorageData,
let rotateBeforeData = rotateBeforeData {
cropData = VideoCropData(
startTime: startTime.seconds,
endTime: endTime.seconds,
preferredTimescale: avAsset.duration.timescale,
cropingData: .init(
offsetX: rotateBeforeStorageData.0,
validX: rotateBeforeStorageData.1,
validWidth: rotateBeforeStorageData.2
),
cropRectData: .init(
offsetX: rotateBeforeData.0,
validX: rotateBeforeData.1,
validWidth: rotateBeforeData.2
)
)
}
var backgroundMusicURL: URL?
if let audioPath = backgroundMusicPath {
backgroundMusicURL = URL(fileURLWithPath: audioPath)
}
let editResult = VideoEditResult(
editedURL: videoURL,
cropData: cropData,
hasOriginalSound: hasOriginalSound,
videoSoundVolume: videoVolume,
backgroundMusicURL: backgroundMusicURL,
backgroundMusicVolume: backgroundMusicVolume,
sizeData: videoView.getVideoEditedData()
)
delegate?.videoEditorViewController(self, didFinish: editResult)
finishHandler?(self, editResult)
}
func toolView(_ toolView: EditorToolView, didSelectItemAt model: EditorToolOptions) {
videoView.stickerEnabled = false
videoView.deselectedSticker()
switch model.type {
case .graffiti:
toolGraffitiClick()
case .music:
toolMusicClick()
case .cropSize:
toolCropSizeClick()
case .cropTime:
toolCropTimeClick()
case .chartlet:
toolChartletClick()
case .text:
toolTextClick()
case .filter:
toolFilterClick()
default:
break
}
}
func toolGraffitiClick() {
videoView.drawEnabled = !videoView.drawEnabled
toolView.stretchMask = videoView.drawEnabled
toolView.layoutSubviews()
if videoView.drawEnabled {
videoView.stickerEnabled = false
showBrushColorView()
}else {
videoView.stickerEnabled = true
hiddenBrushColorView()
}
}
func toolMusicClick() {
if let shouldClick = delegate?.videoEditorViewController(shouldClickMusicTool: self),
!shouldClick {
return
}
toolView.deselected()
videoView.drawEnabled = false
hiddenBrushColorView()
if musicView.musics.isEmpty {
if let loadHandler = config.music.handler {
let showLoading = loadHandler { [weak self] infos in
self?.musicView.reloadData(infos: infos)
}
if showLoading {
musicView.showLoading()
}
}else {
if let editorDelegate = delegate {
if editorDelegate.videoEditorViewController(
self,
loadMusic: { [weak self] infos in
self?.musicView.reloadData(infos: infos)
}) {
musicView.showLoading()
}
}else {
let infos = PhotoTools.defaultMusicInfos()
if infos.isEmpty {
ProgressHUD.showWarning(
addedTo: view,
text: "暂无配乐".localized,
animated: true,
delayHide: 1.5
)
return
}else {
musicView.reloadData(infos: infos)
}
}
}
}
isMusicState = !isMusicState
musicView.reloadContentOffset()
updateMusicView()
hidenTopView()
}
func toolCropSizeClick() {
toolView.deselected()
videoView.drawEnabled = false
hiddenBrushColorView()
videoView.stickerEnabled = false
videoView.startCropping(true)
pState = .cropSize
toolCropSizeAnimation()
}
func toolCropSizeAnimation() {
if state == .cropSize {
cropConfirmView.showReset = true
cropConfirmView.isHidden = false
cropToolView.isHidden = false
hidenTopView()
}else {
showTopView()
}
UIView.animate(withDuration: 0.25) {
self.cropConfirmView.alpha = self.state == .cropSize ? 1 : 0
self.cropToolView.alpha = self.state == .cropSize ? 1 : 0
} completion: { (isFinished) in
if self.state != .cropSize {
self.cropConfirmView.isHidden = true
self.cropToolView.isHidden = true
}
}
}
func toolChartletClick() {
toolView.deselected()
videoView.drawEnabled = false
hiddenBrushColorView()
chartletView.firstRequest()
showChartlet = true
hidenTopView()
showChartletView()
}
func toolTextClick() {
toolView.deselected()
videoView.drawEnabled = false
hiddenBrushColorView()
videoView.stickerEnabled = true
if config.text.modalPresentationStyle == .fullScreen {
isPresentText = true
}
let textVC = EditorStickerTextViewController(config: config.text)
textVC.delegate = self
let nav = EditorStickerTextController(rootViewController: textVC)
nav.modalPresentationStyle = config.text.modalPresentationStyle
present(nav, animated: true, completion: nil)
}
func toolFilterClick() {
toolView.deselected()
videoView.drawEnabled = false
videoView.stickerEnabled = false
hiddenBrushColorView()
hidenTopView()
showFilterView()
videoView.canLookOriginal = true
}
func showBrushColorView() {
brushColorView.isHidden = false
UIView.animate(withDuration: 0.25) {
self.brushColorView.alpha = 1
}
}
func hiddenBrushColorView() {
if brushColorView.isHidden {
return
}
UIView.animate(withDuration: 0.25) {
self.brushColorView.alpha = 0
} completion: { (_) in
if self.videoView.drawEnabled { return }
self.brushColorView.isHidden = true
}
}
func showChartletView() {
UIView.animate(withDuration: 0.25) {
self.setChartletViewFrame()
}
}
func hiddenChartletView() {
UIView.animate(withDuration: 0.25) {
self.setChartletViewFrame()
}
}
func updateMusicView() {
UIView.animate(withDuration: 0.25) {
self.toolView.alpha = self.isMusicState ? 0 : 1
self.setMusicViewFrame()
} completion: { (_) in
self.toolView.alpha = self.isMusicState ? 0 : 1
self.setMusicViewFrame()
}
}
/// 进入裁剪时长界面
func toolCropTimeClick() {
if state == .normal {
toolView.deselected()
videoView.drawEnabled = false
hiddenBrushColorView()
cropConfirmView.showReset = false
beforeStartTime = videoView.playerView.playStartTime
beforeEndTime = videoView.playerView.playEndTime
if let offset = currentCropOffset {
cropView.collectionView.setContentOffset(offset, animated: false)
}else {
let insetLeft = cropView.collectionView.contentInset.left
let insetTop = cropView.collectionView.contentInset.top
cropView.collectionView.setContentOffset(CGPoint(x: -insetLeft, y: -insetTop), animated: false)
}
if currentValidRect.equalTo(.zero) {
cropView.resetValidRect()
}else {
cropView.frameMaskView.validRect = currentValidRect
cropView.startLineAnimation(at: videoView.playerView.player.currentTime())
}
videoView.playerView.playStartTime = cropView.getStartTime(real: true)
videoView.playerView.playEndTime = cropView.getEndTime(real: true)
cropConfirmView.isHidden = false
cropView.isHidden = false
cropView.updateTimeLabels()
pState = .cropTime
if currentValidRect.equalTo(.zero) {
videoView.playerView.resetPlay()
startPlayTimer()
}
hidenTopView()
videoView.startCropTime(true)
UIView.animate(withDuration: 0.25, delay: 0, options: [.layoutSubviews]) {
self.cropView.alpha = 1
self.cropConfirmView.alpha = 1
}
}
}
}
extension VideoEditorViewController: EditorStickerTextViewControllerDelegate {
func stickerTextViewController(
_ controller: EditorStickerTextViewController,
didFinish stickerItem: EditorStickerItem
) {
videoView.updateSticker(item: stickerItem)
}
func stickerTextViewController(
_ controller: EditorStickerTextViewController,
didFinish stickerText: EditorStickerText
) {
let item = EditorStickerItem(
image: stickerText.image,
imageData: nil,
text: stickerText
)
videoView.addSticker(item: item, isSelected: false)
}
}
extension VideoEditorViewController: PhotoEditorCropToolViewDelegate {
func cropToolView(didRotateButtonClick cropToolView: PhotoEditorCropToolView) {
videoView.rotate()
}
func cropToolView(didMirrorHorizontallyButtonClick cropToolView: PhotoEditorCropToolView) {
videoView.mirrorHorizontally(animated: true)
}
func cropToolView(didChangedAspectRatio cropToolView: PhotoEditorCropToolView, at model: PhotoEditorCropToolModel) {
videoView.changedAspectRatio(of: CGSize(width: model.widthRatio, height: model.heightRatio))
}
}
| mit | db801dd4465985641b4b905663c40b1e | 35.131818 | 120 | 0.552397 | 5.679886 | false | false | false | false |
cpmpercussion/microjam | Pods/Repeat/Sources/Repeat/Debouncer.swift | 1 | 2884 | //
// Repeat
// A modern alternative to NSTimer made in GCD with debouncer and throttle
// -----------------------------------------------------------------------
// Created by: Daniele Margutti
// [email protected]
// http://www.danielemargutti.com
//
// Twitter: @danielemargutti
//
//
// 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
/// The Debouncer will delay a function call, and every time it's getting called it will
/// delay the preceding call until the delay time is over.
open class Debouncer {
/// Typealias for callback type
public typealias Callback = (() -> Void)
/// Delay interval
private (set) public var delay: Repeater.Interval
/// Callback to activate
public var callback: Callback?
/// Internal timer to fire callback event.
private var timer: Repeater?
/// Initialize a new debouncer with given delay and callback.
/// Debouncer class to delay functions that only get delay each other until the timer fires.
///
/// - Parameters:
/// - delay: delay interval
/// - callback: callback to activate
public init(_ delay: Repeater.Interval, callback: Callback? = nil) {
self.delay = delay
self.callback = callback
}
/// Call debouncer to start the callback after the delayed time.
/// Multiple calls will ignore the older calls and overwrite the firing time.
///
/// - Parameters:
/// - newDelay: New delay interval
public func call(newDelay: Repeater.Interval? = nil) {
if let newDelay = newDelay {
self.delay = newDelay
}
if self.timer == nil {
self.timer = Repeater.once(after: self.delay, { [weak self] _ in
guard let callback = self?.callback else {
debugPrint("Debouncer fired but callback not set.")
return
}
callback()
})
} else {
self.timer?.reset(self.delay, restart: true)
}
}
}
| mit | 78a02bb2c3154544d614ebf2cb98caf0 | 34.170732 | 93 | 0.693828 | 4.16763 | false | false | false | false |
Duraiamuthan/HybridWebRTC_iOS | WebRTCSupport/Pods/XWebView/XWebView/XWVChannel.swift | 1 | 7994 | /*
Copyright 2015 XWebView
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
import Foundation
import WebKit
public class XWVChannel : NSObject, WKScriptMessageHandler {
private(set) public var identifier: String?
public let runLoop: NSRunLoop?
public let queue: dispatch_queue_t?
private(set) public weak var webView: WKWebView?
var typeInfo: XWVMetaObject!
private var instances = [Int: XWVBindingObject]()
private var userScript: XWVUserScript?
private(set) var principal: XWVBindingObject {
get { return instances[0]! }
set { instances[0] = newValue }
}
private class var sequenceNumber: UInt {
struct sequence{
static var number: UInt = 0
}
sequence.number += 1
return sequence.number
}
private static var defaultQueue: dispatch_queue_t = {
let label = "org.xwebview.default-queue"
return dispatch_queue_create(label, DISPATCH_QUEUE_SERIAL)
}()
public convenience init(webView: WKWebView) {
self.init(webView: webView, queue: XWVChannel.defaultQueue)
}
public convenience init(webView: WKWebView, thread: NSThread) {
let selector = #selector(NSRunLoop.currentRunLoop)
let runLoop = invoke(NSRunLoop.self, selector: selector, withArguments: [], onThread: thread) as! NSRunLoop
self.init(webView: webView, runLoop: runLoop)
}
public init(webView: WKWebView, queue: dispatch_queue_t) {
assert(dispatch_queue_get_label(queue).memory != 0, "Queue must be labeled")
self.webView = webView
self.queue = queue
runLoop = nil
webView.prepareForPlugin()
}
public init(webView: WKWebView, runLoop: NSRunLoop) {
self.webView = webView
self.runLoop = runLoop
queue = nil
webView.prepareForPlugin()
}
public func bindPlugin(object: AnyObject, toNamespace namespace: String) -> XWVScriptObject? {
guard identifier == nil, let webView = webView else { return nil }
let id = (object as? XWVScripting)?.channelIdentifier ?? String(XWVChannel.sequenceNumber)
identifier = id
webView.configuration.userContentController.addScriptMessageHandler(self, name: id)
typeInfo = XWVMetaObject(plugin: object.dynamicType)
principal = XWVBindingObject(namespace: namespace, channel: self, object: object)
let script = WKUserScript(source: generateStubs(),
injectionTime: WKUserScriptInjectionTime.AtDocumentStart,
forMainFrameOnly: true)
userScript = XWVUserScript(webView: webView, script: script)
log("+Plugin object \(object) is bound to \(namespace) with channel \(id)")
return principal as XWVScriptObject
}
public func unbind() {
guard let id = identifier else { return }
let namespace = principal.namespace
let plugin = principal.plugin
instances.removeAll(keepCapacity: false)
webView?.configuration.userContentController.removeScriptMessageHandlerForName(id)
userScript = nil
identifier = nil
log("+Plugin object \(plugin) is unbound from \(namespace)")
}
public func userContentController(userContentController: WKUserContentController, didReceiveScriptMessage message: WKScriptMessage) {
// A workaround for crash when postMessage(undefined)
guard unsafeBitCast(message.body, COpaquePointer.self) != nil else { return }
if let body = message.body as? [String: AnyObject], let opcode = body["$opcode"] as? String {
let target = (body["$target"] as? NSNumber)?.integerValue ?? 0
if let object = instances[target] {
if opcode == "-" {
if target == 0 {
// Dispose plugin
unbind()
} else if let instance = instances.removeValueForKey(target) {
// Dispose instance
log("+Instance \(target) is unbound from \(instance.namespace)")
} else {
log("?Invalid instance id: \(target)")
}
} else if let member = typeInfo[opcode] where member.isProperty {
// Update property
object.updateNativeProperty(opcode, withValue: body["$operand"] ?? NSNull())
} else if let member = typeInfo[opcode] where member.isMethod {
// Invoke method
if let args = (body["$operand"] ?? []) as? [AnyObject] {
object.invokeNativeMethod(opcode, withArguments: args)
} // else malformatted operand
} else {
log("?Invalid member name: \(opcode)")
}
} else if opcode == "+" {
// Create instance
let args = body["$operand"] as? [AnyObject]
let namespace = "\(principal.namespace)[\(target)]"
instances[target] = XWVBindingObject(namespace: namespace, channel: self, arguments: args)
log("+Instance \(target) is bound to \(namespace)")
} // else Unknown opcode
} else if let obj = principal.plugin as? WKScriptMessageHandler {
// Plugin claims for raw messages
obj.userContentController(userContentController, didReceiveScriptMessage: message)
} else {
// discard unknown message
log("-Unknown message: \(message.body)")
}
}
private func generateStubs() -> String {
func generateMethod(key: String, this: String, prebind: Bool) -> String {
let stub = "XWVPlugin.invokeNative.bind(\(this), '\(key)')"
return prebind ? "\(stub);" : "function(){return \(stub).apply(null, arguments);}"
}
func rewriteStub(stub: String, forKey key: String) -> String {
return (principal.plugin as? XWVScripting)?.rewriteGeneratedStub?(stub, forKey: key) ?? stub
}
let prebind = !(typeInfo[""]?.isInitializer ?? false)
let stubs = typeInfo.reduce("") {
let key = $1.0
let member = $1.1
let stub: String
if member.isMethod && !key.isEmpty {
let method = generateMethod("\(key)\(member.type)", this: prebind ? "exports" : "this", prebind: prebind)
stub = "exports.\(key) = \(method)"
} else if member.isProperty {
let value = principal.serialize(principal[key])
stub = "XWVPlugin.defineProperty(exports, '\(key)', \(value), \(member.setter != nil));"
} else {
return $0
}
return $0 + rewriteStub(stub, forKey: key) + "\n"
}
let base: String
if let member = typeInfo[""] {
if member.isInitializer {
base = "'\(member.type)'"
} else {
base = generateMethod("\(member.type)", this: "arguments.callee", prebind: false)
}
} else {
base = rewriteStub("null", forKey: ".base")
}
return rewriteStub(
"(function(exports) {\n" +
rewriteStub(stubs, forKey: ".local") +
"})(XWVPlugin.createPlugin('\(identifier!)', '\(principal.namespace)', \(base)));\n",
forKey: ".global"
)
}
}
| gpl-3.0 | 839869da8d094abd1ae28d06be234b38 | 41.521277 | 137 | 0.594071 | 5.027673 | false | false | false | false |
rolfzhang/Observable | Observable/CombinedObservable.swift | 1 | 1854 | //
// CombinedObservable.swift
// Observable
//
// Created by Rolf on 2016/10/20.
// Copyright © 2016年 Rolf Zhang. All rights reserved.
//
import Foundation
protocol CombinedObservable: ObservableType, ObserverType {}
public class ObservableTwo<O1: ObservableType, O2: ObservableType>: NSObject, CombinedObservable {
public typealias T = (O1.T?, O2.T?)
public let observers: NSMutableArray = []
weak var o1: O1?
weak var o2: O2?
public init(_ o1: O1, _ o2: O2) {
self.o1 = o1
self.o2 = o2
super.init()
attach()
update()
}
public func value() -> T? {
return (o1?.value(), o2?.value())
}
public func update() { notify() }
public func attach() {
o1?.addObserver(self)
o2?.addObserver(self)
}
public func detach() {
o1?.removeObserver(self)
o2?.removeObserver(self)
}
}
public class ObservableThree<O1: ObservableType, O2: ObservableType, O3: ObservableType>: NSObject, CombinedObservable {
public typealias T = (O1.T?, O2.T?, O3.T?)
public let observers: NSMutableArray = []
weak var o1: O1?
weak var o2: O2?
weak var o3: O3?
public init(_ o1: O1, _ o2: O2, _ o3: O3) {
self.o1 = o1
self.o2 = o2
self.o3 = o3
super.init()
attach()
update()
}
public func value() -> T? {
return (o1?.value(), o2?.value(), o3?.value())
}
public func update() {
notify()
}
public func attach() {
o1?.addObserver(self)
o2?.addObserver(self)
o3?.addObserver(self)
}
public func detach() {
o1?.removeObserver(self)
o2?.removeObserver(self)
o3?.removeObserver(self)
}
}
| mit | b61f0f4338dafad0c765adb245afd041 | 20.776471 | 120 | 0.54349 | 3.665347 | false | false | false | false |
ragnar/VindsidenApp | VindsidenKit/PlotFetcher.swift | 1 | 3347 | //
// PlotFetcher.swift
// VindsidenApp
//
// Created by Ragnar Henriksen on 16.06.15.
// Copyright © 2015 RHC. All rights reserved.
//
import Foundation
class PlotURLSession : NSObject, URLSessionDataDelegate {
class var sharedPlotSession: PlotURLSession {
struct Singleton {
static let sharedAppSession = PlotURLSession()
}
return Singleton.sharedAppSession
}
fileprivate var privateSharedSession: Foundation.URLSession?
override init() {
super.init()
}
func sharedSession() -> Foundation.URLSession {
if let _sharedSession = privateSharedSession {
return _sharedSession
} else {
privateSharedSession = Foundation.URLSession(configuration: URLSessionConfiguration.ephemeral, delegate: self, delegateQueue: nil)
return privateSharedSession!
}
}
func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, willCacheResponse proposedResponse: CachedURLResponse, completionHandler: @escaping (CachedURLResponse?) -> Void) {
DLOG("")
completionHandler(nil)
}
func urlSession(_ session: URLSession, didBecomeInvalidWithError error: Error?) {
DLOG("Error: \(String(describing: error?.localizedDescription))")
self.privateSharedSession = nil
}
}
open class PlotFetcher : NSObject {
var characters:String = ""
var result = [[String:String]]()
var currentPlot = [String:String]()
open func fetchForStationId( _ stationId: Int, completionHandler:@escaping (([[String:String]], Error?) -> Void)) {
let request = URLRequest(url: URL(string: "http://vindsiden.no/xml.aspx?id=\(stationId)&hours=\(Int(AppConfig.Global.plotHistory-1))")!)
DLOG("\(request)")
let task = PlotURLSession.sharedPlotSession.sharedSession().dataTask(with: request, completionHandler: { (data: Data?, response: URLResponse?, error: Error?) -> Void in
guard let data = data else {
DLOG("Error: \(String(describing: error))")
completionHandler( [[String:String]](), error)
return;
}
let parser = XMLParser(data: data)
parser.delegate = self
parser.parse()
DispatchQueue.main.async(execute: { () -> Void in
completionHandler(self.result, error)
})
})
task.resume()
}
open class func invalidate() -> Void {
PlotURLSession.sharedPlotSession.sharedSession().invalidateAndCancel()
}
}
extension PlotFetcher: XMLParserDelegate {
public func parser(_ parser: XMLParser, didStartElement elementName: String, namespaceURI: String?, qualifiedName qName: String?, attributes attributeDict: [String : String]) {
if elementName == "Measurement" {
currentPlot = [String:String]()
}
characters = ""
}
public func parser(_ parser: XMLParser, didEndElement elementName: String, namespaceURI: String?, qualifiedName qName: String?) {
if elementName == "Measurement" {
result.append(currentPlot)
} else {
currentPlot[elementName] = characters
}
}
public func parser(_ parser: XMLParser, foundCharacters string: String) {
characters += string
}
}
| bsd-2-clause | 72339d22f701e1a46d4a85d0b8c694ba | 30.566038 | 188 | 0.638972 | 5.085106 | false | false | false | false |
tkremenek/swift | test/type/self.swift | 3 | 10661 | // RUN: %target-typecheck-verify-swift -swift-version 5
struct S0<T> {
func foo(_ other: Self) { }
}
class C0<T> {
func foo(_ other: Self) { } // expected-error{{covariant 'Self' or 'Self?' can only appear as the type of a property, subscript or method result; did you mean 'C0'?}}
}
enum E0<T> {
func foo(_ other: Self) { }
}
// rdar://problem/21745221
struct X {
typealias T = Int
}
extension X {
struct Inner {
}
}
extension X.Inner {
func foo(_ other: Self) { }
}
// SR-695
class Mario {
func getFriend() -> Self { return self } // expected-note{{overridden declaration is here}}
func getEnemy() -> Mario { return self }
}
class SuperMario : Mario {
override func getFriend() -> SuperMario { // expected-error{{cannot override a Self return type with a non-Self return type}}
return SuperMario()
}
override func getEnemy() -> Self { return self }
}
final class FinalMario : Mario {
override func getFriend() -> FinalMario {
return FinalMario()
}
}
// These references to Self are now possible (SE-0068)
class A<T> {
typealias _Self = Self
// expected-error@-1 {{covariant 'Self' or 'Self?' can only appear as the type of a property, subscript or method result; did you mean 'A'?}}
let b: Int
required init(a: Int) {
print("\(Self.self).\(#function)")
Self.y()
b = a
}
static func z(n: Self? = nil) {
// expected-error@-1 {{covariant 'Self' or 'Self?' can only appear as the type of a property, subscript or method result; did you mean 'A'?}}
print("\(Self.self).\(#function)")
}
class func y() {
print("\(Self.self).\(#function)")
Self.z()
}
func x() -> A? {
print("\(Self.self).\(#function)")
Self.y()
Self.z()
let _: Self = Self.init(a: 66)
return Self.init(a: 77) as? Self as? A
// expected-warning@-1 {{conditional cast from 'Self' to 'Self' always succeeds}}
// expected-warning@-2 {{conditional downcast from 'Self?' to 'A<T>' is equivalent to an implicit conversion to an optional 'A<T>'}}
}
func copy() -> Self {
let copy = Self.init(a: 11)
return copy
}
subscript (i: Int) -> Self { // expected-error {{mutable subscript cannot have covariant 'Self' type}}
get {
return Self.init(a: i)
}
set(newValue) {
}
}
}
class B: A<Int> {
let a: Int
required convenience init(a: Int) {
print("\(Self.self).\(#function)")
self.init()
}
init() {
print("\(Self.self).\(#function)")
Self.y()
Self.z()
a = 99
super.init(a: 88)
}
override class func y() {
print("override \(Self.self).\(#function)")
}
}
class C {
required init() {
}
func f() {
func g(_: Self) {}
let x: Self = self as! Self
g(x)
typealias _Self = Self
}
func g() {
_ = Self.init() as? Self
// expected-warning@-1 {{conditional cast from 'Self' to 'Self' always succeeds}}
}
func h(j: () -> Self) -> () -> Self {
// expected-error@-1 {{covariant 'Self' or 'Self?' can only appear at the top level of method result type}}
return { return self }
}
func i() -> (Self, Self) {}
// expected-error@-1 {{covariant 'Self' or 'Self?' can only appear at the top level of method result type}}
func j() -> Self.Type {}
// expected-error@-1 {{covariant 'Self' or 'Self?' can only appear at the top level of method result type}}
let p0: Self? // expected-error {{stored property cannot have covariant 'Self' type}}
var p1: Self? // expected-error {{stored property cannot have covariant 'Self' type}}
static func staticFunc() -> Self {}
let stored: Self = Self.staticFunc() // expected-error {{stored property cannot have covariant 'Self' type}}
// expected-error@-1 {{covariant 'Self' type cannot be referenced from a stored property initializer}}
var prop: Self { // expected-error {{mutable property cannot have covariant 'Self' type}}
get {
return self
}
set (newValue) {
}
}
subscript (i: Int) -> Self { // expected-error {{mutable subscript cannot have covariant 'Self' type}}
get {
return self
}
set (newValue) {
}
}
}
extension C {
static var rdar57188331 = Self.staticFunc() // expected-error {{covariant 'Self' type cannot be referenced from a stored property initializer}} expected-error {{stored property cannot have covariant 'Self' type}}
static var rdar57188331Var = ""
static let rdar57188331Ref = UnsafeRawPointer(&Self.rdar57188331Var) // expected-error {{covariant 'Self' type cannot be referenced from a stored property initializer}}
}
struct S1 {
typealias _SELF = Self
let j = 99.1
subscript (i: Int) -> Self {
get {
return self
}
set(newValue) {
}
}
var foo: Self {
get {
return self// as! Self
}
set (newValue) {
}
}
func x(y: () -> Self, z: Self) {
}
}
struct S2 {
let x = 99
struct S3<T> {
let x = 99
static func x() {
Self.y()
}
func f() {
func g(_: Self) {}
}
static func y() {
print("HERE")
}
func foo(a: [Self]) -> Self? {
Self.x()
return self as? Self
// expected-warning@-1 {{conditional cast from 'S2.S3<T>' to 'S2.S3<T>' always succeeds}}
}
}
func copy() -> Self {
let copy = Self.init()
return copy
}
var copied: Self {
let copy = Self.init()
return copy
}
}
extension S2 {
static func x() {
Self.y()
}
static func y() {
print("HERE")
}
func f() {
func g(_: Self) {}
}
func foo(a: [Self]) -> Self? {
Self.x()
return Self.init() as? Self
// expected-warning@-1 {{conditional cast from 'S2' to 'S2' always succeeds}}
}
subscript (i: Int) -> Self {
get {
return Self.init()
}
set(newValue) {
}
}
}
enum E {
static func f() {
func g(_: Self) {}
print("f()")
}
case e
func h(h: Self) -> Self {
Self.f()
return .e
}
}
class SelfStoredPropertyInit {
static func myValue() -> Int { return 123 }
var value = Self.myValue() // expected-error {{covariant 'Self' type cannot be referenced from a stored property initializer}}
}
// rdar://problem/55273931 - erroneously rejecting 'Self' in lazy initializer
class Foo {
static var value: Int = 17
lazy var doubledValue: Int = {
Self.value * 2
}()
}
// https://bugs.swift.org/browse/SR-11681 - duplicate diagnostics
struct Box<T> {
let boxed: T
}
class Boxer {
lazy var s = Box<Self>(boxed: self as! Self)
// expected-error@-1 {{stored property cannot have covariant 'Self' type}}
// expected-error@-2 {{mutable property cannot have covariant 'Self' type}}
var t = Box<Self>(boxed: Self())
// expected-error@-1 {{stored property cannot have covariant 'Self' type}}
// expected-error@-2 {{covariant 'Self' type cannot be referenced from a stored property initializer}}
required init() {}
}
// https://bugs.swift.org/browse/SR-12133 - a type named 'Self' should be found first
struct OuterType {
struct `Self` {
let string: String
}
var foo: `Self`? {
let optional: String? = "foo"
return optional.map { `Self`(string: $0) }
}
}
// rdar://69804933 - CSApply assigns wrong type to MemberRefExpr for property with
// DynamicSelfType
class HasDynamicSelfProperty {
var me: Self {
return self
}
}
// SILGen doesn't care about the MemberRefExpr's type, so it's hard to come up with an
// example that actually fails. Here, the rogue 'Self' type was diagnosed as being invalid
// in a stored property initializer.
class UsesDynamicSelfProperty {
var c = HasDynamicSelfProperty().me
}
// Test that dynamic 'Self' gets substituted with the object type of the
// associated 'self' parameter in 'super'-based invocations.
do {
class A {
required init() {}
func method() -> Self { self }
var property: Self { self }
subscript() -> Self { self }
class func method() -> Self { self.init() }
class var property: Self { self.init() }
class subscript() -> Self { self.init() }
}
class B: A {
override func method() -> Self { super.method() }
override var property: Self { super.property }
override subscript() -> Self { super[] }
override class func method() -> Self {
// Constructors must always have dynamic 'Self' replaced with the base
// object type.
// FIXME: Statically dispatches to the superclass init, but constructs an
// object of the 'Self' type.
let _: Self = super.init() // expected-error {{cannot convert value of type 'A' to specified type 'Self'}}
return super.method()
}
override class var property: Self { super.property }
override class subscript() -> Self { super[] }
}
class C: B {}
class D: C {
func testWithStaticSelf() {
let _: Self = super.method() // expected-error {{cannot convert value of type 'D' to specified type 'Self'}}
let _: Self = super.property // expected-error {{cannot convert value of type 'D' to specified type 'Self'}}
let _: Self = super[] // expected-error {{cannot convert value of type 'D' to specified type 'Self'}}
let _: () -> Self = super.method // expected-error {{cannot convert value of type '() -> D' to specified type '() -> Self'}}
}
static func testWithStaticSelfStatic() {
// Constructors must always have dynamic 'Self' replaced with the base
// object type.
// FIXME: Statically dispatches to the superclass init, but constructs an
// object of the 'Self' type.
let _: Self = super.init() // expected-error {{cannot convert value of type 'C' to specified type 'Self'}}
let _: Self = super.method() // expected-error {{cannot convert value of type 'D' to specified type 'Self'}}
let _: Self = super.property // expected-error {{cannot convert value of type 'D' to specified type 'Self'}}
let _: Self = super[] // expected-error {{cannot convert value of type 'D' to specified type 'Self'}}
let _: () -> Self = super.method
// expected-error@-1 {{partial application of 'super' instance method with metatype base is not allowed}}
// expected-error@-2 {{cannot convert value of type '(C) -> () -> D' to specified type '() -> Self'}}
}
}
}
// https://bugs.swift.org/browse/SR-14731
struct Generic<T> {
func foo() -> Self<Int> {}
// expected-error@-1 {{cannot specialize 'Self'}}
// expected-note@-2 {{did you mean to explicitly reference 'Generic' instead?}}{{17-21=Generic}}
}
struct NonGeneric {
func foo() -> Self<Int> {}
// expected-error@-1 {{cannot specialize 'Self'}}
}
protocol P {
func foo() -> Self<Int>
// expected-error@-1 {{cannot specialize non-generic type 'Self'}}
} | apache-2.0 | 082977249edaec2892a288832ca0091e | 27.131926 | 214 | 0.62058 | 3.666094 | false | false | false | false |
testpress/ios-app | ios-app/UI/SubjectAnalyticsTabViewController.swift | 1 | 6621 | //
// SubjectAnalyticsTabViewController.swift
// ios-app
//
// Copyright © 2017 Testpress. 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.
//
import UIKit
import XLPagerTabStrip
class SubjectAnalyticsTabViewController: ButtonBarPagerTabStripViewController {
@IBOutlet weak var contentView: UIView!
var activityIndicator: UIActivityIndicatorView! // Progress bar
var emptyView: EmptyView!
var parentSubjectId: String!
var analyticsUrl: String!
var subjects: [Subject] = []
var pager: SubjectPager!
override func viewDidLoad() {
self.setStatusBarColor()
settings.style.buttonBarBackgroundColor = .white
settings.style.buttonBarItemBackgroundColor = .white
settings.style.selectedBarBackgroundColor = Colors.getRGB(Colors.PRIMARY)
settings.style.buttonBarItemFont = UIFont(name: "Helvetica-Bold", size: 12)!
settings.style.selectedBarHeight = 4.0
settings.style.buttonBarMinimumLineSpacing = 0
settings.style.buttonBarItemTitleColor = Colors.getRGB(Colors.TAB_TEXT_COLOR)
settings.style.buttonBarItemsShouldFillAvailableWidth = true
settings.style.buttonBarLeftContentInset = 0
settings.style.buttonBarRightContentInset = 0
changeCurrentIndexProgressive = { (oldCell: ButtonBarViewCell?, newCell: ButtonBarViewCell?,
progressPercentage: CGFloat, changeCurrentIndex: Bool, animated: Bool) -> Void in
guard changeCurrentIndex == true else { return }
oldCell?.label.textColor = Colors.getRGB(Colors.TAB_TEXT_COLOR)
newCell?.label.textColor = Colors.getRGB(Colors.PRIMARY)
}
super.viewDidLoad()
buttonBarView.isHidden = true
emptyView = EmptyView.getInstance(parentView: contentView)
activityIndicator = UIUtils.initActivityIndicator(parentView: contentView)
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
if subjects.isEmpty {
if analyticsUrl == nil {
analyticsUrl = Constants.BASE_URL + TPEndpoint.getSubjectAnalytics.urlPath
}
loadSubjects()
}
}
func getPager() -> SubjectPager {
if pager == nil {
if parentSubjectId == nil {
parentSubjectId = "null"
}
pager = SubjectPager(analyticsUrl, parentSubjectId: parentSubjectId)
}
return pager
}
func loadSubjects() {
activityIndicator.startAnimating()
getPager().next(completion: {
items, error in
if let error = error {
debugPrint(error.message ?? "No error")
debugPrint(error.kind)
var retryButtonText: String?
var retryHandler: (() -> Void)?
if error.kind == .network {
retryButtonText = Strings.TRY_AGAIN
retryHandler = {
self.emptyView.hide()
self.loadSubjects()
}
}
self.activityIndicator.stopAnimating()
let (image, title, description) = error.getDisplayInfo()
self.emptyView.show(image: image, title: title, description: description,
retryButtonText: retryButtonText, retryHandler: retryHandler)
return
}
if self.pager.hasMore {
self.loadSubjects()
} else {
self.subjects = Array(items!.values)
self.subjects = self.subjects.sorted(by: { $0.name! < $1.name! })
self.activityIndicator.stopAnimating()
if self.subjects.isEmpty {
self.emptyView.show(
image: Images.AnalyticsFlatIcon.image,
title: Strings.NO_ANALYTICS,
description: Strings.NO_SUBJECT_ANALYTICS_DESCRIPTION
)
return
}
self.buttonBarView.isHidden = false
self.reloadPagerTabStripView()
}
})
}
// MARK: - PagerTabStripDataSource
override func viewControllers(for pagerTabStripController: PagerTabStripViewController) ->
[UIViewController] {
let overallAnalyticsViewController = storyboard?.instantiateViewController(
withIdentifier: Constants.OVERALL_SUBJECT_ANALYTICS_VIEW_CONTROLLER)
as! OverallSubjectAnalyticsViewController
overallAnalyticsViewController.subjects = subjects
let individualAnalyticsViewController = storyboard?.instantiateViewController(
withIdentifier: Constants.INDIVIDUAL_SUBJECT_ANALYTICS_VIEW_CONTROLLER)
as! IndividualSubjectAnalyticsViewController
individualAnalyticsViewController.subjects = subjects
individualAnalyticsViewController.analyticsUrl = analyticsUrl
return [overallAnalyticsViewController, individualAnalyticsViewController]
}
@IBAction func back() {
dismiss(animated: true, completion: nil)
}
override func viewDidLayoutSubviews() {
// Set frames of the view here to support both portrait & landscape view
activityIndicator?.frame = contentView.frame
}
}
| mit | abcab5c0f860a6c49957b92656b730f0 | 39.613497 | 100 | 0.629607 | 5.614928 | false | false | false | false |
linhaosunny/smallGifts | 小礼品/小礼品/Classes/Module/Base/SearchBar/SearchViewController.swift | 1 | 4544 | //
// SearchViewController.swift
// 小礼品
//
// Created by 李莎鑫 on 2017/4/21.
// Copyright © 2017年 李莎鑫. All rights reserved.
//
import UIKit
import SnapKit
import QorumLogs
class SearchViewController: UIViewController {
//MARK: 属性
fileprivate let searchIdentifer = "searchCell"
var headerViewHeightConstraint:Constraint?
//MARK: 懒加载
fileprivate lazy var searchBar:SearchBar = { () -> SearchBar in
let bar = SearchBar()
bar.customBorder(withColor: UIColor.white)
bar.tintColor = SystemNavgationBarTintColor
bar.bounds.size = CGSize(width: ScreenWidth - margin*6, height: 44)
bar.delegate = self
bar.showsBookmarkButton = true
bar.placeholder = "快选一份礼物,送给亲爱的Ta吧"
return bar
}()
lazy var searchHeaderView:SearchHeaderView = { () -> SearchHeaderView in
let view = SearchHeaderView(withFinshedLayout: { [unowned self] (height) in
self.searchHeaderView.bounds.size = CGSize(width: ScreenWidth, height: height)
self.tableView.tableHeaderView = self.searchHeaderView
})
view.viewModel = SearchHeaderViewModel(withModel: SearchViewDataModel())
view.delegate = self
return view
}()
lazy var tableView:UITableView = { () -> UITableView in
let view = UITableView(frame: CGRect.zero, style: .plain)
view.backgroundColor = SystemGlobalBackgroundColor
view.separatorStyle = .none
view.sectionFooterHeight = 0.0001
view.sectionHeaderHeight = 0.0001
view.delegate = self
view.dataSource = self
view.register(SearchGiftCell.self, forCellReuseIdentifier: self.searchIdentifer)
return view
}()
//MARK: 系统方法
override func viewDidLoad() {
super.viewDidLoad()
setupSearchView()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func viewWillLayoutSubviews() {
super.viewWillLayoutSubviews()
setupSearchViewSubView()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
setupSearchViewBeforeViewAppear()
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
setupSearchViewBeforeViewDisappear()
}
//MARK: 私有方法
private func setupSearchView() {
view.backgroundColor = SystemGlobalBackgroundColor
navigationItem.titleView = searchBar
tableView.tableHeaderView = searchHeaderView
view.addSubview(tableView)
}
private func setupSearchViewSubView(){
tableView.snp.makeConstraints { (make) in
make.edges.equalToSuperview().inset(UIEdgeInsets.zero)
}
}
private func setupSearchViewBeforeViewAppear() {
searchBar.becomeFirstResponder()
}
private func setupSearchViewBeforeViewDisappear() {
searchBar.resignFirstResponder()
}
}
//MARK: 代理方法
extension SearchViewController:UITableViewDelegate,UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 1
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: searchIdentifer, for: indexPath)
cell.selectionStyle = .none
return cell
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 44.0
}
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return margin
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
navigationController?.pushViewController(SearchGiftViewController(), animated: true)
}
}
//MARK: 代理方法 -> SearchHeaderViewDelegate
extension SearchViewController:SearchHeaderViewDelegate {
func searchHeaderViewClickHotButton(button: UIButton) {
searchBar.text = button.titleLabel?.text
}
}
extension SearchViewController:UISearchBarDelegate {
func searchBarBookmarkButtonClicked(_ searchBar: UISearchBar) {
QL2("语言搜索")
}
}
| mit | cb38baa9e845b735cbe3fe2eef256ce0 | 29.251701 | 100 | 0.664493 | 5.383777 | false | false | false | false |
RunningCharles/Arithmetic | src/15MinDiffWith2Sets.swift | 1 | 1115 | #!/usr/bin/swift
func sum(_ arr: [Int]) -> Int {
var sum = 0
for item in arr {
sum += item
}
return sum
}
func minDiff(_ a: inout [Int], _ b: inout [Int]) {
let sumA = sum(a)
let sumB = sum(b)
if sumA == sumB { return }
var big = a
var small = b
if sumB > sumA {
big = b
small = a
}
let diff = abs(sumA - sumB)
var pi = -1
var pj = -1
var maxDiff = Int.max
for i in 0 ..< big.count {
for j in 0 ..< small.count {
if big[i] > small[j] {
let tmpDiff = abs(diff - 2 * (big[i] - small[j]))
if tmpDiff < maxDiff && tmpDiff < diff {
pi = i
pj = j
maxDiff = tmpDiff
}
}
}
}
if pi >= 0 && pj >= 0 {
let tmp = big[pi]
big[pi] = small[pj]
small[pj] = tmp
a = big
b = small
minDiff(&a, &b)
}
}
var a = [100, 99, 98, 1, 2, 3];
var b = [1, 2, 3, 4, 5, 40];
minDiff(&a, &b)
print("a:", a)
print("b:", b)
| bsd-3-clause | 7f0b80a3c5eccded8bc183014aa742ce | 18.561404 | 65 | 0.392825 | 3.149718 | false | false | false | false |
DmIvanov/DIAuth | DIAuth/DIAuth/DISocialNetworkCache.swift | 1 | 1863 | //
// DISocialNetworkCache.swift
// Created by Dmitry Ivanov on 26.09.15.
//
import KeychainAccess
let kDISNUserIdKey = "kDISNUserId"
let kDISNTokenKey = "kDISNToken"
let kDISNUserNameKey = "kDISNUserName"
let kDISNTypeKey = "defaultsSNTypeKey"
class DISocialNetworkCache {
//MARK: Social Network Data affairs
class func writeSNDataToCache(id: String?, token: String?, name: String?) {
let keychain = appKeychain()
if id != nil {
keychain[kDISNUserIdKey] = id
}
if token != nil {
keychain[kDISNTokenKey] = token
}
if name != nil {
keychain[kDISNUserNameKey] = name
}
}
class func readSNDataFromCache() -> (id: String?, token: String?, name: String?) {
let keychain = appKeychain()
let id = keychain[kDISNUserIdKey]
let token = keychain[kDISNTokenKey]
let userName = keychain[kDISNUserNameKey]
return (id, token, userName)
}
class func resetCacheForSNData() {
let keychain = appKeychain()
keychain[kDISNUserIdKey] = nil
keychain[kDISNTokenKey] = nil
keychain[kDISNUserNameKey] = nil
}
//MARK: Social Network Type affairs
class func writeSNTypeToCache(type: String) {
NSUserDefaults.standardUserDefaults().setObject(type, forKey: kDISNTypeKey)
}
class func readSNTypeFromCache() -> String? {
return NSUserDefaults.standardUserDefaults().objectForKey(kDISNTypeKey) as? String
}
class func resetCacheForSNType() {
NSUserDefaults.standardUserDefaults().removeObjectForKey(kDISNTypeKey)
}
//MARK: Setters & getters
private class func appKeychain() -> Keychain {
return Keychain(service: NSBundle.mainBundle().bundleIdentifier!)
}
}
| mit | 3c40d0bbde2e01fb23422b77a32dc94f | 27.661538 | 90 | 0.633387 | 4.634328 | false | false | false | false |
lhc70000/iina | iina/AppDelegate.swift | 1 | 20127 | //
// AppDelegate.swift
// iina
//
// Created by lhc on 8/7/16.
// Copyright © 2016 lhc. All rights reserved.
//
import Cocoa
import MediaPlayer
import Sparkle
/** Max time interval for repeated `application(_:openFile:)` calls. */
fileprivate let OpenFileRepeatTime = TimeInterval(0.2)
/** Tags for "Open File/URL" menu item when "ALways open file in new windows" is off. Vice versa. */
fileprivate let NormalMenuItemTag = 0
/** Tags for "Open File/URL in New Window" when "Always open URL" when "Open file in new windows" is off. Vice versa. */
fileprivate let AlternativeMenuItemTag = 1
@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {
/** Whether performed some basic initialization, like bind menu items. */
var isReady = false
/**
Becomes true once `application(_:openFile:)` or `droppedText()` is called.
Mainly used to distinguish normal launches from others triggered by drag-and-dropping files.
*/
var openFileCalled = false
var shouldIgnoreOpenFile = false
/** Cached URL when launching from URL scheme. */
var pendingURL: String?
/** Cached file paths received in `application(_:openFile:)`. */
private var pendingFilesForOpenFile: [String] = []
/** The timer for `OpenFileRepeatTime` and `application(_:openFile:)`. */
private var openFileTimer: Timer?
private var commandLineStatus = CommandLineStatus()
// Windows
lazy var openURLWindow: OpenURLWindowController = OpenURLWindowController()
lazy var aboutWindow: AboutWindowController = AboutWindowController()
lazy var fontPicker: FontPickerWindowController = FontPickerWindowController()
lazy var inspector: InspectorWindowController = InspectorWindowController()
lazy var historyWindow: HistoryWindowController = HistoryWindowController()
lazy var vfWindow: FilterWindowController = {
let w = FilterWindowController()
w.filterType = MPVProperty.vf
return w
}()
lazy var afWindow: FilterWindowController = {
let w = FilterWindowController()
w.filterType = MPVProperty.af
return w
}()
lazy var preferenceWindowController: NSWindowController = {
return PreferenceWindowController(viewControllers: [
PrefGeneralViewController(),
PrefUIViewController(),
PrefCodecViewController(),
PrefSubViewController(),
PrefNetworkViewController(),
PrefControlViewController(),
PrefKeyBindingViewController(),
PrefAdvancedViewController(),
PrefUtilsViewController(),
])
}()
@IBOutlet weak var menuController: MenuController!
@IBOutlet weak var dockMenu: NSMenu!
private func getReady() {
menuController.bindMenuItems()
PlayerCore.loadKeyBindings()
isReady = true
}
// MARK: - App Delegate
func applicationWillFinishLaunching(_ notification: Notification) {
registerUserDefaultValues()
Logger.log("App will launch")
// register for url event
NSAppleEventManager.shared().setEventHandler(self, andSelector: #selector(self.handleURLEvent(event:withReplyEvent:)), forEventClass: AEEventClass(kInternetEventClass), andEventID: AEEventID(kAEGetURL))
// beta channel
if FirstRunManager.isFirstRun(for: .joinBetaChannel) {
let result = Utility.quickAskPanel("beta_channel")
Preference.set(result, for: .receiveBetaUpdate)
}
SUUpdater.shared().feedURL = URL(string: Preference.bool(for: .receiveBetaUpdate) ? AppData.appcastBetaLink : AppData.appcastLink)!
// handle arguments
let arguments = ProcessInfo.processInfo.arguments.dropFirst()
guard arguments.count > 0 else { return }
var iinaArgs: [String] = []
var iinaArgFilenames: [String] = []
var dropNextArg = false
Logger.log("Got arguments \(arguments)")
for arg in arguments {
if dropNextArg {
dropNextArg = false
continue
}
if arg.first == "-" {
if arg[arg.index(after: arg.startIndex)] == "-" {
// args starting with --
iinaArgs.append(arg)
} else {
// args starting with -
dropNextArg = true
}
} else {
// assume args starting with nothing is a filename
iinaArgFilenames.append(arg)
}
}
Logger.log("IINA arguments: \(iinaArgs)")
Logger.log("Filenames from arguments: \(iinaArgFilenames)")
commandLineStatus.parseArguments(iinaArgs)
let (version, build) = Utility.iinaVersion()
print("IINA \(version) Build \(build)")
guard !iinaArgFilenames.isEmpty || commandLineStatus.isStdin else {
print("This binary is not intended for being used as a command line tool. Please use the bundled iina-cli.")
print("Please ignore this message if you are running in a debug environment.")
return
}
shouldIgnoreOpenFile = true
commandLineStatus.isCommandLine = true
commandLineStatus.filenames = iinaArgFilenames
}
func applicationDidFinishLaunching(_ aNotification: Notification) {
Logger.log("App launched")
if !isReady {
getReady()
}
// show alpha in color panels
NSColorPanel.shared.showsAlpha = true
// other initializations at App level
if #available(macOS 10.12.2, *) {
NSApp.isAutomaticCustomizeTouchBarMenuItemEnabled = false
NSWindow.allowsAutomaticWindowTabbing = false
}
if #available(macOS 10.13, *) {
if RemoteCommandController.useSystemMediaControl {
Logger.log("Setting up MediaPlayer integration")
RemoteCommandController.setup()
NowPlayingInfoManager.updateState(.unknown)
}
}
let _ = PlayerCore.first
// if have pending open request
if let url = pendingURL {
parsePendingURL(url)
}
if !commandLineStatus.isCommandLine {
// check whether showing the welcome window after 0.1s
Timer.scheduledTimer(timeInterval: TimeInterval(0.1), target: self, selector: #selector(self.checkForShowingInitialWindow), userInfo: nil, repeats: false)
} else {
var lastPlayerCore: PlayerCore? = nil
let getNewPlayerCore = { () -> PlayerCore in
let pc = PlayerCore.newPlayerCore
self.commandLineStatus.assignMPVArguments(to: pc)
lastPlayerCore = pc
return pc
}
if commandLineStatus.isStdin {
getNewPlayerCore().openURLString("-")
} else {
let validFileURLs: [URL] = commandLineStatus.filenames.compactMap { filename in
if Regex.url.matches(filename) {
return URL(string: filename.addingPercentEncoding(withAllowedCharacters: .urlAllowed) ?? filename)
} else {
return FileManager.default.fileExists(atPath: filename) ? URL(fileURLWithPath: filename) : nil
}
}
if commandLineStatus.openSeparateWindows {
validFileURLs.forEach { url in
getNewPlayerCore().openURL(url)
}
} else {
getNewPlayerCore().openURLs(validFileURLs)
}
}
// enter PIP
if #available(OSX 10.12, *), let pc = lastPlayerCore, commandLineStatus.enterPIP {
pc.mainWindow.enterPIP()
}
}
NSRunningApplication.current.activate(options: [.activateIgnoringOtherApps, .activateAllWindows])
NSApplication.shared.servicesProvider = self
}
/** Show welcome window if `application(_:openFile:)` wasn't called, i.e. launched normally. */
@objc
func checkForShowingInitialWindow() {
if !openFileCalled {
showWelcomeWindow()
}
}
private func showWelcomeWindow(checkingForUpdatedData: Bool = false) {
let actionRawValue = Preference.integer(for: .actionAfterLaunch)
let action: Preference.ActionAfterLaunch = Preference.ActionAfterLaunch(rawValue: actionRawValue) ?? .welcomeWindow
switch action {
case .welcomeWindow:
let window = PlayerCore.first.initialWindow!
window.showWindow(nil)
if checkingForUpdatedData {
window.loadLastPlaybackInfo()
window.reloadData()
}
case .openPanel:
openFile(self)
default:
break
}
}
func applicationShouldTerminateAfterLastWindowClosed(_ sender: NSApplication) -> Bool {
guard PlayerCore.active.mainWindow.isWindowLoaded || PlayerCore.active.initialWindow.isWindowLoaded else { return false }
return Preference.bool(for: .quitWhenNoOpenedWindow)
}
func applicationShouldTerminate(_ sender: NSApplication) -> NSApplication.TerminateReply {
guard !PlayerCore.active.mainWindow.isWindowHidden else { return .terminateCancel }
Logger.log("App should terminate")
for pc in PlayerCore.playerCores {
pc.terminateMPV()
}
return .terminateNow
}
func applicationShouldHandleReopen(_ sender: NSApplication, hasVisibleWindows flag: Bool) -> Bool {
guard !flag else { return true }
Logger.log("Handle reopen")
showWelcomeWindow(checkingForUpdatedData: true)
return true
}
func applicationWillTerminate(_ notification: Notification) {
Logger.log("App will terminate")
Logger.closeLogFile()
}
/**
When dragging multiple files to App icon, cocoa will simply call this method repeatedly.
Therefore we must cache all possible calls and handle them together.
*/
func application(_ sender: NSApplication, openFile filename: String) -> Bool {
openFileCalled = true
openFileTimer?.invalidate()
pendingFilesForOpenFile.append(filename)
openFileTimer = Timer.scheduledTimer(timeInterval: OpenFileRepeatTime, target: self, selector: #selector(handleOpenFile), userInfo: nil, repeats: false)
return true
}
/** Handle pending file paths if `application(_:openFile:)` not being called again in `OpenFileRepeatTime`. */
@objc
func handleOpenFile() {
if !isReady {
getReady()
}
// if launched from command line, should ignore openFile once
if shouldIgnoreOpenFile {
shouldIgnoreOpenFile = false
return
}
// open pending files
let urls = pendingFilesForOpenFile.map { URL(fileURLWithPath: $0) }
pendingFilesForOpenFile.removeAll()
if PlayerCore.activeOrNew.openURLs(urls) == 0 {
Utility.showAlert("nothing_to_open")
}
}
// MARK: - Accept dropped string and URL
@objc
func droppedText(_ pboard: NSPasteboard, userData:String, error: NSErrorPointer) {
if let url = pboard.string(forType: .string) {
openFileCalled = true
PlayerCore.active.openURLString(url)
}
}
// MARK: - Dock menu
func applicationDockMenu(_ sender: NSApplication) -> NSMenu? {
return dockMenu
}
// MARK: - URL Scheme
@objc func handleURLEvent(event: NSAppleEventDescriptor, withReplyEvent replyEvent: NSAppleEventDescriptor) {
openFileCalled = true
guard let url = event.paramDescriptor(forKeyword: keyDirectObject)?.stringValue else { return }
Logger.log("URL event: \(url)")
if isReady {
parsePendingURL(url)
} else {
pendingURL = url
}
}
/**
Parses the pending iina:// url.
- Parameter url: the pending URL.
- Note:
The iina:// URL scheme currently supports the following actions:
__/open__
- `url`: a url or string to open.
- `new_window`: 0 or 1 (default) to indicate whether open the media in a new window.
- `enqueue`: 0 (default) or 1 to indicate whether to add the media to the current playlist.
- `full_screen`: 0 (default) or 1 to indicate whether open the media and enter fullscreen.
- `pip`: 0 (default) or 1 to indicate whether open the media and enter pip.
- `mpv_*`: additional mpv options to be passed. e.g. `mpv_volume=20`.
Options starting with `no-` are not supported.
*/
private func parsePendingURL(_ url: String) {
Logger.log("Parsing URL \(url)")
guard let parsed = URLComponents(string: url) else {
Logger.log("Cannot parse URL using URLComponents", level: .warning)
return
}
// handle url scheme
guard let host = parsed.host else { return }
if host == "open" || host == "weblink" {
// open a file or link
guard let queries = parsed.queryItems else { return }
let queryDict = [String: String](uniqueKeysWithValues: queries.map { ($0.name, $0.value ?? "") })
// url
guard let urlValue = queryDict["url"], !urlValue.isEmpty else {
Logger.log("Cannot find parameter \"url\", stopped")
return
}
// new_window
let player: PlayerCore
if let newWindowValue = queryDict["new_window"], newWindowValue == "0" {
player = PlayerCore.active
} else {
player = PlayerCore.newPlayerCore
}
// enqueue
if let enqueueValue = queryDict["enqueue"], enqueueValue == "1", !PlayerCore.lastActive.info.playlist.isEmpty {
PlayerCore.lastActive.addToPlaylist(urlValue)
PlayerCore.lastActive.postNotification(.iinaPlaylistChanged)
PlayerCore.lastActive.sendOSD(.addToPlaylist(1))
} else {
player.openURLString(urlValue)
}
// presentation options
if let fsValue = queryDict["full_screen"], fsValue == "1" {
// full_screeen
player.mpv.setFlag(MPVOption.Window.fullscreen, true)
} else if let pipValue = queryDict["pip"], pipValue == "1" {
// pip
if #available(OSX 10.12, *) {
player.mainWindow.enterPIP()
}
}
// mpv options
for query in queries {
if query.name.hasPrefix("mpv_") {
let mpvOptionName = String(query.name.dropFirst(4))
guard let mpvOptionValue = query.value else { continue }
Logger.log("Setting \(mpvOptionName) to \(mpvOptionValue)")
player.mpv.setString(mpvOptionName, mpvOptionValue)
}
}
Logger.log("Finished URL scheme handling")
}
}
// MARK: - Menu actions
@IBAction func openFile(_ sender: AnyObject) {
Logger.log("Menu - Open file")
let panel = NSOpenPanel()
panel.title = NSLocalizedString("alert.choose_media_file.title", comment: "Choose Media File")
panel.canCreateDirectories = false
panel.canChooseFiles = true
panel.canChooseDirectories = true
panel.allowsMultipleSelection = true
if panel.runModal() == .OK {
if Preference.bool(for: .recordRecentFiles) {
for url in panel.urls {
NSDocumentController.shared.noteNewRecentDocumentURL(url)
}
}
let isAlternative = (sender as? NSMenuItem)?.tag == AlternativeMenuItemTag
let playerCore = PlayerCore.activeOrNewForMenuAction(isAlternative: isAlternative)
if playerCore.openURLs(panel.urls) == 0 {
Utility.showAlert("nothing_to_open")
}
}
}
@IBAction func openURL(_ sender: AnyObject) {
Logger.log("Menu - Open URL")
openURLWindow.isAlternativeAction = sender.tag == AlternativeMenuItemTag
openURLWindow.showWindow(nil)
openURLWindow.resetFields()
}
@IBAction func menuNewWindow(_ sender: Any) {
PlayerCore.newPlayerCore.initialWindow.showWindow(nil)
}
@IBAction func menuOpenScreenshotFolder(_ sender: NSMenuItem) {
let screenshotPath = Preference.string(for: .screenshotFolder)!
let absoluteScreenshotPath = NSString(string: screenshotPath).expandingTildeInPath
let url = URL(fileURLWithPath: absoluteScreenshotPath, isDirectory: true)
NSWorkspace.shared.open(url)
}
@IBAction func menuSelectAudioDevice(_ sender: NSMenuItem) {
if let name = sender.representedObject as? String {
PlayerCore.active.setAudioDevice(name)
}
}
@IBAction func showPreferences(_ sender: AnyObject) {
preferenceWindowController.showWindow(self)
}
@IBAction func showVideoFilterWindow(_ sender: AnyObject) {
vfWindow.showWindow(self)
}
@IBAction func showAudioFilterWindow(_ sender: AnyObject) {
afWindow.showWindow(self)
}
@IBAction func showAboutWindow(_ sender: AnyObject) {
aboutWindow.showWindow(self)
}
@IBAction func showHistoryWindow(_ sender: AnyObject) {
historyWindow.showWindow(self)
}
@IBAction func helpAction(_ sender: AnyObject) {
NSWorkspace.shared.open(URL(string: AppData.wikiLink)!)
}
@IBAction func githubAction(_ sender: AnyObject) {
NSWorkspace.shared.open(URL(string: AppData.githubLink)!)
}
@IBAction func websiteAction(_ sender: AnyObject) {
NSWorkspace.shared.open(URL(string: AppData.websiteLink)!)
}
private func registerUserDefaultValues() {
UserDefaults.standard.register(defaults: [String: Any](uniqueKeysWithValues: Preference.defaultPreference.map { ($0.0.rawValue, $0.1) }))
}
}
struct CommandLineStatus {
var isCommandLine = false
var isStdin = false
var openSeparateWindows = false
var enterPIP = false
var mpvArguments: [(String, String)] = []
var iinaArguments: [(String, String)] = []
var filenames: [String] = []
mutating func parseArguments(_ args: [String]) {
mpvArguments.removeAll()
iinaArguments.removeAll()
for arg in args {
let splitted = arg.dropFirst(2).split(separator: "=", maxSplits: 1)
let name = String(splitted[0])
if (name.hasPrefix("mpv-")) {
// mpv args
if splitted.count <= 1 {
mpvArguments.append((String(name.dropFirst(4)), "yes"))
} else {
mpvArguments.append((String(name.dropFirst(4)), String(splitted[1])))
}
} else {
// other args
if splitted.count <= 1 {
iinaArguments.append((name, "yes"))
} else {
iinaArguments.append((name, String(splitted[1])))
}
if name == "stdin" {
isStdin = true
}
if name == "separate-windows" {
openSeparateWindows = true
}
if name == "pip" {
enterPIP = true
}
}
}
}
func assignMPVArguments(to playerCore: PlayerCore) {
for arg in mpvArguments {
playerCore.mpv.setString(arg.0, arg.1)
}
}
}
@available(macOS 10.13, *)
class RemoteCommandController {
static let remoteCommand = MPRemoteCommandCenter.shared()
static var useSystemMediaControl: Bool = Preference.bool(for: .useMediaKeys)
static func setup() {
remoteCommand.playCommand.addTarget { _ in
PlayerCore.lastActive.togglePause(false)
return .success
}
remoteCommand.pauseCommand.addTarget { _ in
PlayerCore.lastActive.togglePause(true)
return .success
}
remoteCommand.togglePlayPauseCommand.addTarget { _ in
PlayerCore.lastActive.togglePause(nil)
return .success
}
remoteCommand.stopCommand.addTarget { _ in
PlayerCore.lastActive.stop()
return .success
}
remoteCommand.nextTrackCommand.addTarget { _ in
PlayerCore.lastActive.navigateInPlaylist(nextMedia: true)
return .success
}
remoteCommand.previousTrackCommand.addTarget { _ in
PlayerCore.lastActive.navigateInPlaylist(nextMedia: false)
return .success
}
remoteCommand.changeRepeatModeCommand.addTarget { _ in
PlayerCore.lastActive.togglePlaylistLoop()
return .success
}
remoteCommand.changeShuffleModeCommand.isEnabled = false
// remoteCommand.changeShuffleModeCommand.addTarget {})
remoteCommand.changePlaybackRateCommand.supportedPlaybackRates = [0.5, 1, 1.5, 2]
remoteCommand.changePlaybackRateCommand.addTarget { event in
PlayerCore.lastActive.setSpeed(Double((event as! MPChangePlaybackRateCommandEvent).playbackRate))
return .success
}
remoteCommand.skipForwardCommand.preferredIntervals = [15]
remoteCommand.skipForwardCommand.addTarget { event in
PlayerCore.lastActive.seek(relativeSecond: (event as! MPSkipIntervalCommandEvent).interval, option: .exact)
return .success
}
remoteCommand.skipBackwardCommand.preferredIntervals = [15]
remoteCommand.skipBackwardCommand.addTarget { event in
PlayerCore.lastActive.seek(relativeSecond: -(event as! MPSkipIntervalCommandEvent).interval, option: .exact)
return .success
}
remoteCommand.changePlaybackPositionCommand.addTarget { event in
PlayerCore.lastActive.seek(absoluteSecond: (event as! MPChangePlaybackPositionCommandEvent).positionTime)
return .success
}
}
}
| gpl-3.0 | c2703bd06291b62eaa7ab4298e81b6f3 | 32.156507 | 206 | 0.684786 | 4.550305 | false | false | false | false |
shorlander/firefox-ios | Client/Frontend/Browser/TabTrayController.swift | 2 | 52944 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Foundation
import UIKit
import SnapKit
import Storage
import ReadingList
import Shared
struct TabTrayControllerUX {
static let CornerRadius = CGFloat(4.0)
static let BackgroundColor = UIConstants.AppBackgroundColor
static let CellBackgroundColor = UIColor(red:0.95, green:0.95, blue:0.95, alpha:1)
static let TextBoxHeight = CGFloat(32.0)
static let FaviconSize = CGFloat(18.0)
static let Margin = CGFloat(15)
static let ToolbarBarTintColor = UIConstants.AppBackgroundColor
static let ToolbarButtonOffset = CGFloat(10.0)
static let CloseButtonSize = CGFloat(18.0)
static let CloseButtonMargin = CGFloat(6.0)
static let CloseButtonEdgeInset = CGFloat(10)
static let NumberOfColumnsThin = 1
static let NumberOfColumnsWide = 3
static let CompactNumberOfColumnsThin = 2
static let MenuFixedWidth: CGFloat = 320
static let RearrangeWobblePeriod: TimeInterval = 0.1
static let RearrangeTransitionDuration: TimeInterval = 0.2
static let RearrangeWobbleAngle: CGFloat = 0.02
static let RearrangeDragScale: CGFloat = 1.1
static let RearrangeDragAlpha: CGFloat = 0.9
// Moved from UIConstants temporarily until animation code is merged
static var StatusBarHeight: CGFloat {
if UIScreen.main.traitCollection.verticalSizeClass == .compact {
return 0
}
return 20
}
}
struct LightTabCellUX {
static let TabTitleTextColor = UIColor.black
}
struct DarkTabCellUX {
static let TabTitleTextColor = UIColor.white
}
protocol TabCellDelegate: class {
func tabCellDidClose(_ cell: TabCell)
}
class TabCell: UICollectionViewCell {
enum Style {
case light
case dark
}
static let Identifier = "TabCellIdentifier"
var style: Style = .light {
didSet {
applyStyle(style)
}
}
let backgroundHolder = UIView()
let background = UIImageViewAligned()
let titleText: UILabel
let innerStroke: InnerStrokedView
let favicon: UIImageView = UIImageView()
let closeButton: UIButton
var title: UIVisualEffectView!
var animator: SwipeAnimator!
var isBeingArranged: Bool = false {
didSet {
if isBeingArranged {
self.contentView.transform = CGAffineTransform(rotationAngle: TabTrayControllerUX.RearrangeWobbleAngle)
UIView.animate(withDuration: TabTrayControllerUX.RearrangeWobblePeriod, delay: 0, options: [.allowUserInteraction, .repeat, .autoreverse], animations: {
self.contentView.transform = CGAffineTransform(rotationAngle: -TabTrayControllerUX.RearrangeWobbleAngle)
}, completion: nil)
} else {
if oldValue {
UIView.animate(withDuration: TabTrayControllerUX.RearrangeTransitionDuration, delay: 0, options: [.allowUserInteraction, .beginFromCurrentState], animations: {
self.contentView.transform = CGAffineTransform.identity
}, completion: nil)
}
}
}
}
weak var delegate: TabCellDelegate?
// Changes depending on whether we're full-screen or not.
var margin = CGFloat(0)
override init(frame: CGRect) {
self.backgroundHolder.backgroundColor = UIColor.white
self.backgroundHolder.layer.cornerRadius = TabTrayControllerUX.CornerRadius
self.backgroundHolder.clipsToBounds = true
self.backgroundHolder.backgroundColor = TabTrayControllerUX.CellBackgroundColor
self.background.contentMode = UIViewContentMode.scaleAspectFill
self.background.clipsToBounds = true
self.background.isUserInteractionEnabled = false
self.background.alignLeft = true
self.background.alignTop = true
self.favicon.backgroundColor = UIColor.clear
self.favicon.layer.cornerRadius = 2.0
self.favicon.layer.masksToBounds = true
self.titleText = UILabel()
self.titleText.textAlignment = NSTextAlignment.left
self.titleText.isUserInteractionEnabled = false
self.titleText.numberOfLines = 1
self.titleText.font = DynamicFontHelper.defaultHelper.DefaultSmallFontBold
self.closeButton = UIButton()
self.closeButton.setImage(UIImage(named: "stop"), for: UIControlState())
self.closeButton.tintColor = UIColor.lightGray
self.closeButton.imageEdgeInsets = UIEdgeInsets(equalInset: TabTrayControllerUX.CloseButtonEdgeInset)
self.innerStroke = InnerStrokedView(frame: self.backgroundHolder.frame)
self.innerStroke.layer.backgroundColor = UIColor.clear.cgColor
super.init(frame: frame)
self.animator = SwipeAnimator(animatingView: self.backgroundHolder, container: self)
self.closeButton.addTarget(self, action: #selector(TabCell.SELclose), for: UIControlEvents.touchUpInside)
contentView.addSubview(backgroundHolder)
backgroundHolder.addSubview(self.background)
backgroundHolder.addSubview(innerStroke)
// Default style is light
applyStyle(style)
self.accessibilityCustomActions = [
UIAccessibilityCustomAction(name: NSLocalizedString("Close", comment: "Accessibility label for action denoting closing a tab in tab list (tray)"), target: self.animator, selector: #selector(SwipeAnimator.SELcloseWithoutGesture))
]
}
fileprivate func applyStyle(_ style: Style) {
self.title?.removeFromSuperview()
let title: UIVisualEffectView
switch style {
case .light:
title = UIVisualEffectView(effect: UIBlurEffect(style: .extraLight))
self.titleText.textColor = LightTabCellUX.TabTitleTextColor
case .dark:
title = UIVisualEffectView(effect: UIBlurEffect(style: .dark))
self.titleText.textColor = DarkTabCellUX.TabTitleTextColor
}
titleText.backgroundColor = UIColor.clear
title.contentView.addSubview(self.closeButton)
title.contentView.addSubview(self.titleText)
title.contentView.addSubview(self.favicon)
backgroundHolder.addSubview(title)
self.title = title
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func layoutSubviews() {
super.layoutSubviews()
let w = frame.width
let h = frame.height
backgroundHolder.frame = CGRect(x: margin,
y: margin,
width: w,
height: h)
background.frame = CGRect(origin: CGPoint(x: 0, y: 0), size: backgroundHolder.frame.size)
title.frame = CGRect(x: 0,
y: 0,
width: backgroundHolder.frame.width,
height: TabTrayControllerUX.TextBoxHeight)
favicon.frame = CGRect(x: 6,
y: (TabTrayControllerUX.TextBoxHeight - TabTrayControllerUX.FaviconSize)/2,
width: TabTrayControllerUX.FaviconSize,
height: TabTrayControllerUX.FaviconSize)
let titleTextLeft = favicon.frame.origin.x + favicon.frame.width + 6
titleText.frame = CGRect(x: titleTextLeft,
y: 0,
width: title.frame.width - titleTextLeft - margin - TabTrayControllerUX.CloseButtonSize - TabTrayControllerUX.CloseButtonMargin * 2,
height: title.frame.height)
innerStroke.frame = background.frame
closeButton.snp.makeConstraints { make in
make.size.equalTo(title.snp.height)
make.trailing.centerY.equalTo(title)
}
let top = (TabTrayControllerUX.TextBoxHeight - titleText.bounds.height) / 2.0
titleText.frame.origin = CGPoint(x: titleText.frame.origin.x, y: max(0, top))
}
override func prepareForReuse() {
// Reset any close animations.
backgroundHolder.transform = CGAffineTransform.identity
backgroundHolder.alpha = 1
self.titleText.font = DynamicFontHelper.defaultHelper.DefaultSmallFontBold
}
override func accessibilityScroll(_ direction: UIAccessibilityScrollDirection) -> Bool {
var right: Bool
switch direction {
case .left:
right = false
case .right:
right = true
default:
return false
}
animator.close(right: right)
return true
}
@objc
func SELclose() {
self.animator.SELcloseWithoutGesture()
}
}
struct PrivateModeStrings {
static let toggleAccessibilityLabel = NSLocalizedString("Private Mode", tableName: "PrivateBrowsing", comment: "Accessibility label for toggling on/off private mode")
static let toggleAccessibilityHint = NSLocalizedString("Turns private mode on or off", tableName: "PrivateBrowsing", comment: "Accessiblity hint for toggling on/off private mode")
static let toggleAccessibilityValueOn = NSLocalizedString("On", tableName: "PrivateBrowsing", comment: "Toggled ON accessibility value")
static let toggleAccessibilityValueOff = NSLocalizedString("Off", tableName: "PrivateBrowsing", comment: "Toggled OFF accessibility value")
}
protocol TabTrayDelegate: class {
func tabTrayDidDismiss(_ tabTray: TabTrayController)
func tabTrayDidAddBookmark(_ tab: Tab)
func tabTrayDidAddToReadingList(_ tab: Tab) -> ReadingListClientRecord?
func tabTrayRequestsPresentationOf(_ viewController: UIViewController)
}
struct TabTrayState {
var isPrivate: Bool = false
}
class TabTrayController: UIViewController {
let tabManager: TabManager
let profile: Profile
weak var delegate: TabTrayDelegate?
weak var appStateDelegate: AppStateDelegate?
var collectionView: UICollectionView!
var draggedCell: TabCell?
var dragOffset: CGPoint = CGPoint.zero
lazy var toolbar: TrayToolbar = {
let toolbar = TrayToolbar()
toolbar.addTabButton.addTarget(self, action: #selector(TabTrayController.SELdidClickAddTab), for: .touchUpInside)
toolbar.menuButton.addTarget(self, action: #selector(TabTrayController.didTapMenu), for: .touchUpInside)
toolbar.maskButton.addTarget(self, action: #selector(TabTrayController.SELdidTogglePrivateMode), for: .touchUpInside)
return toolbar
}()
var tabTrayState: TabTrayState {
return TabTrayState(isPrivate: self.privateMode)
}
var leftToolbarButtons: [UIButton] {
return [toolbar.addTabButton]
}
var rightToolbarButtons: [UIButton]? {
return [toolbar.maskButton]
}
fileprivate(set) internal var privateMode: Bool = false {
didSet {
if oldValue != privateMode {
updateAppState()
}
tabDataSource.tabs = tabsToDisplay
toolbar.styleToolbar(privateMode)
collectionView?.reloadData()
}
}
fileprivate var tabsToDisplay: [Tab] {
return self.privateMode ? tabManager.privateTabs : tabManager.normalTabs
}
fileprivate lazy var emptyPrivateTabsView: EmptyPrivateTabsView = {
let emptyView = EmptyPrivateTabsView()
emptyView.learnMoreButton.addTarget(self, action: #selector(TabTrayController.SELdidTapLearnMore), for: UIControlEvents.touchUpInside)
return emptyView
}()
fileprivate lazy var tabDataSource: TabManagerDataSource = {
return TabManagerDataSource(tabs: self.tabsToDisplay, cellDelegate: self, tabManager: self.tabManager)
}()
fileprivate lazy var tabLayoutDelegate: TabLayoutDelegate = {
let delegate = TabLayoutDelegate(profile: self.profile, traitCollection: self.traitCollection)
delegate.tabSelectionDelegate = self
return delegate
}()
init(tabManager: TabManager, profile: Profile) {
self.tabManager = tabManager
self.profile = profile
super.init(nibName: nil, bundle: nil)
tabManager.addDelegate(self)
}
convenience init(tabManager: TabManager, profile: Profile, tabTrayDelegate: TabTrayDelegate) {
self.init(tabManager: tabManager, profile: profile)
self.delegate = tabTrayDelegate
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
deinit {
NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIApplicationWillResignActive, object: nil)
NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIApplicationWillEnterForeground, object: nil)
NotificationCenter.default.removeObserver(self, name: NotificationDynamicFontChanged, object: nil)
self.tabManager.removeDelegate(self)
}
func SELDynamicFontChanged(_ notification: Notification) {
guard notification.name == NotificationDynamicFontChanged else { return }
self.collectionView.reloadData()
}
// MARK: View Controller Callbacks
override func viewDidLoad() {
super.viewDidLoad()
view.accessibilityLabel = NSLocalizedString("Tabs Tray", comment: "Accessibility label for the Tabs Tray view.")
collectionView = UICollectionView(frame: view.frame, collectionViewLayout: UICollectionViewFlowLayout())
collectionView.dataSource = tabDataSource
collectionView.delegate = tabLayoutDelegate
collectionView.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: UIConstants.ToolbarHeight, right: 0)
collectionView.register(TabCell.self, forCellWithReuseIdentifier: TabCell.Identifier)
collectionView.backgroundColor = TabTrayControllerUX.BackgroundColor
if AppConstants.MOZ_REORDER_TAB_TRAY {
collectionView.addGestureRecognizer(UILongPressGestureRecognizer(target: self, action: #selector(didLongPressTab)))
}
view.addSubview(collectionView)
view.addSubview(toolbar)
makeConstraints()
view.insertSubview(emptyPrivateTabsView, aboveSubview: collectionView)
emptyPrivateTabsView.snp.makeConstraints { make in
make.top.left.right.equalTo(self.collectionView)
make.bottom.equalTo(self.toolbar.snp.top)
}
if let tab = tabManager.selectedTab, tab.isPrivate {
privateMode = true
}
// register for previewing delegate to enable peek and pop if force touch feature available
if traitCollection.forceTouchCapability == .available {
registerForPreviewing(with: self, sourceView: view)
}
emptyPrivateTabsView.isHidden = !privateTabsAreEmpty()
NotificationCenter.default.addObserver(self, selector: #selector(TabTrayController.SELappWillResignActiveNotification), name: NSNotification.Name.UIApplicationWillResignActive, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(TabTrayController.SELappDidBecomeActiveNotification), name: NSNotification.Name.UIApplicationDidBecomeActive, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(TabTrayController.SELDynamicFontChanged(_:)), name: NotificationDynamicFontChanged, object: nil)
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
NotificationCenter.default.addObserver(self, selector: #selector(TabTrayController.SELdidClickSettingsItem), name: NSNotification.Name(rawValue: NotificationStatusNotificationTapped), object: nil)
}
override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: NotificationStatusNotificationTapped), object: nil)
}
override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
super.traitCollectionDidChange(previousTraitCollection)
// Update the trait collection we reference in our layout delegate
tabLayoutDelegate.traitCollection = traitCollection
self.collectionView.collectionViewLayout.invalidateLayout()
}
fileprivate func cancelExistingGestures() {
if let visibleCells = self.collectionView.visibleCells as? [TabCell] {
for cell in visibleCells {
cell.animator.cancelExistingGestures()
}
}
}
override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
super.viewWillTransition(to: size, with: coordinator)
if AppConstants.MOZ_REORDER_TAB_TRAY {
self.cancelExistingGestures()
}
coordinator.animate(alongsideTransition: { _ in
self.collectionView.collectionViewLayout.invalidateLayout()
}, completion: nil)
}
override var preferredStatusBarStyle: UIStatusBarStyle {
return UIStatusBarStyle.lightContent
}
fileprivate func makeConstraints() {
collectionView.snp.makeConstraints { make in
make.left.bottom.right.equalTo(view)
make.top.equalTo(self.topLayoutGuide.snp.bottom)
}
toolbar.snp.makeConstraints { make in
make.left.right.bottom.equalTo(view)
make.height.equalTo(UIConstants.ToolbarHeight)
}
}
// MARK: Selectors
func SELdidClickDone() {
presentingViewController!.dismiss(animated: true, completion: nil)
}
func SELdidClickSettingsItem() {
assert(Thread.isMainThread, "Opening settings requires being invoked on the main thread")
let settingsTableViewController = AppSettingsTableViewController()
settingsTableViewController.profile = profile
settingsTableViewController.tabManager = tabManager
settingsTableViewController.settingsDelegate = self
let controller = SettingsNavigationController(rootViewController: settingsTableViewController)
controller.popoverDelegate = self
controller.modalPresentationStyle = UIModalPresentationStyle.formSheet
present(controller, animated: true, completion: nil)
}
func SELdidClickAddTab() {
openNewTab()
LeanplumIntegration.sharedInstance.track(eventName: .openedNewTab, withParameters: ["Source":"Tab Tray" as AnyObject])
}
func SELdidTapLearnMore() {
let appVersion = Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as! String
if let langID = Locale.preferredLanguages.first {
let learnMoreRequest = URLRequest(url: "https://support.mozilla.org/1/mobile/\(appVersion)/iOS/\(langID)/private-browsing-ios".asURL!)
openNewTab(learnMoreRequest)
}
}
@objc
fileprivate func didTapMenu() {
let state = mainStore.updateState(.tabTray(tabTrayState: self.tabTrayState))
let mvc = MenuViewController(withAppState: state, presentationStyle: .modal)
mvc.delegate = self
mvc.actionDelegate = self
mvc.menuTransitionDelegate = MenuPresentationAnimator()
mvc.modalPresentationStyle = .overCurrentContext
mvc.fixedWidth = TabTrayControllerUX.MenuFixedWidth
if AppConstants.MOZ_REORDER_TAB_TRAY {
self.cancelExistingGestures()
}
self.present(mvc, animated: true, completion: nil)
}
func didLongPressTab(_ gesture: UILongPressGestureRecognizer) {
switch gesture.state {
case .began:
let pressPosition = gesture.location(in: self.collectionView)
guard let indexPath = self.collectionView.indexPathForItem(at: pressPosition) else {
break
}
self.collectionView.beginInteractiveMovementForItem(at: indexPath)
self.view.isUserInteractionEnabled = false
self.tabDataSource.isRearrangingTabs = true
for item in 0..<self.tabDataSource.collectionView(self.collectionView, numberOfItemsInSection: 0) {
guard let cell = self.collectionView.cellForItem(at: IndexPath(item: item, section: 0)) as? TabCell else {
continue
}
if item == indexPath.item {
let cellPosition = cell.contentView.convert(cell.bounds.center, to: self.collectionView)
self.draggedCell = cell
self.dragOffset = CGPoint(x: pressPosition.x - cellPosition.x, y: pressPosition.y - cellPosition.y)
UIView.animate(withDuration: TabTrayControllerUX.RearrangeTransitionDuration, delay: 0, options: [.allowUserInteraction, .beginFromCurrentState], animations: {
cell.contentView.transform = CGAffineTransform(scaleX: TabTrayControllerUX.RearrangeDragScale, y: TabTrayControllerUX.RearrangeDragScale)
cell.contentView.alpha = TabTrayControllerUX.RearrangeDragAlpha
}, completion: nil)
continue
}
cell.isBeingArranged = true
}
break
case .changed:
if let view = gesture.view, let draggedCell = self.draggedCell {
var dragPosition = gesture.location(in: view)
let offsetPosition = CGPoint(x: dragPosition.x + draggedCell.frame.center.x * (1 - TabTrayControllerUX.RearrangeDragScale), y: dragPosition.y + draggedCell.frame.center.y * (1 - TabTrayControllerUX.RearrangeDragScale))
dragPosition = CGPoint(x: offsetPosition.x - self.dragOffset.x, y: offsetPosition.y - self.dragOffset.y)
collectionView.updateInteractiveMovementTargetPosition(dragPosition)
}
case .ended, .cancelled:
for item in 0..<self.tabDataSource.collectionView(self.collectionView, numberOfItemsInSection: 0) {
guard let cell = self.collectionView.cellForItem(at: IndexPath(item: item, section: 0)) as? TabCell else {
continue
}
if !cell.isBeingArranged {
UIView.animate(withDuration: TabTrayControllerUX.RearrangeTransitionDuration, delay: 0, options: [.allowUserInteraction, .beginFromCurrentState], animations: {
cell.contentView.transform = CGAffineTransform.identity
cell.contentView.alpha = 1
}, completion: nil)
continue
}
cell.isBeingArranged = false
}
self.tabDataSource.isRearrangingTabs = false
self.view.isUserInteractionEnabled = true
gesture.state == .ended ? self.collectionView.endInteractiveMovement() : self.collectionView.cancelInteractiveMovement()
default:
break
}
}
func SELdidTogglePrivateMode() {
let scaleDownTransform = CGAffineTransform(scaleX: 0.9, y: 0.9)
let fromView: UIView
if !privateTabsAreEmpty(), let snapshot = collectionView.snapshotView(afterScreenUpdates: false) {
snapshot.frame = collectionView.frame
view.insertSubview(snapshot, aboveSubview: collectionView)
fromView = snapshot
} else {
fromView = emptyPrivateTabsView
}
tabManager.willSwitchTabMode()
privateMode = !privateMode
// If we are exiting private mode and we have the close private tabs option selected, make sure
// we clear out all of the private tabs
let exitingPrivateMode = !privateMode && tabManager.shouldClearPrivateTabs()
toolbar.maskButton.setSelected(privateMode, animated: true)
collectionView.layoutSubviews()
let toView: UIView
if !privateTabsAreEmpty(), let newSnapshot = collectionView.snapshotView(afterScreenUpdates: !exitingPrivateMode) {
emptyPrivateTabsView.isHidden = true
//when exiting private mode don't screenshot the collectionview (causes the UI to hang)
newSnapshot.frame = collectionView.frame
view.insertSubview(newSnapshot, aboveSubview: fromView)
collectionView.alpha = 0
toView = newSnapshot
} else {
emptyPrivateTabsView.isHidden = false
toView = emptyPrivateTabsView
}
toView.alpha = 0
toView.transform = scaleDownTransform
UIView.animate(withDuration: 0.2, delay: 0, options: [], animations: { () -> Void in
fromView.transform = scaleDownTransform
fromView.alpha = 0
toView.transform = CGAffineTransform.identity
toView.alpha = 1
}) { finished in
if fromView != self.emptyPrivateTabsView {
fromView.removeFromSuperview()
}
if toView != self.emptyPrivateTabsView {
toView.removeFromSuperview()
}
self.collectionView.alpha = 1
}
}
fileprivate func privateTabsAreEmpty() -> Bool {
return privateMode && tabManager.privateTabs.count == 0
}
func changePrivacyMode(_ isPrivate: Bool) {
if isPrivate != privateMode {
guard let _ = collectionView else {
privateMode = isPrivate
return
}
SELdidTogglePrivateMode()
}
}
fileprivate func openNewTab(_ request: URLRequest? = nil) {
toolbar.isUserInteractionEnabled = false
// We're only doing one update here, but using a batch update lets us delay selecting the tab
// until after its insert animation finishes.
self.collectionView.performBatchUpdates({ _ in
let tab = self.tabManager.addTab(request, isPrivate: self.privateMode)
self.tabManager.selectTab(tab)
}, completion: { finished in
self.toolbar.isUserInteractionEnabled = true
if finished {
_ = self.navigationController?.popViewController(animated: true)
if request == nil && NewTabAccessors.getNewTabPage(self.profile.prefs) == .blankPage {
if let bvc = self.navigationController?.topViewController as? BrowserViewController {
DispatchQueue.main.asyncAfter(deadline: .now() + 0.6) {
bvc.urlBar.tabLocationViewDidTapLocation(bvc.urlBar.locationView)
}
}
}
}
})
}
fileprivate func updateAppState() {
let state = mainStore.updateState(.tabTray(tabTrayState: self.tabTrayState))
self.appStateDelegate?.appDidUpdateState(state)
}
fileprivate func closeTabsForCurrentTray() {
tabManager.removeTabsWithUndoToast(tabsToDisplay)
self.collectionView.reloadData()
}
}
// MARK: - App Notifications
extension TabTrayController {
func SELappWillResignActiveNotification() {
if privateMode {
collectionView.alpha = 0
}
}
func SELappDidBecomeActiveNotification() {
// Re-show any components that might have been hidden because they were being displayed
// as part of a private mode tab
UIView.animate(withDuration: 0.2, delay: 0, options: UIViewAnimationOptions(), animations: {
self.collectionView.alpha = 1
},
completion: nil)
}
}
extension TabTrayController: TabSelectionDelegate {
func didSelectTabAtIndex(_ index: Int) {
let tab = tabsToDisplay[index]
tabManager.selectTab(tab)
_ = self.navigationController?.popViewController(animated: true)
}
}
extension TabTrayController: PresentingModalViewControllerDelegate {
func dismissPresentedModalViewController(_ modalViewController: UIViewController, animated: Bool) {
dismiss(animated: animated, completion: { self.collectionView.reloadData() })
}
}
extension TabTrayController: TabManagerDelegate {
func tabManager(_ tabManager: TabManager, didSelectedTabChange selected: Tab?, previous: Tab?) {
}
func tabManager(_ tabManager: TabManager, willAddTab tab: Tab) {
}
func tabManager(_ tabManager: TabManager, willRemoveTab tab: Tab) {
}
func tabManager(_ tabManager: TabManager, didAddTab tab: Tab) {
// Get the index of the added tab from it's set (private or normal)
guard let index = tabsToDisplay.index(of: tab) else { return }
if !privateTabsAreEmpty() {
emptyPrivateTabsView.isHidden = true
}
tabDataSource.addTab(tab)
self.collectionView?.performBatchUpdates({ _ in
self.collectionView.insertItems(at: [IndexPath(item: index, section: 0)])
}, completion: { finished in
if finished {
tabManager.selectTab(tab)
// don't pop the tab tray view controller if it is not in the foreground
if self.presentedViewController == nil {
_ = self.navigationController?.popViewController(animated: true)
}
}
})
}
func tabManager(_ tabManager: TabManager, didRemoveTab tab: Tab) {
// it is possible that we are removing a tab that we are not currently displaying
// through the Close All Tabs feature (which will close tabs that are not in our current privacy mode)
// check this before removing the item from the collection
let removedIndex = tabDataSource.removeTab(tab)
if removedIndex > -1 {
self.collectionView.performBatchUpdates({
self.collectionView.deleteItems(at: [IndexPath(item: removedIndex, section: 0)])
}, completion: { finished in
guard finished && self.privateTabsAreEmpty() else { return }
self.emptyPrivateTabsView.isHidden = false
})
// Workaround: On iOS 8.* devices, cells don't get reloaded during the deletion but after the
// animation has finished which causes cells that animate from above to suddenly 'appear'. This
// is fixed on iOS 9 but for iOS 8 we force a reload on non-visible cells during the animation.
if floor(NSFoundationVersionNumber) <= NSFoundationVersionNumber_iOS_8_3 {
let visibleCount = collectionView.indexPathsForVisibleItems.count
var offscreenIndexPaths = [IndexPath]()
for i in 0..<(tabsToDisplay.count - visibleCount) {
offscreenIndexPaths.append(IndexPath(item: i, section: 0))
}
self.collectionView.reloadItems(at: offscreenIndexPaths)
}
}
}
func tabManagerDidAddTabs(_ tabManager: TabManager) {
}
func tabManagerDidRestoreTabs(_ tabManager: TabManager) {
}
func tabManagerDidRemoveAllTabs(_ tabManager: TabManager, toast: ButtonToast?) {
guard privateMode else {
return
}
if let toast = toast {
view.addSubview(toast)
toast.snp.makeConstraints { make in
make.left.right.equalTo(view)
make.bottom.equalTo(toolbar.snp.top)
}
toast.showToast()
}
}
}
extension TabTrayController: UIScrollViewAccessibilityDelegate {
func accessibilityScrollStatus(for scrollView: UIScrollView) -> String? {
var visibleCells = collectionView.visibleCells as! [TabCell]
var bounds = collectionView.bounds
bounds = bounds.offsetBy(dx: collectionView.contentInset.left, dy: collectionView.contentInset.top)
bounds.size.width -= collectionView.contentInset.left + collectionView.contentInset.right
bounds.size.height -= collectionView.contentInset.top + collectionView.contentInset.bottom
// visible cells do sometimes return also not visible cells when attempting to go past the last cell with VoiceOver right-flick gesture; so make sure we have only visible cells (yeah...)
visibleCells = visibleCells.filter { !$0.frame.intersection(bounds).isEmpty }
let cells = visibleCells.map { self.collectionView.indexPath(for: $0)! }
let indexPaths = cells.sorted { (a: IndexPath, b: IndexPath) -> Bool in
return a.section < b.section || (a.section == b.section && a.row < b.row)
}
if indexPaths.count == 0 {
return NSLocalizedString("No tabs", comment: "Message spoken by VoiceOver to indicate that there are no tabs in the Tabs Tray")
}
let firstTab = indexPaths.first!.row + 1
let lastTab = indexPaths.last!.row + 1
let tabCount = collectionView.numberOfItems(inSection: 0)
if firstTab == lastTab {
let format = NSLocalizedString("Tab %@ of %@", comment: "Message spoken by VoiceOver saying the position of the single currently visible tab in Tabs Tray, along with the total number of tabs. E.g. \"Tab 2 of 5\" says that tab 2 is visible (and is the only visible tab), out of 5 tabs total.")
return String(format: format, NSNumber(value: firstTab as Int), NSNumber(value: tabCount as Int))
} else {
let format = NSLocalizedString("Tabs %@ to %@ of %@", comment: "Message spoken by VoiceOver saying the range of tabs that are currently visible in Tabs Tray, along with the total number of tabs. E.g. \"Tabs 8 to 10 of 15\" says tabs 8, 9 and 10 are visible, out of 15 tabs total.")
return String(format: format, NSNumber(value: firstTab as Int), NSNumber(value: lastTab as Int), NSNumber(value: tabCount as Int))
}
}
}
extension TabTrayController: SwipeAnimatorDelegate {
func swipeAnimator(_ animator: SwipeAnimator, viewWillExitContainerBounds: UIView) {
let tabCell = animator.container as! TabCell
if let indexPath = collectionView.indexPath(for: tabCell) {
let tab = tabsToDisplay[indexPath.item]
tabManager.removeTab(tab)
UIAccessibilityPostNotification(UIAccessibilityAnnouncementNotification, NSLocalizedString("Closing tab", comment: "Accessibility label (used by assistive technology) notifying the user that the tab is being closed."))
}
}
}
extension TabTrayController: TabCellDelegate {
func tabCellDidClose(_ cell: TabCell) {
let indexPath = collectionView.indexPath(for: cell)!
let tab = tabsToDisplay[indexPath.item]
tabManager.removeTab(tab)
}
}
extension TabTrayController: SettingsDelegate {
func settingsOpenURLInNewTab(_ url: URL) {
let request = URLRequest(url: url)
openNewTab(request)
}
}
fileprivate class TabManagerDataSource: NSObject, UICollectionViewDataSource {
unowned var cellDelegate: TabCellDelegate & SwipeAnimatorDelegate
fileprivate var tabs: [Tab]
fileprivate var tabManager: TabManager
var isRearrangingTabs: Bool = false
init(tabs: [Tab], cellDelegate: TabCellDelegate & SwipeAnimatorDelegate, tabManager: TabManager) {
self.cellDelegate = cellDelegate
self.tabs = tabs
self.tabManager = tabManager
super.init()
}
/**
Removes the given tab from the data source
- parameter tab: Tab to remove
- returns: The index of the removed tab, -1 if tab did not exist
*/
func removeTab(_ tabToRemove: Tab) -> Int {
var index: Int = -1
for (i, tab) in tabs.enumerated() where tabToRemove === tab {
index = i
tabs.remove(at: index)
break
}
return index
}
/**
Adds the given tab to the data source
- parameter tab: Tab to add
*/
func addTab(_ tab: Tab) {
tabs.append(tab)
}
@objc func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let tabCell = collectionView.dequeueReusableCell(withReuseIdentifier: TabCell.Identifier, for: indexPath) as! TabCell
tabCell.animator.delegate = cellDelegate
tabCell.delegate = cellDelegate
let tab = tabs[indexPath.item]
tabCell.style = tab.isPrivate ? .dark : .light
tabCell.titleText.text = tab.displayTitle
if !tab.displayTitle.isEmpty {
tabCell.accessibilityLabel = tab.displayTitle
} else {
tabCell.accessibilityLabel = tab.url?.aboutComponent ?? "" // If there is no title we are most likely on a home panel.
}
if AppConstants.MOZ_REORDER_TAB_TRAY {
tabCell.isBeingArranged = self.isRearrangingTabs
}
tabCell.isAccessibilityElement = true
tabCell.accessibilityHint = NSLocalizedString("Swipe right or left with three fingers to close the tab.", comment: "Accessibility hint for tab tray's displayed tab.")
if let favIcon = tab.displayFavicon {
tabCell.favicon.sd_setImage(with: URL(string: favIcon.url)!)
} else {
var defaultFavicon = UIImage(named: "defaultFavicon")
if tab.isPrivate {
defaultFavicon = defaultFavicon?.withRenderingMode(.alwaysTemplate)
tabCell.favicon.image = defaultFavicon
tabCell.favicon.tintColor = UIColor.white
} else {
tabCell.favicon.image = defaultFavicon
}
}
tabCell.background.image = tab.screenshot
return tabCell
}
@objc func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return tabs.count
}
@objc fileprivate func collectionView(_ collectionView: UICollectionView, moveItemAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath) {
let fromIndex = sourceIndexPath.item
let toIndex = destinationIndexPath.item
tabs.insert(tabs.remove(at: fromIndex), at: toIndex < fromIndex ? toIndex : toIndex - 1)
tabManager.moveTab(isPrivate: tabs[fromIndex].isPrivate, fromIndex: fromIndex, toIndex: toIndex)
}
}
@objc protocol TabSelectionDelegate: class {
func didSelectTabAtIndex(_ index: Int)
}
fileprivate class TabLayoutDelegate: NSObject, UICollectionViewDelegateFlowLayout {
weak var tabSelectionDelegate: TabSelectionDelegate?
fileprivate var traitCollection: UITraitCollection
fileprivate var profile: Profile
fileprivate var numberOfColumns: Int {
let compactLayout = profile.prefs.boolForKey("CompactTabLayout") ?? true
// iPhone 4-6+ portrait
if traitCollection.horizontalSizeClass == .compact && traitCollection.verticalSizeClass == .regular {
return compactLayout ? TabTrayControllerUX.CompactNumberOfColumnsThin : TabTrayControllerUX.NumberOfColumnsThin
} else {
return TabTrayControllerUX.NumberOfColumnsWide
}
}
init(profile: Profile, traitCollection: UITraitCollection) {
self.profile = profile
self.traitCollection = traitCollection
super.init()
}
fileprivate func cellHeightForCurrentDevice() -> CGFloat {
let compactLayout = profile.prefs.boolForKey("CompactTabLayout") ?? true
let shortHeight = (compactLayout ? TabTrayControllerUX.TextBoxHeight * 6 : TabTrayControllerUX.TextBoxHeight * 5)
if self.traitCollection.verticalSizeClass == UIUserInterfaceSizeClass.compact {
return shortHeight
} else if self.traitCollection.horizontalSizeClass == UIUserInterfaceSizeClass.compact {
return shortHeight
} else {
return TabTrayControllerUX.TextBoxHeight * 8
}
}
@objc func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
return TabTrayControllerUX.Margin
}
@objc func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let cellWidth = floor((collectionView.bounds.width - TabTrayControllerUX.Margin * CGFloat(numberOfColumns + 1)) / CGFloat(numberOfColumns))
return CGSize(width: cellWidth, height: self.cellHeightForCurrentDevice())
}
@objc func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
return UIEdgeInsets(equalInset: TabTrayControllerUX.Margin)
}
@objc func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
return TabTrayControllerUX.Margin
}
@objc func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
tabSelectionDelegate?.didSelectTabAtIndex(indexPath.row)
}
}
struct EmptyPrivateTabsViewUX {
static let TitleColor = UIColor.white
static let TitleFont = UIFont.systemFont(ofSize: 22, weight: UIFontWeightMedium)
static let DescriptionColor = UIColor.white
static let DescriptionFont = UIFont.systemFont(ofSize: 17)
static let LearnMoreFont = UIFont.systemFont(ofSize: 15, weight: UIFontWeightMedium)
static let TextMargin: CGFloat = 18
static let LearnMoreMargin: CGFloat = 30
static let MaxDescriptionWidth: CGFloat = 250
static let MinBottomMargin: CGFloat = 10
}
// View we display when there are no private tabs created
fileprivate class EmptyPrivateTabsView: UIView {
fileprivate lazy var titleLabel: UILabel = {
let label = UILabel()
label.textColor = EmptyPrivateTabsViewUX.TitleColor
label.font = EmptyPrivateTabsViewUX.TitleFont
label.textAlignment = NSTextAlignment.center
return label
}()
fileprivate var descriptionLabel: UILabel = {
let label = UILabel()
label.textColor = EmptyPrivateTabsViewUX.DescriptionColor
label.font = EmptyPrivateTabsViewUX.DescriptionFont
label.textAlignment = NSTextAlignment.center
label.numberOfLines = 0
label.preferredMaxLayoutWidth = EmptyPrivateTabsViewUX.MaxDescriptionWidth
return label
}()
fileprivate var learnMoreButton: UIButton = {
let button = UIButton(type: .system)
button.setTitle(
NSLocalizedString("Learn More", tableName: "PrivateBrowsing", comment: "Text button displayed when there are no tabs open while in private mode"),
for: UIControlState())
button.setTitleColor(UIConstants.PrivateModeTextHighlightColor, for: UIControlState())
button.titleLabel?.font = EmptyPrivateTabsViewUX.LearnMoreFont
return button
}()
fileprivate var iconImageView: UIImageView = {
let imageView = UIImageView(image: UIImage(named: "largePrivateMask"))
return imageView
}()
override init(frame: CGRect) {
super.init(frame: frame)
titleLabel.text = NSLocalizedString("Private Browsing",
tableName: "PrivateBrowsing", comment: "Title displayed for when there are no open tabs while in private mode")
descriptionLabel.text = NSLocalizedString("Firefox won't remember any of your history or cookies, but new bookmarks will be saved.",
tableName: "PrivateBrowsing", comment: "Description text displayed when there are no open tabs while in private mode")
addSubview(titleLabel)
addSubview(descriptionLabel)
addSubview(iconImageView)
addSubview(learnMoreButton)
titleLabel.snp.makeConstraints { make in
make.center.equalTo(self)
}
iconImageView.snp.makeConstraints { make in
make.bottom.equalTo(titleLabel.snp.top).offset(-EmptyPrivateTabsViewUX.TextMargin)
make.centerX.equalTo(self)
}
descriptionLabel.snp.makeConstraints { make in
make.top.equalTo(titleLabel.snp.bottom).offset(EmptyPrivateTabsViewUX.TextMargin)
make.centerX.equalTo(self)
}
learnMoreButton.snp.makeConstraints { (make) -> Void in
make.top.equalTo(descriptionLabel.snp.bottom).offset(EmptyPrivateTabsViewUX.LearnMoreMargin).priority(10)
make.bottom.lessThanOrEqualTo(self).offset(-EmptyPrivateTabsViewUX.MinBottomMargin).priority(1000)
make.centerX.equalTo(self)
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
extension TabTrayController: TabPeekDelegate {
func tabPeekDidAddBookmark(_ tab: Tab) {
delegate?.tabTrayDidAddBookmark(tab)
}
func tabPeekDidAddToReadingList(_ tab: Tab) -> ReadingListClientRecord? {
return delegate?.tabTrayDidAddToReadingList(tab)
}
func tabPeekDidCloseTab(_ tab: Tab) {
if let index = self.tabDataSource.tabs.index(of: tab),
let cell = self.collectionView?.cellForItem(at: IndexPath(item: index, section: 0)) as? TabCell {
cell.SELclose()
}
}
func tabPeekRequestsPresentationOf(_ viewController: UIViewController) {
delegate?.tabTrayRequestsPresentationOf(viewController)
}
}
extension TabTrayController: UIViewControllerPreviewingDelegate {
func previewingContext(_ previewingContext: UIViewControllerPreviewing, viewControllerForLocation location: CGPoint) -> UIViewController? {
guard let collectionView = collectionView else { return nil }
let convertedLocation = self.view.convert(location, to: collectionView)
guard let indexPath = collectionView.indexPathForItem(at: convertedLocation),
let cell = collectionView.cellForItem(at: indexPath) else { return nil }
let tab = tabDataSource.tabs[indexPath.row]
let tabVC = TabPeekViewController(tab: tab, delegate: self)
if let browserProfile = profile as? BrowserProfile {
tabVC.setState(withProfile: browserProfile, clientPickerDelegate: self)
}
previewingContext.sourceRect = self.view.convert(cell.frame, from: collectionView)
return tabVC
}
func previewingContext(_ previewingContext: UIViewControllerPreviewing, commit viewControllerToCommit: UIViewController) {
guard let tpvc = viewControllerToCommit as? TabPeekViewController else { return }
tabManager.selectTab(tpvc.tab)
_ = self.navigationController?.popViewController(animated: true)
delegate?.tabTrayDidDismiss(self)
}
}
extension TabTrayController: ClientPickerViewControllerDelegate {
func clientPickerViewController(_ clientPickerViewController: ClientPickerViewController, didPickClients clients: [RemoteClient]) {
if let item = clientPickerViewController.shareItem {
self.profile.sendItems([item], toClients: clients)
}
clientPickerViewController.dismiss(animated: true, completion: nil)
}
func clientPickerViewControllerDidCancel(_ clientPickerViewController: ClientPickerViewController) {
clientPickerViewController.dismiss(animated: true, completion: nil)
}
}
extension TabTrayController: UIAdaptivePresentationControllerDelegate, UIPopoverPresentationControllerDelegate {
// Returning None here makes sure that the Popover is actually presented as a Popover and
// not as a full-screen modal, which is the default on compact device classes.
func adaptivePresentationStyle(for controller: UIPresentationController, traitCollection: UITraitCollection) -> UIModalPresentationStyle {
return UIModalPresentationStyle.none
}
}
extension TabTrayController: MenuViewControllerDelegate {
func menuViewControllerDidDismiss(_ menuViewController: MenuViewController) { }
func shouldCloseMenu(_ menuViewController: MenuViewController, forRotationToNewSize size: CGSize, forTraitCollection traitCollection: UITraitCollection) -> Bool {
return false
}
}
extension TabTrayController: MenuActionDelegate {
func performMenuAction(_ action: MenuAction, withAppState appState: AppState) {
if let menuAction = AppMenuAction(rawValue: action.action) {
switch menuAction {
case .openNewNormalTab:
DispatchQueue.main.async {
if self.privateMode {
self.SELdidTogglePrivateMode()
}
self.openNewTab()
}
case .openNewPrivateTab:
DispatchQueue.main.async {
if !self.privateMode {
self.SELdidTogglePrivateMode()
}
self.openNewTab()
}
case .openSettings:
DispatchQueue.main.async {
self.SELdidClickSettingsItem()
}
case .closeAllTabs:
DispatchQueue.main.async {
self.closeTabsForCurrentTray()
}
case .openTopSites:
DispatchQueue.main.async {
self.openNewTab(PrivilegedRequest(url: HomePanelType.topSites.localhostURL) as URLRequest)
}
case .openBookmarks:
DispatchQueue.main.async {
self.openNewTab(PrivilegedRequest(url: HomePanelType.bookmarks.localhostURL) as URLRequest)
}
case .openHistory:
DispatchQueue.main.async {
self.openNewTab(PrivilegedRequest(url: HomePanelType.history.localhostURL) as URLRequest)
}
case .openReadingList:
DispatchQueue.main.async {
self.openNewTab(PrivilegedRequest(url: HomePanelType.readingList.localhostURL) as URLRequest)
}
default: break
}
}
}
}
// MARK: - Toolbar
class TrayToolbar: UIView {
fileprivate let toolbarButtonSize = CGSize(width: 44, height: 44)
lazy var settingsButton: UIButton = {
let button = UIButton()
button.setImage(UIImage.templateImageNamed("settings"), for: .normal)
button.accessibilityLabel = NSLocalizedString("Settings", comment: "Accessibility label for the Settings button in the Tab Tray.")
button.accessibilityIdentifier = "TabTrayController.settingsButton"
return button
}()
lazy var addTabButton: UIButton = {
let button = UIButton()
button.setImage(UIImage.templateImageNamed("add"), for: .normal)
button.accessibilityLabel = NSLocalizedString("Add Tab", comment: "Accessibility label for the Add Tab button in the Tab Tray.")
button.accessibilityIdentifier = "TabTrayController.addTabButton"
return button
}()
lazy var menuButton: UIButton = {
let button = UIButton()
button.setImage(UIImage.templateImageNamed("bottomNav-menu-pbm"), for: .normal)
button.accessibilityLabel = Strings.AppMenuButtonAccessibilityLabel
button.accessibilityIdentifier = "TabTrayController.menuButton"
return button
}()
lazy var maskButton: PrivateModeButton = PrivateModeButton()
fileprivate let sideOffset: CGFloat = 32
fileprivate override init(frame: CGRect) {
super.init(frame: frame)
backgroundColor = .white
addSubview(addTabButton)
var buttonToCenter: UIButton?
addSubview(menuButton)
buttonToCenter = menuButton
maskButton.accessibilityIdentifier = "TabTrayController.maskButton"
buttonToCenter?.snp.makeConstraints { make in
make.center.equalTo(self)
make.size.equalTo(toolbarButtonSize)
}
addTabButton.snp.makeConstraints { make in
make.centerY.equalTo(self)
make.left.equalTo(self).offset(sideOffset)
make.size.equalTo(toolbarButtonSize)
}
addSubview(maskButton)
maskButton.snp.makeConstraints { make in
make.centerY.equalTo(self)
make.right.equalTo(self).offset(-sideOffset)
make.size.equalTo(toolbarButtonSize)
}
styleToolbar(false)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
fileprivate func styleToolbar(_ isPrivate: Bool) {
addTabButton.tintColor = isPrivate ? .white : .darkGray
menuButton.tintColor = isPrivate ? .white : .darkGray
backgroundColor = isPrivate ? UIConstants.PrivateModeToolbarTintColor : .white
maskButton.styleForMode(privateMode: isPrivate)
}
}
| mpl-2.0 | 3323389d6ce03f98920bd406d5c45573 | 40.786898 | 304 | 0.674222 | 5.629945 | false | false | false | false |
LoveAlwaysYoung/EnjoyUniversity | EnjoyUniversity/EnjoyUniversity/Classes/ViewModel/ActivityListViewModel.swift | 1 | 8875 | //
// ActivityListViewModel.swift
// EnjoyUniversity
//
// Created by lip on 17/3/30.
// Copyright © 2017年 lip. All rights reserved.
//
import Foundation
import YYModel
class ActivityListViewModel{
// 获取当前活动
var vmlist = [ActivityViewModel]()
// 获取用户参加的所有活动
var participatedlist = [ActivityViewModel]()
// 用户创建的所有活动
var createdlist = [ActivityViewModel]()
// 用户收藏的所有活动
var collectedlist = [ActivityViewModel]()
// 用户搜索的所有活动
var searchedlist = [ActivityViewModel]()
/// 加载活动数据
///
/// - Parameters:
/// - isPullingUp: 上拉加载更多标记
/// - completion: 是否加载成功,是否需要刷新表格
func loadActivityList(isPullingUp:Bool = false,completion:@escaping (Bool,Bool)->()){
var maxtime:String?
// var mintime:String?
// 判断下拉刷新
// if !isPullingUp && vmlist.count > 0 {
// mintime = vmlist.first?.activitymodel.avStarttime
// }
// 判断上拉加载
if isPullingUp && vmlist.count > 0 {
maxtime = vmlist.last?.activitymodel.avStarttime
}
EUNetworkManager.shared.getActivityList(mintime: nil, maxtime: maxtime) { (array, isSuccess) in
if !isSuccess{
completion(false,false)
return
}
guard let modelarray = NSArray.yy_modelArray(with: Activity.self, json: array ?? []) as? [Activity] else{
completion(false,false)
return
}
// 判断是否已加载全部数据
if modelarray.count == 0{
completion(true,false)
return
}
// 接受数据
var tempvmlist = [ActivityViewModel]()
for model in modelarray{
tempvmlist.append(ActivityViewModel(model: model))
}
// 拼接数据
if isPullingUp{
self.vmlist = self.vmlist + tempvmlist
}else{
self.vmlist = tempvmlist
}
completion(true, true)
}
}
/// 我参加的活动
///
/// - Parameter completion: 是否需要刷新表格
func loadParticipatdActivity(completion:@escaping (Bool)->()){
EUNetworkManager.shared.getParticipatedActivityList { (array, isSuccess) in
if !isSuccess{
completion(false)
return
}
guard let modelarray = NSArray.yy_modelArray(with: Activity.self, json: array ?? []) as? [Activity] else{
completion(false)
return
}
// 判断是否需要刷新
if modelarray.count == 0{
completion(false)
return
}
// 接受数据
var tempvmlist = [ActivityViewModel]()
for model in modelarray{
tempvmlist.append(ActivityViewModel(model: model))
}
tempvmlist = tempvmlist.sorted(by: { (x:ActivityViewModel, y:ActivityViewModel) -> Bool in
return Int(x.activitymodel.avStarttime ?? "0") ?? 0 < Int(y.activitymodel.avStarttime ?? "0") ?? 0
})
// 将已结束的活动放倒最末端
self.participatedlist.removeAll()
var finishedList = [ActivityViewModel]()
for viewmodel in tempvmlist{
if viewmodel.isFinished{
finishedList.append(viewmodel)
}else{
self.participatedlist.append(viewmodel)
}
}
self.participatedlist = self.participatedlist + finishedList
completion(true)
}
}
/// 我创建的活动
///
/// - Parameter completion: 是否需要刷新表格
func loadCreatedActivity(completion:@escaping (Bool)->()){
EUNetworkManager.shared.getCreatedActivityList { (array, isSuccess) in
if !isSuccess{
completion(false)
return
}
guard let modelarray = NSArray.yy_modelArray(with: Activity.self, json: array ?? []) as? [Activity] else{
completion(false)
return
}
// 判断是否需要刷新
if modelarray.count == 0{
completion(false)
return
}
// 接受数据
var tempvmlist = [ActivityViewModel]()
for model in modelarray{
tempvmlist.append(ActivityViewModel(model: model))
}
tempvmlist = tempvmlist.sorted(by: { (x:ActivityViewModel, y:ActivityViewModel) -> Bool in
return Int(x.activitymodel.avStarttime ?? "0") ?? 0 < Int(y.activitymodel.avStarttime ?? "0") ?? 0
})
// 将已结束的活动放倒最末端
self.createdlist.removeAll()
var finishedList = [ActivityViewModel]()
for viewmodel in tempvmlist{
if viewmodel.isFinished{
finishedList.append(viewmodel)
}else{
self.createdlist.append(viewmodel)
}
}
self.createdlist = self.createdlist + finishedList
completion(true)
}
}
/// 加载我收藏的活动
///
/// - Parameter completion: 完成回调 网络请求是否成功,是否有数据
func loadMyCollectedActivity(completion:@escaping (Bool,Bool)->()){
EUNetworkManager.shared.getMyActivityCollection { (isSuccess, array) in
if !isSuccess{
completion(false,false)
return
}
guard let array = array,let modelarray = NSArray.yy_modelArray(with: Activity.self, json: array) as? [Activity] else{
completion(true, false)
return
}
if modelarray.count == 0{
completion(true,false)
return
}
// 接受数据
var tempvmlist = [ActivityViewModel]()
for model in modelarray{
tempvmlist.append(ActivityViewModel(model: model))
}
tempvmlist = tempvmlist.sorted(by: { (x:ActivityViewModel, y:ActivityViewModel) -> Bool in
return Int(x.activitymodel.avStarttime ?? "0") ?? 0 < Int(y.activitymodel.avStarttime ?? "0") ?? 0
})
// 将已结束的活动放倒最末端
self.collectedlist.removeAll()
var finishedList = [ActivityViewModel]()
for viewmodel in tempvmlist{
if viewmodel.isFinished{
finishedList.append(viewmodel)
}else{
self.collectedlist.append(viewmodel)
}
}
self.collectedlist = self.collectedlist + finishedList
completion(true,true)
}
}
/// 加载搜索的活动
///
/// - Parameter completion: 完成回调
func loadSearchedActivity(keyword:String,isPullup:Bool,completion:@escaping (Bool,Bool)->()){
var page = 1
let rows = EUREQUESTCOUNT
if searchedlist.count >= rows{
page = searchedlist.count / rows + 1
}
EUNetworkManager.shared.searchActivity(keyword: keyword, page: page, rows: rows) { (isSuccess, array) in
if !isSuccess{
completion(false,false)
return
}
guard let array = array,let modelarray = NSArray.yy_modelArray(with: Activity.self, json: array) as? [Activity] else{
completion(true,false)
return
}
var temp = [ActivityViewModel]()
for model in modelarray{
temp.append(ActivityViewModel(model: model))
}
if isPullup{
self.searchedlist = self.searchedlist + temp
}else{
self.searchedlist = temp
}
completion(true,true)
}
}
}
| mit | 3cf2ab08fada338c48408ebf1e9d928e | 28.921708 | 129 | 0.488107 | 5.442071 | false | false | false | false |
davedelong/DDMathParser | MathParser/Sources/MathParser/PeekingIterator.swift | 1 | 879 | //
// PeekingIterator.swift
// DDMathParser
//
// Created by Dave DeLong on 8/14/15.
//
//
import Foundation
protocol PeekingIteratorType: IteratorProtocol {
func peek() -> Element?
}
internal final class PeekingIterator<G: IteratorProtocol>: PeekingIteratorType {
typealias Element = G.Element
private var generator: G
private var peekBuffer = Array<Element>()
init(generator: G) {
self.generator = generator
}
func next() -> Element? {
if let n = peekBuffer.first {
peekBuffer.removeFirst()
return n
}
return generator.next()
}
func peek() -> Element? {
if let p = peekBuffer.first { return p }
if let p = generator.next() {
peekBuffer.append(p)
return p
}
return nil
}
}
| mit | 6ac4814da52a171ed2b4e9ec3bf25d01 | 18.977273 | 80 | 0.558589 | 4.439394 | false | false | false | false |
ReactiveX/RxSwift | Tests/RxCocoaTests/RxObjCRuntimeState.swift | 1 | 4271 | //
// RxObjCRuntimeState.swift
// Tests
//
// Created by Krunoslav Zaher on 11/27/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
import XCTest
struct RxObjCRuntimeChange {
let dynamicSublasses: Int
let swizzledForwardClasses: Int
let interceptedClasses: Int
let methodsSwizzled: Int
let methodsForwarded: Int
/**
Takes into account default methods that were swizzled while creating dynamic subclasses.
*/
static func changes(dynamicSubclasses: Int = 0, swizzledForwardClasses: Int = 0, interceptedClasses: Int = 0, methodsSwizzled: Int = 0, methodsForwarded: Int = 0) -> RxObjCRuntimeChange {
return RxObjCRuntimeChange(
dynamicSublasses: dynamicSubclasses,
swizzledForwardClasses: swizzledForwardClasses,
interceptedClasses: dynamicSubclasses + interceptedClasses,
methodsSwizzled: methodsSwizzled + 1/*class*/ * dynamicSubclasses + 3/*forwardInvocation, respondsToSelector, methodSignatureForSelector*/ * swizzledForwardClasses,
methodsForwarded: methodsForwarded
)
}
}
final class RxObjCRuntimeState {
// total number of dynamically generated classes
let dynamicSublasses: Int
// total number of classes that have swizzled forwarding mechanism
let swizzledForwardClasses: Int
// total number of classes that have at least one selector intercepted by either forwarding or sending messages
let interceptingClasses: Int
// total numbers of methods that are swizzled, methods used for forwarding (forwardInvocation, respondsToSelector, methodSignatureForSelector, class) also count
let methodsSwizzled: Int
// total number of methods that are intercepted by forwarding
let methodsForwarded: Int
init() {
#if TRACE_RESOURCES
dynamicSublasses = RX_number_of_dynamic_subclasses()
swizzledForwardClasses = RX_number_of_forwarding_enabled_classes()
interceptingClasses = RX_number_of_intercepting_classes()
methodsSwizzled = RX_number_of_swizzled_methods()
methodsForwarded = RX_number_of_forwarded_methods()
#else
dynamicSublasses = 0
swizzledForwardClasses = 0
interceptingClasses = 0
methodsSwizzled = 0
methodsForwarded = 0
#endif
}
func assertAfterThisMoment(_ previous: RxObjCRuntimeState, changed: RxObjCRuntimeChange) {
#if TRACE_RESOURCES
let realChangeOfDynamicSubclasses = dynamicSublasses - previous.dynamicSublasses
XCTAssertEqual(realChangeOfDynamicSubclasses, changed.dynamicSublasses)
if (realChangeOfDynamicSubclasses != changed.dynamicSublasses) {
print("dynamic subclasses: real = \(realChangeOfDynamicSubclasses) != expected = \(changed.dynamicSublasses)")
}
let realSwizzledForwardClasses = swizzledForwardClasses - previous.swizzledForwardClasses
XCTAssertEqual(realSwizzledForwardClasses, changed.swizzledForwardClasses)
if (realSwizzledForwardClasses != changed.swizzledForwardClasses) {
print("forward classes: real = \(realSwizzledForwardClasses) != expected = \(changed.swizzledForwardClasses)")
}
let realInterceptingClasses = interceptingClasses - previous.interceptingClasses
XCTAssertEqual(realInterceptingClasses, changed.interceptedClasses)
if (realInterceptingClasses != changed.interceptedClasses) {
print("intercepting classes: real = \(realInterceptingClasses) != expected = \(changed.interceptedClasses)")
}
let realMethodsSwizzled = methodsSwizzled - previous.methodsSwizzled
XCTAssertEqual(realMethodsSwizzled, changed.methodsSwizzled)
if (realMethodsSwizzled != changed.methodsSwizzled) {
print("swizzled methods: real = \(realMethodsSwizzled) != expected = \(changed.methodsSwizzled)")
}
let realMethodsForwarded = methodsForwarded - previous.methodsForwarded
XCTAssertEqual(realMethodsForwarded, changed.methodsForwarded)
if (realMethodsForwarded != changed.methodsForwarded) {
print("forwarded methods: real = \(realMethodsForwarded) != expected = \(changed.methodsForwarded)")
}
#endif
}
}
| mit | 7daad5f64a940b3aedafb26d5d905e10 | 46.977528 | 191 | 0.721077 | 5.618421 | false | false | false | false |
philipgeorgiev123/SwiftEvents | SwiftEventsModule/SwiftEvents/EventHub.swift | 1 | 5660 | //
// Created by freezing on 19/01/15.
// Copyright (c) 2015 iccode ltd. All rights reserved.
//
import Foundation
private let _eventHubInstance : EventHub = EventHub()
private let _eventHubListener : EventDispatcher = EventDispatcher()
// class definition to capture event->function relationship
class ObjectFunction {
var listener : (Event)->()
var dispatcher : IEventDispatcherProtocol
var isOnce : Bool
init(f : @escaping (Event)->(),obj : IEventDispatcherProtocol, isOnce : Bool = false)
{
self.listener = f
self.dispatcher = obj
self.isOnce = isOnce
}
}
public class EventHub {
class var instance : EventHub
{
return _eventHubInstance
}
class var listener : IEventDispatcherProtocol
{
return _eventHubListener
}
var _eventFunctionMap : [String : Array<ObjectFunction>] = [String : Array<ObjectFunction>]()
init ()
{
}
func addEventListener(name : String, withFunction f : @escaping (Event)->())
{
addEventListener(name: name, withFunction: f, withDispatcher: _eventHubListener)
}
func addEventListenerOnce(name : String,
withFunction f : @escaping (Event)->(),
withDispatcher d : IEventDispatcherProtocol) {
addEventListener(name: name, withFunction: f, withDispatcher: d, isOnce: true)
}
func addEventListener(name : String,
withFunction f : @escaping (Event)->(),
withDispatcher d : IEventDispatcherProtocol,
isOnce : Bool = false
)
{
if var objectListeners: Array<ObjectFunction> = _eventFunctionMap[name]
{
for (_, o) in objectListeners.enumerated()
{
if o.dispatcher === d
{
print("multiple listeners are not supported by the framework :", name , " for ", d)
return
}
}
objectListeners.append(ObjectFunction(f: f, obj: d, isOnce : isOnce))
_eventFunctionMap[name] = objectListeners
// add it to the list if not found
} else {
var objectListeners = Array<ObjectFunction>()
objectListeners.append(ObjectFunction(f: f, obj: d, isOnce : isOnce))
_eventFunctionMap[name] = objectListeners
}
}
func removeEventListener(name:String)
{
removeEventListener(name: name, withDispatcher: _eventHubListener)
}
func removeEventListener(name :String, withDispatcher dispatcher : IEventDispatcherProtocol)
{
if var objectListeners: Array<ObjectFunction> = _eventFunctionMap[name]
{
for (index, o) in objectListeners.enumerated()
{
// they can be only on dispatcher so bail after that
if o.dispatcher === dispatcher
{
objectListeners.remove(at:index)
break
}
}
_eventFunctionMap[name] = objectListeners
}
}
func hasEventListener(name : String, withDispatcher d : IEventDispatcherProtocol)->Bool
{
if let objectListeners: Array<ObjectFunction> = _eventFunctionMap[name]
{
for (_ , o) in objectListeners.enumerated()
{
if o.dispatcher === d
{
return true
}
}
}
return false
}
func myEventsList(withDispatcher dispatcher : IEventDispatcherProtocol) -> Array<String>
{
var allEventsListenedTo = Array<String>()
for (name, objectFunctions) in _eventFunctionMap
{
for (_, o) in objectFunctions.enumerated()
{
if (o.dispatcher === dispatcher)
{
allEventsListenedTo.append(name)
}
}
}
return allEventsListenedTo
}
open func debugHubState() {
for (name, objectFunctions) in _eventFunctionMap
{
print(name + " " + String(objectFunctions.count))
}
}
func removeAllListeners()
{
removeAllListeners(dispatcher: _eventHubListener)
}
func removeAllListeners(dispatcher : IEventDispatcherProtocol)
{
for (name, var objectFunctions) in _eventFunctionMap
{
for (index, o) in objectFunctions.enumerated()
{
if (o.dispatcher === dispatcher)
{
objectFunctions.remove(at:index)
if objectFunctions.count == 0
{
_eventFunctionMap.removeValue(forKey:name)
} else
{
_eventFunctionMap[name] = objectFunctions
}
break
}
}
}
}
func trigger(e : Event)
{
if let arrayListeners: Array<ObjectFunction> = _eventFunctionMap[e.type]
{
for o : ObjectFunction in arrayListeners
{
o.listener(e)
if (o.isOnce)
{
removeEventListener(name: e.type, withDispatcher: o.dispatcher)
o.isOnce = false
}
}
}
}
}
| mit | 0aabb05d7a67c3b4be21bef8f13940b3 | 28.633508 | 103 | 0.515901 | 5.77551 | false | false | false | false |
ehtd/HackerNews | Hackyto/Hackyto/Controllers/TableController.swift | 1 | 6826 | //
// TableController.swift
// Hackyto
//
// Created by Ernesto Torres on 10/22/14.
// Copyright (c) 2014 ehtd. All rights reserved.
//
import UIKit
class TableController: UITableViewController {
fileprivate let hackerNewsAPI: HackerNewsAPI
fileprivate var stories = [Story]()
fileprivate let pullToRefresh = UIRefreshControl()
fileprivate let cellIdentifier = "StoryCell"
static var colorIndex = 0
init(type: ContentType) {
hackerNewsAPI = HackerNewsAPI(for: type)
super.init(nibName: nil, bundle: nil)
}
required init?(coder aDecoder: NSCoder) {
hackerNewsAPI = HackerNewsAPI(for: .top)
super.init(coder: aDecoder)
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
}
override func viewDidLoad() {
super.viewDidLoad()
tableView.register(UINib(nibName: cellIdentifier, bundle: nil), forCellReuseIdentifier: cellIdentifier)
navigationController?.isNavigationBarHidden = true
addStylesToTableView()
addPullToRefresh()
retrieveStories()
}
}
// MARK: - Styles
extension TableController {
func addStylesToTableView() {
view.backgroundColor = ColorFactory.darkGrayColor()
tableView.backgroundColor = ColorFactory.darkGrayColor()
tableView.separatorColor = UIColor.clear
tableView.separatorStyle = UITableViewCellSeparatorStyle.none
tableView.estimatedRowHeight = 130.0
tableView.rowHeight = UITableViewAutomaticDimension
}
}
// MARK: - Pull to Refresh
extension TableController {
func addPullToRefresh() {
pullToRefresh.backgroundColor = ColorFactory.colorFromNumber(TableController.colorIndex)
pullToRefresh.tintColor = UIColor.white
pullToRefresh.addTarget(self, action: #selector(TableController.retrieveStories), for: UIControlEvents.valueChanged)
tableView.addSubview(pullToRefresh)
tableView.contentOffset = CGPoint(x: 0, y: -self.pullToRefresh.frame.size.height)
pullToRefresh.beginRefreshing()
}
func stopPullToRefresh() {
let delayTime = DispatchTime.now() + Double(Int64(0.05 * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC)
DispatchQueue.main.asyncAfter(deadline: delayTime) { [weak self] in
if let strongSelf = self {
strongSelf.pullToRefresh.endRefreshing()
strongSelf.updatePullToRefreshColor()
}
}
}
func updatePullToRefreshColor() {
let delayTime = DispatchTime.now() + Double(Int64(0.5 * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC)
DispatchQueue.main.asyncAfter(deadline: delayTime) { [weak self] in
if let strongSelf = self {
TableController.colorIndex += 1
strongSelf.pullToRefresh.backgroundColor = ColorFactory.colorFromNumber(TableController.colorIndex)
}
}
}
}
// MARK: - Content
extension TableController {
func retrieveStories() {
stories = [Story]()
tableView.reloadData()
hackerNewsAPI
.onSuccess { [weak self] (stories) in
if let strongSelf = self {
strongSelf.stories.append(contentsOf: stories)
strongSelf.tableView.reloadData()
strongSelf.stopPullToRefresh()
}
}
.onError { [weak self] (error) in
print(error)
self?.stopPullToRefresh()
}
.fetch()
}
}
// MARK: - UITableViewController delegate / data source
extension TableController {
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return stories.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell: StoryCell = self.tableView.dequeueReusableCell(withIdentifier: cellIdentifier) as! StoryCell
self.configureBasicCell(cell, indexPath: indexPath)
// Seems sometimes the cell didn't update its height. Use to layout again.
cell.layoutIfNeeded();
return cell
}
func configureBasicCell(_ cell: StoryCell, indexPath: IndexPath) {
let story = stories[indexPath.row]
cell.configureCell(title: story.title,
author: story.author,
storyKey: story.storyId,
number: indexPath.row + 1)
cell.configureComments(comments: story.comments)
cell.launchComments = { [weak self] (key) in
self?.openWebBrowser(title: "HN comments",
urlString: Constants.hackerNewsBaseURLString + String(describing: story.storyId))
}
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let story = stories[indexPath.row]
if let urlString = story.urlString { // Ask HN stories have this field empty
openWebBrowser(title: story.title, urlString: urlString)
}
else {
openWebBrowser(title: story.title,
urlString: Constants.hackerNewsBaseURLString + String(describing: story.storyId))
}
}
}
// MARK: - Browser
extension TableController {
func openWebBrowser(title: String?, urlString: String?) {
if let urlString = urlString {
let url = URL(string: urlString)
if let url = url {
let webViewController = WebViewController(url: url)
DispatchQueue.main.async(execute: { [weak self] in
if let strongSelf = self {
strongSelf.present(webViewController, animated: true, completion: nil)
}
})
}
}
}
}
// MARK: - Status bar
extension TableController {
override var preferredStatusBarStyle : UIStatusBarStyle {
return UIStatusBarStyle.lightContent
}
override var prefersStatusBarHidden: Bool {
return false
}
}
// MARK: Pagination
extension TableController {
func updateContent(_ scrollView: UIScrollView) {
let maxY = scrollView.contentSize.height - view.frame.height
let tableOffsetForRefresh = 2 * view.frame.height
if scrollView.contentOffset.y >= maxY - tableOffsetForRefresh {
hackerNewsAPI.next()
}
}
override func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
if decelerate == false {
updateContent(scrollView)
}
}
override func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
updateContent(scrollView)
}
}
| gpl-3.0 | bde50d14b797ebd785be07ad99efeaaf | 30.311927 | 124 | 0.634193 | 5.210687 | false | false | false | false |
narner/AudioKit | AudioKit/Common/User Interface/AKOutputWaveformPlot.swift | 1 | 4371 | //
// AKOutputWaveformPlot
// AudioKitUI
//
// Created by Aurelius Prochazka, revision history on Github.
// Copyright © 2017 Aurelius Prochazka. All rights reserved.
//
#if !JAZZY_HACK
import AudioKit
#endif
/// Wrapper class for plotting audio from the final mix in a waveform plot
@IBDesignable
open class AKOutputWaveformPlot: EZAudioPlot {
public var isConnected = false
internal func setupNode() {
if !isConnected {
AudioKit.engine.outputNode.installTap(onBus: 0,
bufferSize: bufferSize,
format: nil) { [weak self] (buffer, _) in
guard let strongSelf = self else {
AKLog("Unable to create strong ref to self")
return
}
buffer.frameLength = strongSelf.bufferSize
let offset = Int(buffer.frameCapacity - buffer.frameLength)
if let tail = buffer.floatChannelData?[0] {
strongSelf.updateBuffer(&tail[offset],
withBufferSize: strongSelf.bufferSize)
}
}
isConnected = true
}
}
// Useful to reconnect after connecting to Audiobus or IAA
@objc func reconnect() {
AudioKit.engine.outputNode.removeTap(onBus: 0)
setupNode()
}
@objc open func pause() {
if isConnected {
AudioKit.engine.outputNode.removeTap(onBus: 0)
isConnected = false
}
}
@objc open func resume() {
setupNode()
}
func setupReconnection() {
NotificationCenter.default.addObserver(self,
selector: #selector(reconnect),
name: NSNotification.Name(rawValue: "IAAConnected"),
object: nil)
NotificationCenter.default.addObserver(self,
selector: #selector(reconnect),
name: NSNotification.Name(rawValue: "IAADisconnected"),
object: nil)
}
internal var bufferSize: UInt32 = 1_024
deinit {
AudioKit.engine.outputNode.removeTap(onBus: 0)
}
/// Initialize the plot in a frame
///
/// - parameter frame: CGRect in which to draw the plot
///
override public init(frame: CGRect) {
super.init(frame: frame)
setupNode()
setupReconnection()
}
/// Initialize the plot in a frame with a different buffer size
///
/// - Parameters:
/// - frame: CGRect in which to draw the plot
/// - bufferSize: size of the buffer - raise this number if the device struggles with generating the waveform
///
@objc public init(frame: CGRect, bufferSize: Int) {
super.init(frame: frame)
self.bufferSize = UInt32(bufferSize)
setupNode()
setupReconnection()
}
/// Required coder-based initialization (for use with Interface Builder)
///
/// - parameter coder: NSCoder
///
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setupNode()
setupReconnection()
}
/// Create a View with the plot (usually for playgrounds)
///
/// - Parameters:
/// - width: Width of the view
/// - height: Height of the view
///
open static func createView(width: CGFloat = 440, height: CGFloat = 200.0) -> AKView {
let frame = CGRect(x: 0.0, y: 0.0, width: width, height: height)
let plot = AKOutputWaveformPlot(frame: frame)
plot.plotType = .buffer
plot.backgroundColor = AKColor.clear
plot.shouldCenterYAxis = true
let containerView = AKView(frame: frame)
containerView.addSubview(plot)
return containerView
}
}
| mit | 2f9ed77611e80e1c54c08093dc199788 | 34.241935 | 118 | 0.505263 | 5.602564 | false | false | false | false |
apple/swift-experimental-string-processing | Sources/_StringProcessing/Algorithms/Algorithms/FirstRange.swift | 1 | 3188 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2021-2022 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
//
//===----------------------------------------------------------------------===//
// MARK: `CollectionSearcher` algorithms
extension Collection {
func _firstRange<S: CollectionSearcher>(
of searcher: S
) -> Range<Index>? where S.Searched == Self {
var state = searcher.state(for: self, in: startIndex..<endIndex)
return searcher.search(self, &state)
}
}
extension BidirectionalCollection {
func _lastRange<S: BackwardCollectionSearcher>(
of searcher: S
) -> Range<Index>? where S.BackwardSearched == Self {
var state = searcher.backwardState(for: self, in: startIndex..<endIndex)
return searcher.searchBack(self, &state)
}
}
// MARK: Fixed pattern algorithms
extension Collection where Element: Equatable {
/// Finds and returns the range of the first occurrence of a given collection
/// within this collection.
///
/// - Parameter other: The collection to search for.
/// - Returns: A range in the collection of the first occurrence of `sequence`.
/// Returns nil if `sequence` is not found.
@available(SwiftStdlib 5.7, *)
public func firstRange<C: Collection>(
of other: C
) -> Range<Index>? where C.Element == Element {
// TODO: Use a more efficient search algorithm
let searcher = ZSearcher<SubSequence>(pattern: Array(other), by: ==)
return searcher.search(self[...], in: startIndex..<endIndex)
}
}
extension BidirectionalCollection where Element: Comparable {
/// Finds and returns the range of the first occurrence of a given collection
/// within this collection.
///
/// - Parameter other: The collection to search for.
/// - Returns: A range in the collection of the first occurrence of `sequence`.
/// Returns `nil` if `sequence` is not found.
@available(SwiftStdlib 5.7, *)
public func firstRange<C: Collection>(
of other: C
) -> Range<Index>? where C.Element == Element {
let searcher = PatternOrEmpty(
searcher: TwoWaySearcher<SubSequence>(pattern: Array(other)))
let slice = self[...]
var state = searcher.state(for: slice, in: startIndex..<endIndex)
return searcher.search(slice, &state)
}
}
// MARK: Regex algorithms
extension BidirectionalCollection where SubSequence == Substring {
/// Finds and returns the range of the first occurrence of a given regex
/// within the collection.
/// - Parameter regex: The regex to search for.
/// - Returns: A range in the collection of the first occurrence of `regex`.
/// Returns `nil` if `regex` is not found.
@_disfavoredOverload
@available(SwiftStdlib 5.7, *)
public func firstRange(of regex: some RegexComponent) -> Range<Index>? {
_firstRange(of: RegexConsumer(regex))
}
@available(SwiftStdlib 5.7, *)
func _lastRange<R: RegexComponent>(of regex: R) -> Range<Index>? {
_lastRange(of: RegexConsumer(regex))
}
}
| apache-2.0 | 77b09ee88561d9dbb67a50b960fd5ede | 35.227273 | 81 | 0.662484 | 4.325645 | false | false | false | false |
apple/swift-async-algorithms | Sources/AsyncSequenceValidation/Event.swift | 1 | 5138 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift Async Algorithms open source project
//
// Copyright (c) 2022 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
//
//===----------------------------------------------------------------------===//
extension AsyncSequenceValidationDiagram {
struct Failure: Error, Equatable { }
enum ParseFailure: Error, CustomStringConvertible, SourceFailure {
case stepInGroup(String, String.Index, SourceLocation)
case nestedGroup(String, String.Index, SourceLocation)
case unbalancedNesting(String, String.Index, SourceLocation)
var location: SourceLocation {
switch self {
case .stepInGroup(_, _, let location): return location
case .nestedGroup(_, _, let location): return location
case .unbalancedNesting(_, _, let location): return location
}
}
var description: String {
switch self {
case .stepInGroup:
return "validation diagram step symbol in group"
case .nestedGroup:
return "validation diagram nested grouping"
case .unbalancedNesting:
return "validation diagram unbalanced grouping"
}
}
}
enum Event {
case value(String, String.Index)
case failure(Error, String.Index)
case finish(String.Index)
case delayNext(String.Index)
case cancel(String.Index)
var results: [Result<String?, Error>] {
switch self {
case .value(let value, _): return [.success(value)]
case .failure(let failure, _): return [.failure(failure)]
case .finish: return [.success(nil)]
case .delayNext: return []
case .cancel: return []
}
}
var index: String.Index {
switch self {
case .value(_, let index): return index
case .failure(_, let index): return index
case .finish(let index): return index
case .delayNext(let index): return index
case .cancel(let index): return index
}
}
static func parse<Theme: AsyncSequenceValidationTheme>(_ dsl: String, theme: Theme, location: SourceLocation) throws -> [(Clock.Instant, Event)] {
var emissions = [(Clock.Instant, Event)]()
var when = Clock.Instant(when: .steps(0))
var string: String?
var grouping = 0
for index in dsl.indices {
let ch = dsl[index]
switch theme.token(dsl[index], inValue: string != nil) {
case .step:
if string == nil {
if grouping == 0 {
when = when.advanced(by: .steps(1))
} else {
throw ParseFailure.stepInGroup(dsl, index, location)
}
} else {
string?.append(ch)
}
case .error:
if string == nil {
if grouping == 0 {
when = when.advanced(by: .steps(1))
}
emissions.append((when, .failure(Failure(), index)))
} else {
string?.append(ch)
}
case .finish:
if string == nil {
if grouping == 0 {
when = when.advanced(by: .steps(1))
}
emissions.append((when, .finish(index)))
} else {
string?.append(ch)
}
case .cancel:
if string == nil {
if grouping == 0 {
when = when.advanced(by: .steps(1))
}
emissions.append((when, .cancel(index)))
} else {
string?.append(ch)
}
case .delayNext:
if string == nil {
if grouping == 0 {
when = when.advanced(by: .steps(1))
}
emissions.append((when, .delayNext(index)))
} else {
string?.append(ch)
}
case .beginValue:
string = ""
case .endValue:
if let value = string {
string = nil
if grouping == 0 {
when = when.advanced(by: .steps(1))
}
emissions.append((when, .value(value, index)))
}
case .beginGroup:
if grouping == 0 {
when = when.advanced(by: .steps(1))
} else {
throw ParseFailure.nestedGroup(dsl, index, location)
}
grouping += 1
case .endGroup:
grouping -= 1
if grouping < 0 {
throw ParseFailure.unbalancedNesting(dsl, index, location)
}
case .skip:
string?.append(ch)
continue
case .value(let str):
if string == nil {
if grouping == 0 {
when = when.advanced(by: .steps(1))
}
emissions.append((when, .value(String(ch), index)))
} else {
string?.append(str)
}
}
}
if grouping != 0 {
throw ParseFailure.unbalancedNesting(dsl, dsl.endIndex, location)
}
return emissions
}
}
}
| apache-2.0 | fe9ed115cf927bb84772651e512001d5 | 30.329268 | 150 | 0.521604 | 4.670909 | false | false | false | false |
ScoutHarris/WordPress-iOS | WordPress/Classes/Models/Notifications/NotificationBlock.swift | 2 | 8945 | import Foundation
// MARK: - NotificationBlock Implementation
//
class NotificationBlock: Equatable {
/// Parsed Media Entities.
///
let media: [NotificationMedia]
/// Parsed Range Entities.
///
let ranges: [NotificationRange]
/// Block Associated Text.
///
let text: String?
/// Text Override: Local (Ephimeral) Edition.
///
var textOverride: String? {
didSet {
parent?.didChangeOverrides()
}
}
/// Available Actions collection.
///
fileprivate let actions: [String: AnyObject]?
/// Action Override Values
///
fileprivate var actionsOverride = [Action: Bool]() {
didSet {
parent?.didChangeOverrides()
}
}
/// Helper used by the +Interface Extension.
///
fileprivate var dynamicAttributesCache = [String: AnyObject]()
/// Meta Fields collection.
///
fileprivate let meta: [String: AnyObject]?
/// Associated Notification
///
fileprivate weak var parent: Notification?
/// Raw Type, expressed as a string.
///
fileprivate let type: String?
/// Designated Initializer.
///
init(dictionary: [String: AnyObject], parent note: Notification) {
let rawMedia = dictionary[BlockKeys.Media] as? [[String: AnyObject]]
let rawRanges = dictionary[BlockKeys.Ranges] as? [[String: AnyObject]]
actions = dictionary[BlockKeys.Actions] as? [String: AnyObject]
media = NotificationMedia.mediaFromArray(rawMedia)
meta = dictionary[BlockKeys.Meta] as? [String: AnyObject]
ranges = NotificationRange.rangesFromArray(rawRanges)
parent = note
type = dictionary[BlockKeys.RawType] as? String
text = dictionary[BlockKeys.Text] as? String
}
}
// MARK: - NotificationBlock Computed Properties
//
extension NotificationBlock {
/// Returns the current Block's Kind. SORRY: Duck Typing code below.
///
var kind: Kind {
if let rawType = type, rawType.isEqual(BlockKeys.UserType) {
return .user
}
if let commentID = metaCommentID, let parentCommentID = parent?.metaCommentID, let _ = metaSiteID, commentID.isEqual(parentCommentID) {
return .comment
}
if let firstMedia = media.first, (firstMedia.kind == .Image || firstMedia.kind == .Badge) {
return .image
}
return .text
}
/// Returns all of the Image URL's referenced by the NotificationMedia instances.
///
var imageUrls: [URL] {
return media.flatMap {
guard $0.kind == .Image && $0.mediaURL != nil else {
return nil
}
return $0.mediaURL as URL?
}
}
/// Returns YES if the associated comment (if any) is approved. NO otherwise.
///
var isCommentApproved: Bool {
return isActionOn(.Approve) || !isActionEnabled(.Approve)
}
/// Comment ID, if any.
///
var metaCommentID: NSNumber? {
return metaIds?[MetaKeys.Comment] as? NSNumber
}
/// Home Site's Link, if any.
///
var metaLinksHome: URL? {
guard let rawLink = metaLinks?[MetaKeys.Home] as? String else {
return nil
}
return URL(string: rawLink)
}
/// Site ID, if any.
///
var metaSiteID: NSNumber? {
return metaIds?[MetaKeys.Site] as? NSNumber
}
/// Home Site's Title, if any.
///
var metaTitlesHome: String? {
return metaTitles?[MetaKeys.Home] as? String
}
/// Parent Notification ID
///
var notificationID: String? {
return parent?.notificationId
}
/// Returns the Meta ID's collection, if any.
///
fileprivate var metaIds: [String: AnyObject]? {
return meta?[MetaKeys.Ids] as? [String: AnyObject]
}
/// Returns the Meta Links collection, if any.
///
fileprivate var metaLinks: [String: AnyObject]? {
return meta?[MetaKeys.Links] as? [String: AnyObject]
}
/// Returns the Meta Titles collection, if any.
///
fileprivate var metaTitles: [String: AnyObject]? {
return meta?[MetaKeys.Titles] as? [String: AnyObject]
}
}
// MARK: - NotificationBlock Methods
//
extension NotificationBlock {
/// Allows us to set a local override for a remote value. This is used to fake the UI, while
/// there's a BG call going on.
///
func setOverrideValue(_ value: Bool, forAction action: Action) {
actionsOverride[action] = value
}
/// Removes any local (temporary) value that might have been set by means of *setActionOverrideValue*.
///
func removeOverrideValueForAction(_ action: Action) {
actionsOverride.removeValue(forKey: action)
}
/// Returns the Notification Block status for a given action. Will return any *Override* that might be set, if any.
///
fileprivate func valueForAction(_ action: Action) -> Bool? {
if let overrideValue = actionsOverride[action] {
return overrideValue
}
let value = actions?[action.rawValue] as? NSNumber
return value?.boolValue
}
/// Returns *true* if a given action is available.
///
func isActionEnabled(_ action: Action) -> Bool {
return valueForAction(action) != nil
}
/// Returns *true* if a given action is toggled on. (I.e.: Approval = On >> the comment is currently approved).
///
func isActionOn(_ action: Action) -> Bool {
return valueForAction(action) ?? false
}
// Dynamic Attribute Cache: Used internally by the Interface Extension, as an optimization.
///
func cacheValueForKey(_ key: String) -> AnyObject? {
return dynamicAttributesCache[key]
}
/// Stores a specified value within the Dynamic Attributes Cache.
///
func setCacheValue(_ value: AnyObject?, forKey key: String) {
guard let value = value else {
dynamicAttributesCache.removeValue(forKey: key)
return
}
dynamicAttributesCache[key] = value
}
/// Finds the first NotificationRange instance that maps to a given URL.
///
func notificationRangeWithUrl(_ url: URL) -> NotificationRange? {
for range in ranges {
if let rangeURL = range.url, (rangeURL as URL == url) {
return range
}
}
return nil
}
/// Finds the first NotificationRange instance that maps to a given CommentID.
///
func notificationRangeWithCommentId(_ commentID: NSNumber) -> NotificationRange? {
for range in ranges {
if let rangeCommentID = range.commentID, rangeCommentID.isEqual(commentID) {
return range
}
}
return nil
}
}
// MARK: - NotificationBlock Parsers
//
extension NotificationBlock {
/// Parses a collection of Block Definitions into NotificationBlock instances.
///
class func blocksFromArray(_ blocks: [[String: AnyObject]], parent: Notification) -> [NotificationBlock] {
return blocks.flatMap {
return NotificationBlock(dictionary: $0, parent: parent)
}
}
}
// MARK: - NotificationBlock Types
//
extension NotificationBlock {
/// Known kinds of Blocks
///
enum Kind {
case text
case image // Includes Badges and Images
case user
case comment
}
/// Known kinds of Actions
///
enum Action: String {
case Approve = "approve-comment"
case Follow = "follow"
case Like = "like-comment"
case Reply = "replyto-comment"
case Spam = "spam-comment"
case Trash = "trash-comment"
}
/// Parsing Keys
///
fileprivate enum BlockKeys {
static let Actions = "actions"
static let Media = "media"
static let Meta = "meta"
static let Ranges = "ranges"
static let RawType = "type"
static let Text = "text"
static let UserType = "user"
}
/// Meta Parsing Keys
///
fileprivate enum MetaKeys {
static let Ids = "ids"
static let Links = "links"
static let Titles = "titles"
static let Site = "site"
static let Post = "post"
static let Comment = "comment"
static let Reply = "reply_comment"
static let Home = "home"
}
}
// MARK: - NotificationBlock Equatable Implementation
//
func == (lhs: NotificationBlock, rhs: NotificationBlock) -> Bool {
return lhs.kind == rhs.kind &&
lhs.text == rhs.text &&
lhs.parent == rhs.parent &&
lhs.ranges.count == rhs.ranges.count &&
lhs.media.count == rhs.media.count
}
| gpl-2.0 | 3fd2d4e9133ed59c61c06bcf34a09167 | 26.693498 | 143 | 0.590721 | 4.656429 | false | false | false | false |
grigaci/RateMyTalkAtMobOS | RateMyTalkAtMobOS/Classes/Model/Entities+CloudKit/RMTRatingCategory+CloudKit.swift | 1 | 2773 | //
// RMTRatingCategory+CloudKit.swift
// RateMyTalkAtMobOSMaster
//
// Created by Bogdan Iusco on 10/4/14.
// Copyright (c) 2014 Grigaci. All rights reserved.
//
import Foundation
import CloudKit
enum RMTRatingCategoryCKAttributes: NSString {
case title = "title"
case detail = "detail"
}
enum RMTRatingCategoryCKRelation: NSString {
case session = "session"
}
extension RMTRatingCategory {
class var ckRecordName: NSString
{
get { return "RMTRatingCategory"}
}
class func create(record: CKRecord, managedObjectContext: NSManagedObjectContext) -> RMTRatingCategory {
let ratingCategory = RMTRatingCategory(entity: RMTRatingCategory.entity(managedObjectContext), insertIntoManagedObjectContext: managedObjectContext)
ratingCategory.ckRecordID = record.recordID.recordName
let title = record.objectForKey(RMTRatingCategoryCKAttributes.title.rawValue) as? NSString
ratingCategory.title = title
ratingCategory.ckRecordID = record.recordID.recordName
let ratingCategoryToSessionRelation = record.objectForKey(RMTRatingCategoryCKRelation.session.rawValue) as? CKReference
if ratingCategoryToSessionRelation != nil {
let sessionRecordID = ratingCategoryToSessionRelation?.recordID.recordName
let session: RMTSession? = RMTSession.sessionWithRecordID(sessionRecordID!, managedObjectContext: managedObjectContext)
if session != nil {
session?.addRatingCategoriesObject(ratingCategory)
}
}
return ratingCategory
}
func createdCKRecord() -> CKRecord {
var ckRecord: CKRecord
let recordIDString = self.ckRecordID!
let recordID = CKRecordID(recordName: recordIDString)
ckRecord = CKRecord(recordType: RMTRating.ckRecordName, recordID: recordID)
return ckRecord;
}
class func ratingCategoryWithRecordID(recordID: NSString, managedObjectContext: NSManagedObjectContext) -> RMTRatingCategory? {
let predicate = NSPredicate(format: "%K == %@", RMTCloudKitAttributes.ckRecordID.rawValue, recordID)
let existingObject = RMTRatingCategory.MR_findFirstWithPredicate(predicate, inContext: managedObjectContext) as? RMTRatingCategory
return existingObject
}
class func ratingCategoryWithID(ratingCategoryID: String, managedObjectContext: NSManagedObjectContext) -> RMTRatingCategory? {
let predicate = NSPredicate(format: "%K == %@", RMTRatingCategoryAttributes.ratingCategoryID.rawValue, ratingCategoryID)
let existingObject = RMTRatingCategory.MR_findFirstWithPredicate(predicate, inContext: managedObjectContext) as? RMTRatingCategory
return existingObject
}
}
| bsd-3-clause | 7a09c44e9e5d7d25c33f54a1d416788c | 38.614286 | 156 | 0.732059 | 5.557114 | false | false | false | false |
Isahkaren/ND-OnTheMap | OnTheMap/Models/User.swift | 1 | 838 | //
// User.swift
// OnTheMap
//
// Created by Isabela Karen de Oliveira Gomes on 20/02/17.
// Copyright © 2017 Isabela Karen de Oliveira Gomes. All rights reserved.
//
import UIKit
class User {
static let logged = User()
var nickname: String?
var lastName: String?
var uniqueKey: String?
init(fromDict dict: [String: Any]) {
guard let user = dict["user"] as? [String: Any] else {
return
}
nickname = user["nickname"] as? String ?? nil
lastName = user["last_name"] as? String ?? nil
uniqueKey = user["key"] as? String ?? nil
}
init() {
}
func updateValues(user: User) {
nickname = user.nickname
lastName = user.lastName
uniqueKey = user.uniqueKey
}
}
| mit | 0e4bae1d35ff19493b414e3de5c866ae | 19.414634 | 74 | 0.542413 | 4.270408 | false | false | false | false |
CaiMiao/CGSSGuide | DereGuide/Live/Model/CGSSBeatmap.swift | 1 | 8695 | //
// CGSSBeatmap.swift
// DereGuide
//
// Created by zzk on 16/7/23.
// Copyright © 2016年 zzk. All rights reserved.
//
import Foundation
import SwiftyJSON
class CGSSBeatmap {
var notes: [CGSSBeatmapNote]
var difficulty: CGSSLiveDifficulty
var shiftingPoints: [BpmShiftingPoint]?
var originalShiftingPoints: [BpmShiftingPoint]?
var isValid: Bool {
return notes.count > 0
}
var numberOfNotes: Int {
if let note = notes.first {
return note.status ?? 0
}
return 0
}
var firstNote: CGSSBeatmapNote? {
if notes.count == 0 {
return nil
}
for i in 0...notes.count - 1 {
if notes[i].finishPos != 0 {
return notes[i]
}
}
return nil
}
var lastNote: CGSSBeatmapNote? {
if notes.count == 0 {
return nil
}
for i in 0...notes.count - 1 {
if notes[notes.count - i - 1].finishPos != 0 {
return notes[notes.count - i - 1]
}
}
return nil
}
lazy var validNotes: [CGSSBeatmapNote] = {
var arr = [CGSSBeatmapNote]()
for i in 0..<self.notes.count {
if self.notes[i].finishPos != 0 {
arr.append(self.notes[i])
}
}
return arr
}()
// begin time of beatmap player
lazy var beginTime = TimeInterval(self.timeOfFirstNote)
func contextFree() {
var positionPressed = [Int?](repeating: nil, count: 5)
var slides = [Int: Int]()
for (index, note) in self.validNotes.enumerated() {
note.comboIndex = index + 1
if note.type == 2 && positionPressed[note.finishPos - 1] == nil {
note.longPressType = 1
positionPressed[note.finishPos - 1] = index
} else if positionPressed[note.finishPos - 1] != nil {
let previousIndex = positionPressed[note.finishPos - 1]!
let previous = validNotes[previousIndex]
note.longPressType = 2
previous.append(note)
let startIndex = previousIndex + 1
validNotes[startIndex..<index].forEach { $0.along = previous }
positionPressed[note.finishPos - 1] = nil
}
if note.groupId != 0 {
if slides[note.groupId] == nil {
// 滑条起始点
slides[note.groupId] = index
} else {
let previousIndex = slides[note.groupId]!
let previous = validNotes[previousIndex]
// 对于个别歌曲(如:维纳斯, absolute nine) 组id存在复用问题 对interval进行额外判断 大于4s的flick间隔判断为不合法
if previous.intervalTo(note) < 4 || note.type == 3 {
previous.append(note)
let startIndex = previousIndex + 1
validNotes[startIndex..<index].forEach { $0.along = previous }
}
slides[note.groupId] = index
}
}
}
}
func addShiftingOffset(info: CGSSBeatmapShiftingInfo, rawBpm: Int) {
// calculate start offset using the first bpm in shifting info
var offset: Float = 0
if let bpm = info.shiftingPoints.first?.bpm {
let bps = Float(bpm) / 60
let spb = 1 / bps
let remainder = timeOfFirstNote.truncatingRemainder(dividingBy: 4 * spb)
if !(remainder < 0.001 || 4 * spb - remainder < 0.001) {
offset = remainder * Float(bpm) / Float(rawBpm)
beginTime = TimeInterval(timeOfFirstNote - remainder)
}
} else {
addStartOffset(rawBpm: rawBpm)
}
// add shift offset for each note using shift info
shiftingPoints = [BpmShiftingPoint]()
originalShiftingPoints = info.shiftingPoints
for range in info.shiftingRanges {
for note in validNotes {
if note.sec < range.start { continue }
if note.sec >= range.end { break }
note.offset = offset + (note.sec - range.start) * ((Float(range.bpm) / Float(rawBpm)) - 1)
}
var point = range.beginPoint
point.timestamp += offset
shiftingPoints?.append(point)
offset += range.length * ((Float(range.bpm) / Float(rawBpm)) - 1)
}
// add offset from shifting info
for note in validNotes {
note.offset += info.offset
}
}
// add start offset for non-shift-bpm live
func addStartOffset(rawBpm: Int) {
let bps = Float(rawBpm) / 60
let spb = 1 / bps
let remainder = timeOfFirstNote.truncatingRemainder(dividingBy: 4 * spb)
if remainder < 0.001 || 4 * spb - remainder < 0.001 { return }
for note in validNotes {
note.offset = remainder
}
beginTime = TimeInterval(timeOfFirstNote - remainder)
}
var timeOfFirstNote: Float {
return firstNote?.sec ?? 0
}
var timeOfLastNote: Float {
return lastNote?.sec ?? 0
}
var totalSeconds: Float {
return notes.last?.sec ?? 0
}
var validSeconds: Float {
return timeOfLastNote - timeOfFirstNote
}
// 折半查找指定秒数对应的combo数
func comboForSec(_ sec: Float) -> Int {
// 为了避免近似带来的误差 导致对压小节线的note计算不准确 此处加上0.0001
let newSec = sec + 0.0001 + timeOfFirstNote
var end = numberOfNotes - 1
var start = 0
while start <= end {
let middle = start + (end - start) / 2
let middleNote = validNotes[middle]
let middleSec = middleNote.sec + middleNote.offset
if newSec < middleSec {
end = middle - 1
} else {
start = middle + 1
}
}
return start
}
init?(data: Data, rawDifficulty: Int) {
if let difficulty = CGSSLiveDifficulty(rawValue: rawDifficulty) {
self.difficulty = difficulty
} else {
return nil
}
if let csv = String.init(data: data, encoding: .utf8) {
let lines = csv.components(separatedBy: "\n")
self.notes = [CGSSBeatmapNote]()
for i in 0..<lines.count {
let line = lines[i]
if i == 0 {
continue
} else {
let comps = line.components(separatedBy: ",")
if comps.count < 8 {
break
}
let note = CGSSBeatmapNote()
note.id = Int(comps[0]) ?? 0
note.sec = Float(comps[1]) ?? 0
note.type = Int(comps[2]) ?? 0
note.startPos = Int(comps[3]) ?? 0
note.finishPos = Int(comps[4]) ?? 0
note.status = Int(comps[5]) ?? 0
note.sync = Int(comps[6]) ?? 0
note.groupId = Int(comps[7]) ?? 0
self.notes.append(note)
}
}
} else {
return nil
}
}
/* debug methods */
#if DEBUG
func exportIntervalToBpm() {
let predict: Float = 1
var arr = [Float]()
for i in 0..<validNotes.count {
if i == 0 { continue }
let note = validNotes[i]
let lastNote = validNotes[i - 1]
arr.append(60 / (note.sec - lastNote.sec) * predict)
}
(arr as NSArray).write(toFile: NSHomeDirectory() + "/beat_interval.plist", atomically: true)
}
func exportNote() {
var arr = [Float]()
for i in 0..<validNotes.count {
let note = validNotes[i]
arr.append(note.sec)
}
(arr as NSArray).write(toFile: NSHomeDirectory() + "/notes.plist", atomically: true)
}
func exportNoteWithOffset() {
var arr = [Float]()
for i in 0..<validNotes.count {
let note = validNotes[i]
arr.append(note.sec + note.offset)
}
(arr as NSArray).write(toFile: NSHomeDirectory() + "/notes_with_offset.plist", atomically: true)
}
#endif
}
| mit | 180f03386ca2649ddd862479c1cf44ee | 31.196226 | 106 | 0.499062 | 4.592034 | false | false | false | false |
kmalkic/LazyKit | LazyKit/Classes/Theming/Main/LazyStyleSheet.swift | 1 | 4057 | //
// LazyStyleSheet.swift
// LazyKit
//
// Created by Malkic Kevin on 20/04/2015.
// Copyright (c) 2015 Malkic Kevin. All rights reserved.
//
import Foundation
import UIKit
internal enum LazyStyleSheetParserType : Int {
case json
case css
}
internal class LazyStyleSheet: NSObject, LazyStyleSheetParserDelegate {
var styleSets = [LazyStyleSet]()
var bodyStyle: LazyStyleSet?
func startParsingFileAtUrl(_ url: URL, parserType: LazyStyleSheetParserType) -> Bool {
let parser: LazyStyleSheetParser?
switch parserType {
case .css:
parser = LazyStyleSheetCSSParser()
default:
parser = nil
}
if parser == nil {
return false
}
parser!.parseData(try? Data(contentsOf: url), delegate: self)
return true
}
func styleThatMatchView(_ view: UIView, styleId: String?, styleClass: String?) -> LazyStyleSet? {
var newStyleSet: LazyStyleSet? = bodyStyle ?? LazyStyleSet()
let possibilities = possibilityPatterns(type(of: view), styleClass: styleClass, styleId: styleId)
let styleSetsTmp = styleSets
for styleSet in styleSetsTmp {
if testPatterns(patterns: styleSet.patterns, possibilities: possibilities) {
newStyleSet = newStyleSet + styleSet
}
}
return newStyleSet
}
func possibilityPatterns(_ klass:AnyClass, styleClass: String?, styleId: String?) -> [String] {
var possibilities = [String]()
let klassName = NSStringFromClass(klass)
possibilities.append(klassName)
if styleClass != nil {
let klasses = styleClass!.components(separatedBy: " ")
for klass in klasses {
possibilities.append( klassName + String(format:".%@",klass) )
possibilities.append( String(format:".%@",klass) )
if styleId != nil {
possibilities.append( klassName + String(format:"#%@",styleId!) )
possibilities.append( String(format:"#%@",styleId!) )
}
if styleId != nil && styleClass != nil {
possibilities.append( klassName + String(format:"#%@.%@",styleId!,klass) )
possibilities.append( String(format:"#%@.%@",styleId!,klass) )
}
}
} else if styleId != nil {
possibilities.append( klassName + String(format:"#%@",styleId!) )
possibilities.append( String(format:"#%@",styleId!) )
}
return possibilities
}
func testPatterns(patterns: [String], possibilities: [String]) -> Bool {
for pattern in patterns {
if possibilities.contains(pattern) {
return true
}
}
return false
}
//MARK - LazyStyleSheetParserDelegate
func didFinishParsing(_ parser: LazyStyleSheetParser, styleSets: [LazyStyleSet]!) {
self.styleSets += styleSets
let searchResults = styleSets.filter() {
for pattern in $0.patterns {
if pattern == "body" {
return true
}
}
return false
}
if searchResults.count > 0 {
bodyStyle = LazyStyleSet()
for style in searchResults {
bodyStyle = bodyStyle + style
}
}
}
func didFailParsing(_ parser: LazyStyleSheetParser, error: NSError) {
}
}
| mit | d9a814afcf5afd3e738c237afbf8a583 | 25.86755 | 105 | 0.496672 | 5.966176 | false | false | false | false |
synchromation/Buildasaur | BuildaKit/CommonExtensions.swift | 2 | 4000 | //
// CommonExtensions.swift
// Buildasaur
//
// Created by Honza Dvorsky on 17/02/2015.
// Copyright (c) 2015 Honza Dvorsky. All rights reserved.
//
import Foundation
public func firstNonNil<T>(objects: [T?]) -> T? {
for i in objects {
if let i = i {
return i
}
}
return nil
}
extension Set {
public func filterSet(includeElement: (Element) -> Bool) -> Set<Element> {
return Set(self.filter(includeElement))
}
}
extension Array {
public func indexOfFirstObjectPassingTest(test: (Element) -> Bool) -> Array<Element>.Index? {
for (idx, obj) in self.enumerate() {
if test(obj) {
return idx
}
}
return nil
}
public func firstObjectPassingTest(test: (Element) -> Bool) -> Element? {
for item in self {
if test(item) {
return item
}
}
return nil
}
}
extension Array {
public func mapVoidAsync(transformAsync: (item: Element, itemCompletion: () -> ()) -> (), completion: () -> ()) {
self.mapAsync(transformAsync, completion: { (_) -> () in
completion()
})
}
public func mapAsync<U>(transformAsync: (item: Element, itemCompletion: (U) -> ()) -> (), completion: ([U]) -> ()) {
let group = dispatch_group_create()
var returnedValueMap = [Int: U]()
for (index, element) in self.enumerate() {
dispatch_group_enter(group)
transformAsync(item: element, itemCompletion: {
(returned: U) -> () in
returnedValueMap[index] = returned
dispatch_group_leave(group)
})
}
dispatch_group_notify(group, dispatch_get_main_queue()) {
//we have all the returned values in a map, put it back into an array of Us
var returnedValues = [U]()
for i in 0 ..< returnedValueMap.count {
returnedValues.append(returnedValueMap[i]!)
}
completion(returnedValues)
}
}
}
extension Array {
//dictionarify an array for fast lookup by a specific key
public func toDictionary(key: (Element) -> String) -> [String: Element] {
var dict = [String: Element]()
for i in self {
dict[key(i)] = i
}
return dict
}
}
public enum NSDictionaryParseError: ErrorType {
case MissingValueForKey(key: String)
case WrongTypeOfValueForKey(key: String, value: AnyObject)
}
extension NSDictionary {
public func get<T>(key: String) throws -> T {
guard let value = self[key] else {
throw NSDictionaryParseError.MissingValueForKey(key: key)
}
guard let typedValue = value as? T else {
throw NSDictionaryParseError.WrongTypeOfValueForKey(key: key, value: value)
}
return typedValue
}
public func getOptionally<T>(key: String) throws -> T? {
guard let value = self[key] else {
return nil
}
guard let typedValue = value as? T else {
throw NSDictionaryParseError.WrongTypeOfValueForKey(key: key, value: value)
}
return typedValue
}
}
extension Array {
public func dictionarifyWithKey(key: (item: Element) -> String) -> [String: Element] {
var dict = [String: Element]()
self.forEach { dict[key(item: $0)] = $0 }
return dict
}
}
extension String {
//returns nil if string is empty
public func nonEmpty() -> String? {
return self.isEmpty ? nil : self
}
}
public func delayClosure(delay: Double, closure: () -> ()) {
dispatch_after(
dispatch_time(
DISPATCH_TIME_NOW,
Int64(delay * Double(NSEC_PER_SEC))
),
dispatch_get_main_queue(),
closure)
}
| mit | 967866e265ad0ac1efb79ea55d5a53d6 | 24.806452 | 120 | 0.54675 | 4.376368 | false | false | false | false |
davidbutz/ChristmasFamDuels | iOS/Boat Aware/UIImage+Decompression.swift | 1 | 3861 | //
// UIImage+Decompression.swift
// Boat Aware
//
// Created by Adam Douglass on 2/8/16.
// Copyright © 2016 Thrive Engineering. All rights reserved.
//
import UIKit
extension UIImage {
var decompressedImage: UIImage {
UIGraphicsBeginImageContextWithOptions(size, true, 0)
drawAtPoint(CGPointZero)
let decompressedImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return decompressedImage
}
func imageWithColoredBorder(borderThickness: CGFloat, borderColor: UIColor, withShadow: Bool) -> UIImage {
var shadowThichness : CGFloat = 0.0;
if (withShadow) {
shadowThichness = 2.0;
}
//
// size_t newWidth = self.size.width + 2 * borderThickness + 2 * shadowThickness;
// size_t newHeight = self.size.height + 2 * borderThickness + 2 * shadowThickness;
// CGRect imageRect = CGRectMake(borderThickness + shadowThickness, borderThickness + shadowThickness, self.size.width, self.size.height);
let newWidth = self.size.width + 2.0 * borderThickness + 2.0 * shadowThichness;
let newHeight = self.size.height + 2.0 * borderThickness + 2.0 * shadowThichness;
let imageRect = CGRectMake(borderThickness + shadowThichness, borderThickness + shadowThichness, self.size.width, self.size.height);
//
// UIGraphicsBeginImageContext(CGSizeMake(newWidth, newHeight));
UIGraphicsBeginImageContext(CGSizeMake(newWidth, newHeight));
// CGContextRef ctx = UIGraphicsGetCurrentContext();
let ctx = UIGraphicsGetCurrentContext();
// CGContextSaveGState(ctx);
CGContextSaveGState(ctx);
// CGContextSetShadow(ctx, CGSizeZero, 4.5f);
// CGContextSetShadow(ctx, CGSizeZero, 4.5);
CGContextSetShadowWithColor(ctx, CGSizeZero, 8, borderColor.CGColor);
// [color setFill];
// borderColor.setFill();
// CGContextFillRect(ctx, CGRectMake(shadowThickness, shadowThickness, newWidth - 2 * shadowThickness, newHeight - 2 * shadowThickness));
// CGContextFillRect(ctx, CGRectMake(shadowThichness, shadowThichness, newWidth - 2.0 * shadowThichness, newHeight - 2.0 * shadowThichness));
// CGContextRestoreGState(ctx);
// CGContextDrawImage(ctx, imageRect, self.CGImage);
self.drawInRect(imageRect);
CGContextRestoreGState(ctx);
// [self drawInRect:imageRect];
// //CGContextDrawImage(ctx, imageRect, self.CGImage); //if use this method, image will be filp vertically
let img = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return img;
// return UIGraphicsGetImageFromCurrentImageContext();
}
func drawOutlie(color:UIColor) -> UIImage
{
let newImageKoef:CGFloat = 1.08
let outlinedImageRect = CGRect(x: 0.0, y: 0.0, width: self.size.width * newImageKoef, height: self.size.height * newImageKoef)
let imageRect = CGRect(x: self.size.width * (newImageKoef - 1) * 0.5, y: self.size.height * (newImageKoef - 1) * 0.5, width: self.size.width, height: self.size.height)
UIGraphicsBeginImageContextWithOptions(outlinedImageRect.size, false, newImageKoef)
self.drawInRect(outlinedImageRect)
let context = UIGraphicsGetCurrentContext()
CGContextSetBlendMode(context, CGBlendMode.SourceIn)
CGContextSetFillColorWithColor(context, color.CGColor)
CGContextFillRect(context, outlinedImageRect)
self.drawInRect(imageRect)
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return newImage
}
} | mit | f5b2802e2d85977d28c48afe049915c3 | 41.9 | 175 | 0.660881 | 5.153538 | false | false | false | false |
EvitaAFD/PicFeed | PicFeed/PicFeed/CloudKit.swift | 1 | 2381 | //
// CloudKit.swift
// PicFeed
//
// Created by Eve Denison on 3/27/17.
// Copyright © 2017 Eve Denison. All rights reserved.
//
import UIKit
import CloudKit
typealias SuccessCompletion = (Bool) -> ()
typealias PostsCompletion = ([Post]?)->()
class CloudKit {
static let shared = CloudKit()
let container = CKContainer.default()
var privateDatabase : CKDatabase {
return container.privateCloudDatabase
}
//save a post to CloudKit
func save(post: Post, completion: @escaping SuccessCompletion){
do {
if let record = try Post.recordFor(post: post) {
privateDatabase.save(record, completionHandler: { (record, error) in
if error != nil {
completion(false)
return
}
if let record = record {
print(record)
completion(true)
}else {
completion(false)
}
})
}
}catch {
print(error)
}
}
func getPosts(completion: @escaping PostsCompletion) {
let postQuery = CKQuery(recordType: "Post", predicate: NSPredicate(value: true))
self.privateDatabase.perform(postQuery, inZoneWith: nil) { (records, error) in
if error != nil {
OperationQueue.main.addOperation {
completion(nil)
}
}
if let records = records {
var posts = [Post]()
for record in records {
if let asset = record["image"] as? CKAsset, let date = record["date"] as? Date {
let path = asset.fileURL.path
if let image = UIImage(contentsOfFile: path) {
let newPost = Post(image: image, date: date)
posts.append(newPost)
}
}
}
OperationQueue.main.addOperation {
completion(posts)
}
}
}
}
}
| mit | 08abaaba34981c55f480e773ed7265e6 | 27.674699 | 100 | 0.438655 | 5.721154 | false | false | false | false |
volodg/iAsync.reactiveKit | Sources/ReactiveKit+AsyncAdditions.swift | 1 | 1619 | //
// ReactiveKit+Additions.swift
// iAsync_reactiveKit
//
// Created by Gorbenko Vladimir on 10/02/16.
// Copyright © 2016 AppDaddy. All rights reserved.
//
import Foundation
import ReactiveKit
//TODO test
public func combineLatest<S: Sequence, T, N, E>(_ producers: S) -> AsyncStream<[T], N, E> where S.Iterator.Element == AsyncStream<T, N, E>, E: Error {
let size = Array(producers).count
if size == 0 {
return AsyncStream.succeeded(with: [])
}
return AsyncStream { observer in
let queue = DispatchQueue(label: "com.ReactiveKit.ReactiveKit.combineLatest")
var results = [Int:AsyncEvent<T, N, E>]()
let dispatchIfPossible = { (currIndex: Int, currEv: AsyncEvent<T, N, E>) -> () in
if let index = results.index(where: { $0.1.isFailure }) {
let el = results[index]
observer(.failure(el.1.error!))
}
if results.count == size && results.all({ $0.1.isSuccess }) {
let els = results.map { $0.1.value! }
observer(.success(els))
}
if case .next(let val) = currEv {
observer(.next(val))
}
}
var disposes = [Disposable]()
for (index, stream) in producers.enumerated() {
let dispose = stream.observe { event in
queue.sync {
results[index] = event
dispatchIfPossible(index, event)
}
}
disposes.append(dispose)
}
return CompositeDisposable(disposes)
}
}
| gpl-3.0 | 0d158f1437867c10355dae25d9477cd8 | 24.68254 | 150 | 0.542027 | 4.170103 | false | false | false | false |
fttios/PrcticeSwift3.0 | Playground/Swift3--Closure-闭包.playground/Contents.swift | 1 | 975 | //: Playground - noun: a place where people can play
import UIKit
var str = "Hello, playground"
/*------------闭包-----------*/
//闭包是一种函数的简写形式,省去函数名,把参数和返回值放入花括号内。
//{(a: Int, b: Int) -> Int in
//执行语句
//return ...
//}
var city = ["zhengzhou","xiamen","hefei","nanchang","nanjing"]
// sorted函数用于对数组的排序,只接受一个函数型参数,描述排序逻辑。
var cityList1 = city.sorted()
func daoxu(a: String, b: String) -> Bool {
return a > b
}
var cityList2 = city.sorted(by: daoxu)
//用闭包表达式来改写:
//NO.1
var cityList3 = city.sorted { (a, b) -> Bool in
return a > b
}
//NO.2
//闭包的自动推断:1.参数和返回类型可自动推断,单表达式可以忽略return关键词
var cityList4 = city.sorted { (a, b) in
a > b
}
//2.可使用快捷参数,前缀$,从0开始递增
var cityList5 = city.sorted { $0 > $1 }
cityList5
| mit | 5d3f68b1f26c451254cbdbd1a46331e4 | 17.075 | 62 | 0.625173 | 2.450847 | false | false | false | false |
toshi586014/closeKeyboardButtonSwift | CloseKeyboardButton/ViewController.swift | 1 | 3058 | //
// ViewController.swift
// CloseKeyboardButton
//
// Created by 3BR-T on 2015/09/09.
// Copyright (c) 2015年 3BR-T. All rights reserved.
//
import UIKit
class ViewController: UIViewController, UITextFieldDelegate {
@IBOutlet weak var inputTextField: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
self.inputTextField.delegate = self
// キーボードに閉じるボタンを追加する
self.makeCloseButton()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func makeCloseButton(){
// 閉じるボタンを配置するUIViewを作成する
let buttonView: UIView = UIView()
// ビューの大きさは、画面の横幅と同じで高さは44にする
let viewWidth: CGFloat = self.view.bounds.size.width
let viewHeight: CGFloat = 44
let viewRect: CGRect = CGRectMake(0, 0, viewWidth, viewHeight)
buttonView.frame = viewRect
// ビューの背景色を設定する
buttonView.backgroundColor = UIColor(white: 0.5, alpha: 0.5)
// 閉じるボタンを作成する
let closeButton: UIButton = UIButton(type: UIButtonType.System)
// ボタンの大きさは、横幅が60で高さは30にする
let buttonWidth: CGFloat = 60
let buttonHeight: CGFloat = 30
let buttonRect: CGRect = CGRectMake(0, 0, buttonWidth, buttonHeight)
closeButton.bounds = buttonRect
// ボタンのx座標は画面の右端からマージンを引いた位置、y座標はボタンビューの真ん中にする
let buttonMargin: CGFloat = 10
let buttonCenterX = self.view.bounds.size.width - buttonMargin - buttonWidth / 2
let buttonCenterY = buttonView.bounds.size.height / 2
let buttonCenter = CGPointMake(buttonCenterX, buttonCenterY)
closeButton.center = buttonCenter
// ボタンのタイトルを『Close』にする
closeButton.setTitle("Close", forState: UIControlState.Normal)
// 閉じるボタンを押したときに呼ばれる動作を設定する
closeButton.addTarget(self, action: "closeKeyboard", forControlEvents: UIControlEvents.TouchUpInside)
// 閉じるボタンをViewに追加する
buttonView.addSubview(closeButton)
// 閉じるボタンつきのViewをUITextFieldのinputAccessoryViewに設定する
self.inputTextField.inputAccessoryView = buttonView
}
// キーボードを閉じる
func closeKeyboard(){
self.inputTextField.resignFirstResponder()
}
// リターンキーを押したときにキーボードを閉じる
func textFieldShouldReturn(textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true
}
}
| mit | 1826b942fa6000f1a25c864ff3d2d373 | 32.102564 | 109 | 0.662665 | 4.677536 | false | false | false | false |
eofster/Telephone | TelephoneTests/SoundIOPresenterTests.swift | 1 | 2569 | //
// SoundIOPresenterTests.swift
// Telephone
//
// Copyright © 2008-2016 Alexey Kuznetsov
// Copyright © 2016-2021 64 Characters
//
// Telephone is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Telephone is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
import Domain
import DomainTestDoubles
import UseCases
import XCTest
final class SoundIOPresenterTests: XCTestCase {
func testUpdatesOutputWithPresentationSoundIOAndAudioDevices() {
let output = SoundPreferencesViewSpy()
let factory = SystemAudioDeviceTestFactory()
let soundIO = SystemDefaultingSoundIO(
SimpleSoundIO(input: factory.someInput, output: factory.firstOutput, ringtoneOutput: factory.someOutput)
)
let devices = SystemAudioDevices(devices: factory.all)
let sut = SoundIOPresenter(output: output)
let systemDefault = PresentationAudioDevice(isSystemDefault: true, name: systemDefaultDeviceName)
sut.update(soundIO: soundIO, devices: devices)
XCTAssertEqual(
output.invokedSoundIO,
PresentationSoundIO(soundIO: soundIO, systemDefaultDeviceName: systemDefaultDeviceName)
)
XCTAssertEqual(
output.invokedDevices,
PresentationAudioDevices(
input: [systemDefault] + devices.input.map(PresentationAudioDevice.init),
output: [systemDefault] + devices.output.map(PresentationAudioDevice.init)
)
)
}
func testUpdatesOutputWithSystemDefaultSoundIOWhenSoundIODevicesAreNil() {
let output = SoundPreferencesViewSpy()
let sut = SoundIOPresenter(output: output)
let systemDefault = PresentationAudioDevice(isSystemDefault: true, name: systemDefaultDeviceName)
sut.update(
soundIO: SystemDefaultingSoundIO(NullSoundIO()),
devices: SystemAudioDevices(devices: SystemAudioDeviceTestFactory().all)
)
XCTAssertEqual(
output.invokedSoundIO,
PresentationSoundIO(input: systemDefault, output: systemDefault, ringtoneOutput: systemDefault)
)
}
}
private let systemDefaultDeviceName = "Use System Setting"
| gpl-3.0 | 7e5c75c76a140cdc91f5ed7a769b73f6 | 37.313433 | 116 | 0.709388 | 5.3147 | false | true | false | false |
faimin/ZDOpenSourceDemo | ZDOpenSourceSwiftDemo/Pods/lottie-ios/lottie-swift/src/Private/NodeRenderSystem/Nodes/RenderContainers/GroupNode.swift | 1 | 5023 | //
// GroupNode.swift
// lottie-swift
//
// Created by Brandon Withrow on 1/18/19.
//
import Foundation
import QuartzCore
import CoreGraphics
final class GroupNodeProperties: NodePropertyMap, KeypathSearchable {
var keypathName: String = "Transform"
var childKeypaths: [KeypathSearchable] = []
init(transform: ShapeTransform?) {
if let transform = transform {
self.anchor = NodeProperty(provider: KeyframeInterpolator(keyframes: transform.anchor.keyframes))
self.position = NodeProperty(provider: KeyframeInterpolator(keyframes: transform.position.keyframes))
self.scale = NodeProperty(provider: KeyframeInterpolator(keyframes: transform.scale.keyframes))
self.rotation = NodeProperty(provider: KeyframeInterpolator(keyframes: transform.rotation.keyframes))
self.opacity = NodeProperty(provider: KeyframeInterpolator(keyframes: transform.opacity.keyframes))
self.skew = NodeProperty(provider: KeyframeInterpolator(keyframes: transform.skew.keyframes))
self.skewAxis = NodeProperty(provider: KeyframeInterpolator(keyframes: transform.skewAxis.keyframes))
} else {
/// Transform node missing. Default to empty transform.
self.anchor = NodeProperty(provider: SingleValueProvider(Vector3D(x: CGFloat(0), y: CGFloat(0), z: CGFloat(0))))
self.position = NodeProperty(provider: SingleValueProvider(Vector3D(x: CGFloat(0), y: CGFloat(0), z: CGFloat(0))))
self.scale = NodeProperty(provider: SingleValueProvider(Vector3D(x: CGFloat(1), y: CGFloat(1), z: CGFloat(1))))
self.rotation = NodeProperty(provider: SingleValueProvider(Vector1D(0)))
self.opacity = NodeProperty(provider: SingleValueProvider(Vector1D(1)))
self.skew = NodeProperty(provider: SingleValueProvider(Vector1D(0)))
self.skewAxis = NodeProperty(provider: SingleValueProvider(Vector1D(0)))
}
self.keypathProperties = [
"Anchor Point" : anchor,
"Position" : position,
"Scale" : scale,
"Rotation" : rotation,
"Opacity" : opacity,
"Skew" : skew,
"Skew Axis" : skewAxis
]
self.properties = Array(keypathProperties.values)
}
let keypathProperties: [String : AnyNodeProperty]
let properties: [AnyNodeProperty]
let anchor: NodeProperty<Vector3D>
let position: NodeProperty<Vector3D>
let scale: NodeProperty<Vector3D>
let rotation: NodeProperty<Vector1D>
let opacity: NodeProperty<Vector1D>
let skew: NodeProperty<Vector1D>
let skewAxis: NodeProperty<Vector1D>
var caTransform: CATransform3D {
return CATransform3D.makeTransform(anchor: anchor.value.pointValue,
position: position.value.pointValue,
scale: scale.value.sizeValue,
rotation: rotation.value.cgFloatValue,
skew: skew.value.cgFloatValue,
skewAxis: skewAxis.value.cgFloatValue)
}
}
final class GroupNode: AnimatorNode {
// MARK: Properties
let groupOutput: GroupOutputNode
let properties: GroupNodeProperties
let rootNode: AnimatorNode?
var container: ShapeContainerLayer = ShapeContainerLayer()
// MARK: Initializer
init(name: String, parentNode: AnimatorNode?, tree: NodeTree) {
self.parentNode = parentNode
self.keypathName = name
self.rootNode = tree.rootNode
self.properties = GroupNodeProperties(transform: tree.transform)
self.groupOutput = GroupOutputNode(parent: parentNode?.outputNode, rootNode: rootNode?.outputNode)
var childKeypaths: [KeypathSearchable] = tree.childrenNodes
childKeypaths.append(properties)
self.childKeypaths = childKeypaths
for childContainer in tree.renderContainers {
container.insertRenderLayer(childContainer)
}
}
// MARK: Keypath Searchable
let keypathName: String
let childKeypaths: [KeypathSearchable]
var keypathLayer: CALayer? {
return container
}
// MARK: Animator Node Protocol
var propertyMap: NodePropertyMap & KeypathSearchable {
return properties
}
var outputNode: NodeOutput {
return groupOutput
}
let parentNode: AnimatorNode?
var hasLocalUpdates: Bool = false
var hasUpstreamUpdates: Bool = false
var lastUpdateFrame: CGFloat? = nil
var isEnabled: Bool = true {
didSet {
container.isHidden = !isEnabled
}
}
func performAdditionalLocalUpdates(frame: CGFloat, forceLocalUpdate: Bool) -> Bool {
return rootNode?.updateContents(frame, forceLocalUpdate: forceLocalUpdate) ?? false
}
func performAdditionalOutputUpdates(_ frame: CGFloat, forceOutputUpdate: Bool) {
rootNode?.updateOutputs(frame, forceOutputUpdate: forceOutputUpdate)
}
func rebuildOutputs(frame: CGFloat) {
container.opacity = Float(properties.opacity.value.cgFloatValue) * 0.01
container.transform = properties.caTransform
groupOutput.setTransform(container.transform, forFrame: frame)
}
}
| mit | 5032f9537a9a733da8fedfcc6f0bff91 | 34.624113 | 120 | 0.706749 | 4.672558 | false | false | false | false |
maxoly/PulsarKit | PulsarKitExample/PulsarKitExample/Application/AppDelegate.swift | 1 | 1075 | //
// AppDelegate.swift
// PulsarKitExample
//
// Created by Massimo Oliviero on 10/08/2018.
// Copyright © 2018 Nacoon. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
UINavigationBar.appearance().isTranslucent = false
UINavigationBar.appearance().barTintColor = .secondary
UINavigationBar.appearance().tintColor = .light
let attributes: [NSAttributedString.Key: Any] = [.foregroundColor: UIColor.light]
UINavigationBar.appearance().titleTextAttributes = attributes
UINavigationBar.appearance().largeTitleTextAttributes = attributes
window = UIWindow(frame: UIScreen.main.bounds)
window?.rootViewController = UINavigationController(rootViewController: HomeViewController())
window?.makeKeyAndVisible()
return true
}
}
| mit | cacfc379c7726bd4dbdb09a5246e5f25 | 33.645161 | 145 | 0.716015 | 5.652632 | false | false | false | false |
lkuczborski/Beacon_Workshop | PorkKit/PorkKit/Pork.swift | 1 | 2018 | //
// Beacon.swift
// ProkKit
//
// Created by Lukasz Stocki on 10/02/16.
// Copyright © 2016 A.C.M.E. All rights reserved.
//
import Foundation
import CoreLocation;
public struct Pork {
public private(set) var major : CLBeaconMajorValue
public private(set) var minor : CLBeaconMinorValue
public private(set) var proximity: CLProximity
public private(set) var rssi : Int
public private(set) var uuid : String
public private(set) var accuracy: CLLocationAccuracy {
willSet {
if case let newAccuracy = newValue where newAccuracy != self.accuracy && newAccuracy != -1 {
self.accuracy = newAccuracy
}
}
}
init(uuid: String, major: CLBeaconMajorValue, minor: CLBeaconMinorValue) {
self.uuid = uuid
self.major = major
self.minor = minor
proximity = .unknown
rssi = 0
accuracy = -1;
}
init(beacon: CLBeacon) {
self.init(uuid: beacon.proximityUUID.uuidString,
major: CLBeaconMajorValue(beacon.major.intValue),
minor: CLBeaconMinorValue(beacon.minor.intValue))
proximity = beacon.proximity
accuracy = beacon.accuracy
rssi = beacon.rssi
}
}
extension Pork : Equatable {
}
public func ==(lhs: Pork, rhs: Pork) -> Bool {
if lhs.uuid != rhs.uuid {
return false
}
if lhs.major != lhs.major {
return false
}
if lhs.minor != rhs.minor {
return false
}
return true
}
extension Pork: CustomStringConvertible {
public var description: String {
return "UUID: \(self.uuid) Major: \(self.major) Minor: \(self.minor)"
}
}
extension Pork: CustomDebugStringConvertible {
public var debugDescription: String {
return self.description
}
}
extension CLBeacon {
var baseData: String {
return "UUID: \(self.proximityUUID.uuidString) Major: \(self.major) Minor: \(self.minor)"
}
}
| mit | dd1f0659ef1d9eec8491260700ba3bc5 | 22.453488 | 104 | 0.609817 | 4.184647 | false | false | false | false |
DMeechan/Rick-and-Morty-Soundboard | Rick and Morty Soundboard/Rick and Morty Soundboard/DataManager.swift | 1 | 4347 | //
// Datas.swift
// Rick and Morty Soundboard
//
// Created by Daniel Meechan on 15/08/2017.
// Copyright © 2017 Rogue Studios. All rights reserved.
//
import Foundation
import Firebase
typealias Datas = DataManager
class DataManager {
static let shared = Datas()
var tracks = [Track]()
var settings: [String: Any] = [:]
let wallpapers: [String] = [
"None",
"Running poster",
"Meeseek",
"Family",
"Running Rick",
"Show me what you got",
"Drugs",
"2 bros",
"Game of Thrones",
"Galactic ad",
"Evil Morty babes",
"Human shield",
"Piloting",
"Cromulon",
"Butter Bot",
"Jail Rick",
"Eating"
]
init() {
}
func setup() {
importSettings()
importTrackData()
// saveData()
}
func saveData() {
do {
// Encode Tracks as JSON Data
let jsonData = try JSONSerialization.data(withJSONObject: settings, options: .prettyPrinted)
let jsonDecoded = try JSONSerialization.jsonObject(with: jsonData, options: [])
// Now cast it with the right type
if let dictFromJSON = jsonDecoded as? [String:Any] {
print("PRINTING SETTINGS JSON:")
print(dictFromJSON)
}
// print(jsonToString(json: jsonData))
// try! realm.write {
// let jsonDecoded = try JSONSerialization.jsonObject(with: jsonData, options: [])
// //realm.create(jsonDecoded)
//
// }
} catch {
print(error.localizedDescription)
}
}
// func jsonToString(json: Any){
// do {
// let data1 = try JSONSerialization.data(withJSONObject: json, options: JSONSerialization.WritingOptions.prettyPrinted) // first of all convert json to the data
// let convertedString = String(data: data1, encoding: String.Encoding.utf8) // the data will be converted to the string
//// print(convertedString)
//
// } catch let myJSONError {
// print(myJSONError)
// }
//
// }
func getWallpaperFilename() -> String {
guard var wallpaper: String = Datas.shared.settings["wallpaper"] as? String else { return "" }
wallpaper.append("_wallpaper")
return wallpaper
}
func importTrackData() {
var items = [Track]()
let inputFile = Bundle.main.path(forResource: "trackData", ofType: "plist")
let inputDataArray = NSArray(contentsOfFile: inputFile!)
for item in inputDataArray as! [Dictionary<String, String>] {
let track = Track(dataDictionary: item)
if track.isUnique() == false {
print("WARNING: \(track.sound) is not unique!")
track.sound += "2"
}
items.append(track)
}
tracks = items
}
func importSettings() {
settings = [
"wallpaper": "Eating",
"theme": Style.themes[0],
"wallpaperBlur": true,
"trackBlur": true,
"simultaneousPlayback": false,
"enableFavourites": false,
"isDeveloper": true,
"tracksClicked": 0
]
}
func getBoolFromSetting(id: String) -> Bool {
// if settings[id] == "true" {
// return true
//
// }
//
return false
}
// MARK: Log events
static func logEvent(eventName: String) {
guard let tracksClicked = Datas.shared.settings["tracksClicked"] as? Int else { return }
Analytics.logEvent(eventName, parameters: [
"tracksClicked": NSInteger(exactly: tracksClicked)! as NSObject,
])
}
}
extension String{
func dictionaryValue() -> [String: AnyObject]
{
if let data = self.data(using: String.Encoding.utf8) {
do {
let json = try JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions.allowFragments) as? [String: AnyObject]
return json!
} catch {
print("Error converting to JSON")
}
}
return NSDictionary() as! [String : AnyObject]
}
}
extension NSDictionary{
func JsonString() -> String
{
do{
let jsonData: Data = try JSONSerialization.data(withJSONObject: self, options: .prettyPrinted)
return String.init(data: jsonData, encoding: .utf8)!
}
catch
{
return "error converting"
}
}
}
| apache-2.0 | 48b51ba02796a5de8473dbc57492904a | 21.518135 | 169 | 0.586056 | 4.227626 | false | false | false | false |
sora0077/QiitaKit | QiitaKit/src/Utility/Utility.swift | 1 | 848 | //
// Utility.swift
// QiitaKit
//
// Created by 林達也 on 2015/06/26.
// Copyright (c) 2015年 林達也. All rights reserved.
//
import Foundation
import APIKit
infix operator ..< { associativity left precedence 140 }
func ..<(left: Int, right: Int) -> Set<Int> {
return Set(Range(start: left, end: right))
}
public extension QiitaRequestToken where Response == () {
func transform(request: NSURLRequest?, response: NSHTTPURLResponse?, object: SerializedObject) throws -> Response {
}
}
func validation(object: AnyObject?) throws {
guard let object = object as? [String: AnyObject] else {
return
}
if let message = object["message"] as? String,
let type = object["type"] as? String
{
throw QiitaKitError.QiitaAPIError(message: message, type: type)
}
}
| mit | f2ba5a091cb4b261675f47e0cca31fd9 | 22.166667 | 119 | 0.641487 | 4.009615 | false | false | false | false |
AgaKhanFoundation/WCF-iOS | Steps4Impact/CommonUI/Views/WebImageView.swift | 1 | 2531 | /**
* Copyright © 2019 Aga Khan Foundation
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR "AS IS" AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
* EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
* OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
* OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
**/
import UIKit
import SDWebImage
class WebImageView: UIImageView {
func fadeInImage(imageURL: URL?, placeHolderImage: UIImage? = nil, completionHandler: @escaping ((Bool) -> Void) = {_ in }) {
if placeHolderImage == nil {
alpha = 0.0
}
// swiftlint:disable:next line_length
let completion: SDExternalCompletionBlock = { [weak self] (image: UIImage?, error: Error?, cacheType: SDImageCacheType, url: URL?) in
if let _ = image {
completionHandler(true)
}
if cacheType == .none {
self?.alpha = 0.0
UIView.animate(withDuration: 0.1, animations: {
self?.alpha = 1.0
})
}
}
sd_imageIndicator = SDWebImageProgressIndicator.`default`
if let placeHolderImage = placeHolderImage {
sd_setImage(with: imageURL, placeholderImage: placeHolderImage, options: [], completed: completion)
} else {
sd_setImage(with: imageURL, completed: completion)
}
}
func stopLoading() {
sd_imageIndicator = nil
sd_cancelCurrentImageLoad()
}
}
| bsd-3-clause | 489e8a62fc6364fe97f8bcf7495cefc8 | 38.53125 | 137 | 0.713043 | 4.591652 | false | false | false | false |
MaddTheSane/WWDC | WWDC/VideoStore.swift | 1 | 8474 | //
// VideoDownloader.swift
// WWDC
//
// Created by Guilherme Rambo on 22/04/15.
// Copyright (c) 2015 Guilherme Rambo. All rights reserved.
//
import Cocoa
public let VideoStoreDownloadedFilesChangedNotification = "VideoStoreDownloadedFilesChangedNotification"
public let VideoStoreNotificationDownloadStarted = "VideoStoreNotificationDownloadStarted"
public let VideoStoreNotificationDownloadCancelled = "VideoStoreNotificationDownloadCancelled"
public let VideoStoreNotificationDownloadPaused = "VideoStoreNotificationDownloadPaused"
public let VideoStoreNotificationDownloadResumed = "VideoStoreNotificationDownloadResumed"
public let VideoStoreNotificationDownloadFinished = "VideoStoreNotificationDownloadFinished"
public let VideoStoreNotificationDownloadProgressChanged = "VideoStoreNotificationDownloadProgressChanged"
private let _SharedVideoStore = VideoStore()
private let _BackgroundSessionIdentifier = "WWDC Video Downloader"
class VideoStore : NSObject, NSURLSessionDownloadDelegate {
private let configuration = NSURLSessionConfiguration.backgroundSessionConfigurationWithIdentifier(_BackgroundSessionIdentifier)
private var backgroundSession: NSURLSession!
private var downloadTasks: [String : NSURLSessionDownloadTask] = [:]
private let defaults = NSUserDefaults.standardUserDefaults()
class func SharedStore() -> VideoStore
{
return _SharedVideoStore;
}
override init() {
super.init()
backgroundSession = NSURLSession(configuration: configuration, delegate: self, delegateQueue: NSOperationQueue.mainQueue())
}
func initialize() {
backgroundSession.getTasksWithCompletionHandler { _, _, pendingTasks in
for task in pendingTasks {
if let key = task.originalRequest?.URL!.absoluteString {
self.downloadTasks[key] = task
}
}
}
NSNotificationCenter.defaultCenter().addObserverForName(LocalVideoStoragePathPreferenceChangedNotification, object: nil, queue: nil) { _ in
self.monitorDownloadsFolder()
NSNotificationCenter.defaultCenter().postNotificationName(VideoStoreDownloadedFilesChangedNotification, object: nil)
}
monitorDownloadsFolder()
}
// MARK: Public interface
func allTasks() -> [NSURLSessionDownloadTask] {
return Array(self.downloadTasks.values)
}
func download(url: String) {
if isDownloading(url) || hasVideo(url) {
return
}
let task = backgroundSession.downloadTaskWithURL(NSURL(string: url)!)
if let key = task.originalRequest?.URL!.absoluteString {
self.downloadTasks[key] = task
}
task.resume()
NSNotificationCenter.defaultCenter().postNotificationName(VideoStoreNotificationDownloadStarted, object: url)
}
func pauseDownload(url: String) -> Bool {
if let task = downloadTasks[url] {
task.suspend()
NSNotificationCenter.defaultCenter().postNotificationName(VideoStoreNotificationDownloadPaused, object: url)
return true
}
print("VideoStore was asked to pause downloading URL \(url), but there's no task for that URL")
return false
}
func resumeDownload(url: String) -> Bool {
if let task = downloadTasks[url] {
task.resume()
NSNotificationCenter.defaultCenter().postNotificationName(VideoStoreNotificationDownloadResumed, object: url)
return true
}
print("VideoStore was asked to resume downloading URL \(url), but there's no task for that URL")
return false
}
func cancelDownload(url: String) -> Bool {
if let task = downloadTasks[url] {
task.cancel()
self.downloadTasks.removeValueForKey(url)
NSNotificationCenter.defaultCenter().postNotificationName(VideoStoreNotificationDownloadCancelled, object: url)
return true
}
print("VideoStore was asked to cancel downloading URL \(url), but there's no task for that URL")
return false
}
func isDownloading(url: String) -> Bool {
let downloading = downloadTasks.keys.filter { taskURL in
return url == taskURL
}
return (downloading.count > 0)
}
func localVideoPath(remoteURL: String) -> String {
return (Preferences.SharedPreferences().localVideoStoragePath as NSString).stringByAppendingPathComponent((remoteURL as NSString).lastPathComponent)
}
func localVideoAbsoluteURLString(remoteURL: String) -> String {
return NSURL(fileURLWithPath: localVideoPath(remoteURL)).absoluteString
}
func hasVideo(url: String) -> Bool {
return (NSFileManager.defaultManager().fileExistsAtPath(localVideoPath(url)))
}
// MARK: URL Session
func URLSession(session: NSURLSession, downloadTask: NSURLSessionDownloadTask, didFinishDownloadingToURL location: NSURL) {
let originalURL = downloadTask.originalRequest!.URL!
let originalAbsoluteURLString = originalURL.absoluteString
let fileManager = NSFileManager.defaultManager()
if (fileManager.fileExistsAtPath(Preferences.SharedPreferences().localVideoStoragePath) == false) {
do {
try fileManager.createDirectoryAtPath(Preferences.SharedPreferences().localVideoStoragePath, withIntermediateDirectories: false, attributes: nil)
} catch _ {
}
}
let localURL = NSURL(fileURLWithPath: localVideoPath(originalAbsoluteURLString))
do {
try fileManager.moveItemAtURL(location, toURL: localURL)
WWDCDatabase.sharedDatabase.updateDownloadedStatusForSessionWithURL(originalAbsoluteURLString, downloaded: true)
} catch _ {
print("VideoStore was unable to move \(location) to \(localURL)")
}
downloadTasks.removeValueForKey(originalAbsoluteURLString)
NSNotificationCenter.defaultCenter().postNotificationName(VideoStoreNotificationDownloadFinished, object: originalAbsoluteURLString)
}
func URLSession(session: NSURLSession, downloadTask: NSURLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) {
let originalURL = downloadTask.originalRequest!.URL!.absoluteString
let info = ["totalBytesWritten": Int(totalBytesWritten), "totalBytesExpectedToWrite": Int(totalBytesExpectedToWrite)]
NSNotificationCenter.defaultCenter().postNotificationName(VideoStoreNotificationDownloadProgressChanged, object: originalURL, userInfo: info)
}
// MARK: File observation
private var folderMonitor: DTFolderMonitor!
private var existingVideoFiles = [String]()
func monitorDownloadsFolder() {
if folderMonitor != nil {
folderMonitor.stopMonitoring()
folderMonitor = nil
}
let videosPath = Preferences.SharedPreferences().localVideoStoragePath
enumerateVideoFiles(videosPath)
folderMonitor = DTFolderMonitor(forURL: NSURL(fileURLWithPath: videosPath)) {
self.enumerateVideoFiles(videosPath)
NSNotificationCenter.defaultCenter().postNotificationName(VideoStoreDownloadedFilesChangedNotification, object: nil)
}
folderMonitor.startMonitoring()
}
/// Updates the downloaded status for the sessions on the database based on the existence of the downloaded video file
private func enumerateVideoFiles(path: String) {
guard let enumerator = NSFileManager.defaultManager().enumeratorAtPath(path) else { return }
guard let files = enumerator.allObjects as? [String] else { return }
// existing/added files
for file in files {
WWDCDatabase.sharedDatabase.updateDownloadedStatusForSessionWithLocalFileName(file, downloaded: true)
}
if existingVideoFiles.count == 0 {
existingVideoFiles = files
return
}
// removed files
let removedFiles = existingVideoFiles.filter { !files.contains($0) }
for file in removedFiles {
WWDCDatabase.sharedDatabase.updateDownloadedStatusForSessionWithLocalFileName(file, downloaded: false)
}
}
// MARK: Teardown
deinit {
if folderMonitor != nil {
folderMonitor.stopMonitoring()
}
}
}
| bsd-2-clause | 69121b048f9444482286c16070db37af | 38.231481 | 178 | 0.705688 | 5.86436 | false | false | false | false |
mbigatti/StatusApp | StatusApp/CloudSynchronizer.swift | 1 | 6803 | //
// CloudSupport.swift
// StatusApp
//
// Created by Massimiliano Bigatti on 13/12/14.
// Copyright (c) 2014 Massimiliano Bigatti. All rights reserved.
//
import Foundation
import CloudKit
/**
iCloud Synchronizer using CloudKit
*/
class CloudSynchronizer {
let entityDatabase = StatusEntityDatabase.sharedInstance
/// singleton
class var sharedInstance : CloudSynchronizer {
struct Static {
static let instance = CloudSynchronizer()
}
return Static.instance
}
func sync() {
cloudStatus.postNotifications = true
let predicate = NSPredicate(format: "TRUEPREDICATE")
let query = CKQuery(recordType: "StatusEntity", predicate: predicate)
CKContainer.defaultContainer().privateCloudDatabase.performQuery(
query, inZoneWithID: nil) { (results: [AnyObject]!, error: NSError!) -> Void in
if error == nil {
//
// download
//
println("Remote elements count \(results.count)")
for record in results as [CKRecord] {
let uuid = record.recordID.recordName
println("Checking remote UUID \(uuid!)")
let filtered = self.entityDatabase.entities.filter({ (element: StatusEntity) -> Bool in
return element.uuid == uuid
})
if filtered.count == 0 {
//
// remote record not present in local database
//
println(" element not present locally, adding \(record) to local database")
let entity = StatusEntity(record: record)
self.entityDatabase.addEntity(entity)
self.entityDatabase.synchronize()
} else {
println(" element already present locally")
}
}
//
// upload
//
for entity in self.entityDatabase.entities {
println("Checking local UUID \(entity.uuid)")
var doUpload = false
if entity.uuid == nil {
doUpload = true
} else {
//
// check if the record still exists in iCloud
// it could be delete manually (for testing)
//
let filtered = results.filter({ (element) -> Bool in
return (element as CKRecord).recordID.recordName == entity.uuid
})
if filtered.count == 0 {
println(" Element not present remotely")
doUpload = true
}
}
if doUpload {
self.createRecord(entity)
}
}
} else {
self.logError(error)
}
cloudStatus.decrementPendingRequest()
}
cloudStatus.incrementPendingRequest()
}
/**
Create a new record on iCloud
:param: entity the entity to be created
*/
func createRecord(entity: StatusEntity) {
let record = entity.toRecord()
CKContainer.defaultContainer().privateCloudDatabase.saveRecord(record) { (savedRecord: CKRecord!, error: NSError!) -> Void in
if (error == nil) {
if entity.uuid == nil {
entity.uuid = savedRecord.recordID.recordName
StatusEntityDatabase.sharedInstance.synchronize()
println("Created remote object with UUID \(entity.uuid)")
} else {
println("Updated remote object with UUID \(entity.uuid)")
}
} else {
self.logError(error)
}
cloudStatus.decrementPendingRequest()
}
cloudStatus.incrementPendingRequest()
}
/**
Update an existing record on iCloud
:param: entity the entity to be updated
*/
func updateRecord(entity: StatusEntity) {
let record = entity.toRecord()
let operation = CKModifyRecordsOperation(recordsToSave: [record], recordIDsToDelete: nil)
operation.savePolicy = .AllKeys
operation.database = CKContainer.defaultContainer().privateCloudDatabase
operation.perRecordCompletionBlock = { (currentRecord: CKRecord!, error: NSError!) -> Void in
if (error == nil) {
println("Updated remote object with UUID \(entity.uuid)")
} else {
self.logError(error)
}
cloudStatus.decrementPendingRequest()
}
NSOperationQueue.mainQueue().addOperation(operation)
cloudStatus.incrementPendingRequest()
}
func deleteRecordWithUUID(uuid : String) {
let recordID = CKRecordID(recordName: uuid)
CKContainer.defaultContainer().privateCloudDatabase.deleteRecordWithID(recordID) { (currentRecordID: CKRecordID!, error: NSError!) -> Void in
if (error == nil) {
println("Deleted remote object with UUID \(recordID)")
} else {
self.logError(error)
}
cloudStatus.decrementPendingRequest()
}
}
private func logError(error: NSError) {
println("iCloud remote error \(error)")
}
}
let cloudStatus = CloudStatus()
class CloudStatus {
private var pendingRequests = 0;
var postNotifications = false;
func incrementPendingRequest() {
pendingRequests++
}
func decrementPendingRequest() {
pendingRequests--
if pendingRequests == 0 && postNotifications {
NSNotificationCenter.defaultCenter().postNotificationName(StatusAppDidUpdateFromCloud, object: nil)
}
}
} | mit | e91cfbea5c526aab2afd20fd61efe160 | 33.714286 | 149 | 0.477289 | 6.630604 | false | false | false | false |
kiliankoe/catchmybus | catchmybus/SettingsWindowController.swift | 1 | 2767 | //
// SettingsWindowController.swift
// catchmybus
//
// Created by Kilian Költzsch on 11/05/15.
// Copyright (c) 2015 Kilian Koeltzsch. All rights reserved.
//
import Cocoa
import IYLoginItem
class SettingsWindowController: NSWindowController {
// MARK: - Outlets
@IBOutlet weak var numRowsToShowLabel: NSTextField!
@IBOutlet weak var numRowsToShowSlider: NSSlider!
@IBOutlet weak var numRowsToShowDescriptionLabel: NSTextField!
@IBOutlet weak var displayNotificationsCheckbox: NSButton!
@IBOutlet weak var startAppAtLoginCheckbox: NSButton!
// MARK: -
override func windowDidLoad() {
super.windowDidLoad()
NSLog("Settings window did load")
let numRowsToShow = NSUserDefaults.standardUserDefaults().integerForKey(kNumRowsToShowKey)
numRowsToShowLabel.integerValue = numRowsToShow
numRowsToShowSlider.integerValue = numRowsToShow
let shouldDisplayNotifications = NSUserDefaults.standardUserDefaults().boolForKey(kShouldDisplayNotifications)
displayNotificationsCheckbox.state = shouldDisplayNotifications ? NSOnState : NSOffState
startAppAtLoginCheckbox.state = NSBundle.mainBundle().isLoginItem() ? NSOnState : NSOffState
// TODO: Use NSLocalizedStrings to update labels for all UI elements
// Implement this method to handle any initialization after your window controller's window has been loaded from its nib file.
}
internal func display() {
// FIXME: This isn't working. Interestingly enough the window is also not opened when I set it to be displayed at launch in the xib. Something's not right.
self.window?.makeKeyAndOrderFront(nil)
// self.showWindow(nil)
NSApp.activateIgnoringOtherApps(true)
NSLog("Settings window displaying")
}
// MARK: - IBActions
@IBAction func numRowsToShowSliderValueChanged(sender: NSSlider) {
numRowsToShowLabel.integerValue = sender.integerValue
NSUserDefaults.standardUserDefaults().setObject(sender.integerValue, forKey: kNumRowsToShowKey)
NSUserDefaults.standardUserDefaults().synchronize()
NSNotificationCenter.defaultCenter().postNotificationName(kUpdatedNumRowsToShowNotification, object: nil)
}
@IBAction func displayNotificationsCheckboxClicked(sender: NSButton) {
if sender.state == NSOnState {
NSUserDefaults.standardUserDefaults().setObject(true, forKey: kShouldDisplayNotifications)
} else {
NSUserDefaults.standardUserDefaults().setObject(false, forKey: kShouldDisplayNotifications)
}
NSUserDefaults.standardUserDefaults().synchronize()
}
@IBAction func startAppAtLoginCheckboxClicked(sender: NSButton) {
if sender.state == NSOnState {
NSBundle.mainBundle().addToLoginItems()
// TODO: Check if this changes state when clicked
} else {
NSBundle.mainBundle().removeFromLoginItems()
}
}
}
| mit | defc32e7398a8d25f23dbd0815e4f13d | 34.012658 | 157 | 0.784526 | 4.720137 | false | false | false | false |
NqiOS/DYTV-swift | DYTV/DYTV/Classes/Main/View/NQPageTitleView.swift | 1 | 6479 | //
// NQPageTitleView.swift
// DYTV
//
// Created by djk on 17/3/9.
// Copyright © 2017年 NQ. All rights reserved.
//
import UIKit
// MARK:- 定义协议
protocol NQPageTitleViewDelegate : class {
func pageTitleView(_ titleView : NQPageTitleView,selectedIndex index : Int)
}
// MARK:- 定义常量
private let kScrollLineH : CGFloat = 2 //滑块高度
private let kNormalColor : (CGFloat, CGFloat, CGFloat) = (85, 85, 85)
private let kSelectColor : (CGFloat, CGFloat, CGFloat) = (255, 128, 0)
// MARK:- 定义PageTitleView类
class NQPageTitleView: UIView {
// MARK:- 定义属性
fileprivate var currentIndex : Int = 0
fileprivate var titles : [String]
weak var delegate : NQPageTitleViewDelegate?
// MARK:- 懒加载属性
fileprivate lazy var titleLabels : [UILabel] = [UILabel]()
fileprivate lazy var scrollView : UIScrollView = {
let scrollView = UIScrollView()
scrollView.showsHorizontalScrollIndicator = false
scrollView.scrollsToTop = false
scrollView.bounces = false
return scrollView
}()
fileprivate lazy var scrollLine : UIView = {
let scrollLine = UIView()
scrollLine.backgroundColor = UIColor.orange
return scrollLine
}()
// MARK:- 自定义构造函数
init(frame: CGRect,titles : [String]) {
self.titles = titles
super.init(frame: frame)
//设置UI界面
setupUI()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
// MARK:- 设置UI界面
extension NQPageTitleView{
fileprivate func setupUI(){
//0.添加UIScrollView
addSubview(scrollView)
scrollView.frame = bounds
//1.添加title对应的Label
setupTitleLabels()
//2.设置底线和滚动的滑块
setupBottomLineAndScrollLine()
}
fileprivate func setupTitleLabels(){
//0.确定label的一些frame的值
let labelW : CGFloat = frame.width / CGFloat(titles.count)
let labelH : CGFloat = frame.height - kScrollLineH
let labelY : CGFloat = 0
for (index,title) in titles.enumerated(){
//1.创建UILabel
let label = UILabel()
//2.设置Label的属性
label.text = title
label.tag = index
label.font = UIFont.systemFont(ofSize: 16.0)
label.textColor = UIColor(r: kNormalColor.0, g: kNormalColor.1, b: kNormalColor.2)
label.textAlignment = .center
//3.设置label的frame
let labelX : CGFloat = labelW * CGFloat(index)
label.frame = CGRect(x: labelX, y: labelY, width: labelW, height: labelH)
//4.将lable添加到scrollView中
scrollView.addSubview(label)
titleLabels.append(label)
//5.给Label添加手势
label.isUserInteractionEnabled = true
let tapGes = UITapGestureRecognizer(target: self, action: #selector(titleLabelClick(_:)))
label.addGestureRecognizer(tapGes)
}
}
fileprivate func setupBottomLineAndScrollLine(){
//0.添加底线
let bottomLine = UIView()
bottomLine.backgroundColor = UIColor.lightGray
let lineH : CGFloat = 0.5
bottomLine.frame = CGRect(x: 0, y: frame.height - lineH, width: frame.width, height: lineH)
addSubview(bottomLine)
//1.添加scrollLine滑块
//1.1获取第一个Label
guard let firstLabel = titleLabels.first else {
return
}
firstLabel.textColor = UIColor(r: kSelectColor.0, g: kSelectColor.1, b: kSelectColor.2)
//1.2设置scrollLine的属性
scrollLine.frame = CGRect(x: firstLabel.frame.origin.x, y: frame.height - kScrollLineH, width: firstLabel.frame.width, height: kScrollLineH)
scrollView.addSubview(scrollLine)
}
}
// MARK:- 监听Label的点击
extension NQPageTitleView{
@objc fileprivate func titleLabelClick(_ tapGes : UITapGestureRecognizer){
//0.获取当前Label
guard let currentLabel = tapGes.view as? UILabel else {
return
}
//1.如果是重复点击同一个title,那么直接返回
if currentLabel.tag == currentIndex{
return
}
//2.获取之前的Label
let oldLabel = titleLabels[currentIndex]
//3.切换文字的颜色
oldLabel.textColor = UIColor(r: kNormalColor.0, g: kNormalColor.1, b: kNormalColor.2)
currentLabel.textColor = UIColor(r: kSelectColor.0, g: kSelectColor.1, b: kSelectColor.2)
//4.保存最新Label的下标值
currentIndex = currentLabel.tag
//5.滚动条位置发生改变
let scrollLineX = CGFloat(currentIndex) * scrollLine.frame.width
UIView.animate(withDuration: 0.15) {
self.scrollLine.frame.origin.x = scrollLineX
}
//6.通知代理,滚动PageContentView里的内容
delegate?.pageTitleView(self, selectedIndex: currentIndex)
}
}
// MARK:- 对外暴露的方法
extension NQPageTitleView{
func setTitleWithProgress(_ progress : CGFloat,sourceIndex : Int,targetIndex : Int){
//0.取出sourceLabel/targetLabel
let sourceLabel = titleLabels[sourceIndex]
let targetLabel = titleLabels[targetIndex]
//1.处理滑块的逻辑
let moveTotalX = targetLabel.frame.origin.x - sourceLabel.frame.origin.x
let moveX = moveTotalX * progress
scrollLine.frame.origin.x = sourceLabel.frame.origin.x + moveX
//2.颜色的渐变(复杂)
//2.1取出颜色的变化范围
let colorDelta = (kSelectColor.0 - kNormalColor.0, kSelectColor.1 - kNormalColor.1, kSelectColor.2 - kNormalColor.2)
//2.2变化sourceLabel
sourceLabel.textColor = UIColor(r: kSelectColor.0 - colorDelta.0 * progress, g: kSelectColor.1 - colorDelta.1 * progress, b: kSelectColor.2 - colorDelta.2 * progress)
// 2.3变化targetLabel
targetLabel.textColor = UIColor(r: kNormalColor.0 + colorDelta.0 * progress, g: kNormalColor.1 + colorDelta.1 * progress, b: kNormalColor.2 + colorDelta.2 * progress)
//3.记录最新的index
currentIndex = targetIndex
}
}
| mit | 50307c473eb38dc5088dc40ddc530e60 | 32.877095 | 174 | 0.620053 | 4.679012 | false | false | false | false |
CatchChat/Yep | Yep/Views/Media/MediaPreviewView.swift | 1 | 12644 | //
// MediaPreviewView.swift
// Yep
//
// Created by NIX on 15/6/15.
// Copyright (c) 2015年 Catch Inc. All rights reserved.
//
import UIKit
import YepKit
import AVFoundation
final class MediaPreviewView: UIView {
weak var parentViewController: UIViewController?
var initialframe: CGRect = CGRectZero
var message: Message? {
didSet {
if let message = message {
switch message.mediaType {
case MessageMediaType.Image.rawValue:
mediaControlView.type = .Image
if
let imageFileURL = message.imageFileURL,
let image = UIImage(contentsOfFile: imageFileURL.path!) {
mediaView.scrollView.hidden = false
mediaView.image = image
mediaView.coverImage = image
mediaControlView.shareAction = {
if let vc = self.parentViewController {
UIView.animateWithDuration(0.3, delay: 0.0, options: .CurveEaseInOut, animations: { [weak self] in
self?.alpha = 0.0
}, completion: nil)
let activityViewController = UIActivityViewController(activityItems: [image], applicationActivities: nil)
activityViewController.completionWithItemsHandler = { (_, _, _, _) in
UIView.animateWithDuration(0.3, delay: 0.0, options: .CurveEaseInOut, animations: { [weak self] in
self?.alpha = 1.0
}, completion: nil)
}
vc.presentViewController(activityViewController, animated: true, completion: nil)
}
}
}
case MessageMediaType.Video.rawValue:
mediaControlView.type = .Video
mediaControlView.playState = .Playing
if
let videoFileURL = message.videoFileURL {
let playerItem = AVPlayerItem(asset: AVURLAsset(URL: videoFileURL, options: [:]))
playerItem.seekToTime(kCMTimeZero)
let player = AVPlayer(playerItem: playerItem)
mediaControlView.timeLabel.text = ""
player.addPeriodicTimeObserverForInterval(CMTimeMakeWithSeconds(0.1, Int32(NSEC_PER_SEC)), queue: nil, usingBlock: { time in
guard let currentItem = player.currentItem else {
return
}
if currentItem.status == .ReadyToPlay {
let durationSeconds = CMTimeGetSeconds(currentItem.duration)
let currentSeconds = CMTimeGetSeconds(time)
let coundDownTime = Double(Int((durationSeconds - currentSeconds) * 10)) / 10
self.mediaControlView.timeLabel.text = "\(coundDownTime)"
}
})
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(MediaPreviewView.playerItemDidReachEnd(_:)), name: AVPlayerItemDidPlayToEndTimeNotification, object: player.currentItem)
mediaControlView.playAction = { mediaControlView in
player.play()
mediaControlView.playState = .Playing
}
mediaControlView.pauseAction = { mediaControlView in
player.pause()
mediaControlView.playState = .Pause
}
mediaView.videoPlayerLayer.player = player
mediaView.videoPlayerLayer.player?.addObserver(self, forKeyPath: "status", options: NSKeyValueObservingOptions(rawValue: 0), context: nil)
mediaView.videoPlayerLayer.addObserver(self, forKeyPath: "readyForDisplay", options: NSKeyValueObservingOptions(rawValue: 0), context: nil)
//mediaView.videoPlayerLayer.player.play()
mediaView.scrollView.hidden = true
if
let imageFileURL = message.videoThumbnailFileURL,
let image = UIImage(contentsOfFile: imageFileURL.path!) {
mediaView.coverImage = image
}
mediaControlView.shareAction = {
if let vc = self.parentViewController {
UIView.animateWithDuration(0.3, delay: 0.0, options: .CurveEaseInOut, animations: { [weak self] in
self?.alpha = 0.0
}, completion: nil)
let activityViewController = UIActivityViewController(activityItems: [videoFileURL], applicationActivities: nil)
activityViewController.completionWithItemsHandler = { (_, _, _, _) in
UIView.animateWithDuration(0.3, delay: 0.0, options: .CurveEaseInOut, animations: { [weak self] in
self?.alpha = 1.0
}, completion: nil)
}
vc.presentViewController(activityViewController, animated: true, completion: nil)
}
}
}
default:
break
}
}
}
}
lazy var mediaView: MediaView = {
let view = MediaView()
return view
}()
lazy var mediaControlView: MediaControlView = {
let view = MediaControlView()
return view
}()
override func didMoveToSuperview() {
super.didMoveToSuperview()
backgroundColor = UIColor.blackColor()
clipsToBounds = true
makeUI()
addHideGesture()
}
func makeUI() {
addSubview(mediaView)
addSubview(mediaControlView)
mediaView.translatesAutoresizingMaskIntoConstraints = false
mediaControlView.translatesAutoresizingMaskIntoConstraints = false
let viewsDictionary: [String: AnyObject] = [
"mediaView": mediaView,
"mediaControlView": mediaControlView,
]
let mediaViewConstraintsV = NSLayoutConstraint.constraintsWithVisualFormat("V:|[mediaView]|", options: [], metrics: nil, views: viewsDictionary)
let mediaViewConstraintsH = NSLayoutConstraint.constraintsWithVisualFormat("H:|[mediaView]|", options: [], metrics: nil, views: viewsDictionary)
NSLayoutConstraint.activateConstraints(mediaViewConstraintsV)
NSLayoutConstraint.activateConstraints(mediaViewConstraintsH)
let mediaControlViewConstraintsH = NSLayoutConstraint.constraintsWithVisualFormat("H:|[mediaControlView]|", options: [], metrics: nil, views: viewsDictionary)
let mediaControlViewConstraintHeight = NSLayoutConstraint(item: mediaControlView, attribute: .Height, relatedBy: .Equal, toItem: nil, attribute: .NotAnAttribute, multiplier: 1.0, constant: 50)
let mediaControlViewConstraintBottom = NSLayoutConstraint(item: mediaControlView, attribute: .Bottom, relatedBy: .Equal, toItem: self, attribute: .Bottom, multiplier: 1.0, constant: 0)
NSLayoutConstraint.activateConstraints(mediaControlViewConstraintsH)
NSLayoutConstraint.activateConstraints([mediaControlViewConstraintHeight, mediaControlViewConstraintBottom])
}
func addHideGesture() {
let swipeUp = UISwipeGestureRecognizer(target: self, action: #selector(MediaPreviewView.hide))
swipeUp.direction = .Up
let swipeDown = UISwipeGestureRecognizer(target: self, action: #selector(MediaPreviewView.hide))
swipeDown.direction = .Down
addGestureRecognizer(swipeUp)
addGestureRecognizer(swipeDown)
}
func hide() {
if let message = message {
if message.mediaType == MessageMediaType.Video.rawValue {
mediaView.videoPlayerLayer.player?.pause()
mediaView.videoPlayerLayer.player?.removeObserver(self, forKeyPath: "status")
}
}
UIView.animateWithDuration(0.05, delay: 0.0, options: .CurveLinear, animations: { [weak self] in
self?.mediaView.coverImageView.alpha = 1
self?.mediaControlView.alpha = 0
}, completion: { _ in
UIView.animateWithDuration(0.10, delay: 0.0, options: .CurveEaseOut, animations: { [weak self] in
guard let strongSelf = self else { return }
strongSelf.frame = strongSelf.initialframe
strongSelf.layoutIfNeeded()
}, completion: { [weak self] _ in
self?.removeFromSuperview()
})
})
}
func showMediaOfMessage(message: Message, inView view: UIView?, withInitialFrame initialframe: CGRect, fromViewController viewController: UIViewController) {
if let parentView = view {
parentView.addSubview(self)
backgroundColor = UIColor.blackColor()
parentViewController = viewController
self.message = message
self.initialframe = initialframe
mediaControlView.alpha = 0
frame = initialframe
layoutIfNeeded()
UIView.animateWithDuration(0.15, delay: 0.0, options: .CurveEaseOut, animations: { [weak self] in
self?.frame = parentView.bounds
self?.layoutIfNeeded()
}, completion: { [weak self] _ in
if message.mediaType != MessageMediaType.Video.rawValue {
self?.mediaView.coverImage = nil
}
UIView.animateWithDuration(0.1, delay: 0.0, options: .CurveLinear, animations: { [weak self] in
self?.mediaControlView.alpha = 1
}, completion: nil)
})
}
}
override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
struct VideoPrepareState {
static var readyToPlay = false
static var readyForDisplay = false
static var isReady: Bool {
return readyToPlay && readyForDisplay
}
}
if let player = object as? AVPlayer {
if player == mediaView.videoPlayerLayer.player {
if keyPath == "status" {
switch player.status {
case AVPlayerStatus.Failed:
println("Failed")
case AVPlayerStatus.ReadyToPlay:
println("ReadyToPlay")
VideoPrepareState.readyToPlay = true
delay(0.3) {
SafeDispatch.async {
self.mediaView.videoPlayerLayer.player?.play()
}
}
case AVPlayerStatus.Unknown:
println("Unknown")
}
}
}
}
if let videoPlayerLayer = object as? AVPlayerLayer {
if keyPath == "readyForDisplay" {
if videoPlayerLayer.readyForDisplay {
VideoPrepareState.readyForDisplay = true
}
}
}
if VideoPrepareState.isReady {
self.mediaView.coverImage = nil
}
}
func playerItemDidReachEnd(notification: NSNotification) {
mediaControlView.playState = .Pause
if let playerItem = notification.object as? AVPlayerItem {
playerItem.seekToTime(kCMTimeZero)
}
}
}
| mit | 1f42e55238309d57f07c70894122cd82 | 37.898462 | 223 | 0.532194 | 6.605016 | false | false | false | false |
velvetroom/columbus | Source/GenericExtensions/ExtensionNSLayoutConstraint.swift | 1 | 9869 | import UIKit
extension NSLayoutConstraint
{
@discardableResult class func topToTop(
view:UIView,
toView:UIView,
constant:CGFloat = 0,
multiplier:CGFloat = 1) -> NSLayoutConstraint
{
let constraint:NSLayoutConstraint = NSLayoutConstraint(
item:view,
attribute:NSLayoutAttribute.top,
relatedBy:NSLayoutRelation.equal,
toItem:toView,
attribute:NSLayoutAttribute.top,
multiplier:multiplier,
constant:constant)
constraint.isActive = true
return constraint
}
@discardableResult class func topToBottom(
view:UIView,
toView:UIView,
constant:CGFloat = 0,
multiplier:CGFloat = 1) -> NSLayoutConstraint
{
let constraint:NSLayoutConstraint = NSLayoutConstraint(
item:view,
attribute:NSLayoutAttribute.top,
relatedBy:NSLayoutRelation.equal,
toItem:toView,
attribute:NSLayoutAttribute.bottom,
multiplier:multiplier,
constant:constant)
constraint.isActive = true
return constraint
}
@discardableResult class func bottomToBottom(
view:UIView,
toView:UIView,
constant:CGFloat = 0,
multiplier:CGFloat = 1) -> NSLayoutConstraint
{
let constraint:NSLayoutConstraint = NSLayoutConstraint(
item:view,
attribute:NSLayoutAttribute.bottom,
relatedBy:NSLayoutRelation.equal,
toItem:toView,
attribute:NSLayoutAttribute.bottom,
multiplier:multiplier,
constant:constant)
constraint.isActive = true
return constraint
}
@discardableResult class func bottomToTop(
view:UIView,
toView:UIView,
constant:CGFloat = 0,
multiplier:CGFloat = 1) -> NSLayoutConstraint
{
let constraint:NSLayoutConstraint = NSLayoutConstraint(
item:view,
attribute:NSLayoutAttribute.bottom,
relatedBy:NSLayoutRelation.equal,
toItem:toView,
attribute:NSLayoutAttribute.top,
multiplier:multiplier,
constant:constant)
constraint.isActive = true
return constraint
}
@discardableResult class func leftToLeft(
view:UIView,
toView:UIView,
constant:CGFloat = 0,
multiplier:CGFloat = 1) -> NSLayoutConstraint
{
let constraint:NSLayoutConstraint = NSLayoutConstraint(
item:view,
attribute:NSLayoutAttribute.left,
relatedBy:NSLayoutRelation.equal,
toItem:toView,
attribute:NSLayoutAttribute.left,
multiplier:multiplier,
constant:constant)
constraint.isActive = true
return constraint
}
@discardableResult class func leftToRight(
view:UIView,
toView:UIView,
constant:CGFloat = 0,
multiplier:CGFloat = 1) -> NSLayoutConstraint
{
let constraint:NSLayoutConstraint = NSLayoutConstraint(
item:view,
attribute:NSLayoutAttribute.left,
relatedBy:NSLayoutRelation.equal,
toItem:toView,
attribute:NSLayoutAttribute.right,
multiplier:multiplier,
constant:constant)
constraint.isActive = true
return constraint
}
@discardableResult class func rightToRight(
view:UIView,
toView:UIView,
constant:CGFloat = 0,
multiplier:CGFloat = 1) -> NSLayoutConstraint
{
let constraint:NSLayoutConstraint = NSLayoutConstraint(
item:view,
attribute:NSLayoutAttribute.right,
relatedBy:NSLayoutRelation.equal,
toItem:toView,
attribute:NSLayoutAttribute.right,
multiplier:multiplier,
constant:constant)
constraint.isActive = true
return constraint
}
@discardableResult class func rightToLeft(
view:UIView,
toView:UIView,
constant:CGFloat = 0,
multiplier:CGFloat = 1) -> NSLayoutConstraint
{
let constraint:NSLayoutConstraint = NSLayoutConstraint(
item:view,
attribute:NSLayoutAttribute.right,
relatedBy:NSLayoutRelation.equal,
toItem:toView,
attribute:NSLayoutAttribute.left,
multiplier:multiplier,
constant:constant)
constraint.isActive = true
return constraint
}
@discardableResult class func width(
view:UIView,
constant:CGFloat = 0,
multiplier:CGFloat = 1) -> NSLayoutConstraint
{
let constraint:NSLayoutConstraint = NSLayoutConstraint(
item:view,
attribute:NSLayoutAttribute.width,
relatedBy:NSLayoutRelation.equal,
toItem:nil,
attribute:NSLayoutAttribute.notAnAttribute,
multiplier:multiplier,
constant:constant)
constraint.isActive = true
return constraint
}
@discardableResult class func widthGreaterOrEqual(
view:UIView,
constant:CGFloat = 0,
multiplier:CGFloat = 1) -> NSLayoutConstraint
{
let constraint:NSLayoutConstraint = NSLayoutConstraint(
item:view,
attribute:NSLayoutAttribute.width,
relatedBy:NSLayoutRelation.greaterThanOrEqual,
toItem:nil,
attribute:NSLayoutAttribute.notAnAttribute,
multiplier:multiplier,
constant:constant)
constraint.isActive = true
return constraint
}
@discardableResult class func height(
view:UIView,
constant:CGFloat = 0,
multiplier:CGFloat = 1) -> NSLayoutConstraint
{
let constraint:NSLayoutConstraint = NSLayoutConstraint(
item:view,
attribute:NSLayoutAttribute.height,
relatedBy:NSLayoutRelation.equal,
toItem:nil,
attribute:NSLayoutAttribute.notAnAttribute,
multiplier:multiplier,
constant:constant)
constraint.isActive = true
return constraint
}
@discardableResult class func heightGreaterOrEqual(
view:UIView,
constant:CGFloat = 0,
multiplier:CGFloat = 1) -> NSLayoutConstraint
{
let constraint:NSLayoutConstraint = NSLayoutConstraint(
item:view,
attribute:NSLayoutAttribute.height,
relatedBy:NSLayoutRelation.greaterThanOrEqual,
toItem:nil,
attribute:NSLayoutAttribute.notAnAttribute,
multiplier:multiplier,
constant:constant)
constraint.isActive = true
return constraint
}
class func size(
view:UIView,
constant:CGFloat,
multiplier:CGFloat = 1)
{
NSLayoutConstraint.width(
view:view,
constant:constant,
multiplier:multiplier)
NSLayoutConstraint.height(
view:view,
constant:constant,
multiplier:multiplier)
}
@discardableResult class func width(
view:UIView,
toView:UIView,
multiplier:CGFloat = 1) -> NSLayoutConstraint
{
let constraint:NSLayoutConstraint = NSLayoutConstraint(
item:view,
attribute:NSLayoutAttribute.width,
relatedBy:NSLayoutRelation.equal,
toItem:toView,
attribute:NSLayoutAttribute.width,
multiplier:multiplier,
constant:0)
constraint.isActive = true
return constraint
}
@discardableResult class func height(
view:UIView,
toView:UIView,
multiplier:CGFloat = 1) -> NSLayoutConstraint
{
let constraint:NSLayoutConstraint = NSLayoutConstraint(
item:view,
attribute:NSLayoutAttribute.height,
relatedBy:NSLayoutRelation.equal,
toItem:toView,
attribute:NSLayoutAttribute.height,
multiplier:multiplier,
constant:0)
constraint.isActive = true
return constraint
}
class func equals(
view:UIView,
toView:UIView,
margin:CGFloat = 0)
{
NSLayoutConstraint.topToTop(
view:view,
toView:toView,
constant:margin)
NSLayoutConstraint.bottomToBottom(
view:view,
toView:toView,
constant:-margin)
NSLayoutConstraint.leftToLeft(
view:view,
toView:toView,
constant:margin)
NSLayoutConstraint.rightToRight(
view:view,
toView:toView,
constant:-margin)
}
class func equalsHorizontal(
view:UIView,
toView:UIView,
margin:CGFloat = 0)
{
NSLayoutConstraint.leftToLeft(
view:view,
toView:toView,
constant:margin)
NSLayoutConstraint.rightToRight(
view:view,
toView:toView,
constant:-margin)
}
class func equalsVertical(
view:UIView,
toView:UIView,
margin:CGFloat = 0)
{
NSLayoutConstraint.topToTop(
view:view,
toView:toView,
constant:margin)
NSLayoutConstraint.bottomToBottom(
view:view,
toView:toView,
constant:-margin)
}
}
| mit | ef361b6e93cb9a3b4197e735f8ea15b1 | 27.523121 | 63 | 0.577059 | 6.080715 | false | false | false | false |
nkirby/Humber | _lib/HMGithub/_src/API/GithubAPI+Issues.swift | 1 | 1224 | // =======================================================
// HMGithub
// Nathaniel Kirby
// =======================================================
import Foundation
import ReactiveCocoa
// =======================================================
public protocol GithubAPIIssueProviding {
func getIssues() -> SignalProducer<[GithubIssueResponse], GithubAPIError>
func getIssue(repoOwner repoOwner: String, repoName: String, issueNumber: String) -> SignalProducer<GithubIssueResponse, GithubAPIError>
}
extension GithubAPI: GithubAPIIssueProviding {
public func getIssues() -> SignalProducer<[GithubIssueResponse], GithubAPIError> {
let request = GithubRequest(method: .GET, endpoint: "/user/issues", parameters: nil)
return self.enqueueAndParseFeed(request: request, toType: GithubIssueResponse.self)
}
public func getIssue(repoOwner repoOwner: String, repoName: String, issueNumber: String) -> SignalProducer<GithubIssueResponse, GithubAPIError> {
let request = GithubRequest(method: .GET, endpoint: "/repos/\(repoOwner)/\(repoName)/issues/\(issueNumber)", parameters: nil)
return self.enqueueAndParse(request: request, toType: GithubIssueResponse.self)
}
}
| mit | f7b51ab2d0621cd270be5d84ddfa2c3e | 46.076923 | 149 | 0.645425 | 5.415929 | false | false | false | false |
cztatsumi-keisuke/TKKeyboardControl | Example/TKKeyboardControl/SecondViewController.swift | 1 | 3287 | //
// SecondViewController.swift
// TKKeyboardControl
//
// Created by cztatsumi-keisuke on 04/25/2016.
// Copyright (c) 2016 cztatsumi-keisuke. All rights reserved.
//
import UIKit
import TKKeyboardControl
class SecondViewController: UIViewController {
let inputBaseView = UIView()
let textField = UITextField()
let sendButton = UIButton()
let sideMargin: CGFloat = 5
let inputBaseViewHeight: CGFloat = 40
let textFieldHeight: CGFloat = 30
let sendButtonWidth: CGFloat = 80
var safeAreaInsets: UIEdgeInsets {
if #available(iOS 11, *) {
return view.safeAreaInsets
}
return UIEdgeInsets.zero
}
override func viewDidLoad() {
super.viewDidLoad()
title = "Second View"
inputBaseView.backgroundColor = UIColor(white: 0.9, alpha: 1.0)
view.addSubview(inputBaseView)
textField.backgroundColor = .white
textField.placeholder = "Input here."
textField.borderStyle = .roundedRect
textField.textAlignment = .left
inputBaseView.addSubview(textField)
sendButton.setTitle("Send", for: .normal)
inputBaseView.addSubview(sendButton)
// Trigger Offset
view.keyboardTriggerOffset = inputBaseViewHeight
// Add Keyboard Pannning
view.addKeyboardPanning(frameBasedActionHandler: { [weak self] keyboardFrameInView, firstResponder, opening, closing in
guard let weakSelf = self else { return }
if let v = firstResponder as? UIView {
print("isDescendant of inputBaseView?: \(v.isDescendant(of: weakSelf.inputBaseView))")
}
weakSelf.inputBaseView.frame.origin.y = keyboardFrameInView.origin.y - weakSelf.inputBaseViewHeight
})
let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(SecondViewController.closeKeyboard))
view.addGestureRecognizer(tapGestureRecognizer)
updateFrame()
}
deinit {
print("deinit called")
view.removeKeyboardControl()
}
override func viewWillLayoutSubviews() {
super.viewWillLayoutSubviews()
updateFrame()
}
private func updateFrame() {
inputBaseView.frame = CGRect(x: 0,
y: view.bounds.size.height - inputBaseViewHeight - safeAreaInsets.bottom,
width: view.bounds.size.width,
height: inputBaseViewHeight)
textField.frame = CGRect(x: sideMargin + safeAreaInsets.left,
y: (inputBaseViewHeight - textFieldHeight)/2,
width: view.bounds.size.width - sendButtonWidth - sideMargin * 3 - (safeAreaInsets.left + safeAreaInsets.right),
height: textFieldHeight)
sendButton.frame = CGRect(x: textField.frame.maxX + sideMargin,
y: sideMargin,
width: sendButtonWidth,
height: textFieldHeight)
}
@objc private func closeKeyboard() {
view.hideKeyboard()
}
}
| mit | f7e7843b4bf2447f0ae5b0f38cc333bc | 33.6 | 145 | 0.598114 | 5.726481 | false | false | false | false |
nfls/nflsers | app/v2/Provider/DeviceProvider.swift | 1 | 1578 | //
// DeviceProvider.swift
// NFLSers-iOS
//
// Created by Qingyang Hu on 01/04/2018.
// Copyright © 2018 胡清阳. All rights reserved.
//
import Foundation
import SwiftyUserDefaults
class DeviceProvider: AbstractProvider<DeviceRequest> {
public private(set) var announcement:String {
get {
return Defaults[.announcement]
}
set {
Defaults[.announcement] = newValue
}
}
public func getAnnouncement(completion: @escaping () -> Void) {
self.request(target: DeviceRequest.announcement(), type: DataWrapper<String>.self, success: { result in
if self.announcement != result.data.value {
self.announcement = result.data.value
completion()
} else {
self.announcement = result.data.value
}
})
}
public func checkUpdate(completion: @escaping (Bool) -> Void) {
self.request(target: DeviceRequest.version(), type: DataWrapper<String>.self, success: { (version) in
let current = Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as! String
if version.data.value.compare(current, options: .numeric) == .orderedDescending {
completion(true)
} else {
completion(false)
}
})
}
public func regitserDevice(token: String) {
self.request(target: .register(token: token), type: PushDevice.self, success: { (_) in
})
}
}
| apache-2.0 | 1ccf550f02640bdbda857d9340d2977a | 29.803922 | 111 | 0.580522 | 4.731928 | false | false | false | false |
qvacua/vimr | NvimView/Sources/NvimView/NvimView+Key.swift | 1 | 11351 | /**
* Tae Won Ha - http://taewon.de - @hataewon
* See LICENSE
*/
import Cocoa
import MessagePack
import RxSwift
public extension NvimView {
override func keyDown(with event: NSEvent) {
self.keyDownDone = false
NSCursor.setHiddenUntilMouseMoves(true)
let modifierFlags = event.modifierFlags
let isMeta = (self.isLeftOptionMeta && modifierFlags.contains(.leftOption))
|| (self.isRightOptionMeta && modifierFlags.contains(.rightOption))
if !isMeta {
let cocoaHandledEvent = NSTextInputContext.current?.handleEvent(event) ?? false
if self.hasMarkedText() {
// mark state ignore Down,Up,Left,Right,=,- etc keys
self.keyDownDone = true
}
if self.keyDownDone, cocoaHandledEvent { return }
}
let capslock = modifierFlags.contains(.capsLock)
let shift = modifierFlags.contains(.shift)
let chars = event.characters!
let charsIgnoringModifiers = shift || capslock
? event.charactersIgnoringModifiers!.lowercased()
: event.charactersIgnoringModifiers!
let flags = self.vimModifierFlags(modifierFlags) ?? ""
let isNamedKey = KeyUtils.isSpecial(key: charsIgnoringModifiers)
let isControlCode = KeyUtils.isControlCode(key: chars) && !isNamedKey
let isPlain = flags.isEmpty && !isNamedKey
let isWrapNeeded = !isControlCode && !isPlain
let namedChars = KeyUtils.namedKey(from: charsIgnoringModifiers)
let finalInput = isWrapNeeded ? self.wrapNamedKeys(flags + namedChars)
: self.vimPlainString(chars)
_ = self.api.input(keys: finalInput, errWhenBlocked: false).syncValue()
self.keyDownDone = true
}
func insertText(_ object: Any, replacementRange: NSRange) {
self.log.debug("\(object) with \(replacementRange)")
let text: String
switch object {
case let string as String: text = string
case let attributedString as NSAttributedString: text = attributedString.string
default: return
}
try? self.bridge
.deleteCharacters(0, andInputEscapedString: self.vimPlainString(text))
.wait()
if self.hasMarkedText() { self._unmarkText() }
self.keyDownDone = true
}
override func doCommand(by aSelector: Selector) {
if self.responds(to: aSelector) {
self.log.debug("calling \(aSelector)")
self.perform(aSelector, with: self)
self.keyDownDone = true
return
}
self.log.debug("\(aSelector) not implemented, forwarding input to neovim")
self.keyDownDone = false
}
override func performKeyEquivalent(with event: NSEvent) -> Bool {
if event.type != .keyDown { return false }
// Cocoa first calls this method to ask whether a subview implements the key equivalent
// in question. For example, if we have ⌘-. as shortcut for a menu item, which is the case
// for "Tools -> Focus Neovim View" by default, at some point in the event processing chain
// this method will be called. If we want to forward the event to Neovim because the user
// could have set it for some action, that menu item shortcut will not work. To work around
// this, we ask NvimViewDelegate whether the event is a shortcut of a menu item. The delegate
// has to be implemented by the user of NvimView.
if self.delegate?.isMenuItemKeyEquivalent(event) == true { return false }
let flags = event.modifierFlags.intersection(.deviceIndependentFlagsMask)
// Emoji menu: Cmd-Ctrl-Space
if flags.contains([.command, .control]), event.keyCode == spaceKeyChar { return false }
// <C-Tab> & <C-S-Tab> do not trigger keyDown events.
// Catch the key event here and pass it to keyDown.
// By rogual in NeoVim dot app:
// https://github.com/rogual/neovim-dot-app/pull/248/files
if flags.contains(.control), event.keyCode == 48 {
self.keyDown(with: event)
return true
}
// Space key (especially in combination with modifiers) can result in
// unexpected chars (e.g. ctrl-space = \0), so catch the event early and
// pass it to keyDown.
if event.keyCode == spaceKeyChar {
self.keyDown(with: event)
return true
}
// <D-.> do not trigger keyDown event.
if flags.contains(.command), event.keyCode == 47 {
self.keyDown(with: event)
return true
}
guard let chars = event.characters else { return false }
// Control code \0 causes rpc parsing problems.
// So we escape as early as possible
if chars == "\0" {
self.api
.input(keys: self.wrapNamedKeys("Nul"), errWhenBlocked: false)
.subscribe(onFailure: { [weak self] error in
self?.log.error("Error in \(#function): \(error)")
})
.disposed(by: self.disposeBag)
return true
}
// For the following two conditions:
// See special cases in vim/os_win32.c from vim sources
// Also mentioned in MacVim's KeyBindings.plist
if flags == .control, chars == "6" {
self.api
.input(keys: "\u{1e}", errWhenBlocked: false) // AKA ^^
.subscribe(onFailure: { [weak self] error in
self?.log.error("Error in \(#function): \(error)")
})
.disposed(by: self.disposeBag)
return true
}
if flags == .control, chars == "2" {
// <C-2> should generate \0, escaping as above
self.api
.input(keys: self.wrapNamedKeys("Nul"), errWhenBlocked: false)
.subscribe(onFailure: { [weak self] error in
self?.log.error("Error in \(#function): \(error)")
})
.disposed(by: self.disposeBag)
return true
}
// NSEvent already sets \u{1f} for <C--> && <C-_>
return false
}
func setMarkedText(_ object: Any, selectedRange: NSRange, replacementRange: NSRange) {
self.log.debug(
"object: \(object), selectedRange: \(selectedRange), replacementRange: \(replacementRange)"
)
defer { self.keyDownDone = true }
switch object {
case let string as String: self.markedText = string
case let attributedString as NSAttributedString: self.markedText = attributedString.string
default: self.markedText = String(describing: object) // should not occur
}
if replacementRange != .notFound {
guard self.ugrid.firstPosition(fromFlatCharIndex: replacementRange.location) != nil
else { return }
// FIXME: here not validate location, only delete by length.
// after delete, cusor should be the location
}
if replacementRange.length > 0 {
try? self.bridge
.deleteCharacters(replacementRange.length, andInputEscapedString: "")
.wait()
}
// delay to wait async gui update handled.
// this avoid insert and then delete flicker
// the markedPosition is not needed since marked Text should always following cursor..
DispatchQueue.main.async { [self, markedText] in
ugrid.updateMark(markedText: markedText!, selectedRange: selectedRange)
markForRender(region: regionForRow(at: ugrid.cursorPosition))
}
self.keyDownDone = true
}
func unmarkText() {
self._unmarkText()
self.keyDownDone = true
}
func _unmarkText() {
guard self.hasMarkedText() else { return }
// wait inserted text gui update event, so hanji in korean get right previous string and can popup candidate window
DispatchQueue.main.async { [self] in
if let markedInfo = self.ugrid.markedInfo {
self.ugrid.markedInfo = nil
self.markForRender(region: regionForRow(at: markedInfo.position))
}
}
self.markedText = nil
}
/**
Return the current selection or the position of the cursor with empty-length
range. For example when you enter "Cmd-Ctrl-Return" you'll get the
Emoji-popup at the rect by firstRectForCharacterRange(actualRange:) where
the first range is the result of this method.
*/
func selectedRange() -> NSRange {
// When the app starts and the Hangul input method is selected,
// this method gets called very early...
guard self.ugrid.hasData else {
self.log.debug("No data in UGrid!")
return .notFound
}
let result: NSRange
result = NSRange(
location: self.ugrid.flatCharIndex(
forPosition: self.ugrid.cursorPositionWithMarkedInfo(allowOverflow: true)
),
length: 0
)
self.log.debug("Returning \(result)")
return result
}
func markedRange() -> NSRange {
guard let marked = self.markedText else {
self.log.debug("No marked text, returning not found")
return .notFound
}
let result = NSRange(
location: self.ugrid.flatCharIndex(forPosition: self.ugrid.cursorPosition),
length: marked.count
)
self.log.debug("Returning \(result)")
return result
}
func hasMarkedText() -> Bool { self.markedText != nil }
func attributedSubstring(
forProposedRange aRange: NSRange,
actualRange _: NSRangePointer?
) -> NSAttributedString? {
self.log.debug("\(aRange)")
if aRange.location == NSNotFound { return nil }
guard
let position = self.ugrid.firstPosition(fromFlatCharIndex: aRange.location),
let inclusiveEndPosition = self.ugrid.lastPosition(
fromFlatCharIndex: aRange.location + aRange.length - 1
)
else { return nil }
self.log.debug("\(position) ... \(inclusiveEndPosition)")
let string = self.ugrid.cells[position.row...inclusiveEndPosition.row]
.map { row in
row.filter { cell in
aRange.location <= cell.flatCharIndex && cell.flatCharIndex <= aRange.inclusiveEndIndex
}
}
.flatMap { $0 }
.map(\.string)
.joined()
let delta = aRange.length - string.utf16.count
if delta != 0 { self.log.debug("delta = \(delta)!") }
self.log.debug("returning '\(string)'")
return NSAttributedString(string: string)
}
func validAttributesForMarkedText() -> [NSAttributedString.Key] { [] }
func firstRect(forCharacterRange aRange: NSRange, actualRange _: NSRangePointer?) -> NSRect {
guard let position = self.ugrid.firstPosition(fromFlatCharIndex: aRange.location) else {
return CGRect.zero
}
self.log.debug("\(aRange)-> \(position.row):\(position.column)")
let resultInSelf = self.rect(forRow: position.row, column: position.column)
let result = self.window?.convertToScreen(self.convert(resultInSelf, to: nil))
return result!
}
func characterIndex(for aPoint: NSPoint) -> Int {
let position = self.position(at: aPoint)
let result = self.ugrid.flatCharIndex(forPosition: position)
self.log.debug("\(aPoint) -> \(position) -> \(result)")
return result
}
internal func vimModifierFlags(_ modifierFlags: NSEvent.ModifierFlags) -> String? {
var result = ""
let control = modifierFlags.contains(.control)
let option = modifierFlags.contains(.option)
let command = modifierFlags.contains(.command)
let shift = modifierFlags.contains(.shift)
if control { result += "C-" }
if option { result += "M-" }
if command { result += "D-" }
if shift { result += "S-" }
if result.count > 0 { return result }
return nil
}
internal func wrapNamedKeys(_ string: String) -> String { "<\(string)>" }
internal func vimPlainString(_ string: String) -> String {
string.replacingOccurrences(of: "<", with: self.wrapNamedKeys("lt"))
}
}
private let spaceKeyChar = 49
| mit | aec364c99691e54a829ba9936caff02a | 32.281525 | 119 | 0.666579 | 4.264938 | false | false | false | false |
rrunfa/StreamRun | Libraries/Alamofire/Validation.swift | 3 | 5367 | // Alamofire.swift
//
// Copyright (c) 2014–2015 Alamofire Software Foundation (http://alamofire.org/)
//
// 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
extension Request {
/**
A closure used to validate a request that takes a URL request and URL response, and returns whether the request was valid.
*/
public typealias Validation = (NSURLRequest, NSHTTPURLResponse) -> Bool
/**
Validates the request, using the specified closure.
If validation fails, subsequent calls to response handlers will have an associated error.
:param: validation A closure to validate the request.
:returns: The request.
*/
public func validate(validation: Validation) -> Self {
delegate.queue.addOperationWithBlock {
if let response = self.response where self.delegate.error == nil && !validation(self.request, response) {
self.delegate.error = NSError(domain: AlamofireErrorDomain, code: -1, userInfo: nil)
}
}
return self
}
// MARK: - Status Code
/**
Validates that the response has a status code in the specified range.
If validation fails, subsequent calls to response handlers will have an associated error.
:param: range The range of acceptable status codes.
:returns: The request.
*/
public func validate<S : SequenceType where S.Generator.Element == Int>(statusCode acceptableStatusCode: S) -> Self {
return validate { _, response in
return contains(acceptableStatusCode, response.statusCode)
}
}
// MARK: - Content-Type
private struct MIMEType {
let type: String
let subtype: String
init?(_ string: String) {
let components = string.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet()).substringToIndex(string.rangeOfString(";")?.endIndex ?? string.endIndex).componentsSeparatedByString("/")
if let type = components.first,
subtype = components.last
{
self.type = type
self.subtype = subtype
} else {
return nil
}
}
func matches(MIME: MIMEType) -> Bool {
switch (type, subtype) {
case (MIME.type, MIME.subtype), (MIME.type, "*"), ("*", MIME.subtype), ("*", "*"):
return true
default:
return false
}
}
}
/**
Validates that the response has a content type in the specified array.
If validation fails, subsequent calls to response handlers will have an associated error.
:param: contentType The acceptable content types, which may specify wildcard types and/or subtypes.
:returns: The request.
*/
public func validate<S : SequenceType where S.Generator.Element == String>(contentType acceptableContentTypes: S) -> Self {
return validate { _, response in
if let responseContentType = response.MIMEType,
responseMIMEType = MIMEType(responseContentType)
{
for contentType in acceptableContentTypes {
if let acceptableMIMEType = MIMEType(contentType)
where acceptableMIMEType.matches(responseMIMEType)
{
return true
}
}
}
return false
}
}
// MARK: - Automatic
/**
Validates that the response has a status code in the default acceptable range of 200...299, and that the content type matches any specified in the Accept HTTP header field.
If validation fails, subsequent calls to response handlers will have an associated error.
:returns: The request.
*/
public func validate() -> Self {
let acceptableStatusCodes: Range<Int> = 200..<300
let acceptableContentTypes: [String] = {
if let accept = self.request.valueForHTTPHeaderField("Accept") {
return accept.componentsSeparatedByString(",")
}
return ["*/*"]
}()
return validate(statusCode: acceptableStatusCodes).validate(contentType: acceptableContentTypes)
}
}
| mit | 88299a81c0b3eb0c1443b302e3ec79f9 | 36 | 224 | 0.639888 | 5.39196 | false | false | false | false |
EasySwift/EasySwift | Carthage/Checkouts/DKChainableAnimationKit/DKChainableAnimationKit/Classes/DKKeyFrameAnimation.swift | 2 | 10931 | //
// DKKeyFrameAnimation.swift
// DKChainableAnimationKit
//
// Created by Draveness on 15/5/13.
// Copyright (c) 2015年 Draveness. All rights reserved.
//
import UIKit
open class DKKeyFrameAnimation: CAKeyframeAnimation {
internal let kFPS = 60
internal typealias DKKeyframeAnimationFunction = (Double, Double, Double, Double) -> Double;
internal var fromValue: AnyObject!
internal var toValue: AnyObject!
internal var functionBlock: DKKeyframeAnimationFunction!
convenience init(keyPath path: String!) {
self.init()
self.keyPath = path
self.functionBlock = DKKeyframeAnimationFunctionLinear
}
internal func calculte() {
self.createValueArray()
}
internal func createValueArray() {
if let fromValue: AnyObject = self.fromValue, let toValue: AnyObject = self.toValue {
if valueIsKindOf(NSNumber.self) {
self.values = self.valueArrayFor(startValue: CGFloat(fromValue.floatValue), endValue: CGFloat(toValue.floatValue)) as [AnyObject]
} else if valueIsKindOf(UIColor.self) {
let fromColor = self.fromValue.cgColor
let toColor = self.toValue.cgColor
let fromComponents = fromColor?.components
let toComponents = toColor?.components
let redValues = self.valueArrayFor(startValue: (fromComponents?[0])!, endValue: (toComponents?[0])!) as! [CGFloat]
let greenValues = self.valueArrayFor(startValue: (fromComponents?[1])!, endValue: (toComponents?[1])!) as! [CGFloat]
let blueValues = self.valueArrayFor(startValue: (fromComponents?[2])!, endValue: (toComponents?[2])!) as! [CGFloat]
let alphaValues = self.valueArrayFor(startValue: (fromComponents?[3])!, endValue: (toComponents?[3])!) as! [CGFloat]
self.values = self.colorArrayFrom(redValues: redValues, greenValues: greenValues, blueValues: blueValues, alphaValues: alphaValues) as [AnyObject]
} else if valueIsKindOf(NSValue.self) {
let valueType: NSString! = NSString(cString: self.fromValue.objCType, encoding: 1)
if valueType.contains("CGRect") {
let fromRect = self.fromValue.cgRectValue
let toRect = self.toValue.cgRectValue
let xValues = self.valueArrayFor(startValue: (fromRect?.origin.x)!, endValue: (toRect?.origin.x)!) as! [CGFloat]
let yValues = self.valueArrayFor(startValue: (fromRect?.origin.y)!, endValue: (toRect?.origin.x)!) as! [CGFloat]
let widthValues = self.valueArrayFor(startValue: (fromRect?.size.width)!, endValue: (toRect?.size.width)!) as! [CGFloat]
let heightValues = self.valueArrayFor(startValue: (fromRect?.size.height)!, endValue: (toRect?.size.height)!) as! [CGFloat]
self.values = self.rectArrayFrom(xValues: xValues, yValues: yValues, widthValues: widthValues, heightValues: heightValues) as [AnyObject]
} else if valueType.contains("CGPoint") {
let fromPoint = self.fromValue.cgPointValue
let toPoint = self.toValue.cgPointValue
let path = self.createPathFromXYValues(self.valueArrayFor(startValue: (fromPoint?.x)!, endValue: (toPoint?.x)!), yValues: self.valueArrayFor(startValue: (fromPoint?.y)!, endValue: (toPoint?.y)!))
self.path = path
} else if valueType.contains("CGSize") {
let fromSize = self.fromValue.cgSizeValue
let toSize = self.toValue.cgSizeValue
let path = self.createPathFromXYValues(self.valueArrayFor(startValue: (fromSize?.width)!, endValue: (toSize?.width)!), yValues: self.valueArrayFor(startValue: (fromSize?.height)!, endValue: (toSize?.height)!))
self.path = path
} else if valueType.contains("CATransform3D") {
let fromTransform = self.fromValue.caTransform3DValue
let toTransform = self.toValue.caTransform3DValue
let m11 = self.valueArrayFor(startValue: (fromTransform?.m11)!, endValue: (toTransform?.m11)!)
let m12 = self.valueArrayFor(startValue: (fromTransform?.m12)!, endValue: (toTransform?.m12)!)
let m13 = self.valueArrayFor(startValue: (fromTransform?.m13)!, endValue: (toTransform?.m13)!)
let m14 = self.valueArrayFor(startValue: (fromTransform?.m14)!, endValue: (toTransform?.m14)!)
let m21 = self.valueArrayFor(startValue: (fromTransform?.m21)!, endValue: (toTransform?.m21)!)
let m22 = self.valueArrayFor(startValue: (fromTransform?.m22)!, endValue: (toTransform?.m22)!)
let m23 = self.valueArrayFor(startValue: (fromTransform?.m23)!, endValue: (toTransform?.m23)!)
let m24 = self.valueArrayFor(startValue: (fromTransform?.m24)!, endValue: (toTransform?.m24)!)
let m31 = self.valueArrayFor(startValue: (fromTransform?.m31)!, endValue: (toTransform?.m31)!)
let m32 = self.valueArrayFor(startValue: (fromTransform?.m32)!, endValue: (toTransform?.m32)!)
let m33 = self.valueArrayFor(startValue: (fromTransform?.m33)!, endValue: (toTransform?.m33)!)
let m34 = self.valueArrayFor(startValue: (fromTransform?.m34)!, endValue: (toTransform?.m34)!)
let m41 = self.valueArrayFor(startValue: (fromTransform?.m41)!, endValue: (toTransform?.m41)!)
let m42 = self.valueArrayFor(startValue: (fromTransform?.m42)!, endValue: (toTransform?.m42)!)
let m43 = self.valueArrayFor(startValue: (fromTransform?.m43)!, endValue: (toTransform?.m43)!)
let m44 = self.valueArrayFor(startValue: (fromTransform?.m44)!, endValue: (toTransform?.m44)!)
self.values = self.createTransformArrayFrom(
m11: m11, m12: m12, m13: m13, m14: m14,
m21: m21, m22: m22, m23: m23, m24: m24,
m31: m31, m32: m32, m33: m33, m34: m34,
m41: m41, m42: m42, m43: m43, m44: m44) as [AnyObject]
}
}
self.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionLinear)
}
}
fileprivate func createTransformArrayFrom(
m11: NSArray, m12: NSArray, m13: NSArray, m14: NSArray,
m21: NSArray, m22: NSArray, m23: NSArray, m24: NSArray,
m31: NSArray, m32: NSArray, m33: NSArray, m34: NSArray,
m41: NSArray, m42: NSArray, m43: NSArray, m44: NSArray) -> NSArray {
let numberOfTransforms = m11.count;
let values = NSMutableArray(capacity: numberOfTransforms)
var value: CATransform3D!
for i in 0..<numberOfTransforms {
value = CATransform3DIdentity;
value.m11 = CGFloat((m11.object(at: i) as AnyObject).floatValue)
value.m12 = CGFloat((m12.object(at: i) as AnyObject).floatValue)
value.m13 = CGFloat((m13.object(at: i) as AnyObject).floatValue)
value.m14 = CGFloat((m14.object(at: i) as AnyObject).floatValue)
value.m21 = CGFloat((m21.object(at: i) as AnyObject).floatValue)
value.m22 = CGFloat((m22.object(at: i) as AnyObject).floatValue)
value.m23 = CGFloat((m23.object(at: i) as AnyObject).floatValue)
value.m24 = CGFloat((m24.object(at: i) as AnyObject).floatValue)
value.m31 = CGFloat((m31.object(at: i) as AnyObject).floatValue)
value.m32 = CGFloat((m32.object(at: i) as AnyObject).floatValue)
value.m33 = CGFloat((m33.object(at: i) as AnyObject).floatValue)
value.m44 = CGFloat((m34.object(at: i) as AnyObject).floatValue)
value.m41 = CGFloat((m41.object(at: i) as AnyObject).floatValue)
value.m42 = CGFloat((m42.object(at: i) as AnyObject).floatValue)
value.m43 = CGFloat((m43.object(at: i) as AnyObject).floatValue)
value.m44 = CGFloat((m44.object(at: i) as AnyObject).floatValue)
values.add(NSValue(caTransform3D: value))
}
return values
}
fileprivate func createPathFromXYValues(_ xValues: NSArray, yValues: NSArray) -> CGPath {
let numberOfPoints = xValues.count
let path = CGMutablePath()
var value = CGPoint(
x: CGFloat((xValues.object(at: 0) as AnyObject).floatValue),
y: CGFloat((yValues.object(at: 0) as AnyObject).floatValue))
path.move(to: value)
for i in 1..<numberOfPoints {
value = CGPoint(
x: CGFloat((xValues.object(at: i) as AnyObject).floatValue),
y: CGFloat((yValues.object(at: i) as AnyObject).floatValue))
path.move(to: value)
}
return path
}
fileprivate func valueIsKindOf(_ klass: AnyClass) -> Bool {
return self.fromValue.isKind(of: klass) && self.toValue.isKind(of: klass)
}
fileprivate func rectArrayFrom(xValues: [CGFloat], yValues: [CGFloat], widthValues: [CGFloat], heightValues: [CGFloat]) -> NSArray {
let numberOfRects = xValues.count
let values: NSMutableArray = []
var value: NSValue
for i in 1..<numberOfRects {
value = NSValue(cgRect: CGRect(x: xValues[i], y: yValues[i], width: widthValues[i], height: heightValues[i]))
values.add(value)
}
return values
}
fileprivate func colorArrayFrom(redValues: [CGFloat], greenValues: [CGFloat], blueValues: [CGFloat], alphaValues: [CGFloat]) -> [CGColor] {
let numberOfColors = redValues.count
var values: [CGColor] = []
var value: CGColor!
for i in 1..<numberOfColors {
value = UIColor(red: redValues[i], green: greenValues[i], blue: blueValues[i], alpha: alphaValues[i]).cgColor
values.append(value)
}
return values
}
fileprivate func valueArrayFor(startValue: CGFloat, endValue: CGFloat) -> NSArray {
let startValue = Double(startValue)
let endValue = Double(endValue)
let steps: Int = Int(ceil(Double(kFPS) * self.duration)) + 2
let increment = 1.0 / (Double)(steps - 1)
var progress = 0.0
var v = 0.0
var value = 0.0
var valueArray: [Double] = []
for _ in 0..<steps {
v = self.functionBlock(self.duration * progress * 1000, 0, 1, self.duration * 1000);
value = startValue + v * (endValue - startValue);
valueArray.append(value)
progress += increment
}
return valueArray as NSArray
}
}
| apache-2.0 | 1535ab3e00514c0d2295844e934139e2 | 52.312195 | 229 | 0.609388 | 4.493832 | false | false | false | false |
quickthyme/PUTcat | PUTcat/Application/Data/Variable/Entity/PCVariable.swift | 1 | 1316 |
import Foundation
final class PCVariable : PCItem, PCValueItem, PCCopyable, PCLocal {
var id: String
var name: String
var value: String
init(id: String, name: String, value: String) {
self.id = id
self.name = name
self.value = value
}
convenience init(name: String, value: String) {
self.init(id: UUID().uuidString, name: name, value: value)
}
convenience init(name: String) {
self.init(name: name, value: "Value")
}
convenience init() {
self.init(name: "New Variable")
}
required convenience init(copy: PCVariable) {
self.init(name: copy.name, value: copy.value)
}
required init(fromLocal: [String:Any]) {
self.id = fromLocal["id"] as? String ?? ""
self.name = fromLocal["name"] as? String ?? ""
self.value = Base64.decode(fromLocal["value"] as? String ?? "")
}
func toLocal() -> [String:Any] {
return [
"id" : self.id,
"name" : self.name,
"value": Base64.encode(self.value)
]
}
}
extension PCVariable : PCLocalExport {
func toLocalExport() -> [String:Any] {
return self.toLocal()
}
}
struct PCParsedVariable {
var id: String
var name: String
var value: String
}
| apache-2.0 | 393bcb83b27f315e4bde5c8f570e7a10 | 22.5 | 71 | 0.567629 | 3.696629 | false | false | false | false |
ahmadbaraka/SwiftLayoutConstraints | Example/Tests/OrSpec.swift | 1 | 3112 | //
// OrSpec.swift
// SwiftLayoutConstraints
//
// Created by Ahmad Baraka on 7/22/16.
// Copyright © 2016 CocoaPods. All rights reserved.
//
import Nimble
import Quick
@testable import SwiftLayoutConstraints
class OrSpec: QuickSpec {
override func spec() {
var view: UIView!
beforeEach {
view = UIView()
}
describe("two") {
it("should add same LhsLayoutConstraint") {
let constraint = LhsLayoutConstraint(view, attribute: .Top)
let array: [LhsLayoutConstraint<UIView>] = constraint | .Bottom
expect(array.count) == 2
expect(array[1].object) == view
expect(array[1].attribute) == NSLayoutAttribute.Bottom
expect(array[1].constant) == DefaultConsant
expect(array[1].multiplier) == DefaultMultiplier
}
it("should add same RhsLayoutConstraint") {
let constraint = RhsLayoutConstraint(view, attribute: .Top, constant: 50, multiplier: 0.5)
let array: [RhsLayoutConstraint<UIView>] = constraint | .Bottom
expect(array.count) == 2
expect(array[1].object) == view
expect(array[1].attribute) == NSLayoutAttribute.Bottom
expect(array[1].constant) == 50
expect(array[1].multiplier) == 0.5
}
}
it("should add multi constraints") {
let constraint = LhsLayoutConstraint(view, attribute: .Top)
let array: [LhsLayoutConstraint<UIView>] = constraint | .Bottom | .Left
expect(array.count) == 3
expect(array[1].object) == view
expect(array[1].attribute) == NSLayoutAttribute.Bottom
expect(array[2].object) == view
expect(array[2].attribute) == NSLayoutAttribute.Left
}
it("should add mixed constraints") {
let con1 = LhsLayoutConstraint(view, attribute: .Top)
let con2 = RhsLayoutConstraint(view, attribute: .Left, constant: 50, multiplier: 0.5)
let array: [RhsLayoutConstraint<UIView>] = con1 | con2 | .Bottom
expect(array.count) == 3
expect(array[0].object) == view
expect(array[0].attribute) == NSLayoutAttribute.Top
expect(array[0].constant) == DefaultConsant
expect(array[0].multiplier) == DefaultMultiplier
expect(array[1].object) == view
expect(array[1].attribute) == NSLayoutAttribute.Left
expect(array[1].constant) == 50
expect(array[1].multiplier) == 0.5
expect(array[2].object) == view
expect(array[2].attribute) == NSLayoutAttribute.Bottom
expect(array[2].constant) == 50
expect(array[2].multiplier) == 0.5
}
}
}
| mit | a543339f73f82d622f6cda5a04bc1fb5 | 35.174419 | 106 | 0.526519 | 4.945946 | false | false | false | false |
hipposan/Oslo | Oslo/ExifView.swift | 1 | 1556 | //
// ExifView.swift
// Oslo
//
// Created by hippo_san on 19/11/2016.
// Copyright © 2016 Ziyideas. All rights reserved.
//
import UIKit
class ExifView: UIView {
@IBOutlet var createdTimeTitleLabel: UILabel! {
didSet {
createdTimeTitleLabel.text = localize(with: "Published")
}
}
@IBOutlet weak var createdTimeLabel: UILabel!
@IBOutlet var dimensionTitleLabel: UILabel! {
didSet {
dimensionTitleLabel.text = localize(with: "Dimensions")
}
}
@IBOutlet weak var dimensionsLabel: UILabel!
@IBOutlet var makeTitleLabel: UILabel! {
didSet {
makeTitleLabel.text = localize(with: "Camera Make")
}
}
@IBOutlet weak var makeLabel: UILabel!
@IBOutlet var modelTitleLabel: UILabel! {
didSet {
modelTitleLabel.text = localize(with: "Camera Model")
}
}
@IBOutlet weak var modelLabel: UILabel!
@IBOutlet var apertureTitleLabel: UILabel! {
didSet {
apertureTitleLabel.text = localize(with: "Aperture")
}
}
@IBOutlet weak var apertureLabel: UILabel!
@IBOutlet var exposureTitleLabel: UILabel! {
didSet {
exposureTitleLabel.text = localize(with: "Exposure Time")
}
}
@IBOutlet weak var exposureTimeLabel: UILabel!
@IBOutlet var focalTitleLabel: UILabel! {
didSet {
focalTitleLabel.text = localize(with: "Focal Length")
}
}
@IBOutlet weak var focalLengthLabel: UILabel!
@IBOutlet var isoTitleLabel: UILabel! {
didSet {
isoTitleLabel.text = localize(with: "ISO")
}
}
@IBOutlet weak var isoLabel: UILabel!
}
| mit | b3b26e439536a08e5ee9887c0f57aace | 24.916667 | 63 | 0.676527 | 4.028497 | false | false | false | false |
hooman/swift | test/Sema/generalized_accessors_availability.swift | 13 | 5346 | // RUN: %empty-directory(%t)
// RUN: %target-swift-frontend -target %target-cpu-apple-macosx10.9 -typecheck -verify %s
// REQUIRES: OS=macosx
@propertyWrapper
struct SetterConditionallyAvailable<T> {
var wrappedValue: T {
get { fatalError() }
@available(macOS 10.10, *)
set { fatalError() }
}
var projectedValue: T {
get { fatalError() }
@available(macOS 10.10, *)
set { fatalError() }
}
}
@propertyWrapper
struct ModifyConditionallyAvailable<T> {
var wrappedValue: T {
get { fatalError() }
@available(macOS 10.10, *)
_modify { fatalError() }
}
var projectedValue: T {
get { fatalError() }
@available(macOS 10.10, *)
_modify { fatalError() }
}
}
struct Butt {
var modify_conditionally_available: Int {
get { fatalError() }
@available(macOS 10.10, *)
_modify { fatalError() }
}
@SetterConditionallyAvailable
var wrapped_setter_conditionally_available: Int
@ModifyConditionallyAvailable
var wrapped_modify_conditionally_available: Int
}
func butt(x: inout Butt) { // expected-note*{{}}
x.modify_conditionally_available = 0 // expected-error{{only available in macOS 10.10 or newer}} expected-note{{}}
x.wrapped_setter_conditionally_available = 0 // expected-error{{only available in macOS 10.10 or newer}} expected-note{{}}
x.wrapped_modify_conditionally_available = 0 // expected-error{{only available in macOS 10.10 or newer}} expected-note{{}}
x.$wrapped_setter_conditionally_available = 0 // expected-error{{only available in macOS 10.10 or newer}} expected-note{{}}
x.$wrapped_modify_conditionally_available = 0 // expected-error{{only available in macOS 10.10 or newer}} expected-note{{}}
if #available(macOS 10.10, *) {
x.modify_conditionally_available = 0
x.wrapped_setter_conditionally_available = 0
x.wrapped_modify_conditionally_available = 0
x.$wrapped_setter_conditionally_available = 0
x.$wrapped_modify_conditionally_available = 0
}
}
@available(macOS 11.0, *)
struct LessAvailable {
@SetterConditionallyAvailable
var wrapped_setter_more_available: Int
@ModifyConditionallyAvailable
var wrapped_modify_more_available: Int
var nested: Nested
struct Nested {
@SetterConditionallyAvailable
var wrapped_setter_more_available: Int
@ModifyConditionallyAvailable
var wrapped_modify_more_available: Int
}
}
func testInferredAvailability(x: inout LessAvailable) { // expected-error {{'LessAvailable' is only available in macOS 11.0 or newer}} expected-note*{{}}
x.wrapped_setter_more_available = 0 // expected-error {{setter for 'wrapped_setter_more_available' is only available in macOS 11.0 or newer}} expected-note{{}}
x.wrapped_modify_more_available = 0 // expected-error {{setter for 'wrapped_modify_more_available' is only available in macOS 11.0 or newer}} expected-note{{}}
x.$wrapped_setter_more_available = 0 // expected-error {{setter for '$wrapped_setter_more_available' is only available in macOS 11.0 or newer}} expected-note{{}}
x.$wrapped_modify_more_available = 0 // expected-error {{setter for '$wrapped_modify_more_available' is only available in macOS 11.0 or newer}} expected-note{{}}
x.nested.wrapped_setter_more_available = 0 // expected-error {{setter for 'wrapped_setter_more_available' is only available in macOS 11.0 or newer}} expected-note{{}}
x.nested.wrapped_modify_more_available = 0 // expected-error {{setter for 'wrapped_modify_more_available' is only available in macOS 11.0 or newer}} expected-note{{}}
x.nested.$wrapped_setter_more_available = 0 // expected-error {{setter for '$wrapped_setter_more_available' is only available in macOS 11.0 or newer}} expected-note{{}}
x.nested.$wrapped_modify_more_available = 0 // expected-error {{setter for '$wrapped_modify_more_available' is only available in macOS 11.0 or newer}} expected-note{{}}
if #available(macOS 11.0, *) {
x.wrapped_setter_more_available = 0
x.wrapped_modify_more_available = 0
x.$wrapped_setter_more_available = 0
x.$wrapped_modify_more_available = 0
x.nested.wrapped_setter_more_available = 0
x.nested.wrapped_modify_more_available = 0
x.nested.$wrapped_setter_more_available = 0
x.nested.$wrapped_modify_more_available = 0
}
}
@propertyWrapper
struct Observable<Value> {
private var stored: Value
init(wrappedValue: Value) { self.stored = wrappedValue }
@available(*, unavailable)
var wrappedValue: Value {
get { fatalError() }
set { fatalError() }
}
static subscript<EnclosingSelf>(
_enclosingInstance observed: EnclosingSelf,
wrapped wrappedKeyPath: ReferenceWritableKeyPath<EnclosingSelf, Value>,
storage storageKeyPath: ReferenceWritableKeyPath<EnclosingSelf, Self>
) -> Value {
get { observed[keyPath: storageKeyPath].stored }
set { observed[keyPath: storageKeyPath].stored = newValue }
}
}
protocol P {}
class Base<T: P> {
@Observable var item: T?
}
struct Item: P {}
class Subclass: Base<Item> {
// Make sure this override isn't incorrectly diagnosed as
// unavailable. Wrapper availability inference should infer
// availability from the static subscript in this case.
override var item: Item? {
didSet {}
}
}
| apache-2.0 | 7b0144127a21ecb337566df15a979819 | 34.403974 | 170 | 0.695473 | 4.007496 | false | false | false | false |
team-pie/DDDKit | DDDKit/Classes/DDDNode.swift | 1 | 4373 | //
// DDDNode.swift
// DDDKit
//
// Created by Guillaume Sabran on 9/27/16.
// Copyright © 2016 Guillaume Sabran. All rights reserved.
//
import Foundation
import GLKit
import GLMatrix
public enum DDDError: Error {
case programNotSetUp
case geometryNotSetUp
case shaderFailedToCompile
case programFailedToLink
}
/**
An element that can be put in a 3d scene
*/
public class DDDNode {
/// The node position from the origin
public var position: Vec3 = Vec3.Zero()
/// The node rotation, in quaternion, from the camera orientation
public var rotation = Quat.fromValues(x: 0, y: 0, z: 0, w: 1)
/// Describes the shape of the node, and how texture are mapped on that shape
public var geometry: DDDGeometry?
/// Describes attributes related to the node's visual aspect
public let material = DDDMaterial()
public init() {
DDDNode.id += 1
self.id = DDDNode.id.hashValue
}
private static var id: Int = 0
fileprivate let id: Int
private let _modelView = Mat4.Identity()
var modelView: Mat4 {
Mat4.fromQuat(q: rotation, andOutputTo: _modelView)
_modelView.translate(by: position)
return _modelView
}
private var hasSetup = false
/**
Ensure the node has loaded its properties
- Parameter context: the current EAGL context in which the drawing will occur
*/
func setUpIfNotAlready(context: EAGLContext) throws {
if hasSetup { return }
}
/**
Prepare the node to be rendered
- Parameter context: the current EAGL context in which the drawing will occur
*/
func willRender(context: EAGLContext) throws {
guard let _ = geometry, let _ = material.shaderProgram else {
throw DDDError.programNotSetUp
}
try setUpIfNotAlready(context: context)
material.properties.forEach { $0.property.willBeUsedAtNextDraw = true }
}
/**
Draw the node
- Parameter with: the projection that should be used
- Parameter pool: the pool of texture slots where texture can be attached
- Return: wether scene computation should restart
*/
func render(with projection: Mat4, pool: DDDTexturePool) -> RenderingResult {
guard let program = material.shaderProgram else { return .notReady }
for prop in material.properties {
let isReady = prop.property.prepareToBeUsed(in: pool)
if isReady != .ok {
return isReady
}
}
material.properties.forEach { prop in
let location = prop.location ?? program.indexFor(uniformNamed: prop.locationName)
if location != -1 {
prop.location = location
prop.property.attach(at: location)
}
}
var shouldDraw = true
material.properties.forEach { prop in
if !prop.property.isReadyToBeUsed() && prop.property.isActive {
shouldDraw = false
}
}
guard shouldDraw else { return .notReady }
material.set(mat4: GLKMatrix4(projection), for: "u_projection")
material.set(mat4: GLKMatrix4(modelView), for: "u_modelview")
let vertexBufferOffset = UnsafeRawPointer(bitPattern: 0)
guard let geometry = geometry else { return .notReady }
geometry.setUpIfNotAlready(for: program)
geometry.prepareToUse()
glDrawElements(GLenum(GL_TRIANGLES), GLsizei(geometry.indices.count), GLenum(GL_UNSIGNED_SHORT), vertexBufferOffset);
return .ok
}
/**
Signal that the node rendering is done. Used to reset some temporary states
*/
func didRender() {
material.properties.forEach { $0.property.willBeUsedAtNextDraw = false }
}
func reset() {
hasSetup = false
geometry?.reset()
material.reset()
}
}
extension DDDNode: Equatable {
public static func ==(lhs: DDDNode, rhs: DDDNode) -> Bool {
return lhs === rhs
}
}
extension DDDNode: Hashable {
public var hashValue: Int {
return id
}
}
// movement
extension DDDNode {
// rotations
public func rotateX(by rad: GLfloat) {
rotate(by: Quat(x: sin(rad), y: 0, z: 0, w: cos(rad)))
}
public func rotateY(by rad: GLfloat) {
rotate(by: Quat(x: 0, y: sin(rad), z: 0, w: cos(rad)))
}
public func rotateZ(by rad: GLfloat) {
rotate(by: Quat(x: 0, y: 0, z: sin(rad), w: cos(rad)))
}
public func rotate(by quat: Quat) {
rotation.multiply(with: quat)
}
// translations
public func translateX(by x: GLfloat) {
translate(by: Vec3(v: (x, 0, 0)))
}
public func translateY(by y: GLfloat) {
translate(by: Vec3(v: (0, y, 0)))
}
public func translateZ(by z: GLfloat) {
translate(by: Vec3(v: (0, 0, z)))
}
public func translate(by v: Vec3) {
position.add(v)
}
}
| mit | 1503bf3d702509cad4f4ae64c5ec9bd6 | 23.288889 | 119 | 0.702425 | 3.334859 | false | false | false | false |
Rapid-SDK/ios | Examples/RapiChat - Chat client/RapiChat macOS/MessageCellView.swift | 1 | 1723 | //
// MessageCellView.swift
// RapiChat
//
// Created by Jan on 29/06/2017.
// Copyright © 2017 Rapid. All rights reserved.
//
import Cocoa
class MessageCellView: NSTableCellView {
static let textFont = NSFont.systemFont(ofSize: 14)
@IBOutlet weak var senderLabel: NSTextField! {
didSet {
senderLabel.font = NSFont.boldSystemFont(ofSize: 12)
}
}
@IBOutlet weak var messageTextLabel: NSTextField! {
didSet {
messageTextLabel.font = MessageCellView.textFont
messageTextLabel.textColor = .appText
messageTextLabel.usesSingleLineMode = false
}
}
@IBOutlet weak var timeLabel: NSTextField! {
didSet {
timeLabel.font = NSFont.systemFont(ofSize: 12)
timeLabel.textColor = .appText
}
}
lazy var dateFormatter: DateFormatter = {
let formatter = DateFormatter()
return formatter
}()
func updateDateFormatterStyleWithDate(_ date: Date) {
if (date as NSDate).isToday() {
dateFormatter.dateStyle = .none
dateFormatter.timeStyle = .short
}
else {
dateFormatter.dateStyle = .short
dateFormatter.timeStyle = .short
}
}
func configure(withMessage message: Message) {
senderLabel.textColor = message.isMyMessage ? NSColor.appRed : .appBlue
senderLabel.stringValue = message.sender
messageTextLabel.stringValue = message.text ?? ""
updateDateFormatterStyleWithDate(message.sentDate)
timeLabel.stringValue = dateFormatter.string(from: message.sentDate)
}
}
| mit | da4cebf50bf6a890be90bb6e05f75cfb | 26.333333 | 79 | 0.607433 | 5.171171 | false | false | false | false |
ishaq/ContactsImporter | ContactsImporter/Libs/TwitterContactsImporter.swift | 1 | 4594 | //
// TwitterContactsImporter.swift
// ContactsImporter
//
// Created by Muhammad Ishaq on 10/10/2014.
// Copyright (c) 2014 Kahaf. All rights reserved.
//
import UIKit
import Social
enum TwitterErrorCodes: Int {
case NoAccountsFound = 1
}
// fetches all the followers of a user
class TwitterContactsImporter {
private var accountStore: ACAccountStore = ACAccountStore()
private var contacts = Array<Contact>()
private var callback: ((contacts: Array<Contact>, error: NSError!) -> Void)! = nil
func importContacts(callback: ((contacts: Array<Contact>, error: NSError!) -> Void)) {
self.callback = callback
let twitterAccountType = self.accountStore.accountTypeWithAccountTypeIdentifier(ACAccountTypeIdentifierTwitter)
self.accountStore.requestAccessToAccountsWithType(twitterAccountType, options: nil) { (accessGranted: Bool, error: NSError!) -> Void in
if accessGranted {
let twitterAccounts = self.accountStore.accountsWithAccountType(twitterAccountType)
if(twitterAccounts.count == 0) {
let code = TwitterErrorCodes.NoAccountsFound.rawValue
let error = NSError(domain: "com.kahaf.ContactsImporter.errors", code: code, userInfo: [NSLocalizedDescriptionKey: "No Twitter Accounts Found, Please sign in to twitter in your iPhone Settings"])
self.callback(contacts: Array<Contact>(), error: error)
return
}
let url = NSURL(string: "https://api.twitter.com/1.1/followers/list.json")
let twitterAccount = twitterAccounts.last as ACAccount
// NOTE: all params are strings because SLRequest does not accept any other parameter type
let params = ["screen_name": twitterAccount.username, "count": "200", "skip_status": "true"]
let request = SLRequest(forServiceType: SLServiceTypeTwitter, requestMethod: SLRequestMethod.GET, URL: url, parameters: params)
request.account = twitterAccount
self.contacts = Array<Contact>()
request.performRequestWithHandler(self.userLookupCallback)
}
}
}
func userLookupCallback(data: NSData!, response: NSHTTPURLResponse!, error: NSError!) {
if(error != nil) {
// show error alert?
self.callback(contacts: self.contacts, error: error)
return
}
if data == nil {
self.callback(contacts: self.contacts, error: nil)
return
}
let json = JSON(data: data)
if let errors = json["errors"].array {
println("errors: \(errors)")
println("\(self.contacts)")
// TODO: pass error object
self.callback(contacts: self.contacts, error: nil)
return
}
let users = json["users"].arrayValue
for u in users {
var name = u["name"].stringValue
if(name == "") {
name = u["screen_name"].stringValue
}
let twitterId = u["id_str"].stringValue
let c = Contact(name: name)
c.twitterId = twitterId
c.imageURL = u["profile_image_url"].stringValue
self.contacts.append(c)
}
let nextCursor = json["next_cursor"].integerValue
if(nextCursor != 0) {
let url = NSURL(string: "https://api.twitter.com/1.1/followers/list.json")
let twitterAccountType = self.accountStore.accountTypeWithAccountTypeIdentifier(ACAccountTypeIdentifierTwitter)
let twitterAccounts = self.accountStore.accountsWithAccountType(twitterAccountType)
let twitterAccount = twitterAccounts.last as ACAccount
// NOTE: all params are strings because SLRequest does not accept any other parameter type
let params = ["screen_name": twitterAccount.username, "count": "200", "skip_status": "true", "cursor": "\(nextCursor)"]
let request = SLRequest(forServiceType: SLServiceTypeTwitter, requestMethod: SLRequestMethod.GET, URL: url, parameters: params)
request.account = twitterAccount
request.performRequestWithHandler(self.userLookupCallback)
}
else {
self.callback(contacts: self.contacts, error: nil)
}
}
}
| cc0-1.0 | 9b4ee4cbc4146849073af3257a3692ed | 40.763636 | 215 | 0.599478 | 5.167604 | false | false | false | false |
Luissoo/Transporter | Transporter/TPCommon.swift | 1 | 2299 | //
// TPCommon.swift
// Example
//
// Created by Le VanNghia on 3/26/15.
// Copyright (c) 2015 Le VanNghia. All rights reserved.
//
import Foundation
// TODO
/*
- completionHander
- uploading
- downloading
- group
*/
public enum TPMethod : String {
case GET = "GET"
case POST = "POST"
case PUT = "PUT"
}
public typealias ProgressHandler = (completedBytes: Int64, totalBytes: Int64) -> ()
public typealias CompletionHandler = (tasks: [TPTransferTask]) -> ()
public typealias TransferCompletionHandler = (response: NSHTTPURLResponse?, json: AnyObject?, error: NSError?) -> ()
infix operator --> { associativity left precedence 160 }
public func --> (left: TPTransferTask, right: TPTransferTask) -> TPTaskGroup {
return TPTaskGroup(left: left, right: right, mode: .Serialization)
}
public func --> (left: TPTaskGroup, right: TPTransferTask) -> TPTaskGroup {
return left.append(right)
}
infix operator ||| { associativity left precedence 160 }
public func ||| (left: TPTransferTask, right: TPTransferTask) -> TPTaskGroup {
return TPTaskGroup(left: left, right: right, mode: .Concurrency)
}
public func ||| (left: TPTaskGroup, right: TPTransferTask) -> TPTaskGroup {
return left.append(right)
}
// http boby builder
func queryStringFromParams(params: [String: AnyObject]) -> String {
let paramsArray = convertParamsToArray(params)
let queryString = paramsArray.map{ "\($0)=\($1)" }.joinWithSeparator("&")
return queryString.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)!
}
func convertParamsToArray(params: [String: AnyObject]) -> [(String, AnyObject)] {
var result = [(String, AnyObject)]()
for (key, value) in params {
if let arrayValue = value as? NSArray {
for nestedValue in arrayValue {
let dic = ["\(key)[]": nestedValue]
result += convertParamsToArray(dic)
}
}
else if let dicValue = value as? NSDictionary {
for (nestedKey, nestedValue) in dicValue {
let dic = ["\(key)[\(nestedKey)]": nestedValue]
result += convertParamsToArray(dic)
}
}
else {
result.append(("\(key)", value))
}
}
return result
} | mit | 46bfa5640067b8197d4489b2e5501c04 | 28.113924 | 116 | 0.638104 | 4.421154 | false | false | false | false |
MrLSPBoy/LSPDouYu | LSPDouYuTV/LSPDouYuTV/NetworkTools.swift | 1 | 978 | //
// NetworkTools.swift
// AlamofireTest
//
// Created by lishaopeng on 17/3/1.
// Copyright © 2017年 lishaopeng. All rights reserved.
//
import UIKit
import Alamofire
enum MethodType {
case GET
case POST
}
class NetworkTools {
class func requestData(_ type : MethodType, URLString : String, parameters : [String : Any]? = nil, finishedCallback : @escaping (_ result : Any) -> ()) {
// 1.获取类型
let method = type == .GET ? HTTPMethod.get : HTTPMethod.post
// 2.发送网络请求
Alamofire.request(URLString, method: method, parameters: parameters).responseJSON { (response) in
// 3.获取结果
guard let result = response.result.value else {
print(response.result.error ?? "网络请求失败")
return
}
// 4.将结果回调出去
finishedCallback(result)
}
}
}
| mit | 80c2adfaa01aeca1012f02d3c5f7b07c | 23.891892 | 159 | 0.558089 | 4.492683 | false | false | false | false |
andresilvagomez/Localize | Source/LocalizeStatic.swift | 2 | 4062 | //
// LocalizeStatic.swift
// Localize
//
// Copyright © 2019 @andresilvagomez.
//
import Foundation
extension Localize {
/// Show all aviable languajes whit criteria name
///
/// - returns: list with storaged languages code
public static var availableLanguages: [String] {
return Localize.shared.availableLanguages
}
/// Return storaged language or default language in device
///
/// - returns: current used language
public static var currentLanguage: String {
return Localize.shared.currentLanguage
}
/// Localize a string using your JSON File
/// If the key is not found return the same key
/// That prevent replace untagged values
///
/// - returns: localized key or same text
public static func localize(key: String, tableName: String? = nil) -> String {
return Localize.shared.localize(key: key, tableName: tableName)
}
/// Localize a string using your JSON File
/// That replace all % character in your string with replace value.
///
/// - parameter value: The replacement value
///
/// - returns: localized key or same text
public static func localize(
key: String,
replace: String,
tableName: String? = nil) -> String {
return Localize.shared.localize(key: key, replace: replace, tableName: tableName)
}
/// Localize a string using your JSON File
/// That replace each % character in your string with each replace value.
///
/// - parameter value: The replacement values
///
/// - returns: localized key or same text
public static func localize(
key: String,
values replace: [Any],
tableName: String? = nil) -> String {
return Localize.shared.localize(key: key, values: replace, tableName: tableName)
}
/// Localize string with dictionary values
/// Get properties in your key with rule :property
/// If property not exist in this string, not is used.
///
/// - parameter value: The replacement dictionary
///
/// - returns: localized key or same text
public static func localize(
key: String,
dictionary replace: [String: String],
tableName: String? = nil) -> String {
return Localize.shared.localize(key: key, dictionary: replace, tableName: tableName)
}
/// Update default language, this stores a language key which can be retrieved the next time
public static func update(language: String) {
return Localize.shared.update(language: language)
}
/// Update base file name, searched in path.
public static func update(fileName: String) {
return Localize.shared.update(fileName: fileName)
}
/// Update the bundle used to load files from.
public static func update(bundle: Bundle) {
return Localize.shared.update(bundle: bundle)
}
/// Update default language
public static func update(defaultLanguage: String) {
return Localize.shared.update(defaultLanguage: defaultLanguage)
}
/// This remove the language key storaged.
public static func resetLanguage() {
return Localize.shared.resetLanguage()
}
/// Display name for current user language.
///
/// - return: String form language code in current user language
public static func displayNameForLanguage(_ language: String) -> String {
return Localize.shared.displayNameForLanguage(language)
}
/// Determines whether a localized string exists for given key
///
/// - parameter key: localization key
/// - returns: boolean value determining whether a localized string exists for give key
public static func localizeExists(forKey key: String, table: String? = nil) -> Bool {
return Localize.shared.localizeExists(forKey: key, table: table)
}
// MARK: Config providers
/// Update provider to localize your app.
public static func update(provider: LocalizeType) {
Localize.shared.update(provider: provider)
}
}
| mit | 01e3c8865f90c942c9a4be30f843a97a | 31.488 | 96 | 0.660921 | 4.755269 | false | false | false | false |
DukeLenny/Weibo | Weibo/Weibo/Class/Tool/Extension/UILabel+Extension.swift | 1 | 832 | //
// UILabel+Extension.swift
// Weibo
//
// Created by LiDinggui on 2018/3/15.
// Copyright © 2018年 DAQSoft. All rights reserved.
//
import UIKit
extension UILabel {
//实例化一个有文本的label
//还需设置:
//1.addSubview
//2.frame
convenience init(backgroundColor: UIColor = UIColor.clear, textColor: UIColor = UIColor.black, font: UIFont = UIFont.systemFont(ofSize: 14.0), text: String = "", textAlignment: NSTextAlignment = .natural, numberOfLines: Int = 1) {
self.init()
self.backgroundColor = backgroundColor
self.textColor = textColor
self.font = font
self.text = text
self.textAlignment = textAlignment
self.numberOfLines = numberOfLines
sizeToFit()
}
}
| mit | cf8ddb2f0e899dc6e8ed92cb2aca7931 | 23.333333 | 234 | 0.60274 | 4.387978 | false | false | false | false |
wordpress-mobile/WordPress-iOS | WordPress/Classes/Stores/NoticeStore.swift | 2 | 7681 | import Foundation
import WordPressFlux
/// Notice represents a small notification that that can be displayed within
/// the app, much like Android toasts or snackbars.
/// Once you've created a Notice, you can dispatch a `NoticeAction` to display it.
///
struct Notice {
typealias ActionHandlerFunction = ((_ accepted: Bool) -> Void)
typealias Tag = String
private let identifier = UUID().uuidString
/// The title of the notice
let title: String
/// An optional subtitle for the notice
let message: String?
/// An optional taptic feedback type. If provided, taptic feedback will be
/// triggered when the notice is displayed.
let feedbackType: UINotificationFeedbackGenerator.FeedbackType?
/// If provided, the notice will be presented as a system notification when
/// the app isn't in the foreground.
let notificationInfo: NoticeNotificationInfo?
/// Style used to configure visual style when displayed
///
let style: NoticeStyle
/// A title for an optional action button that can be displayed as part of
/// a notice
let actionTitle: String?
/// A title for an optional cancel button that can be displayed as part of a notice
///
let cancelTitle: String?
/// An optional value that can be used as a reference by consumers.
///
/// This is not used in the Notice system at all.
let tag: Tag?
/// An optional handler closure that will be called when the action button
/// is tapped, if you've provided an action title
let actionHandler: ActionHandlerFunction?
init(title: String,
message: String? = nil,
feedbackType: UINotificationFeedbackGenerator.FeedbackType? = nil,
notificationInfo: NoticeNotificationInfo? = nil,
style: NoticeStyle = NormalNoticeStyle(),
actionTitle: String? = nil,
cancelTitle: String? = nil,
tag: String? = nil,
actionHandler: ActionHandlerFunction? = nil) {
self.title = title
self.message = message
self.feedbackType = feedbackType
self.notificationInfo = notificationInfo
self.actionTitle = actionTitle
self.cancelTitle = cancelTitle
self.tag = tag
self.actionHandler = actionHandler
self.style = style
}
}
extension Notice: Equatable {
static func ==(lhs: Notice, rhs: Notice) -> Bool {
return lhs.identifier == rhs.identifier
}
}
struct NoticeNotificationInfo {
/// Unique identifier for this notice. When displayed as a system notification,
/// this value will be used as the `UNNotificationRequest`'s identifier.
let identifier: String
/// Optional category identifier for this notice. If provided, this value
/// will be used as the `UNNotificationContent`'s category identifier.
let categoryIdentifier: String?
/// Optional title. If provided, this will override the notice's
/// standard title when displayed as a notification.
let title: String?
/// Optional body text. If provided, this will override the notice's
/// standard message when displayed as a notification.
let body: String?
/// If provided, this will be added to the `UNNotificationRequest` for this notice.
let userInfo: [String: Any]?
init(identifier: String, categoryIdentifier: String? = nil, title: String? = nil, body: String? = nil, userInfo: [String: Any]? = nil) {
self.identifier = identifier
self.categoryIdentifier = categoryIdentifier
self.title = title
self.body = body
self.userInfo = userInfo
}
}
/// Objective-C bridge for ActionDispatcher specific for notices.
///
class NoticesDispatch: NSObject {
@objc static func lock() -> Void {
ActionDispatcher.dispatch(NoticeAction.lock)
}
@objc static func unlock() -> Void {
ActionDispatcher.dispatch(NoticeAction.unlock)
}
}
/// NoticeActions can be posted to control or report the display of notices.
///
enum NoticeAction: Action {
/// The specified notice will be queued for display to the user
case post(Notice)
/// The currently displayed notice should be removed from the notice store
///
/// Prefer to use `clear` or `clearWithTag` whenever possible to make sure the correct
/// `Notice` is being dismissed. Here is an example fake scenario that may make `dismiss`
/// not ideal:
///
/// 1. MediaBrowser posts NoticeA. NoticeA is displayed.
/// 2. Editor posts NoticeB.
/// 3. Eventually, NoticeB is displayed.
/// 4. MediaBrowser dispatches `dismiss` which dismisses **NoticeB**!
///
/// If MediaBrowser used `clear` or `clearWithTag`, the NoticeB should not have been dismissed
/// prematurely.
case dismiss
/// Removes the given `Notice` from the Store.
case clear(Notice)
/// Removes all Notices that have the given tag.
///
/// - SeeAlso: `Notice.tag`
case clearWithTag(Notice.Tag)
/// Removes all Notices except the current one.
case empty
// Prevents the notices from showing up untill an unlock action.
case lock
// Show the missed notices.
case unlock
}
struct NoticeStoreState {
fileprivate var notice: Notice?
}
/// NoticeStore queues notices for display to the user.
///
/// To interact with or modify the `NoticeStore`, use `ActionDispatcher` and dispatch Actions of
/// type `NoticeAction`. Example:
///
/// ```
/// let notice = Notice(title: "Hello, my old friend!")
/// ActionDispatcher.dispatch(NoticeAction.post(notice))
/// ```
///
/// - SeeAlso: `NoticeAction`
class NoticeStore: StatefulStore<NoticeStoreState> {
private var pending = Queue<Notice>()
private var storeLocked = false
init(dispatcher: ActionDispatcher = .global) {
super.init(initialState: NoticeStoreState(), dispatcher: dispatcher)
}
override func onDispatch(_ action: Action) {
guard let action = action as? NoticeAction else {
return
}
switch action {
case .post(let notice):
enqueueNotice(notice)
case .clear(let notice):
clear(notice: notice)
case .clearWithTag(let tag):
clear(tag: tag)
case .dismiss:
dequeueNotice()
case .empty:
emptyQueue()
case .lock:
lock()
case .unlock:
unlock()
}
}
// MARK: - Accessors
/// Returns the notice that should be displayed to the user, if one is available.
var currentNotice: Notice? {
return state.notice
}
// MARK: - Action handlers
private func enqueueNotice(_ notice: Notice) {
if state.notice == nil && !storeLocked {
state.notice = notice
} else {
pending.push(notice)
}
}
private func dequeueNotice() {
if !storeLocked {
state.notice = pending.pop()
}
}
private func lock() {
if storeLocked {
return
}
state.notice = nil
storeLocked = true
}
private func unlock() {
if !storeLocked {
return
}
storeLocked = false
dequeueNotice()
}
private func clear(notice: Notice) {
pending.removeAll { $0 == notice }
if state.notice == notice {
state.notice = pending.pop()
}
}
private func clear(tag: Notice.Tag) {
pending.removeAll { $0.tag == tag }
if state.notice?.tag == tag {
state.notice = pending.pop()
}
}
private func emptyQueue() {
pending.removeAll()
}
}
| gpl-2.0 | 0ad48904440c29828b56f36c08f032e1 | 29.121569 | 140 | 0.638068 | 4.706495 | false | false | false | false |
kellanburket/Passenger | Pod/Classes/BaseObject.swift | 1 | 11615 | //
// Base.swift
// Pods
//
// Created by Kellan Cummings on 7/10/15.
//
//
import Foundation
import Wildcard
/**
Base object upon which Passenger's `Passenger`, `Model`, `Entity`, and `Resource` classes are based. Provides a number of useful reflection methods, which are used internally.
*/
public class BaseObject: NSObject {
internal var mirrors: [String: MirrorType] {
var mirrors = [String: MirrorType]()
let reflection = reflect(self)
var writeMirrors: (MirrorType -> Void) -> (MirrorType -> Void) = { f in
return { reflection in
for i in 0..<reflection.count {
let (name, mirror) = reflection[i]
//println("\tMirror <\(self.dynamicType).\(name)>")
//println("\t\tCount: \(mirror.count)")
//println("\t\tDisposition: \(self.dynamicType.getDisposition(mirror.disposition))")
//println("\t\tValue Type: \(mirror.valueType)")
if name == "super" {
f(mirror)
} else {
mirrors[name] = mirror
}
}
}
}
Y(writeMirrors)(reflection)
return mirrors
}
/**
Returns a string description of the object for console output
*/
override public var description: String {
return describeSelf()
}
internal func describeSelf(_ tabs: Int = 0) -> String {
return ""
}
internal func parseMirror(mirror: MirrorType) -> Any? {
if mirror.count >= 1 && mirror.disposition == .Optional {
return parseOptionalMirror(mirror)
} else if mirror.count >= 1 && mirror.disposition == .Class {
//println("\tCount: \(mirror.count)")
//println("\tDisposition: \(self.dynamicType.getDisposition(mirror.disposition))")
//println("\tValue: \(mirror.value)")
//println("\tValue Type: \(mirror.valueType)\n")
return mirror.value //parseObjectMirror(mirror)
} else if mirror.count >= 1 && mirror.disposition == .Struct {
//println("\tCount: \(mirror.count)")
//println("\tDisposition: \(self.dynamicType.getDisposition(mirror.disposition))")
//println("\tValue: \(mirror.value)")
//println("\tValue Type: \(mirror.valueType)\n")
return mirror.value //parseObjectMirror(mirror)
} else if mirror.count >= 1 && mirror.disposition == .KeyContainer {
return parseDictionaryMirror(mirror)
} else if mirror.count >= 1 && mirror.disposition == .IndexContainer {
return parseArrayMirror(mirror)
} else if let value: AnyObject = mirror.value as? AnyObject {
//println("Primitive Mirror")
//println("\tCount: \(mirror.count)")
//println("\tDisposition: \(self.dynamicType.getDisposition(mirror.disposition))")
//println("\tValue: \(mirror.value)")
//println("\tValue Type: \(mirror.valueType)\n")
return mirror.value
}
//println("Nil Mirror")
//println("\tCount: \(mirror.count)")
//println("\tValue: \(mirror.value)")
//println("\tValue Type: \(mirror.valueType)")
//println("\tSummary: \(mirror.summary)")
return nil
}
internal func parseStructMirror(mirror: MirrorType) -> Any? {
for i in 0..<mirror.count {
let (name, structMirror) = mirror[i]
if let item = parseMirror(structMirror) {
}
}
return nil
}
internal func parseArrayMirror(mirror: MirrorType) -> Any? {
var array = [Any]()
for i in 0..<mirror.count {
let (mirrorIndex, arrayMirror) = mirror[i]
if let item = parseMirror(arrayMirror) {
array << item
} else {
println("Coult not parse \(arrayMirror.valueType)")
}
}
return array.count > 0 ? array : nil
}
internal func parseDictionaryMirror(mirror: MirrorType) -> Any? {
var hash = [String: Any]()
for i in 0..<mirror.count {
let (mirrorIndex, tupleMirror) = mirror[i]
if tupleMirror.count == 2 && tupleMirror.disposition == .Tuple {
var keyMirror = tupleMirror[0].1
var valueMirror = tupleMirror[1].1
if let key = keyMirror.value as? String {
//println("\t\tAdding Dictionary Key '\(key)'")
//println("\t\t\tCount: \(valueMirror.count)")
//println("\t\t\tDisposition: \(self.dynamicType.getDisposition(keyMirror.disposition))")
//println("\t\t\tValue: \(valueMirror.value)")
//println("\t\t\tValue Type: \(valueMirror.valueType)")
//println("\t\t\tSummary: \(valueMirror.summary)")
hash[key] = parseMirror(valueMirror)
} else {
println("\t\tKey Mirror not a String")
println("\t\t\tCount: \(keyMirror.count)")
println("\t\t\tDisposition: \(self.dynamicType.getDisposition(keyMirror.disposition))")
println("\t\t\tValue: \(keyMirror.value)")
println("\t\t\tValue Type: \(keyMirror.valueType)")
println("\t\t\tSummary: \(keyMirror.summary)")
}
} else {
println("\t\tName: \(mirrorIndex)")
println("\t\t\tCount: \(tupleMirror.count)")
println("\t\t\tDisposition: \(self.dynamicType.getDisposition(tupleMirror.disposition))")
println("\t\t\tValue: \(tupleMirror.value)")
println("\t\t\tValue Type: \(tupleMirror.valueType)")
println("\t\t\tSummary: \(tupleMirror.summary)")
}
}
return hash.count > 0 ? hash : nil
}
internal func parseOptionalMirror(mirror: MirrorType) -> Any? {
if mirror.count == 1 {
let (optionalType, optionalMirror) = mirror[0]
if optionalType == "Some" {
return parseMirror(optionalMirror)
/*
println("OptionalMirror(\(optionalType)) \(optionalMirror.valueType)")
println("\t\tCount: \(optionalMirror.count)")
println("\t\tDisposition: \(getDisposition(optionalMirror.disposition))")
println("\t\tValue: \(optionalMirror.value)")
println("\t\tValue Type: \(optionalMirror.valueType)")
println("\t\tSummary: \(optionalMirror.summary)")
*/
} else {
println("OptionalMirror(\(optionalType)) \(optionalMirror.valueType)")
println("\t\tCount: \(optionalMirror.count)")
println("\t\tDisposition: \(self.dynamicType.getDisposition(optionalMirror.disposition))")
println("\t\tValue: \(optionalMirror.value)")
println("\t\tValue Type: \(optionalMirror.valueType)")
println("\t\tSummary: \(optionalMirror.summary)")
}
} else {
println("\tOptional Mirror (Count > 1): \(mirror.valueType)")
println("\t\tCount: \(mirror.count)")
println("\t\tValue: \(mirror.value)")
println("\t\tValue Type: \(mirror.valueType)")
println("\t\tSummary: \(mirror.summary)")
}
return nil
}
internal class func getDisposition(disposition: MirrorDisposition) -> String {
switch disposition {
case .Struct: return "Struct"
case .Class: return "Class"
case .Enum: return "Enum"
case .Tuple: return "Tuple"
case .Aggregate: return "Aggregate"
case .IndexContainer: return "IndexContainer"
case .KeyContainer: return "KeyContainer"
case .MembershipContainer: return "Membership Container"
case .Container: return "Container"
case .Optional: return "Optional"
case .ObjCObject: return "Objective C Object"
default: return "Unknown"
}
}
internal func getSubtype(type: Any.Type) -> Any.Type? {
if type is Array<Int>.Type {
return Int.self
} else if type is Array<UInt>.Type {
return UInt.self
} else if type is Array<Int8>.Type {
return Int8.self
} else if type is Array<UInt8>.Type {
return UInt8.self
} else if type is Array<Int16>.Type {
return Int16.self
} else if type is Array<UInt16>.Type {
return UInt16.self
} else if type is Array<Int32>.Type {
return Int32.self
} else if type is Array<UInt32>.Type {
return UInt32.self
} else if type is Array<Int64>.Type {
return Int64.self
} else if type is Array<UInt64>.Type {
return UInt64.self
} else if type is Array<String>.Type {
return String.self
} else if type is Array<Character>.Type {
return Character.self
} else if type is Array<Bool>.Type {
return Bool.self
} else if type is Array<Float>.Type {
return Float.self
} else if type is Array<Double>.Type {
return Double.self
} else if type is Array<NSURL>.Type {
return NSURL.self
} else if type is Array<UIColor>.Type {
return UIColor.self
} else if type is Array<NSAttributedString>.Type {
return NSAttributedString.self
} else if type is Array<NSDate>.Type {
return NSDate.self
}
return nil
}
internal func describeProperty(value: AnyObject, _ tabs: Int = 0) -> String {
var output = ""
if let arr = value as? [AnyObject] {
output += describePropertyArray(arr, tabs + 1)
} else if let hash = value as? [String: AnyObject] {
output += describePropertyDictionary(hash, tabs + 1)
} else if let value = value as? Serializable {
output += describePropertySerializable(value)
}
return output
}
internal func describePropertyArray(arr: [AnyObject], _ tabs: Int = 0) -> String {
var output = ""
for value in arr {
output += "\n" + "\t".repeat(tabs)
output += describeProperty(value, tabs + 1)
output += "\n" + "\t".repeat(tabs) + "---------------------------"
}
return output
}
internal func describePropertyDictionary(hash: [String: AnyObject], _ tabs: Int = 0) -> String {
var output = ""
for (key, value) in hash {
//println("\tDescribing \(key)")
output += "\n" + "\t".repeat(tabs) + "\(key): "
output += describeProperty(value, tabs + 1)
}
return output
}
internal func describePropertyPrimitive(value: AnyObject) -> String {
return "\(value)"
}
internal func describePropertySerializable(value: Serializable) -> String {
return value.__prepare()
}
}
| mit | 4ec723970154207698b52f450a3d70f6 | 37.207237 | 179 | 0.530693 | 4.915362 | false | false | false | false |
phatblat/Nimble | Sources/Nimble/Matchers/Equal.swift | 47 | 4826 | import Foundation
/// A Nimble matcher that succeeds when the actual value is equal to the expected value.
/// Values can support equal by supporting the Equatable protocol.
///
/// @see beCloseTo if you want to match imprecise types (eg - floats, doubles).
public func equal<T: Equatable>(_ expectedValue: T?) -> Predicate<T> {
return Predicate.define("equal <\(stringify(expectedValue))>") { actualExpression, msg in
let actualValue = try actualExpression.evaluate()
switch (expectedValue, actualValue) {
case (nil, _?):
return PredicateResult(status: .fail, message: msg.appendedBeNilHint())
case (nil, nil), (_, nil):
return PredicateResult(status: .fail, message: msg)
case (let expected?, let actual?):
let matches = expected == actual
return PredicateResult(bool: matches, message: msg)
}
}
}
/// A Nimble matcher allowing comparison of collection with optional type
public func equal<T: Equatable>(_ expectedValue: [T?]) -> Predicate<[T?]> {
return Predicate.define("equal <\(stringify(expectedValue))>") { actualExpression, msg in
guard let actualValue = try actualExpression.evaluate() else {
return PredicateResult(
status: .fail,
message: msg.appendedBeNilHint()
)
}
let matches = expectedValue == actualValue
return PredicateResult(bool: matches, message: msg)
}
}
/// A Nimble matcher that succeeds when the actual set is equal to the expected set.
public func equal<T>(_ expectedValue: Set<T>?) -> Predicate<Set<T>> {
return equal(expectedValue, stringify: { stringify($0) })
}
/// A Nimble matcher that succeeds when the actual set is equal to the expected set.
public func equal<T: Comparable>(_ expectedValue: Set<T>?) -> Predicate<Set<T>> {
return equal(expectedValue, stringify: {
if let set = $0 {
return stringify(Array(set).sorted { $0 < $1 })
} else {
return "nil"
}
})
}
private func equal<T>(_ expectedValue: Set<T>?, stringify: @escaping (Set<T>?) -> String) -> Predicate<Set<T>> {
return Predicate { actualExpression in
var errorMessage: ExpectationMessage =
.expectedActualValueTo("equal <\(stringify(expectedValue))>")
guard let expectedValue = expectedValue else {
return PredicateResult(
status: .fail,
message: errorMessage.appendedBeNilHint()
)
}
guard let actualValue = try actualExpression.evaluate() else {
return PredicateResult(
status: .fail,
message: errorMessage.appendedBeNilHint()
)
}
errorMessage = .expectedCustomValueTo(
"equal <\(stringify(expectedValue))>",
"<\(stringify(actualValue))>"
)
if expectedValue == actualValue {
return PredicateResult(
status: .matches,
message: errorMessage
)
}
let missing = expectedValue.subtracting(actualValue)
if missing.count > 0 {
errorMessage = errorMessage.appended(message: ", missing <\(stringify(missing))>")
}
let extra = actualValue.subtracting(expectedValue)
if extra.count > 0 {
errorMessage = errorMessage.appended(message: ", extra <\(stringify(extra))>")
}
return PredicateResult(
status: .doesNotMatch,
message: errorMessage
)
}
}
public func ==<T: Equatable>(lhs: Expectation<T>, rhs: T?) {
lhs.to(equal(rhs))
}
public func !=<T: Equatable>(lhs: Expectation<T>, rhs: T?) {
lhs.toNot(equal(rhs))
}
public func ==<T: Equatable>(lhs: Expectation<[T]>, rhs: [T]?) {
lhs.to(equal(rhs))
}
public func !=<T: Equatable>(lhs: Expectation<[T]>, rhs: [T]?) {
lhs.toNot(equal(rhs))
}
public func == <T>(lhs: Expectation<Set<T>>, rhs: Set<T>?) {
lhs.to(equal(rhs))
}
public func != <T>(lhs: Expectation<Set<T>>, rhs: Set<T>?) {
lhs.toNot(equal(rhs))
}
public func ==<T: Comparable>(lhs: Expectation<Set<T>>, rhs: Set<T>?) {
lhs.to(equal(rhs))
}
public func !=<T: Comparable>(lhs: Expectation<Set<T>>, rhs: Set<T>?) {
lhs.toNot(equal(rhs))
}
public func ==<T, C: Equatable>(lhs: Expectation<[T: C]>, rhs: [T: C]?) {
lhs.to(equal(rhs))
}
public func !=<T, C: Equatable>(lhs: Expectation<[T: C]>, rhs: [T: C]?) {
lhs.toNot(equal(rhs))
}
#if canImport(Darwin)
extension NMBObjCMatcher {
@objc public class func equalMatcher(_ expected: NSObject) -> NMBMatcher {
return NMBPredicate { actualExpression in
return try equal(expected).satisfies(actualExpression).toObjectiveC()
}
}
}
#endif
| apache-2.0 | 3adf0f64e7460a2585509b4795066976 | 31.608108 | 112 | 0.606092 | 4.391265 | false | false | false | false |
Corey2121/the-oakland-post | The Oakland Post/ZoomToPoint.swift | 3 | 1556 | //
// ZoomToPoint.swift
// The Oakland Post
//
// Created by Andrew Clissold on 7/30/14.
// Ported to Swift from https://gist.github.com/TimOliver/6138097
// Tim Oliver's blog post on the matter:
// http://www.timoliver.com.au/2012/01/14/zooming-to-a-point-in-uiscrollview/
//
extension UIScrollView {
func zoomToPoint(point: CGPoint, withScale scale: CGFloat, animated: Bool) {
var x, y, width, height: CGFloat
//Normalize current content size back to content scale of 1.0f
width = (self.contentSize.width / self.zoomScale)
height = (self.contentSize.height / self.zoomScale)
var contentSize = CGSize(width: width, height: height)
//translate the zoom point to relative to the content rect
x = (point.x / self.bounds.size.width) * contentSize.width
y = (point.y / self.bounds.size.height) * contentSize.height
var zoomPoint = CGPoint(x: x, y: y)
//derive the size of the region to zoom to
width = self.bounds.size.width / scale
height = self.bounds.size.height / scale
var zoomSize = CGSize(width: width, height: height)
//offset the zoom rect so the actual zoom point is in the middle of the rectangle
x = zoomPoint.x - zoomSize.width / 2.0
y = zoomPoint.y - zoomSize.height / 2.0
width = zoomSize.width
height = zoomSize.height
var zoomRect = CGRect(x: x, y: y, width: width, height: height)
//apply the resize
self.zoomToRect(zoomRect, animated: animated)
}
}
| bsd-3-clause | d07c3ccba5392b98c8f2a579111e770d | 37.9 | 89 | 0.648458 | 3.813725 | false | false | false | false |
yoshinorisano/RxSwift | RxDataSourceStarterKit/SectionModel.swift | 23 | 1612 | //
// SectionModel.swift
// RxCocoa
//
// Created by Krunoslav Zaher on 6/16/15.
// Copyright (c) 2015 Krunoslav Zaher. All rights reserved.
//
import Foundation
public struct SectionModel<Section, ItemType> : SectionModelType, CustomStringConvertible {
public typealias Item = ItemType
public var model: Section
public var items: [Item]
public init(model: Section, items: [Item]) {
self.model = model
self.items = items
}
public init(original: SectionModel, items: [Item]) {
self.model = original.model
self.items = items
}
public var description: String {
get {
return "\(self.model) > \(items)"
}
}
}
public struct HashableSectionModel<Section: Hashable, ItemType: Hashable> : Hashable, SectionModelType, CustomStringConvertible {
public typealias Item = ItemType
public var model: Section
public var items: [Item]
public init(model: Section, items: [Item]) {
self.model = model
self.items = items
}
public init(original: HashableSectionModel, items: [Item]) {
self.model = original.model
self.items = items
}
public var description: String {
get {
return "HashableSectionModel(model: \"\(self.model)\", items: \(items))"
}
}
public var hashValue: Int {
get {
return self.model.hashValue
}
}
}
public func == <S, I>(lhs: HashableSectionModel<S, I>, rhs: HashableSectionModel<S, I>) -> Bool {
return lhs.model == rhs.model
} | mit | 1a34145b7fa505bbe6a9ef533329ce1c | 23.439394 | 129 | 0.604839 | 4.453039 | false | false | false | false |
andrebocchini/SwiftChattyOSX | Pods/SwiftChatty/SwiftChatty/Common Models/Mappable/Event.swift | 1 | 1909 | //
// Event.swift
// SwiftChatty
//
// Created by Andre Bocchini on 1/26/16.
// Copyright © 2016 Andre Bocchini. All rights reserved.
//
import Genome
/// A convenience protocol to make it easy to map different event types into
/// the same property.
public protocol EventDataType {}
/// Models possible events that the server can use to let client know that
/// something has changed and that it needs to update its copy of the Chatty.
///
/// -SeeAlso: http://winchatty.com/v2/readme#_Toc421451679
public struct Event {
public var id: Int = 0
public var date: String = ""
public var type: EventType?
public var data: EventDataType?
public init() {}
}
extension Event: CommonMappableModel {
public mutating func sequence(map: Map) throws {
var typeString: String = ""
try id <~ map["eventId"]
try date <~ map["eventDate"]
try typeString <~ map["eventType"]
switch typeString {
case "newPost":
type = EventType.NewPost
var newPostEvent: EventNewPost?
try newPostEvent <~ map["eventData"]
data = newPostEvent
case "categoryChange":
type = EventType.CategoryChange
var categoryChangeEvent: EventCategoryChange?
try categoryChangeEvent <~ map["eventData"]
data = categoryChangeEvent
case "serverMessage":
type = EventType.ServerMessage
var serverMessageEvent: EventServerMessage?
try serverMessageEvent <~ map["eventData"]
data = serverMessageEvent
case "lolCountsUpdate":
type = EventType.LolCountsUpdate
var lolCountUpdatesEvent: EventLolCountUpdates?
try lolCountUpdatesEvent <~ map["eventData"]
data = lolCountUpdatesEvent
default:
type = nil
data = nil
}
}
}
| mit | 9f73e0793ea314b353079bdf6ba7ba9d | 27.909091 | 77 | 0.624738 | 4.79397 | false | false | false | false |
luckymore0520/leetcode | CombinationSum.playground/Contents.swift | 1 | 1923 | //: Playground - noun: a place where people can play
import UIKit
//Given a set of candidate numbers (C) (without duplicates) and a target number (T), find all unique combinations in C where the candidate numbers sums to T.
//
//The same repeated number may be chosen from C unlimited number of times.
//
//Note:
//All numbers (including target) will be positive integers.
//The solution set must not contain duplicate combinations.
//For example, given candidate set [2, 3, 6, 7] and target 7,
//A solution set is:
//[
//[7],
//[2, 2, 3]
//]
class Solution {
func combinationSum(_ candidates: [Int], _ target: Int) -> [[Int]] {
let sorted = candidates.sorted()
return combinationSumInsortedArray(sorted, target, 0) ?? []
}
func combinationSumInsortedArray(_ candidates: [Int], _ target: Int, _ start:Int) -> [[Int]]? {
if target == 0 {
return []
} else {
var result:[[Int]] = []
for i in start...candidates.count-1 {
let num = candidates[i]
if (num <= target) {
//返回是nil 代表不存在,直接考虑下一个
if let remains = combinationSumInsortedArray(candidates, target - num, i) {
if remains.isEmpty {
result.append([num])
} else {
for remain in remains {
var complete = remain
complete.insert(num, at: 0)
result.append(complete)
}
}
}
} else {
break
}
}
return result.isEmpty ? nil : result
}
}
}
let solution = Solution()
let result = solution.combinationSum([2,3,6,7], 7)
print(result) | mit | 3693263a29f35ebec13dcec624541f34 | 32.192982 | 157 | 0.505024 | 4.680693 | false | false | false | false |
thiagolioy/Notes | Tests/MinorChordSpec.swift | 1 | 15397 | //
// MinorChordSpec.swift
// Notes
//
// Created by Thiago Lioy on 26/08/17.
// Copyright © 2017 com.tplioy. All rights reserved.
//
import Foundation
import Quick
import Nimble
@testable import Notes
class MinorChordSpec: QuickSpec {
override func spec() {
describe("Minor Chord") {
var chord: MinorChord!
beforeEach {
let key = Note(name: .C, intonation: .natural)
chord = MinorChord(key: key)
}
it("should have the expected symbol") {
expect(chord.symbol).to(equal("m"))
}
it("should have the expected intervals") {
expect(chord.chordIntervals).to(equal([
.root,
.minorThird,
.perfectFifth
]))
}
context("in the key of C natural") {
var rootChord: MinorChord!
beforeEach {
let key = Note(name: .C, intonation: .natural)
rootChord = MinorChord(key: key)
}
it("should have the expected full name") {
expect(rootChord.fullName()).to(equal("Cm"))
}
it("should have the expected chord tones") {
let notes = rootChord.chordTones()
expect(notes).to(equal([
Note(name: .C, intonation: .natural),
Note(name: .E, intonation: .flat),
Note(name: .G, intonation: .natural),
]))
}
}
context("in the key of C sharp") {
var rootChord: MinorChord!
beforeEach {
let key = Note(name: .C, intonation: .sharp)
rootChord = MinorChord(key: key)
}
it("should have the expected full name") {
expect(rootChord.fullName()).to(equal("C♯m"))
}
it("should have the expected chord tones") {
let notes = rootChord.chordTones()
expect(notes).to(equal([
Note(name: .C, intonation: .sharp),
Note(name: .E, intonation: .natural),
Note(name: .G, intonation: .sharp),
]))
}
}
context("in the key of D flat") {
var rootChord: MinorChord!
beforeEach {
let key = Note(name: .D, intonation: .flat)
rootChord = MinorChord(key: key)
}
it("should have the expected full name") {
expect(rootChord.fullName()).to(equal("D♭m"))
}
it("should have the expected chord tones") {
let notes = rootChord.chordTones()
expect(notes).to(equal([
Note(name: .D, intonation: .flat),
Note(name: .F, intonation: .flat),
Note(name: .A, intonation: .flat),
]))
}
}
context("in the key of D natural") {
var rootChord: MinorChord!
beforeEach {
let key = Note(name: .D, intonation: .natural)
rootChord = MinorChord(key: key)
}
it("should have the expected full name") {
expect(rootChord.fullName()).to(equal("Dm"))
}
it("should have the expected chord tones") {
let notes = rootChord.chordTones()
expect(notes).to(equal([
Note(name: .D, intonation: .natural),
Note(name: .F, intonation: .natural),
Note(name: .A, intonation: .natural),
]))
}
}
context("in the key of D sharp") {
var rootChord: MinorChord!
beforeEach {
let key = Note(name: .D, intonation: .sharp)
rootChord = MinorChord(key: key)
}
it("should have the expected full name") {
expect(rootChord.fullName()).to(equal("D♯m"))
}
it("should have the expected chord tones") {
let notes = rootChord.chordTones()
expect(notes).to(equal([
Note(name: .D, intonation: .sharp),
Note(name: .F, intonation: .sharp),
Note(name: .A, intonation: .sharp),
]))
}
}
context("in the key of E flat") {
var rootChord: MinorChord!
beforeEach {
let key = Note(name: .E, intonation: .flat)
rootChord = MinorChord(key: key)
}
it("should have the expected full name") {
expect(rootChord.fullName()).to(equal("E♭m"))
}
it("should have the expected chord tones") {
let notes = rootChord.chordTones()
expect(notes).to(equal([
Note(name: .E, intonation: .flat),
Note(name: .G, intonation: .flat),
Note(name: .B, intonation: .flat),
]))
}
}
context("in the key of E natural") {
var rootChord: MinorChord!
beforeEach {
let key = Note(name: .E, intonation: .natural)
rootChord = MinorChord(key: key)
}
it("should have the expected full name") {
expect(rootChord.fullName()).to(equal("Em"))
}
it("should have the expected chord tones") {
let notes = rootChord.chordTones()
expect(notes).to(equal([
Note(name: .E, intonation: .natural),
Note(name: .G, intonation: .natural),
Note(name: .B, intonation: .natural),
]))
}
}
context("in the key of F natural") {
var rootChord: MinorChord!
beforeEach {
let key = Note(name: .F, intonation: .natural)
rootChord = MinorChord(key: key)
}
it("should have the expected full name") {
expect(rootChord.fullName()).to(equal("Fm"))
}
it("should have the expected chord tones") {
let notes = rootChord.chordTones()
expect(notes).to(equal([
Note(name: .F, intonation: .natural),
Note(name: .A, intonation: .flat),
Note(name: .C, intonation: .natural),
]))
}
}
context("in the key of F sharp") {
var rootChord: MinorChord!
beforeEach {
let key = Note(name: .F, intonation: .sharp)
rootChord = MinorChord(key: key)
}
it("should have the expected full name") {
expect(rootChord.fullName()).to(equal("F♯m"))
}
it("should have the expected chord tones") {
let notes = rootChord.chordTones()
expect(notes).to(equal([
Note(name: .F, intonation: .sharp),
Note(name: .A, intonation: .natural),
Note(name: .C, intonation: .sharp),
]))
}
}
context("in the key of G flat") {
var rootChord: MinorChord!
beforeEach {
let key = Note(name: .G, intonation: .flat)
rootChord = MinorChord(key: key)
}
it("should have the expected full name") {
expect(rootChord.fullName()).to(equal("G♭m"))
}
it("should have the expected chord tones") {
let notes = rootChord.chordTones()
expect(notes).to(equal([
Note(name: .G, intonation: .flat),
Note(name: .B, intonation: .doubleFlat),
Note(name: .D, intonation: .flat),
]))
}
}
context("in the key of G natural") {
var rootChord: MinorChord!
beforeEach {
let key = Note(name: .G, intonation: .natural)
rootChord = MinorChord(key: key)
}
it("should have the expected full name") {
expect(rootChord.fullName()).to(equal("Gm"))
}
it("should have the expected chord tones") {
let notes = rootChord.chordTones()
expect(notes).to(equal([
Note(name: .G, intonation: .natural),
Note(name: .B, intonation: .flat),
Note(name: .D, intonation: .natural),
]))
}
}
context("in the key of G sharp") {
var rootChord: MinorChord!
beforeEach {
let key = Note(name: .G, intonation: .sharp)
rootChord = MinorChord(key: key)
}
it("should have the expected full name") {
expect(rootChord.fullName()).to(equal("G♯m"))
}
it("should have the expected chord tones") {
let notes = rootChord.chordTones()
expect(notes).to(equal([
Note(name: .G, intonation: .sharp),
Note(name: .B, intonation: .natural),
Note(name: .D, intonation: .sharp),
]))
}
}
context("in the key of A flat") {
var rootChord: MinorChord!
beforeEach {
let key = Note(name: .A, intonation: .flat)
rootChord = MinorChord(key: key)
}
it("should have the expected full name") {
expect(rootChord.fullName()).to(equal("A♭m"))
}
it("should have the expected chord tones") {
let notes = rootChord.chordTones()
expect(notes).to(equal([
Note(name: .A, intonation: .flat),
Note(name: .C, intonation: .flat),
Note(name: .E, intonation: .flat),
]))
}
}
context("in the key of A natural") {
var rootChord: MinorChord!
beforeEach {
let key = Note(name: .A, intonation: .natural)
rootChord = MinorChord(key: key)
}
it("should have the expected full name") {
expect(rootChord.fullName()).to(equal("Am"))
}
it("should have the expected chord tones") {
let notes = rootChord.chordTones()
expect(notes).to(equal([
Note(name: .A, intonation: .natural),
Note(name: .C, intonation: .natural),
Note(name: .E, intonation: .natural),
]))
}
}
context("in the key of A sharp") {
var rootChord: MinorChord!
beforeEach {
let key = Note(name: .A, intonation: .sharp)
rootChord = MinorChord(key: key)
}
it("should have the expected full name") {
expect(rootChord.fullName()).to(equal("A♯m"))
}
it("should have the expected chord tones") {
let notes = rootChord.chordTones()
expect(notes).to(equal([
Note(name: .A, intonation: .sharp),
Note(name: .C, intonation: .sharp),
Note(name: .E, intonation: .sharp),
]))
}
}
context("in the key of B flat") {
var rootChord: MinorChord!
beforeEach {
let key = Note(name: .B, intonation: .flat)
rootChord = MinorChord(key: key)
}
it("should have the expected full name") {
expect(rootChord.fullName()).to(equal("B♭m"))
}
it("should have the expected chord tones") {
let notes = rootChord.chordTones()
expect(notes).to(equal([
Note(name: .B, intonation: .flat),
Note(name: .D, intonation: .flat),
Note(name: .F, intonation: .natural),
]))
}
}
context("in the key of B natural") {
var rootChord: MinorChord!
beforeEach {
let key = Note(name: .B, intonation: .natural)
rootChord = MinorChord(key: key)
}
it("should have the expected full name") {
expect(rootChord.fullName()).to(equal("Bm"))
}
it("should have the expected chord tones") {
let notes = rootChord.chordTones()
expect(notes).to(equal([
Note(name: .B, intonation: .natural),
Note(name: .D, intonation: .natural),
Note(name: .F, intonation: .sharp),
]))
}
}
}
}
}
| mit | ca6d5d249ce5a15e5a3140082a4aa0d1 | 37.536341 | 66 | 0.388593 | 5.70538 | false | false | false | false |
elkanaoptimove/OptimoveSDK | OptimoveSDK/Common/Extensions/Extensions.swift | 1 | 1332 | //
// Extensions.swift
// iOS-SDK
//
// Created by Mobile Developer Optimove on 04/09/2017.
// Copyright © 2017 Optimove. All rights reserved.
//
import Foundation
extension String
{
func contains(_ find: String) -> Bool
{
return self.range(of: find) != nil
}
func containsIgnoringCase(_ find: String) -> Bool
{
return self.range(of: find, options: .caseInsensitive) != nil
}
func setAsMongoKey() -> String
{
return self.replacingOccurrences(of: ".", with: "_")
}
func deletingPrefix(_ prefix: String) -> String {
guard self.hasPrefix(prefix) else { return self }
return String(self.dropFirst(prefix.count))
}
}
extension URL
{
public var queryParameters: [String: String]?
{
guard let components = URLComponents(url: self,
resolvingAgainstBaseURL: true),
let queryItems = components.queryItems else
{
return nil
}
var parameters = [String: String]()
for item in queryItems
{
parameters[item.name] = item.value
}
return parameters
}
}
extension Notification.Name {
public static let internetStatusChanged = Notification.Name.init("internetStatusChanged")
}
| mit | eec237e09faf077dfad786395b70b9c3 | 22.350877 | 93 | 0.588279 | 4.573883 | false | false | false | false |
Chakery/CGYPay | CGYPay/Classes/CGYPayCore/CGYPayWxOrder.swift | 1 | 866 | //
// CGYPayWxOrder.swift
// CGYPay
//
// Created by Chakery on 16/3/31.
// Copyright © 2016年 Chakery. All rights reserved.
//
// 微信支付订单
import Foundation
/**
* 微信订单
*/
public struct CGYPayWxOrder {
/// 商家id
public var partnerId: String
/// 订单id
public var prepayid: String
/// 随机字符串
public var nonceStr: String
/// 时间戳
public var timeStamp: UInt32
/// 扩展字段
public var package: String
/// 签名
public var sign: String
public init(partnerId: String, prepayid: String, nonceStr: String, timeStamp: UInt32, package: String, sign: String) {
self.partnerId = partnerId
self.prepayid = prepayid
self.nonceStr = nonceStr
self.timeStamp = timeStamp
self.package = package
self.sign = sign
}
} | mit | 5978203b786c08ec156c80dcbd4d1415 | 20.837838 | 122 | 0.6171 | 3.555066 | false | false | false | false |
ello/ello-ios | Sources/Utilities/Mentionables.swift | 1 | 438 | ////
/// Mentionables.swift
//
struct Mentionables {
static func findAll(_ regions: [Regionable]) -> [String] {
var mentions = [String]()
let regex = Regex("\\B@[\\w-]+")!
for region in regions {
if let textRegion = region as? TextRegion {
let matches = regex.matches(textRegion.content)
mentions += matches
}
}
return mentions
}
}
| mit | 0ea45df6c745129245f91bdd37b4f7a1 | 24.764706 | 63 | 0.515982 | 4.515464 | false | false | false | false |
ello/ello-ios | Specs/Controllers/Stream/Cells/NotificationCellSpec.swift | 1 | 4259 | ////
/// NotificationCellSpec.swift
//
@testable import Ello
import Quick
import Nimble
class NotificationCellSpec: QuickSpec {
override func spec() {
describe("NotificationCell") {
it("should set its titleTextView height") {
let subject = NotificationCell()
subject.frame.size = CGSize(width: 320, height: 40)
let author: User = .stub(["username": "ello"])
let post: Post = .stub(["author": author])
let activity: Activity = stub([
"kind": Activity.Kind.postMentionNotification,
"subject": post,
])
subject.title = NotificationAttributedTitle.from(
notification: Notification(activity: activity)
)
subject.layoutIfNeeded()
expect(subject.titleTextView.frame.size.height) == 17
}
it("should set its titleTextView height") {
let subject = NotificationCell()
subject.frame.size = CGSize(width: 160, height: 40)
let author: User = .stub(["username": "ello"])
let post: Post = .stub(["author": author])
let activity: Activity = stub([
"kind": Activity.Kind.postMentionNotification,
"subject": post,
])
subject.title = NotificationAttributedTitle.from(
notification: Notification(activity: activity)
)
subject.layoutIfNeeded()
expect(subject.titleTextView.frame.size.height) == 51
}
context("snapshots") {
var author: User!
var post: Post!
var activity: Activity!
var title: NSAttributedString!
var createdAt: Date!
var aspectRatio: CGFloat!
var image: UIImage!
beforeEach {
author = User.stub(["username": "ello"])
post = Post.stub(["author": author])
activity = Activity.stub([
"kind": Activity.Kind.postMentionNotification,
"subject": post,
])
title = NotificationAttributedTitle.from(
notification: Notification(activity: activity)
)
createdAt = Date(timeIntervalSinceNow: -86_460)
aspectRatio = 1
image = UIImage.imageWithColor(.blue, size: CGSize(width: 300, height: 300))!
}
let expectations: [(hasImage: Bool, canReply: Bool, buyButton: Bool)] = [
(hasImage: true, canReply: false, buyButton: false),
(hasImage: true, canReply: false, buyButton: true),
(hasImage: true, canReply: true, buyButton: false),
(hasImage: true, canReply: true, buyButton: true),
]
for (hasImage, canReply, buyButton) in expectations {
it(
"notification\(hasImage ? " with image" : "")\(canReply ? " with reply button" : "")\(buyButton ? " with buy button" : "")"
) {
let subject = NotificationCell()
subject.title = title
subject.createdAt = createdAt
subject.user = author
subject.canReplyToComment = canReply
subject.canBackFollow = false
subject.post = post
subject.comment = nil
subject.aspectRatio = aspectRatio
subject.buyButtonVisible = buyButton
if hasImage {
subject.imageURL = URL(string: "http://ello.co/image.png")
subject.notificationImageView.image = image
}
expectValidSnapshot(subject, device: .phone6_Portrait)
}
}
}
}
}
}
| mit | 20fdcf489179bcefec88128d277182db | 40.754902 | 147 | 0.476403 | 5.981742 | false | false | false | false |
Rivukis/Spry | Sources/Spry/Spyable.swift | 1 | 14191 | //
// Spyable.swift
// SpryExample
//
// Created by Brian Radebaugh on 11/1/15.
// Copyright © 2015 Brian Radebaugh. All rights reserved.
//
import Foundation
/**
A global NSMapTable to hold onto calls for types conforming to Spyable. This map table has "weak to strong objects" options.
- Important: Do NOT use this object.
*/
private var callsMapTable: NSMapTable<AnyObject, RecordedCallsDictionary> = NSMapTable.weakToStrongObjects()
/**
A protocol used to spy on an object's function calls. A small amount of boilerplate is requried.
- Important: All the functions specified in this protocol come with default implementation that should NOT be overridden.
- Note: The `Spryable` protocol exists as a convenience to conform to both `Spyable` and `Stubbable` at the same time.
*/
public protocol Spyable: class {
// MARK: Instance
/**
The type that represents function names when spying.
Ideal to use an enum with raw type of `String`. An enum with raw type of `String` also automatically satisfies StringRepresentable protocol.
Property signatures are just the property name
Function signatures are the function name with "()" at the end. If there are parameters then the public facing parameter names are listed in order with ":" after each. If a parameter does not have a public facing name then the private name is used instead
- Note: This associatedtype has the exact same name as Stubbable's so that a single type will satisfy both.
## Example ##
```swift
enum Function: String, StringRepresentable {
// property signatures are just the property name
case myProperty = "myProperty"
// function signatures are the function name with parameter names listed at the end in "()"
case giveMeAString = "noParameters()"
case hereAreTwoParameters = "hereAreTwoParameters(string1:string2:)"
case paramWithDifferentNames = "paramWithDifferentNames(publicName:)"
case paramWithNoPublicName = "paramWithNoPublicName(privateName:)"
}
func noParameters() -> Bool {
// ...
}
func hereAreTwoParameters(string1: String, string2: String) -> Bool {
// ...
}
func paramWithDifferentNames(publicName privateName: String) -> String {
// ...
}
func paramWithNoPublicName(_ privateName: String) -> String {
// ...
}
```
*/
associatedtype Function: StringRepresentable
/**
This is where the recorded calls information for instance functions and properties is held. Defaults to using NSMapTable.
Should ONLY read from this property when debugging.
- Important: Do not modify this property's value.
- Note: Override this property if the Spyable object cannot be weakly referenced.
## Example Overriding ##
```swift
var _callsDictionary: RecordedCallsDictionary = RecordedCallsDictionary()
```
*/
var _callsDictionary: RecordedCallsDictionary { get }
/**
Used to record a function call. Must call in every function for Spyable to work properly.
- Important: Do NOT implement function. Use default implementation provided by Spry.
- Parameter function: The function signature to be recorded. Defaults to #function.
- Parameter arguments: The function arguments being passed in. Must include all arguments in the proper order for Spyable to work properly.
*/
func recordCall(functionName: String, arguments: Any?..., file: String, line: Int)
/**
Used to determine if a function has been called with the specified arguments and the amount of times specified.
- Important: Do NOT implement function. Use default implementation provided by Spry.
- Important: Only use this function if NOT using the provided `haveReceived()` matcher used in conjunction with [Quick/Nimble](https://github.com/Quick).
- Parameter function: The `Function` specified.
- Parameter arguments: The arguments specified. If this value is an empty array, then any parameters passed into the actual function call will result in a success (i.e. passing in `[]` is equivalent to passing in Argument.anything for every expected parameter.)
- Parameter countSpecifier: Used to specify the amount of times this function needs to be called for a successful result. See `CountSpecifier` for more detials.
- Returns: A DidCallResult. See `DidCallResult` for more details.
*/
func didCall(_ function: Function, withArguments arguments: [SpryEquatable?], countSpecifier: CountSpecifier) -> DidCallResult
/**
Removes all recorded calls.
- Important: Do NOT implement function. Use default implementation provided by Spry.
- Important: The spied object will have NO way of knowing about calls made before this function is called. Use with caution.
*/
func resetCalls()
// MARK: Static
/**
The type that represents function names when spying.
Ideal to use an enum with raw type of `String`. An enum with raw type of `String` also automatically satisfies StringRepresentable protocol.
Property signatures are just the property name
Function signatures are the function name with "()" at the end. If there are parameters then the public facing parameter names are listed in order with ":" after each. If a parameter does not have a public facing name then the private name is used instead
- Note: This associatedtype has the exact same name as Stubbable's so that a single type will satisfy both.
## Example ##
```swift
enum ClassFunction: String, StringRepresentable {
// property signatures are just the property name
case myProperty = "myProperty"
// function signatures are the function name with parameter names listed at the end in "()"
case giveMeAString = "noParameters()"
case hereAreTwoParameters = "hereAreTwoParameters(string1:string2:)"
case paramWithDifferentNames = "paramWithDifferentNames(publicName:)"
case paramWithNoPublicName = "paramWithNoPublicName(privateName:)"
}
class func noParameters() -> Bool {
// ...
}
class func hereAreTwoParameters(string1: String, string2: String) -> Bool {
// ...
}
class func paramWithDifferentNames(publicName privateName: String) -> String {
// ...
}
class func paramWithNoPublicName(_ privateName: String) -> String {
// ...
}
```
*/
associatedtype ClassFunction: StringRepresentable
/**
This is where the recorded calls information for class functions and properties is held. Defaults to using NSMapTable.
Should ONLY read from this property when debugging.
- Important: Do not modify this property's value.
- Note: Override this property if the Spyable object cannot be weakly referenced.
## Example Overriding ##
```swift
var _callsDictionary: RecordedCallsDictionary = RecordedCallsDictionary()
```
*/
static var _callsDictionary: RecordedCallsDictionary { get }
/**
Used to record a function call. Must call in every function for Spyable to work properly.
- Important: Do NOT implement function. Use default implementation provided by Spry.
- Parameter function: The function signature to be recorded. Defaults to #function.
- Parameter arguments: The function arguments being passed in. Must include all arguments in the proper order for Spyable to work properly.
*/
static func recordCall(functionName: String, arguments: Any?..., file: String, line: Int)
/**
Used to determine if a function has been called with the specified arguments and the amount of times specified.
- Important: Do NOT implement function. Use default implementation provided by Spry.
- Important: Only use this function if NOT using the provided `haveReceived()` matcher used in conjunction with [Quick/Nimble](https://github.com/Quick).
- Parameter function: The `Function` specified.
- Parameter arguments: The arguments specified. If this value is an empty array, then any parameters passed into the actual function call will result in a success (i.e. passing in `[]` is equivalent to passing in Argument.anything for every expected parameter.)
- Parameter countSpecifier: Used to specify the amount of times this function needs to be called for a successful result. See `CountSpecifier` for more detials.
- Returns: A DidCallResult. See `DidCallResult` for more details.
*/
static func didCall(_ function: ClassFunction, withArguments arguments: [SpryEquatable?], countSpecifier: CountSpecifier) -> DidCallResult
/**
Removes all recorded calls.
- Important: Do NOT implement function. Use default implementation provided by Spry.
- Important: The spied object will have NO way of knowing about calls made before this function is called. Use with caution.
*/
static func resetCalls()
}
// MARK - Spyable Extension
public extension Spyable {
// MARK: Instance
var _callsDictionary: RecordedCallsDictionary {
get {
guard let callsDict = callsMapTable.object(forKey: self) else {
let callsDict = RecordedCallsDictionary()
callsMapTable.setObject(callsDict, forKey: self)
return callsDict
}
return callsDict
}
}
func recordCall(functionName: String = #function, arguments: Any?..., file: String = #file, line: Int = #line) {
let function = Function(functionName: functionName, type: Self.self, file: file, line: line)
internal_recordCall(function: function, arguments: arguments)
}
func didCall(_ function: Function, withArguments arguments: [SpryEquatable?] = [], countSpecifier: CountSpecifier = .atLeast(1)) -> DidCallResult {
let success: Bool
switch countSpecifier {
case .exactly(let count): success = timesCalled(function, arguments: arguments) == count
case .atLeast(let count): success = timesCalled(function, arguments: arguments) >= count
case .atMost(let count): success = timesCalled(function, arguments: arguments) <= count
}
let recordedCallsDescription = _callsDictionary.friendlyDescription
return DidCallResult(success: success, recordedCallsDescription: recordedCallsDescription)
}
func resetCalls() {
_callsDictionary.clearAllCalls()
}
// MARK: Static
static var _callsDictionary: RecordedCallsDictionary {
get {
guard let callsDict = callsMapTable.object(forKey: self) else {
let callsDict = RecordedCallsDictionary()
callsMapTable.setObject(callsDict, forKey: self)
return callsDict
}
return callsDict
}
}
static func recordCall(functionName: String = #function, arguments: Any?..., file: String = #file, line: Int = #line) {
let function = ClassFunction(functionName: functionName, type: self, file: file, line: line)
internal_recordCall(function: function, arguments: arguments)
}
static func didCall(_ function: ClassFunction, withArguments arguments: [SpryEquatable?] = [], countSpecifier: CountSpecifier = .atLeast(1)) -> DidCallResult {
let success: Bool
switch countSpecifier {
case .exactly(let count): success = timesCalled(function, arguments: arguments) == count
case .atLeast(let count): success = timesCalled(function, arguments: arguments) >= count
case .atMost(let count): success = timesCalled(function, arguments: arguments) <= count
}
let recordedCallsDescription = _callsDictionary.friendlyDescription
return DidCallResult(success: success, recordedCallsDescription: recordedCallsDescription)
}
static func resetCalls() {
_callsDictionary.clearAllCalls()
}
// MARK: - Internal Functions
/// This is for `Spryable` to act as a pass-through to record a call.
internal func internal_recordCall(function: Function, arguments: [Any?]) {
let call = RecordedCall(functionName: function.rawValue, arguments: arguments)
_callsDictionary.add(call: call)
}
/// This is for `Spryable` to act as a pass-through to record a call.
internal static func internal_recordCall(function: ClassFunction, arguments: [Any?]) {
let call = RecordedCall(functionName: function.rawValue, arguments: arguments)
_callsDictionary.add(call: call)
}
// MARK: - Private Functions
private func timesCalled(_ function: Function, arguments: [SpryEquatable?]) -> Int {
return numberOfMatchingCalls(fakeType: Self.self, functionName: function.rawValue, arguments: arguments, callsDictionary: _callsDictionary)
}
private static func timesCalled(_ function: ClassFunction, arguments: [SpryEquatable?]) -> Int {
return numberOfMatchingCalls(fakeType: Self.self, functionName: function.rawValue, arguments: arguments, callsDictionary: _callsDictionary)
}
}
// MARK: Private Functions
private func numberOfMatchingCalls<T>(fakeType: T.Type, functionName: String, arguments: [SpryEquatable?], callsDictionary: RecordedCallsDictionary) -> Int {
let matchingFunctions = callsDictionary.getCalls(for: functionName)
// if no args passed in then only check if function was called (allows user to not care about args being passed in)
if arguments.isEmpty {
return matchingFunctions.count
}
return matchingFunctions.reduce(0) {
return $0 + isEqualArgsLists(fakeType: fakeType, functionName: functionName, specifiedArgs: arguments, actualArgs: $1.arguments).toInt()
}
}
private func matchingIndexesFor(functionName: String, functionList: [String]) -> [Int] {
return functionList.enumerated().map { $1 == functionName ? $0 : -1 }.filter { $0 != -1 }
}
private func isOptional(_ value: Any) -> Bool {
let mirror = Mirror(reflecting: value)
return mirror.displayStyle == .optional
}
| mit | 7b487143fb234edee0b0053b9f6cea4a | 40.982249 | 266 | 0.699084 | 5.120895 | false | false | false | false |
huangboju/Moots | UICollectionViewLayout/Blueprints-master/Example-OSX/Scenes/ExampleDataMocks.swift | 1 | 1914 | //
// ExampleDataMocks.swift
// Example-OSX
//
// Created by Chris on 16/01/2019.
// Copyright © 2019 Christoffer Winterkvist. All rights reserved.
//
import Foundation
class ExampleDataMocks {
var sections: [ExampleSection]?
init(numberOfSections sections: Int, numberOfRowsInSection rows: Int) {
setupDummyData(numberOfSections: sections, numberOfRowsInSection: rows)
}
}
private extension ExampleDataMocks {
func setupDummyData(numberOfSections sectionCount: Int, numberOfRowsInSection rowCount: Int) {
var exampleSections = [ExampleSection]()
for index in 1...sectionCount {
let title = NSLocalizedString("Section \(index)", comment: "Section title with index")
let exampleSection = createExampleSection(withTitle: title,
andNumberOfRows: rowCount)
exampleSections.append(exampleSection)
}
sections = exampleSections
}
func createExampleSection(withTitle title: String, andNumberOfRows rowCount: Int) -> ExampleSection {
var sectionContents = [ExampleContent]()
for index in 1...rowCount {
let contentTitle = NSLocalizedString("Title \(index)", comment: "Contents title with index")
let exampleContent = createExampleContent(withTitle: contentTitle)
sectionContents.append(exampleContent)
}
let exampleSection = ExampleSection(title: title,
contents: sectionContents)
return exampleSection
}
func createExampleContent(withTitle title: String) -> ExampleContent {
let message = Lorem.tweet
let exampleContent = ExampleContent(title: title,
message: message,
iconImage: nil)
return exampleContent
}
}
| mit | 11cf272997a947e4e9bfbb25dca88fb2 | 35.788462 | 105 | 0.629378 | 5.561047 | false | false | false | false |
usharif/GrapeVyne | GrapeVyne/Network.swift | 1 | 6682 | //
// Network.swift
// StoryApp
//
// Created by Umair Sharif on 1/28/17.
// Copyright © 2017 usharif. All rights reserved.
//
import Foundation
import Alamofire
import Kanna
import SwiftyJSON
import Async
class SnopesScrapeNetwork {
private let factCheckURL = "http://www.snopes.com/category/facts/page/"
private let whatsNewURL = "http://www.snopes.com/whats-new/page/"
private let hotFiftyURL = "http://www.snopes.com/50-hottest-urban-legends/"
let pageNum = 15
var counter = 0
public func prepareDB() -> [Story] {
var arrayOfParsedStories = [Story]()
let managedObject = CoreDataManager.fetchModel(entity: "CDStory")
if managedObject.isEmpty { // Nothing in Core Data
for i in 1...pageNum {
let tempArray = getStoriesFor(url: "\(factCheckURL)\(i)")
for story in tempArray {
let parsedStory = getFactValueFor(story: story)
if let storyWithID = CoreDataManager.writeToModel(parsedStory) {
arrayOfParsedStories.append(storyWithID)
}
}
}
} else if managedObject.count > 1500 {// Automatically refresh database
for object in managedObject {
CoreDataManager.deleteObjectBy(id: object.objectID)
}
for i in 1...pageNum {
let tempArray = getStoriesFor(url: "\(factCheckURL)\(i)")
for story in tempArray {
let parsedStory = getFactValueFor(story: story)
if let storyWithID = CoreDataManager.writeToModel(parsedStory) {
arrayOfParsedStories.append(storyWithID)
}
}
}
} else { // Something in Core Data
print("Stories in CD \(managedObject.count)")
for object in managedObject {
let title = object.value(forKey: "title") as! String
let factValue = object.value(forKey: "fact") as! Bool
let urlString = object.value(forKey: "urlString") as! String
let id = object.objectID
let tempStory = Story(title: title, url: urlString, fact: factValue, id: id)
arrayOfParsedStories.append(tempStory)
}
}
return arrayOfParsedStories
}
public func getStories() -> [Story] {
var arrayOfParsedStories = [Story]()
counter += 1
let tempArray = getStoriesFor(url: "\(factCheckURL)\(pageNum+counter)")
for story in tempArray {
let parsedStory = getFactValueFor(story: story)
if let storyWithID = CoreDataManager.writeToModel(parsedStory) {
arrayOfParsedStories.append(storyWithID)
}
}
return arrayOfParsedStories
}
public func getStoriesFor(url: String) -> [Story] {
var array = [Story]()
let session = URLSession(configuration: .default)
if let data = session.synchronousDataTask(with: URL(string: url)!).0,
let html = String(data: data, encoding: .utf8) {
array = self.scrapeStories(html: html)
}
return array
}
public func getFactValueFor(story: Story) -> Story {
var parsedStory = story
let session = URLSession(configuration: .default)
if let data = session.synchronousDataTask(with: URL(string: story.url)!).0,
let html = String(data: data, encoding: .utf8) {
if let factValueString = self.scrapeFactValue(html: html), let factValue = determineStoryReliable(factString: factValueString) {
parsedStory.fact = factValue
}
}
return parsedStory
}
private func scrapeFactValue(html: String) -> String? {
var ratingString: String?
if let doc = Kanna.HTML(html: html, encoding: .utf8) {
let xmlElement = doc.at_xpath("/html/body/main/section/div[2]/div/article/div[4]/div[1]/span", namespaces: nil)
if let rating = xmlElement?.text {
ratingString = rating
}
if ratingString == nil {
let xmlElement = doc.at_xpath("/html/body/main/section/div[2]/div/article/div[4]/div[2]/span", namespaces: nil)
if let rating = xmlElement?.text {
ratingString = rating
}
}
}
return ratingString
}
private func scrapeStories(html: String) -> [Story] {
var _arrayOfStories = [Story]()
if let doc = Kanna.HTML(html: html, encoding: .utf8) {
for story in doc.xpath("//*[@id='main-list']/article/a") {
var parsedStory = Story(title: "", url: "", fact: false, id: nil)
if let url = story["href"] {
parsedStory.url = url
}
let h2 = story.css("h2")
for title in h2 {
if let text = title.text {
parsedStory.title = text
}
}
if parsedStory.title.contains("?") {
if !parsedStory.title.lowercased().containsIncorrectSyntaxQuestion() {
_arrayOfStories.append(parsedStory)
}
}
}
}
return _arrayOfStories
}
}
fileprivate func determineStoryReliable(factString: String) -> Bool? {
switch factString {
case "TRUE", "MOSTLY TRUE":
return true
case "FALSE", "MOSTLY FALSE", "MIXTURE", "MISCAPTIONED", "UNPROVEN", "SCAM", "OUTDATED":
return false
default:
return nil
}
}
extension URLSession {
func synchronousDataTask(with url: URL) -> (Data?, URLResponse?, Error?) {
var data: Data?
var response: URLResponse?
var error: Error?
let semaphore = DispatchSemaphore(value: 0)
let dataTask = self.dataTask(with: url) {
data = $0
response = $1
error = $2
semaphore.signal()
}
dataTask.resume()
_ = semaphore.wait(timeout: .distantFuture)
return (data, response, error)
}
}
extension String {
func containsIncorrectSyntaxQuestion() -> Bool {
let incorrectSyntaxQuestionArray = ["what","why","when","where","how"]
for string in incorrectSyntaxQuestionArray {
if self.contains(string) {
return true
}
}
return false
}
}
| mit | 962416fc7338e49272a186f312acbe4d | 35.113514 | 140 | 0.549918 | 4.708245 | false | false | false | false |
Aishwarya-Ramakrishnan/sparkios | Source/Phone/Call/VideoLicense.swift | 1 | 3456 | // Copyright 2016 Cisco Systems Inc
//
// 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
class VideoLicense {
static let sharedInstance = VideoLicense()
private let userDefaults = UserDefaults.sharedInstance
func checkActivation(_ completion: @escaping (_ isActivated: Bool) -> Void) {
guard needActivation() else {
completion(true)
return
}
promptForActivation(completion)
}
func disableActivation() {
userDefaults.isVideoLicenseActivationDisabled = true
}
// It's used for development only, to reset video license settings.
func resetActivation() {
userDefaults.removeVideoLicenseSetting()
}
private func promptForActivation(_ completion: @escaping (_ isActivated: Bool) -> Void) {
let AlertTitle = "Activate License"
let AlertMessage = "To enable video calls, activate a free video license (H.264 AVC) from Cisco. By selecting 'Activate', you accept the Cisco End User License Agreement and Notices."
let alertController = UIAlertController(title: AlertTitle, message: AlertMessage, preferredStyle: UIAlertControllerStyle.alert)
alertController.addAction(UIAlertAction(title: "Activate", style: UIAlertActionStyle.default) { _ in
self.activateLicense()
completion(true)
})
alertController.addAction(UIAlertAction(title: "View License", style: UIAlertActionStyle.default) { _ in
completion(false)
self.viewLicense()
})
alertController.addAction(UIAlertAction(title: "Cancel", style: UIAlertActionStyle.cancel) { _ in
completion(false)
})
alertController.present(true, completion: nil)
}
private func needActivation() -> Bool {
if userDefaults.isVideoLicenseActivated || userDefaults.isVideoLicenseActivationDisabled {
return false
}
return true
}
private func activateLicense() {
userDefaults.isVideoLicenseActivated = true
CallMetrics.sharedInstance.reportVideoLicenseActivation()
}
private func viewLicense() {
guard let url = URL(string: "http://www.openh264.org/BINARY_LICENSE.txt") else {
return
}
UIApplication.shared.openURL(url)
}
}
| mit | 51a3c809e43ed3de0d781d0b27b5069a | 38.272727 | 191 | 0.679977 | 5.189189 | false | false | false | false |
truemetal/vapor-2-heroku-auth-template | Sources/App/Models/User.swift | 1 | 1682 | import Authentication
import Vapor
final class User: AppModel {
var id: Int?
var username: String
var passwordHash: String
var createdAt: Date?
var updatedAt: Date?
static let createdAtKey: TimestampKey? = \.createdAt
static let updatedAtKey: TimestampKey? = \.updatedAt
init(id: Int? = nil, username: String, passwordHash: String) {
self.id = id
self.username = username
self.passwordHash = passwordHash
}
var tokens: Children<User, AccessToken> { children(\.userID) }
class func register(username: String, password: String, on conn: DatabaseConnectable) throws -> EventLoopFuture<User> {
return try User(username: username, passwordHash: BCrypt.hash(password)).save(on: conn)
}
func `public`() throws -> PublicUser { return try PublicUser(id: requireID(), username: username) }
}
extension User: PasswordAuthenticatable {
static var usernameKey: WritableKeyPath<User, String> { \.username }
static var passwordKey: WritableKeyPath<User, String> { \.passwordHash }
}
extension User: TokenAuthenticatable {
typealias TokenType = AccessToken
}
extension User: Migration {
static func prepare(on conn: AppDatabase.Connection) -> Future<Void> {
return AppDatabase.create(User.self, on: conn) { builder in
builder.field(for: \.id, isIdentifier: true)
builder.field(for: \.username)
builder.field(for: \.passwordHash)
builder.field(for: \.createdAt)
builder.field(for: \.updatedAt)
}
}
}
// MARK: -
struct PublicUser: Content {
var id: Int
var username: String
}
| mit | 0ad5aafb123d75fb627d8faf9312fa49 | 29.035714 | 123 | 0.659929 | 4.346253 | false | false | false | false |
lwg123/swift_LWGWB | LWGWB/LWGWB/classes/Home/UIPopover/PopoverAnimator.swift | 1 | 4112 | //
// PopoverAnimator.swift
// LWGWB
//
// Created by weiguang on 2017/2/8.
// Copyright © 2017年 weiguang. All rights reserved.
//
import UIKit
class PopoverAnimator: NSObject {
// MARK: - 对外提供的属性
var isPresented : Bool = false
var presentedFrame : CGRect = CGRect.zero
var callBack : ((_ presented : Bool) -> ())?
// MARK: -自定义构造函数
// 注意:如果自定义了一个构造函数,但是没有对默认构造函数init()进行重写,那么自定义的构造函数会覆盖默认的init()构造函数
init(callBack : @escaping (_ presented : Bool) -> ()) {
self.callBack = callBack;
}
}
// MARK:- 自定义转场代理的方法
extension PopoverAnimator : UIViewControllerTransitioningDelegate {
// 目的:改变弹出view的尺寸
func presentationController(forPresented presented: UIViewController, presenting: UIViewController?, source: UIViewController) -> UIPresentationController? {
let presentation = XMGPresentionController(presentedViewController: presented, presenting: presenting)
presentation.presentedFrame = presentedFrame
return presentation
}
// 目的:自定义弹出的动画
func animationController(forPresented presented: UIViewController, presenting: UIViewController, source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
isPresented = true
callBack!(isPresented)
return self
}
// 目的:自定义消失的动画
func animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
isPresented = false
callBack!(isPresented)
return self
}
}
// MARK:- 弹出和消失动画代理的方法
extension PopoverAnimator : UIViewControllerAnimatedTransitioning {
/// 动画执行的时间
func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
return 0.5
}
/// 获取`转场的上下文`:可以通过转场上下文获取弹出的View和消失的View
// UITransitionContextFromViewKey : 获取消失的View
// UITransitionContextToViewKey : 获取弹出的View
func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
isPresented ? animationForPresentedView(transitionContext) : animationForDismissedView(transitionContext)
}
/// 自定义弹出动画
fileprivate func animationForPresentedView(_ transitionContext: UIViewControllerContextTransitioning) {
// 1.获取弹出的View
let presentView = transitionContext.view(forKey: UITransitionContextViewKey.to)!
// 2.将弹出的View添加到containerView中
transitionContext.containerView.addSubview(presentView)
// 3.执行动画
presentView.transform = CGAffineTransform(scaleX: 1.0, y: 0.0)
presentView.layer.anchorPoint = CGPoint(x: 0.5, y: 0)
UIView.animate(withDuration: transitionDuration(using: transitionContext), animations: { () -> Void in
presentView.transform = CGAffineTransform.identity
}, completion: {(_) -> Void in
// 必须告诉转场上下文你已经完成动画
transitionContext.completeTransition(true)
})
}
/// 自定义消失动画
fileprivate func animationForDismissedView(_ transitionContext: UIViewControllerContextTransitioning){
// 1.获取消失的View
let dismissView = transitionContext.view(forKey: UITransitionContextViewKey.from)
// 2.执行动画
UIView.animate(withDuration: transitionDuration(using: transitionContext), animations: { () -> Void in
dismissView?.transform = CGAffineTransform(scaleX: 1.0, y: 0.00001)
}, completion: {(_) -> Void in
dismissView?.removeFromSuperview()
// 必须告诉专场上下文你已经完成动画
transitionContext.completeTransition(true)
})
}
}
| mit | e7ade69d3db110f6c54755687285d054 | 34.754902 | 170 | 0.684124 | 5.39497 | false | false | false | false |
TongjiUAppleClub/WeCitizens | WeCitizens/RRTagCollectionViewCell.swift | 1 | 3591 | //
// RRTagCollectionViewCell.swift
// RRTagController
//
// Created by Remi Robert on 20/02/15.
// Copyright (c) 2015 Remi Robert. All rights reserved.
//
import UIKit
let RRTagCollectionViewCellIdentifier = "RRTagCollectionViewCellIdentifier"
class RRTagCollectionViewCell: UICollectionViewCell {
var iSelected: Bool = false
lazy var textContent: UILabel! = {
let textContent = UILabel(frame: CGRectZero)
textContent.layer.masksToBounds = true
textContent.layer.cornerRadius = 20
textContent.layer.borderWidth = 2
textContent.layer.borderColor = UIColor(red:0.88, green:0.88, blue:0.88, alpha:1).CGColor
textContent.font = UIFont.boldSystemFontOfSize(17)
textContent.textAlignment = NSTextAlignment.Center
return textContent
}()
func initContent(tag: Tag) {
self.contentView.addSubview(textContent)
textContent.text = tag.textContent
textContent.sizeToFit()
textContent.frame.size.width = textContent.frame.size.width + 30
textContent.frame.size.height = textContent.frame.size.height + 20
iSelected = tag.isSelected
textContent.backgroundColor = UIColor.clearColor()
self.textContent.layer.backgroundColor = (self.iSelected == true) ? colorSelectedTag.CGColor : colorUnselectedTag.CGColor
self.textContent.textColor = (self.iSelected == true) ? colorTextSelectedTag : colorTextUnSelectedTag
}
func initAddButtonContent() {
self.contentView.addSubview(textContent)
textContent.text = "+"
textContent.sizeToFit()
textContent.frame.size = CGSizeMake(40, 40)
textContent.backgroundColor = UIColor.clearColor()
self.textContent.layer.backgroundColor = UIColor.grayColor().CGColor
self.textContent.textColor = UIColor.whiteColor()
}
func animateSelection(selection: Bool) {
iSelected = selection
self.textContent.frame.size = CGSizeMake(self.textContent.frame.size.width - 20, self.textContent.frame.size.height - 20)
self.textContent.frame.origin = CGPointMake(self.textContent.frame.origin.x + 10, self.textContent.frame.origin.y + 10)
UIView.animateWithDuration(0.5, delay: 0, usingSpringWithDamping: 0.3, initialSpringVelocity: 0.4, options: UIViewAnimationOptions(), animations: { () -> Void in
self.textContent.layer.backgroundColor = (self.iSelected == true) ? colorSelectedTag.CGColor : colorUnselectedTag.CGColor
self.textContent.textColor = (self.iSelected == true) ? colorTextSelectedTag : colorTextUnSelectedTag
self.textContent.frame.size = CGSizeMake(self.textContent.frame.size.width + 20, self.textContent.frame.size.height + 20)
self.textContent.center = CGPointMake(self.contentView.frame.size.width / 2, self.contentView.frame.size.height / 2)
}, completion: nil)
}
class func contentHeight(content: String) -> CGSize {
let styleText = NSMutableParagraphStyle()
styleText.alignment = NSTextAlignment.Center
let attributs = [NSParagraphStyleAttributeName:styleText, NSFontAttributeName:UIFont.boldSystemFontOfSize(17)]
let sizeBoundsContent = (content as NSString).boundingRectWithSize(CGSizeMake(UIScreen.mainScreen().bounds.size.width,
UIScreen.mainScreen().bounds.size.height), options: NSStringDrawingOptions.UsesLineFragmentOrigin, attributes: attributs, context: nil)
return CGSizeMake(sizeBoundsContent.width + 30, sizeBoundsContent.height + 20)
}
}
| mit | e404c1192c384462bde55095569aa20c | 48.875 | 169 | 0.713172 | 4.75 | false | false | false | false |
barteljan/VISPER | Example/VISPER-Reactive-Tests/ReactiveTests.swift | 1 | 3672 | //
// RxTests.swift
// ReactiveReSwift
//
// Created by Charlotte Tortorella on 25/11/16.
// Copyright © 2016 Benjamin Encz. All rights reserved.
//
import XCTest
@testable import VISPER_Reactive
/*
The MIT License (MIT)
Copyright (c) 2016 ReSwift Contributors
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 ReactiveTests: XCTestCase {
func testObservablePropertySendsNewValues() {
let values = (10, 20, 30)
var receivedValue: Int?
let property = ObservableProperty(values.0)
property.subscribe {
receivedValue = $0
}
XCTAssertEqual(receivedValue, values.0)
property.value = values.1
XCTAssertEqual(receivedValue, values.1)
property.value = values.2
XCTAssertEqual(receivedValue, values.2)
}
func testObservablePropertyMapsValues() {
let values = (10, 20, 30)
var receivedValue: Int?
let property = ObservableProperty(values.0)
property.map { $0 * 10 }.subscribe {
receivedValue = $0
}
XCTAssertEqual(receivedValue, values.0 * 10)
property.value = values.1
XCTAssertEqual(receivedValue, values.1 * 10)
property.value = values.2
XCTAssertEqual(receivedValue, values.2 * 10)
}
func testObservablePropertyFiltersValues() {
let values = [10, 10, 20, 20, 30, 30, 30]
var lastReceivedValue: Int?
var receivedValues: [Int] = []
let property = ObservableProperty(10)
property.distinct().subscribe {
XCTAssertNotEqual(lastReceivedValue, $0)
lastReceivedValue = $0
receivedValues += [$0]
}
values.forEach { property.value = $0 }
XCTAssertEqual(receivedValues, [10, 20, 30])
}
func testObservablePropertyDisposesOfReferences() {
let property = ObservableProperty(())
let reference = property.subscribe({})
XCTAssertEqual(property.subscriptions.count, 1)
reference?.dispose()
XCTAssertEqual(property.subscriptions.count, 0)
}
func testSubscriptionBagDisposesOfReferences() {
let property = ObservableProperty(()).deliveredOn(DispatchQueue.global())
let bag = SubscriptionReferenceBag(property.subscribe({}))
bag += property.subscribe({})
XCTAssertEqual(property.subscriptions.count, 2)
bag.dispose()
XCTAssertEqual(property.subscriptions.count, 0)
}
func testThatDisposingOfAReferenceTwiceIsOkay() {
let property = ObservableProperty(())
let reference = property.subscribe({})
reference?.dispose()
reference?.dispose()
}
}
| mit | b586efb446180e18c75b12be6df8c8c4 | 39.788889 | 461 | 0.683465 | 4.830263 | false | true | false | false |
justinsacbibit/chat | Chat-iOS-Swift/Controllers/ChatViewController.swift | 1 | 11419 | //
// ChatViewController.swift
// Chat-iOS-Swift
//
// Created by Justin Sacbibit on 2014-07-28.
// Copyright (c) 2014 Justin Sacbibit. All rights reserved.
//
import UIKit
protocol ChatViewControllerDelegate {
func chatViewControllerDidLogout(chatViewController: ChatViewController)
}
class ChatViewController: JSQMessagesViewController, UIAlertViewDelegate {
var delegate: ChatViewControllerDelegate?
var user: User?
private var messages: Array<JSQMessageData> = []
private var socket: SIOSocket?
private var outgoingBubbleImageView = JSQMessagesBubbleImageFactory.outgoingMessageBubbleImageViewWithColor(UIColor.jsq_messageBubbleLightGrayColor())
private var incomingBubbleImageView = JSQMessagesBubbleImageFactory.incomingMessageBubbleImageViewWithColor(UIColor.jsq_messageBubbleBlueColor())
private var systemBubbleImageView = JSQMessagesBubbleImageFactory.incomingMessageBubbleImageViewWithColor(UIColor.jsq_messageBubbleGreenColor())
private var avatars = [String: UIImage]()
private var typing = false
private var stopTypingTimer: NSTimer?
override func viewDidLoad() {
super.viewDidLoad()
if let username = self.user?.username {
var image = JSQMessagesAvatarFactory.avatarWithUserInitials(avatarLetters(username),
backgroundColor: UIColor(white: CGFloat(0.85), alpha: 1),
textColor: UIColor(white: 0.6, alpha: 1),
font: UIFont.systemFontOfSize(14),
diameter: UInt(self.collectionView.collectionViewLayout.outgoingAvatarViewSize.width))
self.avatars[username] = image
}
var systemAvatar = JSQMessagesAvatarFactory.avatarWithImage(UIImage(named: "SHIP"),
diameter: UInt(self.collectionView.collectionViewLayout.incomingAvatarViewSize.width))
self.avatars["System"] = systemAvatar
setupUI()
var url = "http://localhost:8080"
url = "http://chat-simple.herokuapp.com/"
connectWebSocket(url)
}
func setupUI() {
navigationItem.title = "General"
navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Action, target: self, action: "options")
}
func options() {
UIAlertView(title: "Log out", message: "Are you sure you want to log out?", delegate: self, cancelButtonTitle: "No", otherButtonTitles: "Yes").show()
}
func connectWebSocket(host: NSString) {
SIOSocket.socketWithHost(host, response: { (socket: SIOSocket!) -> Void in
self.socket = socket
socket.onConnect = { () -> () in
socket.emit("addUser", message: self.user?.username)
}
socket.on("login", executeBlock: { (response) -> Void in
if let json = response as? Dictionary<String, AnyObject> {
if let numUsers = json["numUsers"] as? NSNumber {
self.connectedToChat(numUsers)
}
}
})
socket.on("typing", executeBlock: { (response) -> Void in
self.showTypingIndicator = true
})
socket.on("stopTyping", executeBlock: { (response) -> Void in
self.showTypingIndicator = false
})
socket.on("newMessage", executeBlock: { (response) -> Void in
if let json = response as? Dictionary<String, String> {
JSQSystemSoundPlayer.jsq_playMessageReceivedSound()
self.messages.append(Message(body: json["message"]!, sender: json["username"]!))
self.finishReceivingMessage()
}
})
socket.on("userJoined", executeBlock: { (response) -> Void in
if let json = response as? Dictionary<String, AnyObject> {
var username = json["username"] as AnyObject? as? String
var numUsers = json["numUsers"] as AnyObject? as? NSNumber
var message = Message(body: NSString(format: "%@ has joined.", username!), sender: "System")
self.messages.append(message)
self.finishReceivingMessage()
}
})
socket.on("userLeft", executeBlock: { (response) -> Void in
if let json = response as? Dictionary<String, AnyObject> {
var username = json["username"] as AnyObject? as? String
var numUsers = json["numUsers"] as AnyObject? as? NSNumber
var message = Message(body: NSString(format: "%@ has left.", username!), sender: "System")
self.messages.append(message)
self.finishReceivingMessage()
}
})
})
}
func connectedToChat(numUsers: NSNumber) {
var message = Message(body: "Welcome to general chat.", sender: "System")
self.messages.append(message)
message = Message(body: NSString(format: "Number of users online: %@", numUsers), sender: "System")
self.messages.append(message)
self.finishReceivingMessage()
}
func avatarLetters(username: String) -> String! {
let nsstring = username as NSString
return nsstring.substringToIndex(2)
}
// MARK: JSQMessagesCollectionViewDataSource
func sender() -> String! {
return self.user?.username
}
override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return self.messages.count
}
override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
var cell = super.collectionView(collectionView, cellForItemAtIndexPath: indexPath) as JSQMessagesCollectionViewCell
var message = self.messages[indexPath.item]
if message.sender() == self.sender() {
cell.textView.textColor = UIColor.blackColor()
} else {
cell.textView.textColor = UIColor.whiteColor()
}
return cell
}
override func collectionView(collectionView: JSQMessagesCollectionView!, messageDataForItemAtIndexPath indexPath: NSIndexPath!) -> JSQMessageData! {
return self.messages[indexPath.item]
}
override func collectionView(collectionView: JSQMessagesCollectionView!, bubbleImageViewForItemAtIndexPath indexPath: NSIndexPath!) -> UIImageView! {
var message = self.messages[indexPath.item]
if message.sender() == "System" {
return UIImageView(image: self.systemBubbleImageView.image, highlightedImage: self.systemBubbleImageView.highlightedImage)
}
if message.sender() == self.sender() {
return UIImageView(image: self.outgoingBubbleImageView.image, highlightedImage: self.outgoingBubbleImageView.highlightedImage)
}
return UIImageView(image: self.incomingBubbleImageView.image, highlightedImage: self.incomingBubbleImageView.highlightedImage)
}
override func collectionView(collectionView: JSQMessagesCollectionView!, avatarImageViewForItemAtIndexPath indexPath: NSIndexPath!) -> UIImageView! {
var message = self.messages[indexPath.item]
if let avatarImage = self.avatars[message.sender()] {
return UIImageView(image: avatarImage)
}
var avatarImage = JSQMessagesAvatarFactory.avatarWithUserInitials(avatarLetters(message.sender()),
backgroundColor: UIColor(white: CGFloat(0.85), alpha: 1),
textColor: UIColor(white: 0.6, alpha: 1),
font: UIFont.systemFontOfSize(14),
diameter: UInt(self.collectionView.collectionViewLayout.outgoingAvatarViewSize.width))
self.avatars[message.sender()] = avatarImage
return UIImageView(image: avatarImage)
}
override func collectionView(collectionView: JSQMessagesCollectionView!, attributedTextForCellTopLabelAtIndexPath indexPath: NSIndexPath!) -> NSAttributedString! {
return nil
}
override func collectionView(collectionView: JSQMessagesCollectionView!, attributedTextForMessageBubbleTopLabelAtIndexPath indexPath: NSIndexPath!) -> NSAttributedString! {
var message = self.messages[indexPath.item]
if message.sender() == self.sender() {
return nil
}
if indexPath.item - 1 > 0 {
var previousMessage = self.messages[indexPath.item - 1]
if previousMessage.sender() == message.sender() {
return nil
}
}
return NSAttributedString(string: message.sender())
}
override func collectionView(collectionView: JSQMessagesCollectionView!, attributedTextForCellBottomLabelAtIndexPath indexPath: NSIndexPath!) -> NSAttributedString! {
return nil
}
override func didPressSendButton(button: UIButton!, withMessageText text: String!, sender: String!, date: NSDate!) {
self.socket?.emit("newMessage", message: text)
JSQSystemSoundPlayer.jsq_playMessageSentSound()
var message = JSQMessage(text: text, sender: sender)
self.messages.append(message)
self.finishSendingMessage()
}
// MARK: JSQMessagesCollectionViewFlowLayout
override func collectionView(collectionView: JSQMessagesCollectionView!, layout collectionViewLayout: JSQMessagesCollectionViewFlowLayout!, heightForMessageBubbleTopLabelAtIndexPath indexPath: NSIndexPath!) -> CGFloat {
var currentMessage = self.messages[indexPath.item]
if currentMessage.sender() == self.sender() {
return 0
}
if indexPath.item - 1 > 0 {
var previousMessage = self.messages[indexPath.item - 1]
if previousMessage.sender() == currentMessage.sender() {
return 0;
}
}
return kJSQMessagesCollectionViewCellLabelHeightDefault;
}
// MARK: UIAlertViewDelegate
func alertView(alertView: UIAlertView!, clickedButtonAtIndex buttonIndex: Int) {
if buttonIndex == 1 {
self.delegate?.chatViewControllerDidLogout(self)
}
}
// MARK: UITextViewDelegate
override func textViewDidChange(textView: UITextView) {
super.textViewDidChange(textView)
if !self.typing {
self.typing = true
self.socket?.emit("typing", message: nil)
}
if self.stopTypingTimer != nil {
self.stopTypingTimer?.invalidate()
self.stopTypingTimer = nil
}
self.stopTypingTimer = NSTimer.scheduledTimerWithTimeInterval(1.5, target: self, selector: "stopTyping", userInfo: nil, repeats: false)
}
func stopTyping() {
if self.typing {
socket?.emit("stopTyping", message: nil)
self.typing = false
}
self.stopTypingTimer?.invalidate()
self.stopTypingTimer = nil
}
}
| mit | 3824774d7d0cd36c10527ade35acaef8 | 40.675182 | 223 | 0.628864 | 5.698104 | false | false | false | false |
Mozharovsky/iOS-Demos | Search Mechanism/Swift/Search Mechanism/ViewController.swift | 1 | 5636 | //
// ViewController.swift
// Search Mechanism
//
// Created by E. Mozharovsky on 11/6/14.
// Copyright (c) 2014 GameApp. All rights reserved.
//
import UIKit
class ViewController: UITableViewController, UISearchResultsUpdating, UISearchControllerDelegate {
// Initialize and sort in alphabetical order.
let cities = ["Boston", "New York", "Oregon", "Tampa", "Los Angeles", "Dallas", "Miami", "Olympia", "Montgomery", "Washington", "Orlando", "Detroit"].sorted {
$0.localizedCaseInsensitiveCompare($1) == NSComparisonResult.OrderedAscending
}
var searchController: UISearchController?
var searchResultsController: UITableViewController?
let identifier = "Cell"
// Filtered results are stored here.
var results: NSMutableArray?
// MARK:- View life cycle
override func viewDidLoad() {
super.viewDidLoad()
// A table for search results and its controller.
let resultsTableView = UITableView(frame: self.tableView.frame)
self.searchResultsController = UITableViewController()
self.searchResultsController?.tableView = resultsTableView
self.searchResultsController?.tableView.dataSource = self
self.searchResultsController?.tableView.delegate = self
// Register cell class for the identifier.
self.tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: self.identifier)
self.searchResultsController?.tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: self.identifier)
self.searchController = UISearchController(searchResultsController: self.searchResultsController!)
self.searchController?.searchResultsUpdater = self
self.searchController?.delegate = self
self.searchController?.searchBar.sizeToFit()
self.tableView.tableHeaderView = self.searchController?.searchBar
self.definesPresentationContext = true
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
self.hideSearchBar()
}
// MARK:- Util methods
func hideSearchBar() {
let yOffset = self.navigationController!.navigationBar.bounds.height + UIApplication.sharedApplication().statusBarFrame.height
self.tableView.contentOffset = CGPointMake(0, self.searchController!.searchBar.bounds.height - yOffset)
}
// MARK:- UITableView methods
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if tableView == self.searchResultsController?.tableView {
if let results = self.results {
return results.count
} else {
return 0
}
} else {
return self.cities.count
}
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier(self.identifier) as UITableViewCell
var text: String?
if tableView == self.searchResultsController?.tableView {
if let results = self.results {
text = self.results!.objectAtIndex(indexPath.row) as? String
}
} else {
text = self.cities[indexPath.row]
}
cell.textLabel.text = text
return cell
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
tableView.deselectRowAtIndexPath(indexPath, animated: true)
if tableView == self.searchResultsController?.tableView {
// Remove search bar & hide it.
self.searchController?.active = false
self.hideSearchBar()
}
}
// MARK:- UISearchResultsUpdating methods
func updateSearchResultsForSearchController(searchController: UISearchController) {
if self.searchController?.searchBar.text.lengthOfBytesUsingEncoding(NSUTF32StringEncoding) > 0 {
if let results = self.results {
results.removeAllObjects()
} else {
results = NSMutableArray(capacity: self.cities.count)
}
let searchBarText = self.searchController!.searchBar.text
let predicate = NSPredicate(block: { (city: AnyObject!, b: [NSObject : AnyObject]!) -> Bool in
var range: NSRange = 0
if city is NSString {
range = city.rangeOfString(searchBarText, options: NSStringCompareOptions.CaseInsensitiveSearch)
}
return range.location != NSNotFound
})
// Get results from predicate and add them to the appropriate array.
let filteredArray = (self.cities as NSArray).filteredArrayUsingPredicate(predicate)
self.results?.addObjectsFromArray(filteredArray)
// Reload a table with results.
self.searchResultsController?.tableView.reloadData()
}
}
// MARK:- UISearchControllerDelegate methods
func didDismissSearchController(searchController: UISearchController) {
UIView.animateKeyframesWithDuration(0.5, delay: 0, options: UIViewKeyframeAnimationOptions.BeginFromCurrentState, animations: { () -> Void in
self.hideSearchBar()
}, completion: nil)
}
}
| mit | 616282abb15b256cc8cf5890d6478f28 | 37.868966 | 162 | 0.649752 | 5.938883 | false | false | false | false |
nakau1/Formations | Formations/Sources/Widgets/Picker/ColorPicker.swift | 1 | 8430 | // =============================================================================
// Formations
// Copyright 2017 yuichi.nakayasu All rights reserved.
// =============================================================================
import UIKit
import Rswift
class ColorPicker: UIViewController {
typealias SelectedHandler = (UIColor) -> Void
private enum Component: Int { case red, green, blue }
private let max = 255
private let recentColorsCount = 10
@IBOutlet private var sliders: [UISlider]!
@IBOutlet private var valueLabels: [UILabel]!
@IBOutlet private var sliderButtons: [UIButton]!
@IBOutlet private var recentButtons: [UIButton]!
@IBOutlet private weak var currentColorButton: UIButton!
@IBOutlet private var hexTextLabels: [UILabel]!
private var selected: SelectedHandler!
// カラーピッカーを表示する
/// - Parameters:
/// - viewController: 表示元のビューコントローラ
/// - defaultColor: 初期表示する色
/// - selected: 選択時の処理
class func show(from viewController: UIViewController, defaultColor: UIColor?, selected: @escaping SelectedHandler) {
let picker = R.storyboard.colorPicker.instantiate(self)
picker.currentColor = defaultColor ?? UIColor.black
picker.selected = selected
Popup.show(picker, from: viewController, options: PopupOptions(.rise(offset: nil)))
}
override func viewDidLoad() {
super.viewDidLoad()
prepare()
}
private var currentColor = UIColor.black
@IBAction private func didTapMinus(_ button: UIButton) {
let slider = sliders[button.tag]
if slider.value > 0 {
slider.value -= 1
updateValueLabel(component(button.tag))
updateBySliders()
}
}
@IBAction private func didTapPlus(_ button: UIButton) {
let slider = sliders[button.tag]
if slider.value < 255 {
slider.value += 1
updateValueLabel(component(button.tag))
updateBySliders()
}
}
@IBAction private func didTapRecent(_ button: UIButton) {
currentColor = recentButton(button.tag).backgroundColor!
updateSliders(color: currentColor)
updateCurrentColorButton(color: currentColor)
updateHexTextLabels(color: currentColor)
}
@IBAction private func didChangeSlider(_ slider: UISlider) {
updateValueLabel(component(slider.tag))
updateBySliders()
}
@IBAction private func didTapCurrentColor() {
saveRecentColor(currentColor)
updateRecentColors()
}
@IBAction private func didTapApply() {
saveRecentColor(currentColor)
selected(currentColor)
dismiss(animated: true) {}
}
private func updateValueLabel(_ component: Component) {
valueLabels[component.rawValue].text = "\(Int(sliderValue(component)))"
}
private func updateSliders(color: UIColor) {
var r: CGFloat = -1, g: CGFloat = -1, b: CGFloat = -1, a: CGFloat = -1
color.getRed(&r, green: &g, blue: &b, alpha: &a)
[r,g,b].enumerated().forEach { i, value in
slider(component(i)).setValue(Float(Int(value * maxCGFloat)), animated: true)
updateValueLabel(component(i))
}
}
private func updateCurrentColorButton(color: UIColor) {
currentColorButton.setBackgroundImage(coloredImage(color), for: .normal)
}
private func updateHexTextLabels(color: UIColor) {
let hex = hexString(color: color)
(0..<6).forEach { i in
hexTextLabel(i).text = hex[i]
}
}
private func updateBySliders() {
let r = sliderValue(.red) / maxCGFloat
let g = sliderValue(.green) / maxCGFloat
let b = sliderValue(.blue) / maxCGFloat
currentColor = UIColor(red: r, green: g, blue: b, alpha: 1)
updateCurrentColorButton(color: currentColor)
updateHexTextLabels(color: currentColor)
}
// MARK: - Prepare (on viewDidLoad)
private func prepare() {
prepareSliderButtons()
prepareCurrentColor()
updateRecentColors()
}
private func prepareSliderButtons() {
sliderButtons.forEach {
$0.layer.cornerRadius = $0.bounds.width / 2
$0.layer.borderWidth = 2
$0.layer.borderColor = $0.titleColor(for: .normal)!.cgColor
}
}
private func prepareCurrentColor() {
updateCurrentColorButton(color: currentColor)
updateHexTextLabels(color: currentColor)
updateSliders(color: currentColor)
}
// MARK: - Recent Colors
private let RecentlyColorsUserDefaultsKey = "ColorPicker.RecentlyUsedColors"
private func updateRecentColors() {
let colors = loadRecentColors()
(0..<recentColorsCount).forEach { i in
recentButton(i).backgroundColor = colors[i]
recentButton(i).setImage(coloredImage(colors[i]), for: .normal)
}
}
private func loadRecentColors() -> [UIColor] {
let hexStrings: [String] = UserDefaults.standard.array(forKey: RecentlyColorsUserDefaultsKey) as? [String] ?? []
return (0..<recentColorsCount).map { i -> UIColor in
return i < hexStrings.count ? color(hexString: hexStrings[i]) : UIColor.gray
}
}
private func saveRecentColor(_ color: UIColor) {
var hexStrings: [String] = UserDefaults.standard.array(forKey: RecentlyColorsUserDefaultsKey) as? [String] ?? []
let newValue = hexString(color: color)
if let index = hexStrings.index(of: newValue) {
hexStrings.remove(at: index)
}
hexStrings.insert(newValue, at: 0)
if hexStrings.count > recentColorsCount {
hexStrings.removeLast()
}
UserDefaults.standard.set(hexStrings, forKey: RecentlyColorsUserDefaultsKey)
UserDefaults.standard.synchronize()
}
// MARK: - Get Element
private func component(_ int: Int) -> Component {
return Component(rawValue: int)!
}
private func slider(_ component: Component) -> UISlider {
return sliders[component.rawValue]
}
private func sliderValue(_ component: Component) -> CGFloat {
return CGFloat(slider(component).value)
}
private func recentButton(_ tag: Int) -> UIButton {
guard let ret = (recentButtons.filter { $0.tag == tag }).first else {
fatalError()
}
return ret
}
private func hexTextLabel(_ tag: Int) -> UILabel {
guard let ret = (hexTextLabels.filter { $0.tag == tag }).first else {
fatalError()
}
return ret
}
// MARK: - Utility
private var maxCGFloat: CGFloat {
return CGFloat(max)
}
private func hexString(color: UIColor) -> String {
var r: CGFloat = -1, g: CGFloat = -1, b: CGFloat = -1
color.getRed(&r, green: &g, blue: &b, alpha: nil)
return [r,g,b].reduce("") { res, value in
let intval = Int(round(value * maxCGFloat))
return res + (NSString(format: "%02X", intval) as String)
}
}
private func color(hexString: String) -> UIColor {
var color: UInt32 = 0
var r: CGFloat = 0.0, g: CGFloat = 0.0, b: CGFloat = 0.0
if Scanner(string: hexString).scanHexInt32(&color) {
r = CGFloat((color & 0xFF0000) >> 16) / maxCGFloat
g = CGFloat((color & 0x00FF00) >> 8) / maxCGFloat
b = CGFloat( color & 0x0000FF ) / maxCGFloat
}
return UIColor(red: r, green: g, blue: b, alpha: 1)
}
private func coloredImage(_ color: UIColor) -> UIImage {
let size = CGSize(width: 400, height: 300)
UIGraphicsBeginImageContext(size)
let context = UIGraphicsGetCurrentContext()!
context.saveGState()
context.setFillColor(color.cgColor)
context.fill(CGRect(x: 0, y: 0, width: size.width, height: size.height))
context.restoreGState()
let ret = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return ret!
}
}
| apache-2.0 | 2ebc45a5888222191582c05e5068d233 | 32.416 | 121 | 0.594326 | 4.719774 | false | false | false | false |
vincent78/blackLand | blackland/Sequence.swift | 1 | 1088 | //
// Sequence.swift
// blackland
//
// Created by vincent on 15/12/1.
// Copyright © 2015年 fruit. All rights reserved.
//
import Foundation
public extension AnySequence {
/**
Checks if self contains the item object.
:param: item The item to search for
:returns: true if self contains item
*/
func contains<T:Equatable> (item: T) -> Bool {
let generator = self.generate()
while let nextItem = generator.next() {
if nextItem as! T == item {
return true
}
}
return false
}
/**
Index of the first occurrence of item, if found.
:param: item The item to search for
:returns: Index of the matched item or nil
*/
func indexOf <U: Equatable> (item: U) -> Int? {
var index = 0
for current in self {
if let equatable = current as? U {
if equatable == item {
return index
}
}
index++
}
return nil
}
} | apache-2.0 | 7da3399c447687219eb40fd5effae495 | 20.72 | 53 | 0.506912 | 4.502075 | false | false | false | false |
blockchain/My-Wallet-V3-iOS | Modules/Platform/Sources/PlatformUIKit/Components/AssetPriceView/Interactor/AssetPriceViewDailyInteractor.swift | 1 | 3124 | // Copyright © Blockchain Luxembourg S.A. All rights reserved.
import Combine
import DIKit
import Foundation
import MoneyKit
import PlatformKit
import RxRelay
import RxSwift
/// Implementation of `AssetPriceViewInteracting` that streams a State for the daily asset price/change.
public final class AssetPriceViewDailyInteractor: AssetPriceViewInteracting {
public var state: Observable<DashboardAsset.State.AssetPrice.Interaction> {
_ = setup
return stateRelay.asObservable()
}
// MARK: - Private Accessors
private lazy var setup: Void = Observable
.combineLatest(
fiatCurrencyService.displayCurrencyPublisher.asObservable(),
refreshRelay.startWith(())
)
.map(\.0)
.flatMapLatest(weak: self) { (self, fiatCurrency) in
self.fetch(fiatCurrency: fiatCurrency).asObservable()
}
.map(DashboardAsset.State.AssetPrice.Interaction.loaded)
.catchAndReturn(.loading)
.bindAndCatch(to: stateRelay)
.disposed(by: disposeBag)
private let cryptoCurrency: CryptoCurrency
private let priceService: PriceServiceAPI
private let stateRelay = BehaviorRelay<DashboardAsset.State.AssetPrice.Interaction>(value: .loading)
private let disposeBag = DisposeBag()
private let fiatCurrencyService: FiatCurrencyServiceAPI
private let refreshRelay = PublishRelay<Void>()
// MARK: - Setup
public init(
cryptoCurrency: CryptoCurrency,
priceService: PriceServiceAPI,
fiatCurrencyService: FiatCurrencyServiceAPI
) {
self.cryptoCurrency = cryptoCurrency
self.priceService = priceService
self.fiatCurrencyService = fiatCurrencyService
}
// MARK: - Public Functions
public func refresh() {
refreshRelay.accept(())
}
private func fetch(
fiatCurrency: FiatCurrency
) -> AnyPublisher<DashboardAsset.Value.Interaction.AssetPrice, Error> {
priceService.price(of: cryptoCurrency, in: fiatCurrency)
.combineLatest(
priceService.price(of: cryptoCurrency, in: fiatCurrency, at: .oneDay)
.optional()
.replaceError(with: nil)
.mapError(to: PriceServiceError.self)
)
.tryMap { currentPrice, previousPrice -> DashboardAsset.Value.Interaction.AssetPrice in
let historicalPrice = previousPrice
.flatMap { previousPrice in
DashboardAsset.Value.Interaction.AssetPrice.HistoricalPrice(
time: .days(1),
currentPrice: currentPrice.moneyValue,
previousPrice: previousPrice.moneyValue
)
}
return DashboardAsset.Value.Interaction.AssetPrice(
currentPrice: currentPrice.moneyValue,
historicalPrice: historicalPrice,
marketCap: currentPrice.marketCap
)
}
.eraseToAnyPublisher()
}
}
| lgpl-3.0 | e9c423193a33965318b369e850be9014 | 34.896552 | 104 | 0.634006 | 5.892453 | false | false | false | false |
oz-swu/studyIOS | studyIOS/studyIOS/Classes/Home/ViewModel/RecommendViewModel.swift | 1 | 4310 | //
// RecommendViewModel.swift
// studyIOS
//
// Created by musou on 26/06/2017.
// Copyright © 2017 musou. All rights reserved.
//
import UIKit
private let kShortName = "game";
class RecommendViewModel {
lazy var anchorGroups : [AnchorGroup] = [AnchorGroup]();
lazy var cycleData : [CycleModel] = [CycleModel]();
lazy var categoryData : [CategoryModel] = [CategoryModel]();
}
// MARK: - sent request
extension RecommendViewModel {
func requestCategory(callback: @escaping () -> ()) {
HttpTemplate.request(url: "https://m.douyu.com/category?type=", method: .get) { (result) in
// print(result);
var hotGameId : String = "hotGameId";
guard result is [String : NSObject] else {
print("no category data");
return;
}
guard let cate1 = result["cate1Info"] as? [[String : NSObject]] else {
print("no cate1 data");
return;
}
guard let cate2 = result["cate2Info"] as? [[String : NSObject]] else {
print("no cate2 data");
return;
}
for cate in cate1 {
guard let shortName = cate["shortName"] as? String else { return }
if (shortName == kShortName) {
guard let cate1Id = cate["cate1Id"] as? String else { return }
hotGameId = cate1Id;
}
}
for cate in cate2 {
guard let cate1Id = cate["cate1Id"] as? String else { return }
if (cate1Id == hotGameId) {
self.categoryData.append(CategoryModel(cate));
}
}
callback();
}
}
func requestData(callback: @escaping () -> ()) {
HttpTemplate.request(url: "https://m.douyu.com/index/getHomeData", method: .get) { (result) in
// print(result);
guard result is [String : NSObject] else {
print("no home data");
return;
}
guard let cycleList = result["banner"] as? [[String : NSObject]] else {
print("no banner data");
return;
}
for cycle in cycleList {
self.cycleData.append(CycleModel(cycle));
}
guard let hotGroups = result["hotList"] as? [[String : NSObject]] else {
print("no hotList data");
return;
};
guard let liveList = result["liveList"] as? [[String : NSObject]] else {
print("no liveList data");
return;
};
guard let yzList = result["yzList"] as? [[String : NSObject]] else {
print("no yzList data");
return;
};
guard let mixGroups = result["mixList"] as? [[String : NSObject]] else {
print("no mixList data");
return;
};
for hot in hotGroups {
self.anchorGroups.append(AnchorGroup(dict: hot));
}
let liveGroup = AnchorGroup(tabName: "正在直播", icon: "home_header_normal");
for live in liveList {
liveGroup.appendData(data: AnchorModel(live));
}
self.anchorGroups.append(liveGroup);
let yzGroup = AnchorGroup(tabName: "颜值", icon: "home_header_phone");
for yz in yzList {
yzGroup.appendData(data: AnchorModel(yz));
}
self.anchorGroups.append(yzGroup);
for mix in mixGroups {
self.anchorGroups.append(AnchorGroup(dict: mix));
}
// for group in anchorGroups {
// print(group.tabName);
// for anchor in group.anchors {
// print(anchor.nickname, anchor.room_name, anchor.anchorCity, anchor.online)
// }
// }
callback();
}
}
}
| mit | 67b538623fa6339ec4b2146b6c61ed76 | 31.55303 | 102 | 0.465906 | 4.927752 | false | false | false | false |
aclissold/the-oakland-post | The Oakland Post/StarredPosts.swift | 2 | 1878 | //
// StarredPosts.swift
// The Oakland Post
//
// Global arrays of starred Posts and their identifiers, as well as helper functions for them.
//
// Created by Andrew Clissold on 9/12/14.
// Copyright (c) 2014 Andrew Clissold. All rights reserved.
//
private(set) var starredPostIdentifiers: [String] = [String]()
class BugFixWrapper { // vars defined globally segfault the compiler in Xcode 6.3 Beta 1
static var starredPosts: [AnyObject] = [AnyObject]() {
didSet {
// Compute starredPostIdentifiers.
starredPostIdentifiers = [String]()
for object in starredPosts {
let ident = object["identifier"] as! String
starredPostIdentifiers.append(ident)
}
// Sort self.
starredPosts.sortInPlace {
let first = ($0 as! PFObject)["date"] as! NSDate
let second = ($1 as! PFObject)["date"] as! NSDate
return first.compare(second) == NSComparisonResult.OrderedDescending
}
}
}
}
func deleteStarredPostWithIdentifier(identifier: String) {
removeFromArray(identifier)
onMain {
// Fetch the starred post from Parse and delete it.
let query = PFQuery(className: "Item")
query.whereKey("identifier", equalTo: identifier)
query.findObjectsInBackgroundWithBlock { (objects, error) in
if error != nil {
showAlertForErrorCode(error!.code)
return
}
objects!.first?.deleteEventually()
}
}
}
private func removeFromArray(identifier: String) {
for (index, object) in (BugFixWrapper.starredPosts as! [PFObject]).enumerate() {
if object["identifier"] as! String == identifier {
BugFixWrapper.starredPosts.removeAtIndex(index)
break
}
}
}
| bsd-3-clause | 8d7306b82b27499ee59f6303748a26e5 | 31.947368 | 95 | 0.607561 | 4.706767 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.