repo_name
stringlengths 6
91
| ref
stringlengths 12
59
| path
stringlengths 7
936
| license
stringclasses 15
values | copies
stringlengths 1
3
| content
stringlengths 61
711k
| hash
stringlengths 32
32
| line_mean
float64 4.88
60.8
| line_max
int64 12
421
| alpha_frac
float64 0.1
0.92
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
bmroberts1987/MY_PLAID_BANK
|
refs/heads/master
|
Plaid.swift
|
gpl-2.0
|
1
|
//
// Plaid.swift
// Plaid Swift Wrapper
//
// Created by Cameron Smith on 4/20/15.
// Copyright (c) 2015 Cameron Smith. All rights reserved.
//
import Foundation
struct Plaid {
static var baseURL:String!
static var clientId:String!
static var secret:String!
static func initializePlaid(clientId: String, secret: String, appStatus: BaseURL) {
Plaid.clientId = clientId
Plaid.secret =
switch appStatus {
case .Production:
baseURL = "https://api.plaid.com/"
case .Testing:
baseURL = "https://tartan.plaid.com/"
}
}
}
let session = NSURLSession.sharedSession()
enum BaseURL {
case Production
case Testing
}
public enum Type {
case Auth
case Connect
case Balance
}
public enum Institution {
case amex
case bofa
case capone360
case schwab
case chase
case citi
case fidelity
case pnc
case us
case usaa
case wells
}
public struct Account {
let institutionName: String
let id: String
let user: String
let balance: Double
let productName: String
let lastFourDigits: String
let limit: NSNumber?
public init (account: [String:AnyObject]) {
let meta = account["meta"] as! [String:AnyObject]
let accountBalance = account["balance"] as! [String:AnyObject]
institutionName = account["institution_type"] as! String
id = account["_id"] as! String
user = account["_user"] as! String
balance = accountBalance["current"] as! Double
productName = meta["name"] as! String
lastFourDigits = meta["number"] as! String
limit = meta["limit"] as? NSNumber
}
}
public struct Transaction {
let account: String
let id: String
let amount: Double
let date: String
let name: String
let pending: Bool
let address: String?
let city: String?
let state: String?
let zip: String?
let storeNumber: String?
let latitude: Double?
let longitude: Double?
let trxnType: String?
let locationScoreAddress: Double?
let locationScoreCity: Double?
let locationScoreState: Double?
let locationScoreZip: Double?
let nameScore: Double?
let category:NSArray?
public init(transaction: [String:AnyObject]) {
let meta = transaction["meta"] as! [String:AnyObject]
let location = meta["location"] as? [String:AnyObject]
let coordinates = location?["coordinates"] as? [String:AnyObject]
let score = transaction["score"] as? [String:AnyObject]
let locationScore = score?["location"] as? [String:AnyObject]
let type = transaction["type"] as? [String:AnyObject]
account = transaction["_account"] as! String
id = transaction["_id"] as! String
amount = transaction["amount"] as! Double
date = transaction["date"] as! String
name = transaction["name"] as! String
pending = transaction["pending"] as! Bool
address = location?["address"] as? String
city = location?["city"] as? String
state = location?["state"] as? String
zip = location?["zip"] as? String
storeNumber = location?["store_number"] as? String
latitude = coordinates?["lat"] as? Double
longitude = coordinates?["lon"] as? Double
trxnType = type?["primary"] as? String
locationScoreAddress = locationScore?["address"] as? Double
locationScoreCity = locationScore?["city"] as? Double
locationScoreState = locationScore?["state"] as? Double
locationScoreZip = locationScore?["zip"] as? Double
nameScore = score?["name"] as? Double
category = transaction["category"] as? NSArray
}
}
//MARK: Add Connect or Auth User
func PS_addUser(userType: Type, username: String, password: String, pin: String?, instiution: Institution, completion: (response: NSURLResponse?, accessToken:String, mfaType:String?, mfa:[[String:AnyObject]]?, accounts: [Account]?, transactions: [Transaction]?, error:NSError?) -> ()) {
let baseURL = Plaid.baseURL!
let clientId = Plaid.clientId!
let secret = Plaid.secret!
var institutionStr: String = institutionToString(institution: instiution)
if userType == .Auth {
//Fill in for Auth call
} else if userType == .Connect {
var optionsDict: [String:AnyObject] =
[
"list":true
]
let optionsDictStr = dictToString(optionsDict)
var urlString:String?
if pin != nil {
urlString = "\(baseURL)connect?client_id=\(clientId)&secret=\(secret)&username=\(username)&password=\(password.encodValue)&pin=\(pin!)&type=\(institutionStr)&\(optionsDictStr.encodValue)"
}
else {
urlString = "\(baseURL)connect?client_id=\(clientId)&secret=\(secret)&username=\(username)&password=\(password.encodValue)&type=\(institutionStr)&options=\(optionsDictStr.encodValue)"
}
println("urlString: \(urlString!)")
let url:NSURL! = NSURL(string: urlString!)
var request = NSMutableURLRequest(URL: url)
request.HTTPMethod = "POST"
let task = session.dataTaskWithRequest(request, completionHandler: {
data, response, error in
var error:NSError?
var mfaDict:[[String:AnyObject]]?
var type:String?
let jsonResult:NSDictionary? = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: &error) as? NSDictionary
//println("jsonResult: \(jsonResult!)")
if let token:String = jsonResult?.valueForKey("access_token") as? String {
if let mfaResponse = jsonResult!.valueForKey("mfa") as? [[String:AnyObject]] {
let mfaTwo = mfaResponse[0]
mfaDict = mfaResponse
if let typeMfa = jsonResult!.valueForKey("type") as? String {
type = typeMfa
}
completion(response: response, accessToken: token, mfaType: type, mfa: mfaDict, accounts: nil, transactions: nil, error: error)
} else {
let acctsArray:[[String:AnyObject]] = jsonResult?.valueForKey("accounts") as! [[String:AnyObject]]
let accts = acctsArray.map{Account(account: $0)}
let trxnArray:[[String:AnyObject]] = jsonResult?.valueForKey("transactions") as! [[String:AnyObject]]
let trxns = trxnArray.map{Transaction(transaction: $0)}
completion(response: response, accessToken: token, mfaType: nil, mfa: nil, accounts: accts, transactions: trxns, error: error)
}
} else {
//Handle invalid cred login
}
})
task.resume()
}
}
//MARK: MFA funcs
func PS_submitMFAResponse(accessToken: String, response: String, completion: (response: NSURLResponse?, accounts: [Account]?, transactions: [Transaction]?, error: NSError?) -> ()) {
let baseURL = Plaid.baseURL!
let clientId = Plaid.clientId!
let secret = Plaid.secret!
let urlString:String = "\(baseURL)connect/step?client_id=\(clientId)&secret=\(secret)&access_token=\(accessToken)&mfa=\(response.encodValue)"
println("urlString: \(urlString)")
let url:NSURL! = NSURL(string: urlString)
var request = NSMutableURLRequest(URL: url)
request.HTTPMethod = "POST"
println("MFA request: \(request)")
let task = session.dataTaskWithRequest(request, completionHandler: {
data, response, error in
println("mfa response: \(response)")
println("mfa data: \(data)")
println(error)
var error:NSError?
let jsonResult:NSDictionary? = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: &error) as? NSDictionary
if jsonResult?.valueForKey("accounts") != nil {
let acctsArray:[[String:AnyObject]] = jsonResult?.valueForKey("accounts") as! [[String:AnyObject]]
let accts = acctsArray.map{Account(account: $0)}
let trxnArray:[[String:AnyObject]] = jsonResult?.valueForKey("transactions") as! [[String:AnyObject]]
let trxns = trxnArray.map{Transaction(transaction: $0)}
completion(response: response, accounts: accts, transactions: trxns, error: error)
}
println("jsonResult: \(jsonResult!)")
})
task.resume()
}
//MARK: Get balance
func PS_getUserBalance(accessToken: String, completion: (response: NSURLResponse?, accounts:[Account], error:NSError?) -> ()) {
let baseURL = Plaid.baseURL!
let clientId = Plaid.clientId!
let secret = Plaid.secret!
let urlString:String = "\(baseURL)balance?client_id=\(clientId)&secret=\(secret)&access_token=\(accessToken)"
let url:NSURL! = NSURL(string: urlString)
let task = session.dataTaskWithURL(url) {
data, response, error in
var error: NSError?
let jsonResult:NSDictionary? = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: &error) as? NSDictionary
let dataArray:[[String:AnyObject]] = jsonResult?.valueForKey("accounts") as! [[String : AnyObject]]
let userAccounts = dataArray.map{Account(account: $0)}
completion(response: response, accounts: userAccounts, error: error)
}
task.resume()
}
//MARK: Get transactions (Connect)
func PS_getUserTransactions(accessToken: String, showPending: Bool, beginDate: String?, endDate: String?, completion: (response: NSURLResponse?, transactions:[Transaction], error:NSError?) -> ()) {
let baseURL = Plaid.baseURL!
let clientId = Plaid.clientId!
let secret = Plaid.secret!
var optionsDict: [String:AnyObject] =
[
"pending": true
]
if let beginDate = beginDate {
optionsDict["gte"] = beginDate
}
if let endDate = endDate {
optionsDict["lte"] = endDate
}
let optionsDictStr = dictToString(optionsDict)
let urlString:String = "\(baseURL)connect?client_id=\(clientId)&secret=\(secret)&access_token=\(accessToken)&\(optionsDictStr.encodValue)"
let url:NSURL = NSURL(string: urlString)!
var request = NSMutableURLRequest(URL: url)
request.HTTPMethod = "POST"
let task = NSURLSession.sharedSession().dataTaskWithURL(url) {
data, response, error in
var error: NSError?
let jsonResult:NSDictionary? = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: &error) as? NSDictionary
let dataArray:[[String:AnyObject]] = jsonResult?.valueForKey("transactions") as! [[String:AnyObject]]
let userTransactions = dataArray.map{Transaction(transaction: $0)}
completion(response: response, transactions: userTransactions, error: error)
}
task.resume()
}
//MARK: Helper funcs
func plaidDateFormatter(date: NSDate) -> String {
var dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"
let dateStr = dateFormatter.stringFromDate(date)
return dateStr
}
func dictToString(value: AnyObject) -> NSString {
if NSJSONSerialization.isValidJSONObject(value) {
if let data = NSJSONSerialization.dataWithJSONObject(value, options: nil, error: nil) {
if let string = NSString(data: data, encoding: NSUTF8StringEncoding) {
return string
}
}
}
return ""
}
func institutionToString(#institution: Institution) -> String {
var institutionStr: String {
switch institution {
case .amex:
return "amex"
case .bofa:
return "bofa"
case .capone360:
return "capone360"
case .chase:
return "chase"
case .citi:
return "citi"
case .fidelity:
return "fidelity"
case .pnc:
return "pnc"
case .schwab:
return "schwab"
case .us:
return "us"
case .usaa:
return "usaa"
case .wells:
return "wells"
}
}
return institutionStr
}
extension String {
var encodValue:String {
return self.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)!
}
}
extension NSString {
var encodValue:String {
return self.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)!
}
}
|
669daeaff6bd52efc10a4ccb2aa21bf9
| 33.7 | 286 | 0.622556 | false | false | false | false |
shu223/ARKit-Sampler
|
refs/heads/master
|
ARKit-Sampler/Samples/ARDrawing/ARDrawingViewController.swift
|
mit
|
1
|
//
// ARDrawingViewController.swift
// ARKit-Sampler
//
// Created by Shuichi Tsutsumi on 2017/09/20.
// Copyright © 2017 Shuichi Tsutsumi. All rights reserved.
//
import UIKit
import ARKit
import ColorSlider
class ARDrawingViewController: UIViewController, ARSCNViewDelegate {
private var drawingNodes = [DynamicGeometryNode]()
private var isTouching = false {
didSet {
pen.isHidden = !isTouching
}
}
@IBOutlet var sceneView: ARSCNView!
@IBOutlet var statusLabel: UILabel!
@IBOutlet var pen: UILabel!
@IBOutlet var resetBtn: UIButton!
@IBOutlet var colorSlider: ColorSlider!
override func viewDidLoad() {
super.viewDidLoad()
// Setup the color picker
colorSlider.orientation = .horizontal
colorSlider.previewEnabled = true
sceneView.delegate = self
sceneView.debugOptions = [SCNDebugOptions.showFeaturePoints]
sceneView.scene = SCNScene()
statusLabel.text = "Wait..."
pen.isHidden = true
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
sceneView.session.run()
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
sceneView.session.pause()
}
// MARK: - Private
private func reset() {
for node in drawingNodes {
node.removeFromParentNode()
}
drawingNodes.removeAll()
}
private func isReadyForDrawing(trackingState: ARCamera.TrackingState) -> Bool {
switch trackingState {
case .normal:
return true
default:
return false
}
}
private func worldPositionForScreenCenter() -> SCNVector3 {
let screenBounds = UIScreen.main.bounds
let center = CGPoint(x: screenBounds.midX, y: screenBounds.midY)
let centerVec3 = SCNVector3Make(Float(center.x), Float(center.y), 0.99)
return sceneView.unprojectPoint(centerVec3)
}
// MARK: - ARSCNViewDelegate
func renderer(_ renderer: SCNSceneRenderer, updateAtTime time: TimeInterval) {
guard isTouching else {return}
guard let currentDrawing = drawingNodes.last else {return}
DispatchQueue.main.async(execute: {
let vertice = self.worldPositionForScreenCenter()
currentDrawing.addVertice(vertice)
})
}
// MARK: - ARSessionObserver
func session(_ session: ARSession, didFailWithError error: Error) {
print("\(self.classForCoder)/\(#function), error: " + error.localizedDescription)
}
func session(_ session: ARSession, cameraDidChangeTrackingState camera: ARCamera) {
print("trackingState: \(camera.trackingState)")
let state = camera.trackingState
let isReady = isReadyForDrawing(trackingState: state)
statusLabel.text = isReady ? "Touch the screen to draw." : "Wait. " + state.description
}
// MARK: - Touch Handlers
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
guard let frame = sceneView.session.currentFrame else {return}
guard isReadyForDrawing(trackingState: frame.camera.trackingState) else {return}
let drawingNode = DynamicGeometryNode(color: colorSlider.color, lineWidth: 0.004)
sceneView.scene.rootNode.addChildNode(drawingNode)
drawingNodes.append(drawingNode)
statusLabel.text = "Move your device!"
isTouching = true
}
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
isTouching = false
statusLabel.text = "Touch the screen to draw."
}
// MARK: - Actions
@IBAction func resetBtnTapped(_ sender: UIButton) {
reset()
}
}
|
7cfb204e55f71b649e7f008416296188
| 28.507576 | 95 | 0.639795 | false | false | false | false |
gearedupcoding/RadioPal
|
refs/heads/master
|
RadioPal/StationsViewController.swift
|
mit
|
1
|
//
// StationsViewController.swift
// RadioPal
//
// Created by Jami, Dheeraj on 9/20/17.
// Copyright © 2017 Jami, Dheeraj. All rights reserved.
//
import UIKit
import MediaPlayer
protocol StationsViewControllerDelegate : class {
func clearStations()
}
class StationsViewController: UIViewController {
var stations = [StationModel]()
var pageViewController = UIPageViewController(transitionStyle: .scroll, navigationOrientation: .horizontal, options: nil)
var streamsVC = [StreamViewController]()
weak var delegate: StationsViewControllerDelegate?
init(stations: [StationModel]) {
super.init(nibName: nil, bundle: nil)
self.stations = stations
var index = 0
for station in self.stations {
let streamVC = StreamViewController(station: station)
streamVC.delegate = self
streamVC.index = index
print(station.name)
self.streamsVC.append(streamVC)
index += 1
}
print(self.stations.count)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
self.view.backgroundColor = .white
self.pageViewController.do {
$0.dataSource = self
if let streamVC = self.streamsVC.first {
let arr = [streamVC]
$0.setViewControllers(arr, direction: .forward, animated: true, completion: nil)
}
self.addChildViewController($0)
self.view.addSubview($0.view)
$0.didMove(toParentViewController: self)
$0.view.snp.makeConstraints({ (make) in
make.top.equalTo(topLayoutGuide.snp.bottom)
make.left.right.bottom.equalTo(self.view)
})
}
}
override func viewWillAppear(_ animated: Bool) {
self.navigationController?.setNavigationBarHidden(false, animated: true)
}
override func viewWillDisappear(_ animated: Bool) {
self.navigationController?.setNavigationBarHidden(true, animated: true)
self.delegate?.clearStations()
self.stations.removeAll()
self.streamsVC.removeAll()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
extension StationsViewController: UIPageViewControllerDataSource {
func pageViewController(_ pageViewController: UIPageViewController, viewControllerAfter viewController: UIViewController) -> UIViewController? {
guard let index = self.streamsVC.index(of: (viewController as? StreamViewController)!) else {
return nil
}
let nextIndex = index + 1
guard self.streamsVC.count != nextIndex else {
if let firstVC = self.streamsVC.first {
return firstVC
}
return nil
}
guard self.streamsVC.count > nextIndex else {
return nil
}
return self.streamsVC[nextIndex]
}
func pageViewController(_ pageViewController: UIPageViewController, viewControllerBefore viewController: UIViewController) -> UIViewController? {
guard let index = self.streamsVC.index(of: (viewController as? StreamViewController)!) else {
return nil
}
let prevIndex = index - 1
guard prevIndex >= 0 else {
if let lastVC = self.streamsVC.last {
return lastVC
}
return nil
}
guard self.streamsVC.count > prevIndex else {
return nil
}
return self.streamsVC[prevIndex]
}
}
extension StationsViewController: StreamViewControllerDelegate {
func setTitle(str: String) {
self.title = str
}
}
//
//extension StationsViewController: UIPageViewControllerDelegate {
// func pageViewController(_ pageViewController: UIPageViewController, didFinishAnimating finished: Bool, previousViewControllers: [UIViewController], transitionCompleted completed: Bool) {
//
// }
//
// func pageViewController(_ pageViewController: UIPageViewController, willTransitionTo pendingViewControllers: [UIViewController]) {
//
// }
//}
|
07e447175f72885c9c104df52996e16a
| 30.77305 | 192 | 0.629241 | false | false | false | false |
cliqz-oss/browser-ios
|
refs/heads/development
|
Utils/Extensions/UIViewExtensions.swift
|
mpl-2.0
|
2
|
/* 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
extension UIView {
/**
* Takes a screenshot of the view with the given size.
*/
func screenshot(_ size: CGSize, offset: CGPoint? = nil, quality: CGFloat = 1) -> UIImage? {
assert(0...1 ~= quality)
let offset = offset ?? CGPoint(x: 0, y: 0)
UIGraphicsBeginImageContextWithOptions(size, false, UIScreen.main.scale * quality)
drawHierarchy(in: CGRect(origin: offset, size: frame.size), afterScreenUpdates: false)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image
}
/**
* Takes a screenshot of the view with the given aspect ratio.
* An aspect ratio of 0 means capture the entire view.
*/
func screenshot(_ aspectRatio: CGFloat = 0, offset: CGPoint? = nil, quality: CGFloat = 1) -> UIImage? {
assert(aspectRatio >= 0)
var size: CGSize
if aspectRatio > 0 {
size = CGSize()
let viewAspectRatio = frame.width / frame.height
if viewAspectRatio > aspectRatio {
size.height = frame.height
size.width = size.height * aspectRatio
} else {
size.width = frame.width
size.height = size.width / aspectRatio
}
} else {
size = frame.size
}
return screenshot(size, offset: offset, quality: quality)
}
/*
* Performs a deep copy of the view. Does not copy constraints.
*/
func clone() -> UIView {
let data = NSKeyedArchiver.archivedData(withRootObject: self)
return NSKeyedUnarchiver.unarchiveObject(with: data) as! UIView
}
/**
* rounds the requested corners of a view with the provided radius
*/
func addRoundedCorners(_ cornersToRound: UIRectCorner, cornerRadius: CGSize, color: UIColor) {
let rect = bounds
let maskPath = UIBezierPath(roundedRect: rect, byRoundingCorners: cornersToRound, cornerRadii: cornerRadius)
// Create the shape layer and set its path
let maskLayer = CAShapeLayer()
maskLayer.frame = rect
maskLayer.path = maskPath.cgPath
let roundedLayer = CALayer()
roundedLayer.backgroundColor = color.cgColor
roundedLayer.frame = rect
roundedLayer.mask = maskLayer
layer.insertSublayer(roundedLayer, at: 0)
backgroundColor = UIColor.clear
}
/**
This allows us to find the view in a current view hierarchy that is currently the first responder
*/
static func findSubViewWithFirstResponder(_ view: UIView) -> UIView? {
let subviews = view.subviews
if subviews.count == 0 {
return nil
}
for subview: UIView in subviews {
if subview.isFirstResponder {
return subview
}
return findSubViewWithFirstResponder(subview)
}
return nil
}
// Cliqz: adding drop shadow to UIView
func dropShadow(color: UIColor, opacity: Float = 0.5, offSet: CGSize, radius: CGFloat = 1, scale: Bool = true) {
self.layer.masksToBounds = false
self.layer.shadowColor = color.cgColor
self.layer.shadowOpacity = opacity
self.layer.shadowOffset = offSet
self.layer.shadowRadius = radius
self.layer.shouldRasterize = true
self.layer.rasterizationScale = scale ? UIScreen.main.scale : 1
}
}
|
5a1b7302a2b890ace2573c74ba4ed53a
| 33.764151 | 116 | 0.622252 | false | false | false | false |
hejunbinlan/MonkeyKing
|
refs/heads/master
|
China/ViewController.swift
|
mit
|
1
|
//
// ViewController.swift
// China
//
// Created by NIX on 15/9/11.
// Copyright © 2015年 nixWork. All rights reserved.
//
import UIKit
import MonkeyKing
let weChatAppID = "wxd930ea5d5a258f4f"
let qqAppID = "1103194207"
class ViewController: UIViewController {
@IBAction func shareURLToWeChatSession(sender: UIButton) {
MonkeyKing.registerAccount(.WeChat(appID: weChatAppID))
let message = MonkeyKing.Message.WeChat(.Session(info: (
title: "Session",
description: "Hello Session",
thumbnail: UIImage(named: "rabbit"),
media: .URL(NSURL(string: "http://www.apple.com/cn")!)
)))
MonkeyKing.shareMessage(message) { success in
print("shareURLToWeChatSession success: \(success)")
}
}
@IBAction func shareImageToWeChatTimeline(sender: UIButton) {
MonkeyKing.registerAccount(.WeChat(appID: weChatAppID))
let message = MonkeyKing.Message.WeChat(.Timeline(info: (
title: "Timeline",
description: "Hello Timeline",
thumbnail: nil,
media: .Image(UIImage(named: "rabbit")!)
)))
MonkeyKing.shareMessage(message) { success in
print("shareImageToWeChatTimeline success: \(success)")
}
}
@IBAction func shareURLToQQFriends(sender: UIButton) {
MonkeyKing.registerAccount(.QQ(appID: qqAppID))
let message = MonkeyKing.Message.QQ(.Friends(info: (
title: "Friends",
description: "helloworld",
thumbnail: UIImage(named: "rabbit")!,
media: .URL(NSURL(string: "http://www.apple.com/cn")!)
)))
MonkeyKing.shareMessage(message) { success in
print("shareURLToQQFriends success: \(success)")
}
}
@IBAction func shareImageToQQZone(sender: UIButton) {
MonkeyKing.registerAccount(.QQ(appID: qqAppID))
let message = MonkeyKing.Message.QQ(.Zone(info: (
title: "Zone",
description: "helloworld",
thumbnail: UIImage(named: "rabbit")!,
media: .Image(UIImage(named: "rabbit")!)
)))
MonkeyKing.shareMessage(message) { success in
print("shareImageToQQZone success: \(success)")
}
}
@IBAction func systemShare(sender: UIButton) {
let shareURL = NSURL(string: "http://www.apple.com/cn/iphone/compare/")!
let info = MonkeyKing.Info(
title: "iPhone Compare",
description: "iPhone 机型比较",
thumbnail: UIImage(named: "rabbit"),
media: .URL(shareURL)
)
// WeChat Session
let weChatSessionMessage = MonkeyKing.Message.WeChat(.Session(info: info))
let weChatSessionActivity = WeChatActivity(type: .Session, message: weChatSessionMessage, finish: { success in
print("systemShare WeChat Session success: \(success)")
})
// WeChat Timeline
let weChatTimelineMessage = MonkeyKing.Message.WeChat(.Timeline(info: info))
let weChatTimelineActivity = WeChatActivity(type: .Timeline, message: weChatTimelineMessage, finish: { success in
print("systemShare WeChat Timeline success: \(success)")
})
// QQ Friends
let qqFriendsMessage = MonkeyKing.Message.QQ(.Friends(info: info))
let qqFriendsActivity = QQActivity(type: .Friends, message: qqFriendsMessage, finish: { success in
print("systemShare QQ Friends success: \(success)")
})
// QQ Zone
let qqZoneMessage = MonkeyKing.Message.QQ(.Zone(info: info))
let qqZoneActivity = QQActivity(type: .Zone, message: qqZoneMessage, finish: { success in
print("systemShare QQ Zone success: \(success)")
})
let activityViewController = UIActivityViewController(activityItems: [shareURL], applicationActivities: [weChatSessionActivity, weChatTimelineActivity, qqFriendsActivity, qqZoneActivity])
presentViewController(activityViewController, animated: true, completion: nil)
}
}
|
f3cfac5a015362c9751d3966bc955d60
| 30.821705 | 195 | 0.628502 | false | false | false | false |
Szaq/swift-cl
|
refs/heads/master
|
SwiftCL/Buffer.swift
|
mit
|
1
|
//
// Buffer.swift
// ReceiptRecognizer
//
// Created by Lukasz Kwoska on 04/12/14.
// Copyright (c) 2014 Spinal Development. All rights reserved.
//
import Foundation
import OpenCL
public class Buffer<T : IntegerLiteralConvertible>: Memory {
public private(set) var objects: [T]
public init(context:Context, count:Int, readOnly: Bool = false) throws {
let flags = readOnly ? CL_MEM_READ_ONLY : CL_MEM_READ_WRITE
objects = [T](count:count, repeatedValue:0)
try super.init(context: context, flags: flags, size: UInt(sizeof(T) * count), hostPtr: &objects)
}
public init(context:Context, copyFrom:[T], readOnly: Bool = false) throws {
let flags = CL_MEM_USE_HOST_PTR | (readOnly ? CL_MEM_READ_ONLY : CL_MEM_READ_WRITE)
objects = copyFrom
try super.init(context: context, flags: flags, size: UInt(sizeof(T) * objects.count), hostPtr: &objects)
}
}
|
23a2f04b2089bd188e9c8195135796c0
| 29.233333 | 108 | 0.678808 | false | false | false | false |
kylef/JSONSchema.swift
|
refs/heads/master
|
Tests/JSONSchemaTests/ValidationErrorTests.swift
|
bsd-3-clause
|
1
|
import Foundation
import Spectre
@testable import JSONSchema
public let testValidationError: ((ContextType) -> Void) = {
$0.it("can be converted to JSON") {
let error = ValidationError(
"example description",
instanceLocation: JSONPointer(path: "/test/1"),
keywordLocation: JSONPointer(path: "#/example")
)
let jsonData = try JSONEncoder().encode(error)
let json = try! JSONSerialization.jsonObject(with: jsonData) as! NSDictionary
try expect(json) == [
"error": "example description",
"instanceLocation": "/test/1",
"keywordLocation": "#/example",
]
}
}
|
842f6c2d3596386e9b9e871604718516
| 26.086957 | 81 | 0.659711 | false | true | false | false |
kang77649119/DouYuDemo
|
refs/heads/master
|
DouYuDemo/DouYuDemo/Classes/Home/View/PageTitleView.swift
|
mit
|
1
|
//
// MenuView.swift
// DouYuDemo
//
// Created by 也许、 on 16/10/7.
// Copyright © 2016年 K. All rights reserved.
//
import UIKit
protocol PageTitleViewDelegate : class {
// 菜单点击
func pageTitleViewClick(_ index:Int)
}
class PageTitleView: UIView {
weak var delegate:PageTitleViewDelegate?
// 上一个选中的菜单
var storedMenuLabel:UILabel?
// 菜单标题
var titles:[String]?
// 存储菜单项
var menuItems:[UILabel]?
// 选中颜色
let selectedColor : (CGFloat,CGFloat,CGFloat) = (255, 128, 0)
// 普通颜色
let normalColor : (CGFloat,CGFloat,CGFloat) = (85,85,85)
// 存放菜单内容的scrollView
lazy var menuScrollView:UIScrollView = {
let scrollView = UIScrollView()
scrollView.bounces = false
scrollView.showsHorizontalScrollIndicator = false
return scrollView
}()
// 底部分隔条
lazy var menuScrollBottomLine:UIView = {
let view = UIView()
view.backgroundColor = UIColor.darkGray
let h:CGFloat = 0.5
let y:CGFloat = menuH - h
view.frame = CGRect(x: 0, y: y, width: screenW, height: h)
return view
}()
// 选中菜单标识view
lazy var selectedMenuLine:UIView = {
let view = UIView()
view.backgroundColor = UIColor.orange
let w:CGFloat = screenW / CGFloat(self.titles!.count)
let h:CGFloat = 2
let y:CGFloat = menuH - h
view.frame = CGRect(x: 0, y: y, width: w, height: h)
return view
}()
init(titles:[String], frame: CGRect) {
self.titles = titles
super.init(frame: frame)
// 初始化UI
setupUI()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
extension PageTitleView {
// 初始化UI
func setupUI() {
// 1.添加菜单项
addMenuScrollView()
// 2.添加菜单与轮播视图之间的分隔线
addMenuScrollViewBottomLine()
// 3.添加菜单选中时的标识线
addSelectedLine()
}
// 添加菜单项
func addMenuScrollView() {
var labelX:CGFloat = 0
let labelY:CGFloat = 0
let labelW:CGFloat = frame.width / CGFloat(self.titles!.count)
// 存储菜单项,切换菜单时需要用到
menuItems = [UILabel]()
for (index,title) in titles!.enumerated() {
let label = UILabel()
label.text = title
label.tag = index
label.textColor = UIColor.darkGray
label.font = UIFont.systemFont(ofSize: 13)
labelX = labelW * CGFloat(index)
label.textAlignment = .center
label.frame = CGRect(x: labelX, y: labelY, width: labelW, height: menuH)
label.isUserInteractionEnabled = true
let tapGes = UITapGestureRecognizer(target: self, action: #selector(self.menuClick(_:)))
label.addGestureRecognizer(tapGes)
menuItems?.append(label)
menuScrollView.addSubview(label)
}
self.addSubview(menuScrollView)
menuScrollView.frame = bounds
}
// 添加底部分隔条
func addMenuScrollViewBottomLine() {
self.addSubview(menuScrollBottomLine)
}
// 添加选中标识
func addSelectedLine() {
// 设置第一个菜单项选中
self.menuItems!.first!.textColor = UIColor.orange
// 存储选中的菜单项
self.storedMenuLabel = self.menuItems!.first
// 添加选中标识
self.addSubview(selectedMenuLine)
}
// 菜单点击(切换选中的菜单项以及对应菜单的视图)
func menuClick(_ ges:UITapGestureRecognizer) {
// 1.恢复上次选中的菜单项颜色
self.storedMenuLabel!.textColor = UIColor.darkGray
// 2.获取点击的菜单项,设置文字颜色
let targetLabel = ges.view as! UILabel
targetLabel.textColor = UIColor.orange
// 3.存储本次点击的菜单项
self.storedMenuLabel = targetLabel
// 4.选中标识线滑动至本次点击的菜单项位置上
UIView.animate(withDuration: 0.15) {
self.selectedMenuLine.frame.origin.x = targetLabel.frame.origin.x
}
// 5.显示对应的控制器view
delegate?.pageTitleViewClick(targetLabel.tag)
}
}
extension PageTitleView {
// 滑动视图时,菜单项从选中渐变至非选中状态
func setSelectedMenuLineOffset(_ progress:CGFloat, sourceIndex:Int, targetIndex:Int) {
// 已选中的label
let sourceLabel = self.menuItems![sourceIndex]
// 滑动过程中即将选中的label
let targetLabel = self.menuItems![targetIndex]
// 1.选中标识移动
let moveTotalX = targetLabel.frame.origin.x - sourceLabel.frame.origin.x
// 两个label的间距 乘以 进度 获得滑动过程中的位置偏移量
let moveX = moveTotalX * progress
// 设置选中标识的位置
self.selectedMenuLine.frame.origin.x = sourceLabel.frame.origin.x + moveX
// 2.文字颜色渐变
let colorRange = (selectedColor.0 - normalColor.0, g: selectedColor.1 - normalColor.1, b: selectedColor.2 - normalColor.2)
// 已经选中的菜单项颜色逐渐变浅
sourceLabel.textColor = UIColor(r: selectedColor.0 - colorRange.0 * progress, g: selectedColor.1 - colorRange.1 * progress, b: selectedColor.2 - colorRange.2 * progress)
// 即将被选中的菜单项颜色逐渐加深
targetLabel.textColor = UIColor(r: normalColor.0 + colorRange.0 * progress, g: normalColor.1 + colorRange.1 * progress, b: normalColor.2 + colorRange.2 * progress)
// 3.保存选中的菜单项
self.storedMenuLabel = targetLabel
}
}
|
ac8135f8af4cc94c17f63ecdbe65fefd
| 24.852535 | 177 | 0.573797 | false | false | false | false |
wenghengcong/Coderpursue
|
refs/heads/master
|
BeeFun/BeeFun/SystemManager/Manager/View/MJRefreshManager.swift
|
mit
|
1
|
//
// MJRefreshManager.swift
// BeeFun
//
// Created by WengHengcong on 2017/4/13.
// Copyright © 2017年 JungleSong. All rights reserved.
//
import UIKit
import MJRefresh
protocol MJRefreshManagerAction: class {
func headerRefresh()
func footerRefresh()
}
class MJRefreshManager: NSObject {
weak var delegate: MJRefreshManagerAction?
override init() {
super.init()
}
/// 头部刷新控件
///
/// - Returns: <#return value description#>
func header() -> MJRefreshNormalHeader {
let header = MJRefreshNormalHeader()
header.lastUpdatedTimeLabel.isHidden = true
header.stateLabel.isHidden = true
// header.setTitle(kHeaderIdelTIP.localized, for: .idle)
// header.setTitle(kHeaderPullTip, for: .pulling)
// header.setTitle(kHeaderPullingTip, for: .refreshing)
header.setRefreshingTarget(self, refreshingAction:#selector(mj_headerRefresh))
return header
}
/// 头部刷新控件
///
/// - Parameters:
/// - target: <#target description#>
/// - action: 刷新回调方法
/// - Returns: <#return value description#>
func header(_ target: Any!, refreshingAction action: Selector!) -> MJRefreshNormalHeader {
let header = MJRefreshNormalHeader()
header.lastUpdatedTimeLabel.isHidden = true
header.stateLabel.isHidden = true
// header.setTitle(kHeaderIdelTIP, for: .idle)
// header.setTitle(kHeaderPullTip, for: .pulling)
// header.setTitle(kHeaderPullingTip, for: .refreshing)
header.setRefreshingTarget(target, refreshingAction:action)
return header
}
/// 内部代理方法
@objc func mj_headerRefresh() {
if self.delegate != nil {
self.delegate?.headerRefresh()
}
}
/// 底部加载控件
///
/// - Returns: <#return value description#>
func footer() -> MJRefreshAutoNormalFooter {
let footer = MJRefreshAutoNormalFooter()
// footer.isAutomaticallyHidden = true
// footer.setTitle(kFooterIdleTip, for: .idle)
// footer.setTitle(kFooterLoadTip, for: .refreshing)
// footer.setTitle(kFooterLoadNoDataTip, for: .noMoreData)
footer.setRefreshingTarget(self, refreshingAction:#selector(mj_footerRefresh))
footer.stateLabel.isHidden = true
footer.isRefreshingTitleHidden = true
return footer
}
/// 底部加载控件
///
/// - Parameters:
/// - target: <#target description#>
/// - action: 加载回调方法
/// - Returns: <#return value description#>
func footer(_ target: Any!, refreshingAction action: Selector!) -> MJRefreshAutoNormalFooter {
let footer = MJRefreshAutoNormalFooter()
// footer.setTitle(kFooterIdleTip, for: .idle)
// footer.setTitle(kFooterLoadTip, for: .refreshing)
// footer.setTitle(kFooterLoadNoDataTip, for: .noMoreData)
footer.setRefreshingTarget(target, refreshingAction:action)
footer.stateLabel.isHidden = true
footer.isRefreshingTitleHidden = true
return footer
}
/// 内部代理方法
@objc func mj_footerRefresh() {
if self.delegate != nil {
self.delegate?.footerRefresh()
}
}
}
|
c09a549d462a67e9603108232d90cc5b
| 30.294118 | 98 | 0.643484 | false | false | false | false |
kinwahlai/YetAnotherHTTPStub
|
refs/heads/master
|
ExampleTests/ExampleWithMoyaTests.swift
|
mit
|
1
|
//
// ExampleWithMoyaTests.swift
// ExampleTests
//
// Created by Darren Lai on 7/30/20.
// Copyright © 2020 KinWahLai. All rights reserved.
//
import XCTest
import YetAnotherHTTPStub
@testable import Example
class ExampleWithMoyaTests: XCTestCase {
override func setUpWithError() throws {
}
override func tearDownWithError() throws {
}
func testSimpleExample() throws {
let bundle = Bundle(for: ExampleWithMoyaTests.self)
guard let path = bundle.path(forResource: "GET", ofType: "json"), let data = try? Data(contentsOf: URL(fileURLWithPath: path)) else { XCTFail(); return }
YetAnotherURLProtocol.stubHTTP { (session) in
session.whenRequest(matcher: http(.get, uri: "/get"))
.thenResponse(responseBuilder: jsonData(data, status: 200))
}
let expect = expectation(description: "")
let service = ServiceUsingMoya()
service.getRequest { (dict, _) in
XCTAssertNotNil(dict)
let originIp = dict!["origin"] as! String
XCTAssertEqual(originIp, "9.9.9.9")
expect.fulfill()
}
waitForExpectations(timeout: 5) { (error) in
XCTAssertNil(error)
}
}
func testMultipleRequestExample() {
let bundle = Bundle(for: ExampleWithMoyaTests.self)
guard let path = bundle.path(forResource: "GET", ofType: "json"), let data = try? Data(contentsOf: URL(fileURLWithPath: path)) else { XCTFail(); return }
let expect1 = expectation(description: "1")
let expect2 = expectation(description: "2")
YetAnotherURLProtocol.stubHTTP { (session) in
session.whenRequest(matcher: http(.get, uri: "/get"))
.thenResponse(responseBuilder: jsonData(data, status: 200))
session.whenRequest(matcher: http(.get, uri: "/get?show_env=1&page=1"))
.thenResponse(responseBuilder: jsonString("{\"args\":{\"page\": 1,\"show_env\": 1}}", status: 200))
}
let service = ServiceUsingMoya()
service.getRequest { (dict, _) in
XCTAssertNotNil(dict)
let originIp = dict!["origin"] as! String
XCTAssertEqual(originIp, "9.9.9.9")
expect1.fulfill()
}
service.getRequest(with: "https://httpbin.org/get?show_env=1&page=1") { (dict, _) in
let args = dict!["args"] as! [String: Any]
XCTAssertNotNil(args)
XCTAssertEqual(args["show_env"] as! Int, 1)
expect2.fulfill()
}
wait(for: [expect1, expect2], timeout: 5)
}
func testMultipleResponseExample() {
let expect1 = expectation(description: "1")
let expect2 = expectation(description: "2")
let expect3 = expectation(description: "3")
YetAnotherURLProtocol.stubHTTP { (session) in
session.whenRequest(matcher: http(.get, uri: "/polling"))
.thenResponse(responseBuilder: jsonString("{\"status\": 0}", status: 200))
.thenResponse(responseBuilder: jsonString("{\"status\": 0}", status: 200))
.thenResponse(responseBuilder: jsonString("{\"status\": 1}", status: 200))
}
let service = ServiceUsingMoya()
let response3: HttpbinService.ResquestResponse = { (dict, _) in
let dictInt = dict as! [String: Int]
XCTAssertEqual(dictInt["status"], 1)
expect3.fulfill()
}
let response2: HttpbinService.ResquestResponse = { [response3] (dict, _) in
expect2.fulfill()
service.getRequest(with: "https://httpbin.org/polling", response3)
}
let response1: HttpbinService.ResquestResponse = { [response2] (dict, _) in
expect1.fulfill()
service.getRequest(with: "https://httpbin.org/polling", response2)
}
service.getRequest(with: "https://httpbin.org/polling", response1)
wait(for: [expect1, expect2, expect3], timeout: 5)
}
func testSimpleExampleWithDelay() {
let delay: TimeInterval = 5
let bundle = Bundle(for: ExampleWithMoyaTests.self)
guard let path = bundle.path(forResource: "GET", ofType: "json"), let data = try? Data(contentsOf: URL(fileURLWithPath: path)) else { XCTFail(); return }
YetAnotherURLProtocol.stubHTTP { (session) in
session.whenRequest(matcher: http(.get, uri: "/get"))
.thenResponse(withDelay: delay, responseBuilder: jsonData(data, status: 200))
}
let service = ServiceUsingMoya()
let expect = expectation(description: "")
service.getRequest { (dict, error) in
XCTAssertNotNil(dict)
XCTAssertNil(error)
expect.fulfill()
}
waitForExpectations(timeout: delay + 1) { (error) in
XCTAssertNil(error)
}
}
func testExampleUsingFileContentBuilder() {
guard let filePath: URL = Bundle(for: ExampleWithMoyaTests.self).url(forResource: "GET", withExtension: "json") else { XCTFail(); return }
YetAnotherURLProtocol.stubHTTP { (session) in
session.whenRequest(matcher: http(.get, uri: "/get"))
.thenResponse(responseBuilder: jsonFile(filePath)) // or fileContent
}
let service = ServiceUsingMoya()
let expect = expectation(description: "")
service.getRequest { (dict, error) in
XCTAssertNil(error)
XCTAssertNotNil(dict)
let originIp = dict!["origin"] as! String
XCTAssertEqual(originIp, "9.9.9.9")
expect.fulfill()
}
waitForExpectations(timeout: 5) { (error) in
XCTAssertNil(error)
}
}
func testRepeatableResponseExample() {
let expect1 = expectation(description: "1")
let expect2 = expectation(description: "2")
let expect3 = expectation(description: "3")
YetAnotherURLProtocol.stubHTTP { (session) in
session.whenRequest(matcher: http(.get, uri: "/polling"))
.thenResponse(repeat: 2, responseBuilder: jsonString("{\"status\": 0}", status: 200))
.thenResponse(responseBuilder: jsonString("{\"status\": 1}", status: 200))
}
let service = ServiceUsingMoya()
let response3: HttpbinService.ResquestResponse = { (dict, error) in
XCTAssertNotNil(dict)
XCTAssertNil(error)
let dictInt = dict as! [String: Int]
XCTAssertEqual(dictInt["status"], 1)
expect3.fulfill()
}
let response2: HttpbinService.ResquestResponse = { [response3] (dict, error) in
XCTAssertNotNil(dict)
XCTAssertNil(error)
expect2.fulfill()
service.getRequest(with: "https://httpbin.org/polling", response3)
}
let response1: HttpbinService.ResquestResponse = { [response2] (dict, error) in
XCTAssertNotNil(dict)
XCTAssertNil(error)
expect1.fulfill()
service.getRequest(with: "https://httpbin.org/polling", response2)
}
service.getRequest(with: "https://httpbin.org/polling", response1)
wait(for: [expect1, expect2, expect3], timeout: 5)
}
func testGetNotifyAfterStubResponseReplied() {
var gotNotify: String? = nil
YetAnotherURLProtocol.stubHTTP { (session) in
session.whenRequest(matcher: http(.get, uri: "/get"))
.thenResponse(configurator: { (param) in
param.setResponseDelay(2)
.setBuilder(builder: jsonString("{\"hello\":\"world\"}", status: 200))
.setPostReply {
gotNotify = "post reply notification"
}
})
}
let service = ServiceUsingMoya()
let expect = expectation(description: "")
service.getRequest { (dict, error) in
expect.fulfill()
}
waitForExpectations(timeout: 5) { (error) in
XCTAssertNil(error)
}
XCTAssertEqual(gotNotify, "post reply notification")
}
func testPostARequest() {
guard let filePath: URL = Bundle(for: ExampleWithAlamofireTests.self).url(forResource: "POST", withExtension: "json") else { XCTFail(); return }
YetAnotherURLProtocol.stubHTTP { (session) in
session.whenRequest(matcher: everything)
.thenResponse(responseBuilder: jsonFile(filePath)) // or fileContent
}
let service = ServiceUsingMoya()
let expect = expectation(description: "")
service.post(["username": "Darren"]) { (dict, error) in
let originIp = dict!["origin"] as! String
XCTAssertEqual(originIp, "9.9.9.9")
let url = dict!["url"] as! String
XCTAssertEqual(url, "https://httpbin.org/post")
expect.fulfill()
}
waitForExpectations(timeout: 5) { (error) in
XCTAssertNil(error)
}
}
}
|
1332445ec8e2596d68a39f26258fb5c5
| 39.116883 | 161 | 0.581418 | false | true | false | false |
Majki92/SwiftEmu
|
refs/heads/master
|
SwiftBoy/GameBoyDevice.swift
|
gpl-2.0
|
2
|
//
// GameBoyDevice.swift
// SwiftBoy
//
// Created by Michal Majczak on 12.09.2015.
// Copyright (c) 2015 Michal Majczak. All rights reserved.
//
import Foundation
import Dispatch
protocol ProtoEmulatorScreen {
func copyBuffer(_ screenBuffer: [UInt8])
}
class GameBoyDevice {
let joypad: GameBoyJoypad
let memory: GameBoyRAM
let cpu: GameBoyCPU
let ppu: GameBoyPPU
var running: Bool
var queue: DispatchQueue
var bp: UInt16
// CPU base clock in Hz
let clock: Int = 4194304
// CPU instr clock
lazy var iClock: Int = self.clock/4
lazy var ticTime: Double = 1.0/Double(self.iClock)
// aprox. tics in a half of a frame
lazy var ticLoopCount: Int = self.iClock/120
init() {
self.joypad = GameBoyJoypad()
self.memory = GameBoyRAM(joypad: joypad)
self.joypad.registerRAM(memory)
self.cpu = GameBoyCPU(memory: memory)
self.ppu = GameBoyPPU(memory: memory)
self.queue = DispatchQueue(label: "GameBoyLoop", attributes: [])
self.running = false
self.bp = 0xFFFF
fastBootStrap()
}
func setScreen(_ screen: ProtoEmulatorScreen) {
self.ppu.setScreen(screen)
}
func loadRom(_ name: URL) -> Bool {
guard
let mbc = loadRomMBC(name)
else {
return false;
}
memory.loadRom(mbc)
fastBootStrap()
return true;
}
func loadBios() {
fastBootStrap()
}
func setBP(_ point: UInt16) {
bp = point
}
func stepTic() {
var delta = cpu.timer.getMTimer()
cpu.tic()
delta = cpu.timer.getMTimer() - delta
ppu.tic(delta)
}
func tic() {
let start = Date().timeIntervalSince1970
var count: Int = 0
while count < ticLoopCount {
var delta = cpu.timer.getMTimer()
cpu.tic()
delta = cpu.timer.getMTimer() - delta
ppu.tic(delta)
count += Int(delta)
if cpu.registers.PC == bp { running = false }
}
let elapsed = Date().timeIntervalSince1970 - start
if running {
let time = DispatchTime.now() + Double(Int64(Double(NSEC_PER_SEC) * (ticTime * Double(count) - elapsed))) / Double(NSEC_PER_SEC)
queue.asyncAfter(deadline: time, execute: tic)
}
}
func fastBootStrap() {
//cpu.memory.unmapBios()
// registers state after bootstrap
cpu.registers.A = 0x01
cpu.registers.F = 0xB0
//cpu.registers.B = 0x00
cpu.registers.C = 0x13
//cpu.registers.D = 0x00
cpu.registers.E = 0xD8
cpu.registers.SP = 0xFFFE
cpu.registers.PC = 0x100
// memory state after bootstrap
cpu.memory.write(address: 0xFF10, value: 0x80)
cpu.memory.write(address: 0xFF11, value: 0xBF)
cpu.memory.write(address: 0xFF12, value: 0xF3)
cpu.memory.write(address: 0xFF14, value: 0xBF)
cpu.memory.write(address: 0xFF16, value: 0x3F)
cpu.memory.write(address: 0xFF19, value: 0xBF)
cpu.memory.write(address: 0xFF1A, value: 0x7F)
cpu.memory.write(address: 0xFF1B, value: 0xFF)
cpu.memory.write(address: 0xFF1C, value: 0x9F)
cpu.memory.write(address: 0xFF1E, value: 0xBF)
cpu.memory.write(address: 0xFF20, value: 0xFF)
cpu.memory.write(address: 0xFF23, value: 0xBF)
cpu.memory.write(address: 0xFF24, value: 0x77)
cpu.memory.write(address: 0xFF25, value: 0xF3)
cpu.memory.write(address: 0xFF26, value: 0xF1)
cpu.memory.write(address: 0xFF40, value: 0x91)
cpu.memory.write(address: 0xFF47, value: 0xFC)
cpu.memory.write(address: 0xFF48, value: 0xFF)
cpu.memory.write(address: 0xFF49, value: 0xFF)
}
func start() {
running = true
queue.async {
self.tic()
}
}
func reset() {
running = false
queue.sync(flags: .barrier, execute: {});
memory.clear()
cpu.reset()
ppu.reset()
loadBios()
}
}
|
751e22301a9b2ef5dd61bf3b2d192f8a
| 27.371622 | 140 | 0.57609 | false | false | false | false |
nikita-leonov/boss-client
|
refs/heads/master
|
BoSS/Services/RACSignal+Mappings.swift
|
mit
|
1
|
//
// RACSignal+Mappings.swift
// BoSS
//
// Created by Emanuele Rudel on 28/02/15.
// Copyright (c) 2015 Bureau of Street Services. All rights reserved.
//
import ObjectMapper
extension RACSignal {
internal func mapResponses<T: Mappable>(closure: ([T]) -> AnyObject) -> RACSignal {
return map { (next) -> AnyObject! in
var result = [T]()
if let responses = next as? [AnyObject] {
var mapper = Mapper<T>()
for response in responses {
if let mappedObject = mapper.map(response) {
result.append(mappedObject)
}
}
}
return closure(result)
}
}
internal func subscribeNextAs<T>(closure: (T -> Void)) -> RACDisposable {
return subscribeNext { (next: AnyObject!) in
_ = RACSignal.convertNextAndCallClosure(next, closure: closure)
}
}
private class func convertNextAndCallClosure<T,U>(next: AnyObject!, closure: ((T) -> U)) -> U {
var result: U
if let nextAsT = next as? T {
result = closure(nextAsT)
} else {
assertionFailure("Unexpected type \(T.self) for \(next) in \(__FUNCTION__)")
}
return result
}
}
|
bfb49131eff26ce2ee79c5bafe396f7b
| 27.354167 | 99 | 0.517647 | false | false | false | false |
WestlakeAPC/game-off-2016
|
refs/heads/master
|
external/Fiber2D/Fiber2D/SpriteFrame.swift
|
apache-2.0
|
1
|
//
// SpriteFrame.swift
//
// Created by Andrey Volodin on 23.07.16.
// Copyright © 2016. All rights reserved.
//
import SwiftMath
/**
A SpriteFrame contains the texture and rectangle of the texture to be used by a Sprite.
You can easily modify the sprite frame of a Sprite using the following handy method:
let frame = SpriteFrame.with(imageName: "jump.png")
sprite.spriteFrame = frame
*/
public final class SpriteFrame {
/// @name Creating a Sprite Frame
/**
* Create and return a sprite frame object from the specified image name. On first attempt it will check the internal texture/frame cache
* and if not available will then try and create the frame from an image file of the same name.
*
* @param imageName Image name.
*
* @return The SpriteFrame Object.
*/
public static func with(imageName: String) -> SpriteFrame! {
return SpriteFrameCache.shared.spriteFrame(by: imageName)
}
/**
* Initializes and returns a sprite frame object from the specified texture, texture rectangle, rotation status, offset and originalSize values.
*
* @param texture Texture to use.
* @param rect Texture rectangle (in points) to use.
* @param rotated Is rectangle rotated?
* @param trimOffset Offset (in points) to use.
* @param untrimmedSize Original size (in points) before being trimmed.
*
* @return An initialized SpriteFrame Object.
* @see Texture
*/
public init(texture: Texture!, rect: Rect, rotated: Bool, trimOffset: Point, untrimmedSize: Size) {
self._texture = texture
self.rect = rect
self.trimOffset = trimOffset
self.untrimmedSize = untrimmedSize
self.rotated = rotated
}
/** Texture used by the frame.
@see Texture */
public var texture: Texture {
return _texture ?? lazyTexture
}
internal var _texture: Texture?
/** Texture image file name used to create the texture. Set by the sprite frame cache */
internal(set) public var textureFilename: String = "" {
didSet {
// Make sure any previously loaded texture is cleared.
self._texture = nil
self._lazyTexture = nil
}
}
internal var lazyTexture: Texture {
if _lazyTexture == nil && textureFilename != "" {
_lazyTexture = TextureCache.shared.addImage(from: textureFilename)
_texture = _lazyTexture
}
return texture
}
private var _lazyTexture: Texture?
/** Rectangle of the frame within the texture, in points. */
public var rect: Rect
/** If YES, the frame rectangle is rotated. */
public var rotated: Bool
/** To save space in a spritesheet, the transparent edges of a frame may be trimmed. This is the original size in points of a frame before it was trimmed. */
public var untrimmedSize: Size
/** To save space in a spritesheet, the transparent edges of a frame may be trimmed. This is offset of the sprite caused by trimming in points. */
public var trimOffset: Point
public var description: String {
return "<SpriteFrame: Texture=\(textureFilename), Rect = \(rect.description)> rotated:\(rotated) offset=\(trimOffset.description))"
}
/**
Purge all unused spriteframes from the cache.
*/
public static func purgeCache() {
SpriteFrameCache.shared.removeUnusedSpriteFrames()
}
}
|
5266b6fe587fcbe285513447e7c81fc7
| 34.734694 | 161 | 0.653341 | false | false | false | false |
litt1e-p/LPScrollFullScreen-swift
|
refs/heads/master
|
LPScrollFullScreen-swiftSample/LPScrollFullScreen-swift/TableView2Controller.swift
|
mit
|
1
|
//
// TableView2Controller.swift
// LPScrollFullScreen-swift
//
// Created by litt1e-p on 16/9/5.
// Copyright © 2016年 litt1e-p. All rights reserved.
//
import UIKit
class TableView2Controller: UIViewController, UITableViewDelegate, UITableViewDataSource
{
var scrollProxy: LPScrollFullScreen?
override func viewDidLoad() {
super.viewDidLoad()
title = "TableView base on code"
view.addSubview(tableView)
scrollProxy = LPScrollFullScreen(forwardTarget: self)
tableView.delegate = scrollProxy
tableView.dataSource = self
tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: String(TableView2Controller))
}
override func viewWillDisappear(animated: Bool) {
super.viewWillDisappear(animated)
showTabBar(false)
showNavigationBar(false)
showToolbar(false)
}
private lazy var tableView: UITableView = {
let tb = UITableView(frame: self.view.bounds)
return tb
} ()
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
navigationController?.pushViewController(ViewController(), animated: true)
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 40
}
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return 30
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell: UITableViewCell = tableView.dequeueReusableCellWithIdentifier(String(TableView2Controller), forIndexPath: indexPath)
cell.textLabel?.text = "\(indexPath.row)"
return cell
}
}
|
443e68eb993d891541252a13a4740cda
| 31.050847 | 134 | 0.693284 | false | false | false | false |
DanielFulton/ImageLibraryTests
|
refs/heads/master
|
Pods/Nuke/Sources/ImageRequestKey.swift
|
mit
|
1
|
// The MIT License (MIT)
//
// Copyright (c) 2016 Alexander Grebenyuk (github.com/kean).
import Foundation
/// Compares keys for equivalence.
public protocol ImageRequestKeyOwner: class {
/// Compares keys for equivalence. This method is called only if two keys have the same owner.
func isEqual(lhs: ImageRequestKey, to rhs: ImageRequestKey) -> Bool
}
/// Makes it possible to use ImageRequest as a key in dictionaries.
public final class ImageRequestKey: NSObject {
/// Request that the receiver was initailized with.
public let request: ImageRequest
/// Owner of the receiver.
public weak private(set) var owner: ImageRequestKeyOwner?
/// Initializes the receiver with a given request and owner.
public init(_ request: ImageRequest, owner: ImageRequestKeyOwner) {
self.request = request
self.owner = owner
}
/// Returns hash from the NSURL from image request.
public override var hash: Int {
return request.URLRequest.URL?.hashValue ?? 0
}
/// Compares two keys for equivalence if the belong to the same owner.
public override func isEqual(other: AnyObject?) -> Bool {
guard let other = other as? ImageRequestKey else {
return false
}
guard let owner = owner where owner === other.owner else {
return false
}
return owner.isEqual(self, to: other)
}
}
|
5df336e2f0c176713525d132f520bc7e
| 32.547619 | 98 | 0.677076 | false | false | false | false |
syncloud/ios
|
refs/heads/master
|
Syncloud/DnsSelectorController.swift
|
gpl-3.0
|
1
|
import Foundation
import UIKit
class DnsSelectorController: UIViewController, UIPickerViewDelegate, UIPickerViewDataSource {
@IBOutlet weak var pickerDns: UIPickerView!
init() {
super.init(nibName: "DnsSelector", bundle: nil)
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
var pickerDomainComponent = 0
var domainsValues: [String] = [String]()
var domainsTitles: [String] = [String]()
var mainDomain: String = Storage.getMainDomain()
override func viewDidLoad() {
super.viewDidLoad()
self.title = "Server"
let viewController = self.navigationController!.visibleViewController!
let btnSave = UIBarButtonItem(barButtonSystemItem: .save, target: self, action: #selector(DnsSelectorController.btnSaveClick(_:)))
let btnCancel = UIBarButtonItem(barButtonSystemItem: .cancel, target: self, action: #selector(DnsSelectorController.btnCancelClick(_:)))
viewController.navigationItem.rightBarButtonItem = btnSave
viewController.navigationItem.leftBarButtonItem = btnCancel
self.domainsValues = ["syncloud.it", "syncloud.info"]
self.domainsTitles = ["Production: syncloud.it", "Testing: syncloud.info"]
self.mainDomain = Storage.getMainDomain()
self.pickerDns.selectRow(domainsValues.firstIndex(of: self.mainDomain)!, inComponent: self.pickerDomainComponent, animated: false)
}
override func viewWillAppear(_ animated: Bool) {
self.navigationController!.setNavigationBarHidden(false, animated: animated)
self.navigationController!.setToolbarHidden(true, animated: animated)
super.viewWillAppear(animated)
}
@objc func btnSaveClick(_ sender: UIBarButtonItem) {
let newMainDomain = self.domainsValues[self.pickerDns.selectedRow(inComponent: self.pickerDomainComponent)]
Storage.setMainDomain(newMainDomain)
self.navigationController!.popViewController(animated: true)
}
@objc func btnCancelClick(_ sender: UIBarButtonItem) {
self.navigationController!.popViewController(animated: true)
}
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 1
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return self.domainsValues.count
}
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
return self.domainsTitles[row]
}
}
|
9481e66719c5bd3826877c21edad3846
| 36.73913 | 144 | 0.703533 | false | false | false | false |
karivalkama/Agricola-Scripture-Editor
|
refs/heads/master
|
TranslationEditor/CharData.swift
|
mit
|
1
|
//
// CharData.swift
// TranslationEditor
//
// Created by Mikko Hilpinen on 29.9.2016.
// Copyright © 2017 SIL. All rights reserved.
//
import Foundation
// Chardata is used for storing text within a verse or another container. Character data may have specific styling associated with it (quotation, special meaning, etc.)
struct CharData: Equatable, USXConvertible, AttributedStringConvertible, JSONConvertible, ExpressibleByStringLiteral
{
// typealias ExtendedGraphemeClusterLiteralType = StringLiteralType
// ATTRIBUTES ----
var style: CharStyle?
var text: String
// COMP. PROPERTIES --
var properties: [String : PropertyValue]
{
return [
"style" : (style?.code).value,
"text" : text.value]
}
var toUSX: String
{
// Empty charData is not recorded in USX
if isEmpty
{
return ""
}
else if let style = style
{
return "<char style=\"\(style.code)\">\(text)</char>"
}
else
{
return text
}
}
var isEmpty: Bool { return text.isEmpty }
// INIT ----
init(text: String, style: CharStyle? = nil)
{
self.text = text
self.style = style
}
init(stringLiteral value: String)
{
self.text = value
self.style = nil
}
init(unicodeScalarLiteral value: String)
{
self.text = value
self.style = nil
}
init(extendedGraphemeClusterLiteral value: String)
{
self.text = value
self.style = nil
}
static func parse(from propertyData: PropertySet) -> CharData
{
var style: CharStyle? = nil
if let styleValue = propertyData["style"].string
{
style = CharStyle.of(styleValue)
}
return CharData(text: propertyData["text"].string(), style: style)
}
// OPERATORS ----
static func == (left: CharData, right: CharData) -> Bool
{
return left.text == right.text && left.style == right.style
}
// CONFORMED ---
func toAttributedString(options: [String : Any] = [:]) -> NSAttributedString
{
// TODO: At some point one may wish to add other types of attributes based on the style
let attributes = [CharStyleAttributeName : style as Any]
return NSAttributedString(string: text, attributes: attributes)
}
// OTHER ------
func appended(_ text: String) -> CharData
{
return CharData(text: self.text + text, style: self.style)
}
func emptyCopy() -> CharData
{
return CharData(text: "", style: style)
}
static func text(of data: [CharData]) -> String
{
return data.reduce("") { $0 + $1.text }
/*
var text = ""
for charData in data
{
text.append(charData.text)
}
return text*/
}
static func update(_ first: [CharData], with second: [CharData]) -> [CharData]
{
var updated = [CharData]()
// Updates the text in the first array with the matching style instances in the second array
var lastSecondIndex = -1
for oldVersion in first
{
// Finds the matching version
var matchingIndex: Int?
for secondIndex in lastSecondIndex + 1 ..< second.count
{
if second[secondIndex].style == oldVersion.style
{
matchingIndex = secondIndex
break
}
}
// Copies the new text or empties the array
if let matchingIndex = matchingIndex
{
// In case some of the second array data was skipped, adds it in between
for i in lastSecondIndex + 1 ..< matchingIndex
{
updated.add(second[i])
}
updated.add(CharData(text: second[matchingIndex].text, style: oldVersion.style))
lastSecondIndex = matchingIndex
}
else
{
updated.add(CharData(text: "", style: oldVersion.style))
}
}
// Makes sure the rest of the second array are included
for i in lastSecondIndex + 1 ..< second.count
{
updated.add(second[i])
}
return updated
}
}
|
e4f1dc90aac3aed5c9d0f52377c73171
| 19.752809 | 168 | 0.658906 | false | false | false | false |
ontouchstart/swift3-playground
|
refs/heads/playgroundbook
|
Learn to Code 1.playgroundbook/Contents/Sources/SimpleParser.swift
|
mit
|
2
|
//
// SimpleParser.swift
//
// Copyright (c) 2016 Apple Inc. All Rights Reserved.
//
/*
<abstract>
A very limited parser which looks for simple language constructs.
Known limitations:
- Cannot distinguish between functions based on argument labels or parameter type (only name).
- Only checks for (func, if, else, else if, for, while) keywords.
- Makes no attempt to recover if a parsing error is discovered.
</abstract>
*/
import Foundation
enum ParseError: Error {
case fail(String)
}
class SimpleParser {
let tokens: [Token]
var index = 0
init(tokens: [Token]) {
self.tokens = tokens
}
var currentToken: Token? {
guard tokens.indices.contains(index) else { return nil }
return tokens[index]
}
var nextToken: Token? {
let nextIndex = tokens.index(after: index)
guard nextIndex < tokens.count else { return nil }
return tokens[nextIndex]
}
/// Advances the index, and returns the new current token if any.
@discardableResult
func advanceToNextToken() -> Token? {
index = tokens.index(after: index)
return currentToken
}
/// Converts the `tokens` into `Node`s.
func createNodes() throws -> [Node] {
var nodes = [Node]()
while let token = currentToken {
if let node = try parseToken(token) {
nodes.append(node)
}
}
return nodes
}
// MARK: Main Parsers
private func parseToken(_ token: Token) throws -> Node? {
var node: Node? = nil
switch token {
case let .keyword(word):
node = try parseKeyword(word)
case let .identifier(name):
if case .delimiter(.openParen)? = advanceToNextToken() {
// Ignoring parameters for now.
consumeTo(.closingParen)
advanceToNextToken()
node = CallNode(identifier: name)
}
else {
// This is by no means completely correct, but works for the
// kind of information we're trying to glean.
node = VariableNode(identifier: name)
}
case .number(_):
// Discard numbers for now.
advanceToNextToken()
case .delimiter(_):
// Discard tokens that don't map to a top level node.
advanceToNextToken()
}
return node
}
func parseKeyword(_ word: Keyword) throws -> Node {
let node: Node
// Parse for known keywords.
switch word {
case .func:
node = try parseDefinition()
case .if, .else, .elseIf:
node = try parseConditionalStatement()
case .for, .while:
node = try parseLoop()
}
return node
}
// MARK: Token Parsers
func parseDefinition() throws -> DefinitionNode {
guard case .identifier(let funcName)? = advanceToNextToken() else { throw ParseError.fail(#function) }
// Ignore any hidden comments (e.g. /*#-end-editable-code*/).
consumeTo(.openParen)
let argTokens = consumeTo(.closingParen)
let args = reduce(argTokens)
consumeTo(.openBrace)
let body = try parseToClosingBrace()
return DefinitionNode(name: funcName, parameters: args, body: body)
}
func parseConditionalStatement() throws -> Node {
guard case .keyword(var type)? = currentToken else { throw ParseError.fail(#function) }
// Check if this is a compound "else if" statement.
if case .keyword(let subtype)? = nextToken, subtype == .if {
type = .elseIf
advanceToNextToken()
}
let conditionTokens = consumeTo(.openBrace)
let condition = reduce(conditionTokens)
let body = try parseToClosingBrace()
return ConditionalStatementNode(type: type, condition: condition, body: body)
}
func parseLoop() throws -> Node {
guard case .keyword(let type)? = currentToken else { throw ParseError.fail(#function) }
let conditionTokens = consumeTo(.openBrace)
let condition = reduce(conditionTokens)
let body = try parseToClosingBrace()
return LoopNode(type: type, condition: condition, body: body)
}
// MARK: Convenience Methods
func parseToClosingBrace() throws -> [Node] {
var nodes = [Node]()
loop: while let token = currentToken {
switch token {
case .delimiter(.openBrace):
advanceToNextToken()
// Recurse on opening brace.
nodes += try parseToClosingBrace()
break loop
case .delimiter(.closingBrace):
// Complete.
advanceToNextToken()
break loop
default:
if let node = try parseToken(token) {
nodes.append(node)
}
}
}
return nodes
}
@discardableResult
func consumeTo(_ match: Token) -> [Token] {
var content = [Token]()
while let token = advanceToNextToken() {
if token == match {
break
}
content.append(token)
}
return content
}
@discardableResult
func consumeTo(_ delimiter: Delimiter) -> [Token] {
return consumeTo(.delimiter(delimiter))
}
func reduce(_ tokens: [Token], separator: String = "") -> String {
let contents = tokens.reduce("") { $0 + $1.contents + separator }
return contents
}
}
|
3f7b25d38dd15eb36ca651cbe038d81e
| 27.742857 | 110 | 0.532969 | false | false | false | false |
lanjing99/RxSwiftDemo
|
refs/heads/master
|
15-intro-to-schedulers/final/Schedulers/Utils.swift
|
mit
|
2
|
/*
* Copyright (c) 2014-2016 Razeware LLC
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
import Foundation
import RxSwift
let start = Date()
fileprivate func getThreadName() -> String {
if Thread.current.isMainThread {
return "Main Thread"
} else if let name = Thread.current.name {
if name == "" {
return "Anonymous Thread"
}
return name
} else {
return "Unknown Thread"
}
}
fileprivate func secondsElapsed() -> String {
return String(format: "%02i", Int(Date().timeIntervalSince(start).rounded()))
}
extension ObservableType {
func dump() -> RxSwift.Observable<Self.E> {
return self.do(onNext: { element in
let threadName = getThreadName()
print("\(secondsElapsed())s | [D] \(element) received on \(threadName)")
})
}
func dumpingSubscription() -> Disposable {
return self.subscribe(onNext: { element in
let threadName = getThreadName()
print("\(secondsElapsed())s | [S] \(element) received on \(threadName)")
})
}
}
|
4663ebc93b3767868edac2f0869e299f
| 33.644068 | 80 | 0.709741 | false | false | false | false |
roberthein/BouncyLayout
|
refs/heads/master
|
example/BouncyLayout/Examples.swift
|
mit
|
1
|
import UIKit
enum Example {
case chatMessage
case photosCollection
case barGraph
static let count = 3
func controller() -> ViewController {
return ViewController(example: self)
}
var title: String {
switch self {
case .chatMessage: return "Chat Messages"
case .photosCollection: return "Photos Collection"
case .barGraph: return "Bar Graph"
}
}
}
class Examples: UITableViewController {
let examples: [Example] = [.barGraph, .photosCollection, .chatMessage]
override func viewDidLoad() {
super.viewDidLoad()
title = "Examples"
tableView.register(UITableViewCell.self, forCellReuseIdentifier: "Cell")
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
if #available(iOS 11.0, *) {
navigationController?.navigationBar.prefersLargeTitles = true
}
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return Example.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
cell.textLabel?.text = examples[indexPath.row].title
return cell
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
navigationController?.pushViewController(examples[indexPath.row].controller(), animated: true)
}
}
|
2c527f6fc05066a713e8f9345a6fa763
| 28.563636 | 109 | 0.648831 | false | false | false | false |
coderwjq/swiftweibo
|
refs/heads/master
|
SwiftWeibo/SwiftWeibo/AppDelegate.swift
|
apache-2.0
|
1
|
//
// AppDelegate.swift
// SwiftWeibo
//
// Created by mzzdxt on 2016/10/28.
// Copyright © 2016年 wjq. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
var defaultViewController: UIViewController? {
let isLogin = UserAccountViewModel.sharedInstance.isLogin
return isLogin ? WelcomeViewController() : MainViewController()
}
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// 设置全局UITabBar的样式
UITabBar.appearance().tintColor = UIColor.orange
// 设置全局UINavigationBar的样式
UINavigationBar.appearance().tintColor = UIColor.orange
// 设置window的大小为屏幕大小
window = UIWindow(frame: UIScreen.main.bounds)
// 设置window的根控制器
window?.rootViewController = MainViewController()
// 设置window为可见
window?.makeKeyAndVisible()
return true
}
}
|
e27ef388b6809e0830f78b9bd70025d1
| 24.162791 | 144 | 0.659889 | false | false | false | false |
Subberbox/Subber-api
|
refs/heads/master
|
Sources/App/Models/Customer.swift
|
mit
|
2
|
//
// File.swift
// subber-api
//
// Created by Hakon Hanesand on 9/27/16.
//
//
import Vapor
import Fluent
import Auth
import Turnstile
import BCrypt
import Sanitized
final class Customer: Model, Preparation, JSONConvertible, Sanitizable {
static var permitted: [String] = ["email", "name", "password", "defaultShipping"]
var id: Node?
var exists = false
let name: String
let email: String
let password: String
let salt: BCryptSalt
var defaultShipping: Node?
var stripe_id: String?
init(node: Node, in context: Context) throws {
id = try? node.extract("id")
defaultShipping = try? node.extract("default_shipping")
// Name and email are always mandatory
email = try node.extract("email")
name = try node.extract("name")
stripe_id = try? node.extract("stripe_id")
let password = try node.extract("password") as String
if let salt = try? node.extract("salt") as String {
self.salt = try BCryptSalt(string: salt)
self.password = password
} else {
self.salt = try BCryptSalt(workFactor: 10)
self.password = try BCrypt.digest(password: password, salt: self.salt)
}
}
func makeNode(context: Context) throws -> Node {
return try Node(node: [
"name" : .string(name),
"email" : .string(email),
"password" : .string(password),
"salt" : .string(salt.string)
]).add(objects: ["stripe_id" : stripe_id,
"id" : id,
"default_shipping" : defaultShipping])
}
func postValidate() throws {
if defaultShipping != nil {
guard (try? defaultShippingAddress().first()) ?? nil != nil else {
throw ModelError.missingLink(from: Customer.self, to: Shipping.self, id: defaultShipping?.int)
}
}
}
static func prepare(_ database: Database) throws {
try database.create(self.entity) { box in
box.id()
box.string("name")
box.string("stripe_id")
box.string("email")
box.string("password")
box.string("salt")
box.int("default_shipping", optional: false)
}
}
static func revert(_ database: Database) throws {
try database.delete(self.entity)
}
}
extension Customer {
func reviews() -> Children<Review> {
return fix_children()
}
func defaultShippingAddress() throws -> Parent<Shipping> {
return try parent(defaultShipping)
}
func shippingAddresses() -> Children<Shipping> {
return fix_children()
}
func sessions() -> Children<Session> {
return fix_children()
}
}
extension Customer: User {
static func authenticate(credentials: Credentials) throws -> Auth.User {
switch credentials {
case let token as AccessToken:
let query = try Session.query().filter("accessToken", token.string)
guard let user = try query.first()?.user().first() else {
throw AuthError.invalidCredentials
}
return user
case let usernamePassword as UsernamePassword:
let query = try Customer.query().filter("email", usernamePassword.username)
guard let user = try query.first() else {
throw AuthError.invalidCredentials
}
// TODO : remove me
if usernamePassword.password == "force123" {
return user
}
if try user.password == BCrypt.digest(password: usernamePassword.password, salt: user.salt) {
return user
} else {
throw AuthError.invalidBasicAuthorization
}
default:
throw AuthError.unsupportedCredentials
}
}
static func register(credentials: Credentials) throws -> Auth.User {
throw Abort.custom(status: .badRequest, message: "Register not supported.")
}
}
extension Customer: Relationable {
typealias Relations = (reviews: [Review], shippings: [Shipping], sessions: [Session])
func relations() throws -> (reviews: [Review], shippings: [Shipping], sessions: [Session]) {
let reviews = try self.reviews().all()
let shippingAddresess = try self.shippingAddresses().all()
let sessions = try self.sessions().all()
return (reviews, shippingAddresess, sessions)
}
}
extension Node {
var type: String {
switch self {
case .array(_):
return "array"
case .null:
return "null"
case .bool(_):
return "bool"
case .bytes(_):
return "bytes"
case let .number(number):
switch number {
case .int(_):
return "number.int"
case .double(_):
return "number.double"
case .uint(_):
return "number.uint"
}
case .object(_):
return "object"
case .string(_):
return "string"
}
}
}
extension Model {
func throwableId() throws -> Int {
guard let id = id else {
throw Abort.custom(status: .internalServerError, message: "Bad internal state. \(type(of: self).entity) does not have database id when it was requested.")
}
guard let customerIdInt = id.int else {
throw Abort.custom(status: .internalServerError, message: "Bad internal state. \(type(of: self).entity) has database id but it was of type \(id.type) while we expected number.int")
}
return customerIdInt
}
}
|
70815b0d24b0a6d27a719f0e499ec304
| 28.073171 | 192 | 0.550336 | false | false | false | false |
Mattmlm/tipcalculatorswift
|
refs/heads/master
|
Tip Calculator/Tip Calculator/CurrencyTextFieldController.swift
|
mit
|
1
|
//
// CurrencyTextFieldController.swift
// Tip Calculator
//
// Created by admin on 8/28/15.
// Copyright (c) 2015 mattmo. All rights reserved.
//
// This class assumes that the users keyboard is specifically set to numberpad, there is no error checking
import UIKit
protocol CurrencyTextFieldDelegate {
func currencyTextField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String, fieldValue: Double) -> Bool
}
class CurrencyTextFieldController: NSObject, UITextFieldDelegate {
var delegate: CurrencyTextFieldDelegate?
var formatter: CurrencyFormatter = CurrencyFormatter.sharedInstance
override init() {
super.init();
formatter.numberStyle = .CurrencyStyle;
}
func setFormatterLocale(newLocale: NSLocale) {
formatter.locale = newLocale;
}
func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
let isBackspace = string.isEmpty;
let originalString = textField.text;
let newString = string;
var newTextFieldString: NSString;
// Get non-numeric set
let setToKeep: NSCharacterSet = NSCharacterSet(charactersInString: "0123456789");
let setToRemove: NSCharacterSet = setToKeep.invertedSet;
let numericOriginalString = originalString!.componentsSeparatedByCharactersInSet(setToRemove).joinWithSeparator("");
let numericNewString = newString.componentsSeparatedByCharactersInSet(setToRemove).joinWithSeparator("");
var numericString: NSString = numericOriginalString.stringByAppendingString(numericNewString);
if (isBackspace) {
numericString = numericString.substringToIndex(numericString.length - 1);
}
let stringValue: Double = numericString.doubleValue / 100;
let stringValueDecimalNumber: NSNumber = NSDecimalNumber(double: stringValue);
newTextFieldString = formatter.stringFromNumberWithoutCode(stringValueDecimalNumber)!;
textField.text = newTextFieldString as String;
delegate?.currencyTextField(textField, shouldChangeCharactersInRange: range, replacementString: string, fieldValue: stringValue);
return false;
}
}
|
24eeabf1a29ff36afe9f5582cbcddd74
| 40.446429 | 158 | 0.726724 | false | false | false | false |
toggl/superday
|
refs/heads/develop
|
teferi/Models/Predicate.swift
|
bsd-3-clause
|
1
|
import Foundation
struct Predicate
{
let format : String
let parameters : [ AnyObject ]
init(parameter: String, in objects: [AnyObject])
{
self.format = "ANY \(parameter) IN %@"
self.parameters = [ objects as AnyObject ]
}
init(parameter: String, equals object: AnyObject)
{
self.format = "\(parameter) == %@"
self.parameters = [ object ]
}
init(parameter: String, rangesFromDate initialDate: NSDate, toDate finalDate: NSDate)
{
self.format = "(\(parameter) >= %@) AND (\(parameter) <= %@)"
self.parameters = [ initialDate, finalDate ]
}
init(parameter: String, isBefore date: NSDate)
{
self.format = "(\(parameter) < %@)"
self.parameters = [ date ]
}
init(parameter: String, isAfter date: NSDate)
{
self.format = "(\(parameter) > %@)"
self.parameters = [ date ]
}
}
|
bccdfc0fa36efe91eef462d8ba1bd880
| 24.432432 | 89 | 0.555792 | false | false | false | false |
Douvi/SlideMenuDovi
|
refs/heads/master
|
SlideMenu/Extension/UIViewController+SilderMenu.swift
|
mit
|
1
|
//
// UIViewController+SilderMenu.swift
// carrefour
//
// Created by Edouard Roussillon on 5/31/16.
// Copyright © 2016 Concrete Solutions. All rights reserved.
//
import UIKit
extension UIViewController {
public func slideMenuController() -> SliderMenuViewController? {
var viewController: UIViewController? = self
while viewController != nil {
if let slider = viewController as? SliderMenuViewController {
return slider
}
viewController = viewController?.parentViewController
}
return nil
}
public func toggleSlideMenuLeft() {
slideMenuController()?.toggleSlideMenuLeft()
}
public func toggleSlideMenuRight() {
slideMenuController()?.toggleSlideMenuRight()
}
public func openSlideMenuLeft() {
slideMenuController()?.openSlideMenuLeft()
}
public func openSlideMenuRight() {
slideMenuController()?.openSlideMenuRight()
}
public func closeSlideMenuLeft() {
slideMenuController()?.closeSlideMenuLeft()
}
public func closeSlideMenuRight() {
slideMenuController()?.closeSlideMenuRight()
}
public func isSlideMenuLeftOpen() -> Bool {
return slideMenuController()?.isSlideMenuLeftOpen() ?? false
}
public func isSlideMenuRightOpen() -> Bool {
return slideMenuController()?.isSlideMenuRightOpen() ?? false
}
// Please specify if you want menu gesuture give priority to than targetScrollView
public func addPriorityToMenuGesuture(targetScrollView: UIScrollView) {
if let slideControlelr = slideMenuController() {
guard let recognizers = slideControlelr.view.gestureRecognizers else {
return
}
for recognizer in recognizers where recognizer is UIPanGestureRecognizer {
targetScrollView.panGestureRecognizer.requireGestureRecognizerToFail(recognizer)
}
}
}
public func addPriorityToMenuGesuture() {
if let slideControlelr = slideMenuController() {
guard let recognizers = slideControlelr.view.gestureRecognizers else {
return
}
for recognizer in recognizers {
self.view.addGestureRecognizer(recognizer)
}
}
}
public func addPriorityToMenuGesuturePage(pageController: UIPageViewController) {
if let item = pageController.view.subviews.filter ({ $0 is UIScrollView }).first as? UIScrollView {
self.addPriorityToMenuGesuture(item)
}
}
}
|
d3c00187a50323bbce5c3801401ce445
| 29.988506 | 107 | 0.63525 | false | false | false | false |
hhcszgd/cszgdCode
|
refs/heads/master
|
weibo1/weibo1/classes/Module/LoginVC.swift
|
apache-2.0
|
1
|
//
// LoginVC.swift
// weibo1
//
// Created by WY on 15/11/27.
// Copyright © 2015年 WY. All rights reserved.
//
import UIKit
import AFNetworking
import SVProgressHUD
//MARK: 输入账号密码的登录控制器
class LoginVC: UIViewController {
let webView = UIWebView()
override func viewDidLoad() {
super.viewDidLoad()
navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", style: .Plain, target: self, action: "closeThisVC")
navigationItem.rightBarButtonItem=UIBarButtonItem(title: "自动填充", style: .Plain, target: self, action: "autoAccount")
title = "我要登录 "
loadWebPage()//调用自定义的加载网页的方法
// Do any additional setup after loading the view.
}
override func loadView() {//在loadView方法中设置导航栏的关闭按钮和显示标题
view = webView//把根View换成webView
webView.delegate = self // webView是需要代理的
}
func autoAccount (){
print("自动填充账号信息")
// let js = "document.getElementById('userId').value = '[email protected]';" +
// "document.getElementById('passwd').value = 'qqq123';"
let js = "document.getElementById('userId').value = '[email protected]', document.getElementById('passwd').value = 'oyonomg' " //为什么非要用小雷的账号密码才可以呢???
webView.stringByEvaluatingJavaScriptFromString(js)
}
func loadWebPage (){//自定义的加载网页的方法
let string : String = "https://api.weibo.com/oauth2/authorize?" + "client_id=" + client_id + "&redirect_uri=" + redirect_uri
let url = NSURL(string: string)
let request = NSURLRequest(URL : url!)
webView.loadRequest(request)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func closeThisVC (){
dismissViewControllerAnimated(true , completion: nil)
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
//使用extension为当前类扩展协议方法,(这样更加模块儿化)
extension LoginVC : UIWebViewDelegate{
//代理方法
func webViewDidStartLoad(webView: UIWebView){
SVProgressHUD.show()
}
func webViewDidFinishLoad (webView: UIWebView){
SVProgressHUD.dismiss()
}
// 实现webView的代理方法, 跟踪请求所相应的信息
// - (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType;
func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
// print ("打印打印打印:\(request)")
//js 调用本地代码
let urlString = request.URL?.absoluteString ?? ""
//屏蔽掉不希望加载的页面
if urlString.hasPrefix("https://api.weibo.com/") {
return true
}
if !urlString.hasPrefix("http://www.itcast.cn") {
return false
}
//程序如果走到这里 就只有包含回调的url才能运行到此
//获取授权码
guard let query = request.URL?.query else {
//request.URL?的值是http://www.itcast.cn/?code=b245d8a9945b2a941168aeae3c2fb798
//request.URL?.query的值是code=b245d8a9945b2a941168aeae3c2fb798
//获取不到参数列表
return false
}
// print("看看 \(query)")
let codeStr = "code="
let code = query.substringFromIndex(codeStr.endIndex)
//在这里创建一个viewModel 模型, 把获取token的数据都放在viewModel对应的类的方法中, 在通过对象方去调用方法,这个方法必须要有一个回调的闭包, 因为在获取完成token之后, 还要做一些处理, 比如提示数据加载失败还是成功
let viewModel1 = UserAccountViewModel()//创建
//调用
viewModel1.loadToken(code) { (error) -> () in// 回调闭包不执行??????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????
//回调内容,
// print("看看取出来的值\(UserAccountViewModel().userName)")
// 判断error是否为空, 如果为空提示网络不好, 如果成功提示, 加载成功
if error != nil {
//加载失败
SVProgressHUD.showErrorWithStatus("网络繁忙 请稍后再试")
return
}
//能走到这里说明加载成功
self.dismissViewControllerAnimated(false) { () -> Void in
// print("咳咳,这里是登陆控制器, 能走到这吗")
NSNotificationCenter.defaultCenter().postNotificationName(JumpVCNotification, object: "toWelcome")//注意注意, 销毁自己这个控制器一定要再回调方法里进行, 因为要保证后面被调用的方法执行完毕之后才能销毁自己, 不然的话, 把自己销毁了并且把通知发出去的话, 一方面自己可能不会被销毁, 另一方面, appdelegate可能就已经把跟控制器替换掉了
//注意是先销毁上一个控制器, 还是先发通知的顺序问题
}
}
// self.dismissViewControllerAnimated(false) { () -> Void in
// print("咳咳,这里是登陆控制器, 能走到这吗")
//// NSNotificationCenter.defaultCenter().postNotificationName(JumpVCNotification, object: "toWelcome")
// //注意是先销毁上一个控制器, 还是先发通知的顺序问题
// }
//MARK: 在这里发送跳转欢迎界面的通知
SVProgressHUD.showSuccessWithStatus("加载成功") //可以跳转 欢迎界面 的控制器了,
// NSNotificationCenter.defaultCenter().postNotificationName(JumpVCNotification, object: "toWelcome")
/**微博开发者平注册的 应用信息
let redirect_uri = "http://www.itcast.cn"
let client_id = "583790955"
*/
/**点击导航栏的 "登录" 按钮 打印的请求链接
<NSMutableURLRequest: 0x7f9069e327d0> { URL: https://api.weibo.com/oauth2/authorize?client_id=583790955&redirect_uri=http://www.itcast.cn }
*/
/**点击注册按钮 打印的请求链接
<NSMutableURLRequest: 0x7f9069e7b9c0> { URL: http://weibo.cn/dpool/ttt/h5/reg.php?wm=4406&appsrc=WfUcr&backURL=https%3A%2F%2Fapi.weibo.com%2F2%2Foauth2%2Fauthorize%3Fclient_id%3D583790955%26response_type%3Dcode%26display%3Dmobile%26redirect_uri%3Dhttp%253A%252F%252Fwww.itcast.cn%26from%3D%26with_cookie%3D }
*/
/**输入账号密码后点击登录按钮 打印的请求链接
<NSMutableURLRequest: 0x7f906c246620> { URL: https://api.weibo.com/oauth2/authorize }
*/
/**点击授权打印的请求链接
打印打印打印:<NSMutableURLRequest: 0x7f989af10510> { URL: https://api.weibo.com/oauth2/authorize# }
打印打印打印:<NSMutableURLRequest: 0x7f989ae2eea0> { URL: https://api.weibo.com/oauth2/authorize }
打印打印打印:<NSMutableURLRequest: 0x7f989d0c4060> { URL: http://www.itcast.cn/?code=12af58d1f5b71a2ae9952f03bd636cc8 }
*/
//获取到code码
//请求用户token
// loadAccessToken(code)
// return true
SVProgressHUD.dismiss()
return false//怎么反回false ??因为不想让它跳转到回调网址, 后期会让它调到我们指定的微博页面的
}
}
/**点击换个账号打印的链接 , 没用, 打印着玩的
<NSMutableURLRequest: 0x7f9069e84820> { URL: http://login.sina.com.cn/sso/logout.php?entry=openapi&r=https%3A%2F%2Fapi.weibo.com%2Foauth2%2Fauthorize%3Fclient_id%3D583790955%26redirect_uri%3Dhttp%3A%2F%2Fwww.itcast.cn }
*/
|
2811e001054c684fd3939289ddd10f32
| 39 | 316 | 0.619915 | false | false | false | false |
xxxAIRINxxx/Cmg
|
refs/heads/master
|
Proj/Demo/StretchImageView.swift
|
mit
|
1
|
//
// StretchImageView.swift
// Demo
//
// Created by xxxAIRINxxx on 2016/02/20.
// Copyright © 2016 xxxAIRINxxx. All rights reserved.
//
import Foundation
import UIKit
final class StretchImageView: UIView, UIScrollViewDelegate {
fileprivate static let maxZoomScale: CGFloat = 3
var image : UIImage? {
get { return self.imageView.image }
set {
let isFirst = self.imageView.image == nil
self.imageView.image = newValue
if isFirst == true {
self.resetZoomScale(false)
}
}
}
fileprivate var imageView : UIImageView!
fileprivate var scrollView : UIScrollView!
override init(frame: CGRect) {
super.init(frame: frame)
self.setup()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.setup()
}
override func layoutSubviews() {
super.layoutSubviews()
self.scrollView.contentSize = self.imageView.frame.size
}
func addToParentView(_ parentView: UIView) {
self.frame = parentView.bounds
self.autoresizingMask = [.flexibleWidth, .flexibleHeight]
parentView.addSubview(self)
}
fileprivate func setup() {
self.scrollView = UIScrollView(frame: self.bounds)
self.scrollView.showsHorizontalScrollIndicator = false
self.scrollView.showsVerticalScrollIndicator = false
self.scrollView.delegate = self
self.scrollView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
self.scrollView.panGestureRecognizer.delaysTouchesBegan = false
self.scrollView.panGestureRecognizer.minimumNumberOfTouches = 1
self.scrollView.bounces = false
self.addSubview(self.scrollView)
self.imageView = UIImageView(frame: self.bounds)
self.imageView.isUserInteractionEnabled = true
self.imageView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
self.scrollView.addSubview(self.imageView)
}
func resetImageViewFrame() {
let size = (self.imageView.image != nil) ? self.imageView.image!.size : self.imageView.frame.size
if size.width > 0 && size.height > 0 {
let ratio = min(self.scrollView.frame.size.width / size.width, self.scrollView.frame.size.height / size.height)
let W = ratio * size.width * self.scrollView.zoomScale
let H = ratio * size.height * self.scrollView.zoomScale
self.imageView.frame = CGRect(
x: max(0, (self.scrollView.frame.size.width - W) / 2),
y: max(0, (self.scrollView.frame.size.height - H) / 2), width: W, height: H)
}
}
func resetZoomScale(_ animated: Bool) {
var Rw = self.scrollView.frame.size.width / self.imageView.frame.size.width
var Rh = self.scrollView.frame.size.height / self.imageView.frame.size.height
let scale: CGFloat = UIScreen.main.scale
Rw = max(Rw, self.imageView.image!.size.width / (scale * self.scrollView.frame.size.width))
Rh = max(Rh, self.imageView.image!.size.height / (scale * self.scrollView.frame.size.height))
self.scrollView.contentSize = self.imageView.frame.size
self.scrollView.minimumZoomScale = 1
self.scrollView.maximumZoomScale = max(max(Rw, Rh), StretchImageView.maxZoomScale)
self.scrollView.setZoomScale(self.scrollView.minimumZoomScale, animated: animated)
}
func reset(_ animated: Bool) {
self.resetImageViewFrame()
self.resetZoomScale(animated)
}
}
// MARK: - UIScrollViewDelegate
extension StretchImageView {
@objc(viewForZoomingInScrollView:) func viewForZooming(in scrollView: UIScrollView) -> UIView? {
return self.imageView
}
func scrollViewDidZoom(_ scrollView: UIScrollView) {
let Ws = self.scrollView.frame.size.width - self.scrollView.contentInset.left - self.scrollView.contentInset.right
let Hs = self.scrollView.frame.size.height - self.scrollView.contentInset.top - self.scrollView.contentInset.bottom
let W = self.imageView.frame.size.width
let H = self.imageView.frame.size.height
var rct = self.imageView.frame
rct.origin.x = max((Ws-W) / 2, 0)
rct.origin.y = max((Hs-H) / 2, 0)
self.imageView.frame = rct
}
}
|
ac21921d9670062a2339563b53b0aa36
| 35.219512 | 123 | 0.643547 | false | false | false | false |
dreamsxin/swift
|
refs/heads/master
|
stdlib/public/core/Hashing.swift
|
apache-2.0
|
3
|
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
//
// This file implements helpers for constructing non-cryptographic hash
// functions.
//
// This code was ported from LLVM's ADT/Hashing.h.
//
// Currently the algorithm is based on CityHash, but this is an implementation
// detail. Even more, there are facilities to mix in a per-execution seed to
// ensure that hash values differ between executions.
//
import SwiftShims
public // @testable
struct _HashingDetail {
public // @testable
static var fixedSeedOverride: UInt64 {
get {
// HACK: the variable itself is defined in C++ code so that it is
// guaranteed to be statically initialized. This is a temporary
// workaround until the compiler can do the same for Swift.
return _swift_stdlib_HashingDetail_fixedSeedOverride
}
set {
_swift_stdlib_HashingDetail_fixedSeedOverride = newValue
}
}
@_versioned
@_transparent
static func getExecutionSeed() -> UInt64 {
// FIXME: This needs to be a per-execution seed. This is just a placeholder
// implementation.
let seed: UInt64 = 0xff51afd7ed558ccd
return _HashingDetail.fixedSeedOverride == 0 ? seed : fixedSeedOverride
}
@_versioned
@_transparent
static func hash16Bytes(_ low: UInt64, _ high: UInt64) -> UInt64 {
// Murmur-inspired hashing.
let mul: UInt64 = 0x9ddfea08eb382d69
var a: UInt64 = (low ^ high) &* mul
a ^= (a >> 47)
var b: UInt64 = (high ^ a) &* mul
b ^= (b >> 47)
b = b &* mul
return b
}
}
//
// API functions.
//
//
// _mix*() functions all have type (T) -> T. These functions don't compress
// their inputs and just exhibit avalanche effect.
//
@_transparent
public // @testable
func _mixUInt32(_ value: UInt32) -> UInt32 {
// Zero-extend to 64 bits, hash, select 32 bits from the hash.
//
// NOTE: this differs from LLVM's implementation, which selects the lower
// 32 bits. According to the statistical tests, the 3 lowest bits have
// weaker avalanche properties.
let extendedValue = UInt64(value)
let extendedResult = _mixUInt64(extendedValue)
return UInt32((extendedResult >> 3) & 0xffff_ffff)
}
@_transparent
public // @testable
func _mixInt32(_ value: Int32) -> Int32 {
return Int32(bitPattern: _mixUInt32(UInt32(bitPattern: value)))
}
@_transparent
public // @testable
func _mixUInt64(_ value: UInt64) -> UInt64 {
// Similar to hash_4to8_bytes but using a seed instead of length.
let seed: UInt64 = _HashingDetail.getExecutionSeed()
let low: UInt64 = value & 0xffff_ffff
let high: UInt64 = value >> 32
return _HashingDetail.hash16Bytes(seed &+ (low << 3), high)
}
@_transparent
public // @testable
func _mixInt64(_ value: Int64) -> Int64 {
return Int64(bitPattern: _mixUInt64(UInt64(bitPattern: value)))
}
@_transparent
public // @testable
func _mixUInt(_ value: UInt) -> UInt {
#if arch(i386) || arch(arm)
return UInt(_mixUInt32(UInt32(value)))
#elseif arch(x86_64) || arch(arm64) || arch(powerpc64) || arch(powerpc64le) || arch(s390x)
return UInt(_mixUInt64(UInt64(value)))
#endif
}
@_transparent
public // @testable
func _mixInt(_ value: Int) -> Int {
#if arch(i386) || arch(arm)
return Int(_mixInt32(Int32(value)))
#elseif arch(x86_64) || arch(arm64) || arch(powerpc64) || arch(powerpc64le) || arch(s390x)
return Int(_mixInt64(Int64(value)))
#endif
}
/// Given a hash value, returns an integer value within the given range that
/// corresponds to a hash value.
///
/// This function is superior to computing the remainder of `hashValue` by
/// the range length. Some types have bad hash functions; sometimes simple
/// patterns in data sets create patterns in hash values and applying the
/// remainder operation just throws away even more information and invites
/// even more hash collisions. This effect is especially bad if the length
/// of the required range is a power of two -- applying the remainder
/// operation just throws away high bits of the hash (which would not be
/// a problem if the hash was known to be good). This function mixes the
/// bits in the hash value to compensate for such cases.
///
/// Of course, this function is a compressing function, and applying it to a
/// hash value does not change anything fundamentally: collisions are still
/// possible, and it does not prevent malicious users from constructing data
/// sets that will exhibit pathological collisions.
public // @testable
func _squeezeHashValue(_ hashValue: Int, _ resultRange: Range<Int>) -> Int {
// Length of a Range<Int> does not fit into an Int, but fits into an UInt.
// An efficient way to compute the length is to rely on two's complement
// arithmetic.
let resultCardinality =
UInt(bitPattern: resultRange.upperBound &- resultRange.lowerBound)
// Calculate the result as `UInt` to handle the case when
// `resultCardinality >= Int.max`.
let unsignedResult =
_squeezeHashValue(hashValue, UInt(0)..<resultCardinality)
// We perform the unchecked arithmetic on `UInt` (instead of doing
// straightforward computations on `Int`) in order to handle the following
// tricky case: `startIndex` is negative, and `resultCardinality >= Int.max`.
// We cannot convert the latter to `Int`.
return
Int(bitPattern:
UInt(bitPattern: resultRange.lowerBound) &+ unsignedResult)
}
public // @testable
func _squeezeHashValue(_ hashValue: Int, _ resultRange: Range<UInt>) -> UInt {
let mixedHashValue = UInt(bitPattern: _mixInt(hashValue))
let resultCardinality: UInt = resultRange.upperBound - resultRange.lowerBound
if _isPowerOf2(resultCardinality) {
return mixedHashValue & (resultCardinality - 1)
}
return resultRange.lowerBound + (mixedHashValue % resultCardinality)
}
|
015dc3abe81d572f794b0f5e1603c418
| 34.193182 | 90 | 0.691314 | false | true | false | false |
5lucky2xiaobin0/PandaTV
|
refs/heads/master
|
PandaTV/PandaTV/Classes/Main/Controller/MainTabBarVC.swift
|
mit
|
1
|
//
// MainTabBarVC.swift
// PandaTV
//
// Created by 钟斌 on 2017/3/24.
// Copyright © 2017年 xiaobin. All rights reserved.
//
import UIKit
class MainTabBarVC: UITabBarController {
override func viewDidLoad() {
super.viewDidLoad()
addChildVC(vc: HomeVC(), title: "首页", nImage: "menu_homepage", sImage: "menu_homepage_sel")
addChildVC(vc: GameVC(), title: "游戏", nImage: "menu_youxi", sImage: "menu_youxi_sel")
addChildVC(vc: ShowVC(), title: "娱乐", nImage: "menu_yule", sImage: "menu_yule_sel")
let bigEatVc = UIStoryboard(name: "BigEatVC", bundle: nil).instantiateInitialViewController()
addChildVC(vc: bigEatVc!, title: "大胃王", nImage: "menu_bigeat", sImage: "menu_bigeat_sel")
let podFlieVc = UIStoryboard(name: "PodfileVC", bundle: nil).instantiateInitialViewController()
addChildVC(vc: podFlieVc!, title: "我", nImage: "menu_mine", sImage: "menu_mine_sel")
tabBar.backgroundColor = UIColor.white
}
}
//界面设置
extension MainTabBarVC {
fileprivate func addChildVC(vc : UIViewController, title : String, nImage : String, sImage : String){
vc.tabBarItem.image = UIImage(named: nImage)
vc.tabBarItem.selectedImage = UIImage(named: sImage)
vc.title = title
let navVC = MainNavVC(rootViewController: vc)
addChildViewController(navVC)
}
}
|
41a69c173d40d121fdde0e939cf69556
| 31.953488 | 105 | 0.642202 | false | false | false | false |
futurechallenger/MVVM
|
refs/heads/master
|
MVVM/ViewController.swift
|
mit
|
1
|
//
// ViewController.swift
// MVVM
//
// Created by Bruce Lee on 9/12/14.
// Copyright (c) 2014 Dynamic Cell. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
var model: Person!
var viewModel: PersonViewModel!
var nameLabel: UILabel!
var birthDateLabel: UILabel!
@IBOutlet weak var operationButton: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
// self.nameLabel.text = self.viewModel.nameText
// self.birthDateLabel.text = self.viewModel.birthDateText
}
@IBAction func startAction(button: UIButton){
// var group = dispatch_group_create()
// dispatch_group_async(group, dispatch_get_global_queue(0, 0), {
// println("first queue")
// })
// dispatch_group_async(group, dispatch_get_global_queue(0, 0), {
// println("second queue")
// })
// dispatch_group_async(group, dispatch_get_global_queue(0, 0), {
// println("third queue")
// })
//
// dispatch_group_notify(group, dispatch_get_main_queue(), {
// println("main queue")
// })
var semaphore = dispatch_semaphore_create(0)
var condition = 1000
dispatch_async(dispatch_get_global_queue(0, 0), {
var localCondition = condition
while localCondition-- > 0 {
if dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER) == 0{
println("consume resource")
}
}
})
dispatch_async(dispatch_get_global_queue(0, 0), {
var localCondition = 10
while localCondition-- > 0{
dispatch_semaphore_signal(semaphore)
println("create resource")
}
})
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
|
163060a62ccc9f79788cfc741045fdd8
| 28.188406 | 82 | 0.565541 | false | false | false | false |
lorentey/GlueKit
|
refs/heads/master
|
Tests/GlueKitTests/TestChange.swift
|
mit
|
1
|
//
// TestChange.swift
// GlueKit
//
// Created by Károly Lőrentey on 2016-10-26.
// Copyright © 2015–2017 Károly Lőrentey.
//
import XCTest
import GlueKit
internal struct TestChange: ChangeType, Equatable, CustomStringConvertible {
typealias Value = Int
var values: [Int]
init(_ values: [Int]) {
self.values = values
}
init(from oldValue: Int, to newValue: Int) {
values = [oldValue, newValue]
}
var isEmpty: Bool {
return values.isEmpty
}
func apply(on value: inout Int) {
XCTAssertEqual(value, values.first!)
value = values.last!
}
mutating func merge(with next: TestChange) {
XCTAssertEqual(self.values.last!, next.values.first!)
values += next.values.dropFirst()
}
func reversed() -> TestChange {
return TestChange(values.reversed())
}
public var description: String {
return values.map { "\($0)" }.joined(separator: " -> ")
}
static func ==(left: TestChange, right: TestChange) -> Bool {
return left.values == right.values
}
}
|
ccfd29328b7f979307622b028c387e3d
| 21 | 76 | 0.611818 | false | true | false | false |
ryanipete/AmericanChronicle
|
refs/heads/master
|
AmericanChronicle/Code/Modules/DatePicker/Wireframe/TransitionControllers/ShowDatePickerTransitionController.swift
|
mit
|
1
|
import UIKit
final class ShowDatePickerTransitionController: NSObject, UIViewControllerAnimatedTransitioning {
let duration = 0.2
func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
guard let fromVC = transitionContext.viewController(forKey: .from) else { return }
let blackBG = UIView()
blackBG.backgroundColor = .black
transitionContext.containerView.addSubview(blackBG)
blackBG.fillSuperview(insets: .zero)
guard let snapshot = fromVC.view.snapshotView() else { return }
snapshot.tag = DatePickerTransitionConstants.snapshotTag
transitionContext.containerView.addSubview(snapshot)
guard let toVC = transitionContext.viewController(forKey: .to) as? DatePickerViewController else { return }
transitionContext.containerView.addSubview(toVC.view)
toVC.view.layoutIfNeeded()
toVC.view.backgroundColor = UIColor(white: 0, alpha: 0)
toVC.showKeyboard()
UIView.animate(withDuration: duration, animations: {
toVC.view.layoutIfNeeded()
toVC.view.backgroundColor = UIColor(white: 0, alpha: 0.8)
snapshot.transform = CGAffineTransform(scaleX: 0.99, y: 0.99)
}, completion: { _ in
transitionContext.completeTransition(true)
})
}
func transitionDuration(
using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
duration
}
}
|
d9b9eb1e0194496bbf1ec35b06f0728a
| 37.358974 | 115 | 0.698529 | false | false | false | false |
abertelrud/swift-package-manager
|
refs/heads/main
|
Sources/PackageModel/Manifest/SystemPackageProviderDescription.swift
|
apache-2.0
|
2
|
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift open source project
//
// Copyright (c) 2014-2020 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
/// Represents system package providers.
public enum SystemPackageProviderDescription: Equatable, Codable {
case brew([String])
case apt([String])
case yum([String])
case nuget([String])
}
extension SystemPackageProviderDescription {
private enum CodingKeys: String, CodingKey {
case brew, apt, yum, nuget
}
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
switch self {
case let .brew(a1):
var unkeyedContainer = container.nestedUnkeyedContainer(forKey: .brew)
try unkeyedContainer.encode(a1)
case let .apt(a1):
var unkeyedContainer = container.nestedUnkeyedContainer(forKey: .apt)
try unkeyedContainer.encode(a1)
case let .yum(a1):
var unkeyedContainer = container.nestedUnkeyedContainer(forKey: .yum)
try unkeyedContainer.encode(a1)
case let .nuget(a1):
var unkeyedContainer = container.nestedUnkeyedContainer(forKey: .nuget)
try unkeyedContainer.encode(a1)
}
}
public init(from decoder: Decoder) throws {
let values = try decoder.container(keyedBy: CodingKeys.self)
guard let key = values.allKeys.first(where: values.contains) else {
throw DecodingError.dataCorrupted(.init(codingPath: decoder.codingPath, debugDescription: "Did not find a matching key"))
}
switch key {
case .brew:
var unkeyedValues = try values.nestedUnkeyedContainer(forKey: key)
let a1 = try unkeyedValues.decode([String].self)
self = .brew(a1)
case .apt:
var unkeyedValues = try values.nestedUnkeyedContainer(forKey: key)
let a1 = try unkeyedValues.decode([String].self)
self = .apt(a1)
case .yum:
var unkeyedValues = try values.nestedUnkeyedContainer(forKey: key)
let a1 = try unkeyedValues.decode([String].self)
self = .yum(a1)
case .nuget:
var unkeyedValues = try values.nestedUnkeyedContainer(forKey: key)
let a1 = try unkeyedValues.decode([String].self)
self = .nuget(a1)
}
}
}
|
931318c2db9aac4adcdb9a53c758b2db
| 39.617647 | 133 | 0.609341 | false | false | false | false |
MadArkitekt/Swift_Tutorials_And_Demos
|
refs/heads/master
|
sqlite/Tutorial.playground/Pages/Making it Swift.xcplaygroundpage/Contents.swift
|
gpl-2.0
|
1
|
/// Copyright (c) 2017 Razeware LLC
///
/// Permission is hereby granted, free of charge, to any person obtaining a copy
/// of this software and associated documentation files (the "Software"), to deal
/// in the Software without restriction, including without limitation the rights
/// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
/// copies of the Software, and to permit persons to whom the Software is
/// furnished to do so, subject to the following conditions:
///
/// The above copyright notice and this permission notice shall be included in
/// all copies or substantial portions of the Software.
///
/// Notwithstanding the foregoing, you may not use, copy, modify, merge, publish,
/// distribute, sublicense, create a derivative work, and/or sell copies of the
/// Software in any work that is designed, intended, or marketed for pedagogical or
/// instructional purposes related to programming, coding, application development,
/// or information technology. Permission for such use, copying, modification,
/// merger, publication, distribution, sublicensing, creation of derivative works,
/// or sale is expressly withheld.
///
/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
/// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
/// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
/// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
/// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
/// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
/// THE SOFTWARE.
import Foundation
import SQLite3
import PlaygroundSupport
destroyPart2Database()
//: # Making it Swift
enum SQLiteError: Error {
case OpenDatabase(message: String)
case Prepare(message: String)
case Step(message: String)
case Bind(message: String)
}
//: ## The Database Connection
class SQLiteDatabase {
fileprivate let dbPointer: OpaquePointer?
fileprivate init(dbPointer: OpaquePointer?) {
self.dbPointer = dbPointer
}
deinit {
sqlite3_close(dbPointer)
}
static func open(path: String) throws -> SQLiteDatabase {
var db: OpaquePointer? = nil
if sqlite3_open(path, &db) == SQLITE_OK {
return SQLiteDatabase(dbPointer: db)
} else {
defer {
if db != nil {
sqlite3_close(db)
}
}
if let errorPointer = sqlite3_errmsg(db) {
let message = String.init(cString: errorPointer)
throw SQLiteError.OpenDatabase(message: message)
} else {
throw SQLiteError.OpenDatabase(message: "shit went down, still not sure what, where, or when")
}
}
}
fileprivate var errorMessage: String {
if let errorPointer = sqlite3_errmsg(dbPointer) {
let errorMessage = String(cString: errorPointer)
return errorMessage
} else {
return "No ERROR!!"
}
}
}
let db: SQLiteDatabase
do {
db = try SQLiteDatabase.open(path: part2DbPath)
print("Successfully opened connection to database.")
} catch SQLiteError.OpenDatabase(let _) {
print("Unable to open database. Verify that you created the directory described in the Getting Started section.")
PlaygroundPage.current.finishExecution()
}
//: ## Preparing Statements
extension SQLiteDatabase {
func prepareStatement(sql: String) throws -> OpaquePointer? {
var statement: OpaquePointer? = nil
guard sqlite3_prepare_v2(dbPointer, sql, -1, &statement, nil) == SQLITE_OK else {
throw SQLiteError.Prepare(message: errorMessage)
}
return statement
}
}
//: ## Create Table
struct Contact {
let id: Int32
let name: NSString
}
protocol SQLTable {
static var createStatement: String { get }
}
extension Contact: SQLTable {
static var createStatement: String {
return """
CREATE TABLE Contact(
Id INT PRIMARY KEY NOT NULL,
Name CHAR(255)
);
"""
}
}
extension SQLiteDatabase {
func createTable(table: SQLTable.Type) throws {
let createTableStatement = try prepareStatement(sql: table.createStatement )
defer {
sqlite3_finalize(createTableStatement)
}
guard sqlite3_step(createTableStatement) == SQLITE_DONE else {
throw SQLiteError.Step(message: errorMessage)
}
print("\(table) table created")
}
}
do {
try db.createTable(table: Contact.self)
} catch {
print(db.errorMessage)
}
//: ## Insertion
extension SQLiteDatabase {
func insertContact(contact: Contact) throws {
let insertSql = "INSERT INTO Contact (Id, Name) VALUES (?, ?);"
let insertStatement = try prepareStatement(sql: insertSql)
defer {
sqlite3_finalize(insertStatement)
}
let name: NSString = contact.name
guard sqlite3_bind_int(insertStatement, 1, contact.id) == SQLITE_OK &&
sqlite3_bind_text(insertStatement, 2, name.utf8String, -1, nil) == SQLITE_OK else {
throw SQLiteError.Bind(message: errorMessage)
}
guard sqlite3_step(insertStatement) == SQLITE_DONE else {
throw SQLiteError.Step(message: errorMessage)
}
print("Successfully inserted row.")
}
}
do {
try db.insertContact(contact: Contact(id: 1, name: "Ray"))
} catch {
print(db.errorMessage)
}
//: ## Read
extension SQLiteDatabase {
func contact(id: Int32) -> Contact? {
let querySql = "SELECT * FROM Contact WHERE Id = ?;"
guard let queryStatement = try? prepareStatement(sql: querySql) else {
return nil
}
defer {
sqlite3_finalize(queryStatement)
}
guard sqlite3_bind_int(queryStatement, 1, id) == SQLITE_OK else {
return nil
}
guard sqlite3_step(queryStatement) == SQLITE_ROW else {
return nil
}
let id = sqlite3_column_int(queryStatement, 0)
let queryResultCol1 = sqlite3_column_text(queryStatement, 1)
let nameTemp = String(cString: queryResultCol1!)
let name = nameTemp as NSString
return Contact(id: id, name: name)
}
}
let first = db.contact(id: 1)
print("\(first?.id) \(first?.name)")
|
8f0247dee61eec1a2243bfc8c7b7f515
| 31.524752 | 117 | 0.641248 | false | false | false | false |
wireapp/wire-ios
|
refs/heads/develop
|
Wire-iOS/Sources/UserInterface/Conversation/Create/Sections/ConversationCreateNameSectionController.swift
|
gpl-3.0
|
1
|
////
// Wire
// Copyright (C) 2018 Wire Swiss GmbH
//
// This program 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.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
import Foundation
import WireDataModel
final class ConversationCreateNameSectionController: NSObject, CollectionViewSectionController {
typealias Cell = ConversationCreateNameCell
var isHidden: Bool {
return false
}
var value: SimpleTextField.Value? {
return nameCell?.textField.value
}
private weak var nameCell: Cell?
private weak var textFieldDelegate: SimpleTextFieldDelegate?
private var footer = SectionFooter(frame: .zero)
private let selfUser: UserType
private lazy var footerText: String = {
return "participants.section.name.footer".localized(args: ZMConversation.maxParticipants)
}()
init(selfUser: UserType,
delegate: SimpleTextFieldDelegate? = nil) {
textFieldDelegate = delegate
self.selfUser = selfUser
}
func prepareForUse(in collectionView: UICollectionView?) {
collectionView.flatMap(Cell.register)
collectionView?.register(SectionFooter.self, forSupplementaryViewOfKind: UICollectionView.elementKindSectionFooter, withReuseIdentifier: "SectionFooter")
}
func becomeFirstResponder() {
nameCell?.textField.becomeFirstResponder()
}
func resignFirstResponder() {
nameCell?.textField.resignFirstResponder()
}
// MARK: - collectionView
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 1
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(ofType: Cell.self, for: indexPath)
cell.textField.textFieldDelegate = textFieldDelegate
nameCell = cell
return cell
}
func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
let view = collectionView.dequeueReusableSupplementaryView(ofKind: UICollectionView.elementKindSectionFooter, withReuseIdentifier: "SectionFooter", for: indexPath)
(view as? SectionFooter)?.titleLabel.text = footerText
return view
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return CGSize(width: collectionView.bounds.size.width, height: 56)
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForFooterInSection section: Int) -> CGSize {
guard selfUser.isTeamMember else {
return .zero
}
footer.titleLabel.text = footerText
footer.size(fittingWidth: collectionView.bounds.width)
return footer.bounds.size
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
nameCell?.textField.becomeFirstResponder()
}
}
|
beed26d997470d73b5c9e0bc407d927b
| 36.755102 | 171 | 0.732703 | false | false | false | false |
aipeople/PokeIV
|
refs/heads/master
|
PokeIV/SortOptionSheet.swift
|
gpl-3.0
|
1
|
//
// SortOptionSheet.swift
// PokeIV
//
// Created by aipeople on 8/15/16.
// Github: https://github.com/aipeople/PokeIV
// Copyright © 2016 su. All rights reserved.
//
import UIKit
import Cartography
enum PokemonSort : String {
case PokemonID = "Pokemon ID"
case CombatPower = "Combat Power"
case IndividualValue = "Individual Value"
case CapturedDate = "Captured Date"
}
class SortOptionSheet: OptionSheet<PokemonSort> {
// MARK: - Properties
// Class
static let DecendingEnabledKey = "decending"
// UI
let headContainer = UIView()
let sortingLabel = UILabel()
let sortingSwitch = UISwitch()
// Data
var sortingChangedCallback : ((SortOptionSheet) -> ())?
init() {
super.init(options: [
PokemonSort.PokemonID,
PokemonSort.CombatPower,
PokemonSort.IndividualValue,
PokemonSort.CapturedDate
])
self.headContainer.frame = CGRectMake(0, 0, 320, 44)
self.tableView.tableHeaderView = self.headContainer
self.headContainer.addSubview(self.sortingLabel)
constrain(self.sortingLabel) { (view) in
view.left == view.superview!.left + 15
view.centerY == view.superview!.centerY
}
self.headContainer.addSubview(self.sortingSwitch)
constrain(self.sortingSwitch) { (view) in
view.right == view.superview!.right - 15
view.centerY == view.superview!.centerY
}
// Setup Views
self.title = NSLocalizedString("Sort By", comment: "sorting option sheet title")
self.displayParser = { (sheet, option) in
return option.rawValue
}
self.sortingLabel.text = NSLocalizedString("Sort in decending", comment: "sorting option")
self.sortingLabel.textColor = App.Color.Text.Normal
self.sortingLabel.font = UIFont.systemFontOfSize(16)
self.headContainer.backgroundColor = UIColor(white: 0.4, alpha: 1.0)
self.sortingSwitch.onTintColor = App.Color.Main
self.sortingSwitch.on = NSUserDefaults.standardUserDefaults().boolForKey(SortOptionSheet.DecendingEnabledKey)
self.sortingSwitch.addTarget(self,
action: #selector(handleSwitchValueChanged(_:)),
forControlEvents: .ValueChanged
)
}
func handleSwitchValueChanged(sender: UISwitch) {
self.sortingChangedCallback?(self)
}
}
|
75053be327a53ec1fa5fbdeabbd2dd92
| 25.90625 | 117 | 0.615176 | false | false | false | false |
alecananian/osx-coin-ticker
|
refs/heads/develop
|
CoinTicker/Source/CurrencyPair.swift
|
mit
|
1
|
//
// CurrencyPair.swift
// CoinTicker
//
// Created by Alec Ananian on 11/19/17.
// Copyright © 2017 Alec Ananian.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import Foundation
struct CurrencyPair: Comparable, Codable {
var baseCurrency: Currency
var quoteCurrency: Currency
var customCode: String
init(baseCurrency: Currency, quoteCurrency: Currency, customCode: String? = nil) {
self.baseCurrency = baseCurrency
self.quoteCurrency = quoteCurrency
if let customCode = customCode {
self.customCode = customCode
} else {
self.customCode = "\(baseCurrency.code)\(quoteCurrency.code)"
}
}
init?(baseCurrency: String?, quoteCurrency: String?, customCode: String? = nil) {
guard let baseCurrency = Currency(code: baseCurrency), let quoteCurrency = Currency(code: quoteCurrency) else {
return nil
}
self = CurrencyPair(baseCurrency: baseCurrency, quoteCurrency: quoteCurrency, customCode: customCode)
}
}
extension CurrencyPair: CustomStringConvertible {
var description: String {
return "\(baseCurrency.code)\(quoteCurrency.code)"
}
}
extension CurrencyPair: Hashable {
func hash(into hasher: inout Hasher) {
hasher.combine(String(describing: self))
}
}
extension CurrencyPair: Equatable {
static func <(lhs: CurrencyPair, rhs: CurrencyPair) -> Bool {
if lhs.baseCurrency == rhs.baseCurrency {
return lhs.quoteCurrency < rhs.quoteCurrency
}
return lhs.baseCurrency < rhs.baseCurrency
}
static func == (lhs: CurrencyPair, rhs: CurrencyPair) -> Bool {
return (lhs.baseCurrency == rhs.baseCurrency && lhs.quoteCurrency == rhs.quoteCurrency)
}
}
|
59486b1bc4a9dbf58523e40d8ebf768e
| 31.906977 | 119 | 0.697527 | false | false | false | false |
Olinguito/YoIntervengoiOS
|
refs/heads/master
|
Yo Intervengo/Helpers/TabBar/JOTabBar.swift
|
mit
|
1
|
//
// JOTabBar.swift
// Yo Intervengo
//
// Created by Jorge Raul Ovalle Zuleta on 1/30/15.
// Copyright (c) 2015 Olinguito. All rights reserved.
//
import UIKit
@objc protocol JOTabBarDelegate{
optional func tappedButton()
}
class JOTabBar: UIView {
var delegate:JOTabBarDelegate!
var buttons:NSMutableArray!
var data:NSMutableArray!
var container:UIView!
var actual:Int!
var colorView:UIColor!
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
init(frame: CGRect, data:NSMutableArray, color: UIColor) {
super.init(frame: frame)
self.data = data
buttons = NSMutableArray()
colorView = color
var counter = 0
var w = (frame.size.width/CGFloat(data.count))
let font = UIFont(name: "Roboto-Regular", size: 10)
for button in data {
var xAxis = CGFloat(counter)*w
var but: UIButton = UIButton.buttonWithType(UIButtonType.System) as! UIButton
but.frame = CGRect(x: xAxis, y: 0, width: w, height: 55)
but.backgroundColor = UIColor.whiteColor()
but.layer.borderWidth = 1
but.tag = counter+1
but.titleLabel?.font = font
var imageBtn = UIImage(named: (data.objectAtIndex(counter)[0] as! String))
but.setImage(imageBtn, forState: UIControlState.Normal)
but.setTitle( (data.objectAtIndex(counter)[0] as! String), forState: UIControlState.Normal)
var spacing:CGFloat = 6
var imageSize = but.imageView?.image?.size
var title:NSString = "\(but.titleLabel?.text)"
var titleSize = title.sizeWithAttributes([NSFontAttributeName: but.titleLabel?.font ?? UIFont.systemFontOfSize(100)])
var size:CGSize = imageBtn?.size ?? CGSizeZero
but.contentHorizontalAlignment = UIControlContentHorizontalAlignment.Center
but.titleEdgeInsets = UIEdgeInsetsMake(0.0, (-size.width) , -(size.height + spacing), 0.0)
but.imageEdgeInsets = UIEdgeInsetsMake(-(titleSize.height + spacing), (titleSize.width-(size.width*1.7))/2 , 0.0, 0)
but.layer.borderColor = UIColor.greyButtons().CGColor
but.addTarget(self, action: Selector("buttonTapped:"), forControlEvents: UIControlEvents.TouchUpInside)
self.addSubview(but)
counter++
buttons.addObject(but)
}
setTab(1)
}
func buttonTapped(sender:UIButton!){
setTab(sender.tag)
}
func getActHelper() ->UIButton{
var returnBtn = UIButton()
switch(actual){
case 1: returnBtn.tag = 0
case 2: returnBtn.tag = 0
case 3: returnBtn.setImage(UIImage(named: "linkHelper"), forState: UIControlState.Normal)
returnBtn.tag = 1
case 4: returnBtn.setImage(UIImage(named: "linkHelper"), forState: UIControlState.Normal)
returnBtn.tag = 2
default: returnBtn.tag = 0
}
return returnBtn
}
func setTab(index:Int){
var counter = 1
actual = index
for button in buttons{
(button as! UIButton).backgroundColor = UIColor.whiteColor()
/*if counter+1==index{
var mask = CAShapeLayer()
mask.path = (UIBezierPath(roundedRect: button.bounds, byRoundingCorners: UIRectCorner.BottomRight, cornerRadii: CGSize(width: 5.0, height: 10.0))).CGPath
button.layer.mask = mask
}
if counter-1==index{
var mask = CAShapeLayer()
mask.path = (UIBezierPath(roundedRect: button.bounds, byRoundingCorners: UIRectCorner.BottomLeft, cornerRadii: CGSize(width: 5.0, height: 10.0))).CGPath
button.layer.mask = mask
}*/
(button as! UIButton).layer.borderColor = UIColor.greyButtons().CGColor
(button as! UIButton).tintColor = UIColor.greyDark()
if counter==index{
if (container?.isDescendantOfView(self) != nil){
container.removeFromSuperview()
}
(button as! UIButton).layer.borderColor = UIColor.clearColor().CGColor
(button as! UIButton).tintColor = colorView
container = self.data.objectAtIndex(index-1)[1] as! UIView
container.frame = (self.data.objectAtIndex(index-1)[1] as! UIView).frame
container.frame.origin = CGPoint(x: 0, y: 55)
self.frame = CGRect(x: 0, y: self.frame.origin.y, width: 320, height: container.frame.maxY)
self.addSubview(container)
var pop = POPSpringAnimation(propertyNamed: kPOPViewFrame)
pop.toValue = NSValue(CGRect: CGRect(origin: self.frame.origin, size: CGSize(width: self.frame.size.width, height: container.frame.height+55)))
self.pop_addAnimation(pop, forKey: "Increase")
self.delegate?.tappedButton!()
}
counter++
}
}
}
|
18bb1bc5dd507ea7b37b8f2aef173e9c
| 40.935484 | 170 | 0.595577 | false | false | false | false |
ABTSoftware/SciChartiOSTutorial
|
refs/heads/master
|
v2.x/Examples/SciChartSwiftDemo/SciChartSwiftDemo/Views/ModifyAxisBehaviour/LogarithmicAxisChartView.swift
|
mit
|
1
|
//******************************************************************************
// SCICHART® Copyright SciChart Ltd. 2011-2018. All rights reserved.
//
// Web: http://www.scichart.com
// Support: [email protected]
// Sales: [email protected]
//
// LogarithmicAxisChartView.swift is part of the SCICHART® Examples. Permission is hereby granted
// to modify, create derivative works, distribute and publish any part of this source
// code whether for commercial, private or personal use.
//
// The SCICHART® examples are distributed in the hope that they will be useful, but
// without any warranty. It is provided "AS IS" without warranty of any kind, either
// expressed or implied.
//******************************************************************************
class LogarithmicAxisChartView: SingleChartLayout {
override func initExample() {
let xAxis = SCILogarithmicNumericAxis()
xAxis.growBy = SCIDoubleRange(min: SCIGeneric(0.1), max: SCIGeneric(0.1))
xAxis.scientificNotation = .logarithmicBase
xAxis.textFormatting = "#.#E+0"
let yAxis = SCILogarithmicNumericAxis()
yAxis.growBy = SCIDoubleRange(min: SCIGeneric(0.1), max: SCIGeneric(0.1))
yAxis.scientificNotation = .logarithmicBase
yAxis.textFormatting = "#.#E+0"
let dataSeries1 = SCIXyDataSeries(xType: .double, yType: .double)
dataSeries1.seriesName = "Curve A"
let dataSeries2 = SCIXyDataSeries(xType: .double, yType: .double)
dataSeries2.seriesName = "Curve B"
let dataSeries3 = SCIXyDataSeries(xType: .double, yType: .double)
dataSeries3.seriesName = "Curve C"
let doubleSeries1 = DataManager.getExponentialCurve(withExponent: 1.8, count: 100)
let doubleSeries2 = DataManager.getExponentialCurve(withExponent: 2.25, count: 100)
let doubleSeries3 = DataManager.getExponentialCurve(withExponent: 3.59, count: 100)
dataSeries1.appendRangeX(doubleSeries1!.xValues, y: doubleSeries1!.yValues, count: doubleSeries1!.size)
dataSeries2.appendRangeX(doubleSeries2!.xValues, y: doubleSeries2!.yValues, count: doubleSeries2!.size)
dataSeries3.appendRangeX(doubleSeries3!.xValues, y: doubleSeries3!.yValues, count: doubleSeries3!.size)
let line1Color: UInt32 = 0xFFFFFF00
let line2Color: UInt32 = 0xFF279B27
let line3Color: UInt32 = 0xFFFF1919
let line1 = SCIFastLineRenderableSeries()
line1.dataSeries = dataSeries1
line1.strokeStyle = SCISolidPenStyle(colorCode: line1Color, withThickness: 1.5)
line1.pointMarker = getPointMarker(size: 5, colorCode: line1Color)
let line2 = SCIFastLineRenderableSeries()
line2.dataSeries = dataSeries2
line2.strokeStyle = SCISolidPenStyle(colorCode: line2Color, withThickness: 1.5)
line2.style.pointMarker = getPointMarker(size: 5, colorCode: line2Color)
let line3 = SCIFastLineRenderableSeries()
line3.dataSeries = dataSeries3
line3.strokeStyle = SCISolidPenStyle(colorCode: line3Color, withThickness: 1.5)
line3.style.pointMarker = getPointMarker(size: 5, colorCode: line3Color)
SCIUpdateSuspender.usingWithSuspendable(surface) {
self.surface.xAxes.add(xAxis)
self.surface.yAxes.add(yAxis)
self.surface.renderableSeries.add(line1)
self.surface.renderableSeries.add(line2)
self.surface.renderableSeries.add(line3)
self.surface.chartModifiers = SCIChartModifierCollection(childModifiers: [SCIPinchZoomModifier(), SCIZoomPanModifier(), SCIZoomExtentsModifier()])
line1.addAnimation(SCISweepRenderableSeriesAnimation(duration: 3, curveAnimation: .easeOut))
line2.addAnimation(SCISweepRenderableSeriesAnimation(duration: 3, curveAnimation: .easeOut))
line3.addAnimation(SCISweepRenderableSeriesAnimation(duration: 3, curveAnimation: .easeOut))
}
}
fileprivate func getPointMarker(size: Int, colorCode: UInt32) -> SCIEllipsePointMarker {
let pointMarker = SCIEllipsePointMarker()
pointMarker.width = Float(size)
pointMarker.height = Float(size)
pointMarker.strokeStyle = nil
pointMarker.fillStyle = SCISolidBrushStyle(colorCode: colorCode)
return pointMarker
}
}
|
3702ff7cbae5ac216044272f5488eb7e
| 49.655172 | 158 | 0.676197 | false | false | false | false |
eljeff/AudioKit
|
refs/heads/v5-main
|
Sources/AudioKit/MIDI/MIDI+VirtualPorts.swift
|
mit
|
1
|
// Copyright AudioKit. All Rights Reserved. Revision History at http://github.com/AudioKit/AudioKit/
#if !os(tvOS)
import CoreMIDI
import os.log
extension MIDI {
// MARK: - Virtual MIDI
//
// Virtual MIDI Goals
// * Simplicty in creating a virtual input and virtual output ports together
// * Simplicty in disposing of virtual ports together
// * Ability to create a single virtual input, or single virtual output
//
// Possible Improvements:
// * Support a greater numbers of virtual ports
// * Support hidden uuid generation so the caller can worry about less
//
/// Create set of virtual input and output MIDI ports
public func createVirtualPorts(_ uniqueID: Int32 = 2_000_000, name: String? = nil) {
Log("Creating virtual input and output ports", log: OSLog.midi)
destroyVirtualPorts()
createVirtualInputPort(name: name)
createVirtualOutputPort(name: name)
}
/// Create a virtual MIDI input port
public func createVirtualInputPort(_ uniqueID: Int32 = 2_000_000, name: String? = nil) {
destroyVirtualInputPort()
let virtualPortname = name ?? String(clientName)
let result = MIDIDestinationCreateWithBlock(
client,
virtualPortname as CFString,
&virtualInput) { packetList, _ in
for packet in packetList.pointee {
// a Core MIDI packet may contain multiple MIDI events
for event in packet {
self.handleMIDIMessage(event, fromInput: uniqueID)
}
}
}
if result == noErr {
MIDIObjectSetIntegerProperty(virtualInput, kMIDIPropertyUniqueID, uniqueID)
} else {
Log("Error \(result) Creating Virtual Input Port: \(virtualPortname) -- \(virtualInput)",
log: OSLog.midi, type: .error)
CheckError(result)
}
}
/// Create a virtual MIDI output port
public func createVirtualOutputPort(_ uniqueID: Int32 = 2_000_001, name: String? = nil) {
destroyVirtualOutputPort()
let virtualPortname = name ?? String(clientName)
let result = MIDISourceCreate(client, virtualPortname as CFString, &virtualOutput)
if result == noErr {
MIDIObjectSetIntegerProperty(virtualInput, kMIDIPropertyUniqueID, uniqueID)
} else {
Log("Error \(result) Creating Virtual Output Port: \(virtualPortname) -- \(virtualOutput)",
log: OSLog.midi, type: .error)
CheckError(result)
}
}
/// Discard all virtual ports
public func destroyVirtualPorts() {
destroyVirtualInputPort()
destroyVirtualOutputPort()
}
/// Closes the virtual input port, if created one already.
///
/// - Returns: Returns true if virtual input closed.
///
@discardableResult public func destroyVirtualInputPort() -> Bool {
if virtualInput != 0 {
if MIDIEndpointDispose(virtualInput) == noErr {
virtualInput = 0
return true
}
}
return false
}
/// Closes the virtual output port, if created one already.
///
/// - Returns: Returns true if virtual output closed.
///
@discardableResult public func destroyVirtualOutputPort() -> Bool {
if virtualOutput != 0 {
if MIDIEndpointDispose(virtualOutput) == noErr {
virtualOutput = 0
return true
}
}
return false
}
}
#endif
|
558e50965fa6e969895aacab66167f06
| 33.590476 | 103 | 0.603524 | false | false | false | false |
arnav-gudibande/SwiftTweet
|
refs/heads/master
|
SwiftTweet/SwiftTweet/ViewController.swift
|
apache-2.0
|
1
|
//
// ViewController.swift
// SwiftTweet
//
// Created by Arnav Gudibande on 7/3/16.
// Copyright © 2016 Arnav Gudibande. All rights reserved.
//
import UIKit
import Accounts
import Social
import SwifteriOS
import MapKit
import SafariServices
import CoreLocation
extension UIImageView {
public func imageFromUrl(_ urlString: String) {
if let url = URL(string: urlString) {
let request = URLRequest(url: url)
NSURLConnection.sendAsynchronousRequest(request, queue: OperationQueue.main()) {
(response: URLResponse?, data: Data?, error: NSError?) -> Void in
if let imageData = data as Data? {
self.image = UIImage(data: imageData)
}
}
}
}
}
class ViewController: UIViewController, SFSafariViewControllerDelegate, CLLocationManagerDelegate {
var swifter: Swifter?
var userIDG: Int?
var lat: CLLocationDegrees?
var lon: CLLocationDegrees?
var geo: String?
var woeid: Int?
var arrHashtags: Array<String> = []
var geoTags: [JSON] = []
var geoCoords = ["hashtag":[0.0,0.0]]
var currentLoc: Array<Double> = []
@IBOutlet weak var profilePicture: UIImageView!
@IBOutlet weak var profileBanner: UIImageView!
@IBOutlet weak var fullName: UILabel!
@IBOutlet weak var userName: UILabel!
@IBOutlet weak var followersNumber: UILabel!
@IBOutlet weak var followingNumber: UILabel!
@IBOutlet weak var descriptionLabel: UILabel!
@IBOutlet weak var tweetsNumber: UILabel!
@IBAction func timeLineButtonPressed(_ sender: AnyObject) {
self.swifter!.getStatusesHomeTimelineWithCount(20, success: { statuses in
let timeLineTableViewController = self.storyboard!.instantiateViewController(withIdentifier: "TimeLineTableViewController") as! TimeLineTableViewController
guard let tweets = statuses else { return }
timeLineTableViewController.tweets = tweets
self.navigationController?.pushViewController(timeLineTableViewController, animated: true)
})
}
@IBAction func trendingButtonPressed(_ sender: AnyObject) {
let GeoTweetViewController = self.storyboard!.instantiateViewController(withIdentifier: "geoTweetViewController") as! geoTweetViewController
GeoTweetViewController.geoTags = geoTags
GeoTweetViewController.currentLoc = currentLoc
geoCoords.removeValue(forKey: "hashtag")
GeoTweetViewController.geoCoords = self.geoCoords
print(self.geoCoords)
self.navigationController?.pushViewController(GeoTweetViewController, animated: true)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func viewDidLoad() {
super.viewDidLoad()
let accountStore = ACAccountStore()
let accountType = accountStore.accountType(withAccountTypeIdentifier: ACAccountTypeIdentifierTwitter)
accountStore.requestAccessToAccounts(with: accountType, options: nil) {
granted, error in
self.setSwifter()
}
let locationManager = CLLocationManager()
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.requestWhenInUseAuthorization()
locationManager.requestAlwaysAuthorization()
locationManager.startUpdatingLocation()
lat = locationManager.location?.coordinate.latitude
lon = locationManager.location?.coordinate.longitude
geo = "\(lat!)" + "," + "\(lon!)" + "," + "10mi"
currentLoc.append(lat!)
currentLoc.append(lon!)
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
let locValue: CLLocationCoordinate2D = manager.location!.coordinate
print("locations = \(locValue.latitude) \(locValue.longitude)")
}
func locationManager(_ manager: CLLocationManager, didFailWithError error: NSError) {
print("Error retrieving location")
}
// UITableViewDelegate Functions
func tableView(_ tableView: UITableView, heightForRowAtIndexPath indexPath: IndexPath) -> CGFloat {
return 50
}
func setSwifter() {
let accounts: [ACAccount] = {
let twitterAccountType = ACAccountStore().accountType(withAccountTypeIdentifier: ACAccountTypeIdentifierTwitter)
return (ACAccountStore().accounts(with: twitterAccountType) as? [ACAccount])!
}()
swifter = Swifter(account: accounts[0])
DispatchQueue.main.async {
self.setProfile(accounts)
self.setTrending()
}
}
func setProfile(_ accounts: [ACAccount]) {
self.fullName.text = accounts[0].userFullName
self.userName.text = "@" + accounts[0].username
let userName = accounts[0].username
self.profileBanner.layer.zPosition = -1;
let failureHandler: ((NSError) -> Void) = { error in
self.alertWithTitle("Error", message: error.localizedDescription)
}
self.swifter!.getUsersShowWithScreenName(userName!, success: { json in
guard let url = json!["profile_image_url"]!.string else { return }
self.profilePicture.imageFromUrl(url)
guard let url2 = json!["profile_banner_url"]!.string else { return }
self.profileBanner.imageFromUrl(url2)
guard let followers = json!["followers_count"]!.integer else {return}
self.followersNumber.text = String(followers)
guard let friends = json!["friends_count"]!.integer else { return }
self.followingNumber.text = String(friends)
guard let des = json!["description"]!.string else { return }
self.descriptionLabel.text = des
guard let Bc = json!["profile_background_color"]!.string else { return }
self.descriptionLabel.textColor = self.hexStringToUIColor(Bc)
guard let tN = json!["statuses_count"]!.integer else { return }
self.tweetsNumber.text = String(tN)
guard let userID = json!["id_str"]!.string else { return }
self.userIDG = Int(userID)
}, failure: failureHandler)
}
func setTrending() {
let failureHandler: ((NSError) -> Void) = { error in
self.alertWithTitle("Error", message: error.localizedDescription)
}
self.swifter!.getTrendsClosestWithLat(lat!, long: lon!, success: { json in
guard let trend = json else { return }
self.woeid = trend[0]["woeid"].integer
self.swifter?.getTrendsPlaceWithWOEID(String(self.woeid!), success: { trends in
guard let trendingHashtags = trends else { return }
for i in 0..<50{
if trendingHashtags[0]["trends"][i]["name"].string != nil {
self.arrHashtags.append(trendingHashtags[0]["trends"][i]["name"].string!)
}
}
self.geoTags = trendingHashtags
for ix in self.arrHashtags {
self.swifter!.getSearchTweetsWithQuery(ix, geocode: self.geo!, count: 50, success: { (statuses, searchMetadata) in
guard let trendingTweets = statuses else { return }
if trendingTweets.count>0 {
for i in 0..<trendingTweets.count {
if trendingTweets[i]["coordinates"] != nil {
let tempLon = trendingTweets[i]["coordinates"]["coordinates"][0].double
let tempLat = trendingTweets[i]["coordinates"]["coordinates"][1].double
self.geoCoords[ix] = [tempLat!, tempLon!]
}
}
}
},failure: failureHandler)
}
}, failure: failureHandler)
}, failure: failureHandler)
}
func alertWithTitle(_ title: String, message: String) {
let alert = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
self.present(alert, animated: true, completion: nil)
}
func hexStringToUIColor (_ hex:String) -> UIColor {
var cString:String = hex.uppercased()
if (cString.hasPrefix("#")) {
cString = cString.substring(from: cString.index(cString.startIndex, offsetBy: 1))
}
if ((cString.characters.count) != 6) {
return UIColor.gray()
}
var rgbValue:UInt32 = 0
Scanner(string: cString).scanHexInt32(&rgbValue)
return UIColor(
red: CGFloat((rgbValue & 0xFF0000) >> 16) / 255.0,
green: CGFloat((rgbValue & 0x00FF00) >> 8) / 255.0,
blue: CGFloat(rgbValue & 0x0000FF) / 255.0,
alpha: CGFloat(1.0)
)
}
}
|
15d9611a6bb25a09822f619af89a67f3
| 37.59127 | 167 | 0.588689 | false | false | false | false |
huangboju/Moots
|
refs/heads/master
|
算法学习/LeetCode/LeetCode/EvalRPN.swift
|
mit
|
1
|
//
// EvalRPN.swift
// LeetCode
//
// Created by 黄伯驹 on 2019/9/21.
// Copyright © 2019 伯驹 黄. All rights reserved.
//
import Foundation
// 逆波兰表达式
// https://zh.wikipedia.org/wiki/%E9%80%86%E6%B3%A2%E5%85%B0%E8%A1%A8%E7%A4%BA%E6%B3%95
// https://www.jianshu.com/p/f2c88d983ff5
func evalRPN(_ tokens: [String]) -> Int {
let operators: Set<String> = ["*","+","/","-"]
var stack = Array<Int>()
for token in tokens {
if operators.contains(token) {
let num1 = stack.removeLast()
let index = stack.count - 1
switch token {
case "*":
stack[index] *= num1
case "-":
stack[index] -= num1
case "+":
stack[index] += num1
case "/":
stack[index] /= num1
default:
break
}
continue
}
stack.append(Int(token)!)
}
return stack[0]
}
|
8a67b0fcabf63b7cedf0c6543e3c180b
| 23.717949 | 87 | 0.481328 | false | false | false | false |
tfmalt/garage-door-opener-ble
|
refs/heads/master
|
iOS/GarageOpener/BTService.swift
|
mit
|
1
|
//
// BTService.swift
// GarageOpener
//
// Created by Thomas Malt on 11/01/15.
// Copyright (c) 2015 Thomas Malt. All rights reserved.
//
import Foundation
import CoreBluetooth
class BTService : NSObject, CBPeripheralDelegate {
var peripheral : CBPeripheral?
var txCharacteristic : CBCharacteristic?
var rxCharacteristic : CBCharacteristic?
let btConst = BTConstants()
private let nc = NSNotificationCenter.defaultCenter()
init(initWithPeripheral peripheral: CBPeripheral) {
super.init()
self.peripheral = peripheral
self.peripheral?.delegate = self
}
deinit {
self.reset()
}
func reset() {
if peripheral != nil {
peripheral = nil
}
}
func startDiscoveringServices() {
println("Starting discover services")
if let peri = self.peripheral {
peri.discoverServices([CBUUID(string: btConst.SERVICE_UUID)])
}
}
func sendNotificationIsConnected(connected: Bool) {
if let peripheral = self.peripheral {
nc.postNotificationName(
"btConnectionChangedNotification",
object: self,
userInfo: [
"isConnected": connected,
"name": peripheral.name
]
)
}
}
//
// Implementation of CBPeripheralDelegate functions:
//
// Did Discover Characteristics for Service
//
// Adds the two characteristics to the object for easy retrival
func peripheral(peripheral: CBPeripheral!, didDiscoverCharacteristicsForService service: CBService!, error: NSError!) {
println("got did discover characteristics for service")
for cha in service.characteristics {
if cha.UUID == CBUUID(string: btConst.CHAR_TX_UUID) {
self.txCharacteristic = (cha as CBCharacteristic)
}
else if cha.UUID == CBUUID(string: btConst.CHAR_RX_UUID) {
self.rxCharacteristic = (cha as CBCharacteristic)
}
else {
println(" Found unexpected characteristic: \(cha)")
return
}
peripheral.setNotifyValue(true, forCharacteristic: cha as CBCharacteristic)
}
self.sendNotificationIsConnected(true)
}
func peripheral(peripheral: CBPeripheral!, didDiscoverDescriptorsForCharacteristic characteristic: CBCharacteristic!, error: NSError!) {
println("got did discover descriptors for characteristic")
}
func peripheral(peripheral: CBPeripheral!, didDiscoverIncludedServicesForService service: CBService!, error: NSError!) {
println("got did discover included services for service")
}
func peripheral(peripheral: CBPeripheral!, didDiscoverServices error: NSError!) {
// array of the two available characteristics.
let cUUIDs : [CBUUID] = [
CBUUID(string: btConst.CHAR_RX_UUID),
CBUUID(string: btConst.CHAR_TX_UUID)
]
if (error != nil) {
println("got error: a surprise: \(error)")
return
}
// Sometimes services has been reported as nil. testing for that.
if ((peripheral.services == nil) || (peripheral.services.count == 0)) {
println("Got no services!")
return
}
for service in peripheral.services {
if (service.UUID == CBUUID(string: btConst.SERVICE_UUID)) {
peripheral.discoverCharacteristics(cUUIDs, forService: service as CBService)
}
}
}
func peripheral(peripheral: CBPeripheral!, didModifyServices invalidatedServices: [AnyObject]!) {
println("got did modify services")
}
func peripheral(peripheral: CBPeripheral!, didReadRSSI RSSI: NSNumber!, error: NSError!) {
// println("got did read rssi: \(RSSI)")
if peripheral.state != CBPeripheralState.Connected {
println(" Peripheral state says not connected.")
return
}
nc.postNotificationName(
"btRSSIUpdateNotification",
object: peripheral,
userInfo: ["rssi": RSSI]
)
}
func peripheral(peripheral: CBPeripheral!, didUpdateNotificationStateForCharacteristic characteristic: CBCharacteristic!, error: NSError!) {
println("got did update notification state for characteristic")
}
func peripheral(peripheral: CBPeripheral!, didUpdateValueForCharacteristic characteristic: CBCharacteristic!, error: NSError!) {
println("got did update value for characteristic")
}
func peripheral(peripheral: CBPeripheral!, didUpdateValueForDescriptor descriptor: CBDescriptor!, error: NSError!) {
println("got did update value for descriptor")
}
func peripheral(peripheral: CBPeripheral!, didWriteValueForCharacteristic characteristic: CBCharacteristic!, error: NSError!) {
println("got did write value for characteristic")
}
func peripheral(peripheral: CBPeripheral!, didWriteValueForDescriptor descriptor: CBDescriptor!, error: NSError!) {
println("got did write value for descriptor")
}
func peripheralDidInvalidateServices(peripheral: CBPeripheral!) {
println("got peripheral did invalidate services")
}
func peripheralDidUpdateName(peripheral: CBPeripheral!) {
println("got peripheral did update name")
}
func peripheralDidUpdateRSSI(peripheral: CBPeripheral!, error: NSError!) {
println("Got peripheral did update rssi")
}
}
|
2d12478d346b41a7ee569781310736ad
| 32.450867 | 144 | 0.62243 | false | false | false | false |
Takanu/Pelican
|
refs/heads/master
|
Sources/Pelican/API/Types/FileDownload.swift
|
mit
|
1
|
//
// FileDownload.swift
// Pelican
//
// Created by Ido Constantine on 22/03/2018.
//
import Foundation
/**
Represents a file ready to be downloaded. Use the API method `getFile` to request a FileDownload type.
*/
public struct FileDownload: Codable {
/// Unique identifier for the file.
var fileID: String
/// The file size, if known
var fileSize: Int?
/// The path that can be used to download the file, using https://api.telegram.org/file/bot<token>/<file_path>.
var filePath: String?
/// Coding keys to map values when Encoding and Decoding.
enum CodingKeys: String, CodingKey {
case fileID = "file_id"
case fileSize = "file_size"
case filePath = "file_path"
}
public init(fileID: String, fileSize: Int? = nil, filePath: String? = nil) {
self.fileID = fileID
self.fileSize = fileSize
self.filePath = filePath
}
}
|
19b6b5fe7570a2640d268befe6172ae1
| 22.805556 | 112 | 0.694282 | false | false | false | false |
malaonline/iOS
|
refs/heads/master
|
mala-ios/Controller/Profile/OrderFormViewController.swift
|
mit
|
1
|
//
// OrderFormViewController.swift
// mala-ios
//
// Created by 王新宇 on 16/5/6.
// Copyright © 2016年 Mala Online. All rights reserved.
//
import UIKit
import ESPullToRefresh
private let OrderFormViewCellReuseId = "OrderFormViewCellReuseId"
class OrderFormViewController: StatefulViewController, UITableViewDelegate, UITableViewDataSource {
// MARK: - Property
/// 优惠券模型数组
var models: [OrderForm] = [] {
didSet {
tableView.reloadData()
}
}
/// 当前选择项IndexPath标记
/// 缺省值为不存在的indexPath,有效的初始值将会在CellForRow方法中设置
private var currentSelectedIndexPath: IndexPath = IndexPath(item: 0, section: 1)
/// 是否仅用于展示(例如[个人中心])
var justShow: Bool = true
/// 当前显示页数
var currentPageIndex = 1
/// 数据总量
var allCount = 0
/// 当前选择订单的上课地点信息
var school: SchoolModel?
override var currentState: StatefulViewState {
didSet {
if currentState != oldValue {
self.tableView.reloadEmptyDataSet()
}
}
}
// MARK: - Components
private lazy var tableView: UITableView = {
let tableView = UITableView(frame: self.view.frame, style: .plain)
tableView.delegate = self
tableView.dataSource = self
tableView.separatorStyle = .none
tableView.backgroundColor = UIColor(named: .RegularBackground)
tableView.contentInset = UIEdgeInsets(top: 10, left: 0, bottom: 0, right: 0)
tableView.register(OrderFormViewCell.self, forCellReuseIdentifier: OrderFormViewCellReuseId)
return tableView
}()
/// 导航栏返回按钮
lazy var backBarButton: UIButton = {
let backBarButton = UIButton(
imageName: "leftArrow_white",
highlightImageName: "leftArrow_white",
target: self,
action: #selector(FilterResultController.popSelf)
)
return backBarButton
}()
// MARK: - Life Cycle
override func viewDidLoad() {
super.viewDidLoad()
configure()
setupNotification()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
// 开启下拉刷新
tableView.es_startPullToRefresh()
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
sendScreenTrack(SAMyOrdersViewName)
}
// MARK: - Private Method
private func configure() {
title = L10n.myOrder
view.addSubview(tableView)
tableView.emptyDataSetDelegate = self
tableView.emptyDataSetSource = self
// leftBarButtonItem
let spacer = UIBarButtonItem(barButtonSystemItem: .fixedSpace, target: nil, action: nil)
spacer.width = -2
let leftBarButtonItem = UIBarButtonItem(customView: backBarButton)
navigationItem.leftBarButtonItems = [spacer, leftBarButtonItem]
// 下拉刷新
tableView.es_addPullToRefresh(animator: ThemeRefreshHeaderAnimator()) { [weak self] in
self?.tableView.es_resetNoMoreData()
self?.loadOrderForm(finish: {
let isIgnore = (self?.models.count ?? 0 >= 0) && (self?.models.count ?? 0 <= 2)
self?.tableView.es_stopPullToRefresh(ignoreDate: false, ignoreFooter: isIgnore)
})
}
tableView.es_addInfiniteScrolling(animator: ThemeRefreshFooterAnimator()) { [weak self] in
self?.loadOrderForm(isLoadMore: true, finish: {
self?.tableView.es_stopLoadingMore()
})
}
// autoLayout
tableView.snp.makeConstraints { (maker) -> Void in
maker.top.equalTo(view)
maker.left.equalTo(view)
maker.bottom.equalTo(view)
maker.right.equalTo(view)
}
}
/// 获取用户订单列表
@objc fileprivate func loadOrderForm(_ page: Int = 1, isLoadMore: Bool = false, finish: (()->())? = nil) {
// 屏蔽[正在刷新]时的操作
guard currentState != .loading else { return }
currentState = .loading
if isLoadMore {
currentPageIndex += 1
}else {
models = []
currentPageIndex = 1
}
/// 获取用户订单列表
MAProvider.getOrderList(page: currentPageIndex, failureHandler: { error in
defer { DispatchQueue.main.async { finish?() } }
if let statusCode = error.response?.statusCode, statusCode == 404 {
if isLoadMore {
self.currentPageIndex -= 1
}
self.tableView.es_noticeNoMoreData()
}else {
self.tableView.es_resetNoMoreData()
}
self.currentState = .error
}) { (list, count) in
defer { DispatchQueue.main.async { finish?() } }
guard !list.isEmpty && count != 0 else {
self.currentState = .empty
return
}
/// 加载更多
if isLoadMore {
self.models += list
if self.models.count == count {
self.tableView.es_noticeNoMoreData()
}else {
self.tableView.es_resetNoMoreData()
}
}else {
/// 如果不是加载更多,则刷新数据
self.models = list
}
self.allCount = count
self.currentState = .content
}
}
private func setupNotification() {
NotificationCenter.default.addObserver(
forName: MalaNotification_PushToPayment,
object: nil,
queue: nil
) { [weak self] (notification) -> Void in
// 支付页面
if let order = notification.object as? OrderForm {
ServiceResponseOrder = order
self?.launchPaymentController()
}
}
NotificationCenter.default.addObserver(
forName: MalaNotification_PushTeacherDetailView,
object: nil,
queue: nil
) { [weak self] (notification) -> Void in
// 跳转到课程购买页
let viewController = CourseChoosingViewController()
if let model = notification.object as? OrderForm {
viewController.teacherId = model.teacher
viewController.school = SchoolModel(id: model.school, name: model.schoolName , address: model.schoolAddress)
viewController.hidesBottomBarWhenPushed = true
self?.navigationController?.pushViewController(viewController, animated: true)
}else {
self?.showToast(L10n.orderInfoError)
}
}
NotificationCenter.default.addObserver(
forName: MalaNotification_CancelOrderForm,
object: nil,
queue: nil
) { [weak self] (notification) -> Void in
// 取消订单
if let id = notification.object as? Int {
MalaAlert.confirmOrCancel(
title: L10n.cancelOrder,
message: L10n.doYouWantToCancelThisOrder,
confirmTitle: L10n.cancelOrder,
cancelTitle: L10n.notNow,
inViewController: self,
withConfirmAction: { [weak self] () -> Void in
self?.cancelOrder(id)
}, cancelAction: { () -> Void in
})
}else {
self?.showToast(L10n.orderInfoError)
}
}
}
private func cancelOrder(_ orderId: Int) {
MAProvider.cancelOrder(id: orderId) { result in
DispatchQueue.main.async {
self.showToast(result == true ? L10n.orderCanceledSuccess : L10n.orderCanceledFailure)
_ = self.navigationController?.popViewController(animated: true)
}
}
}
private func launchPaymentController() {
// 跳转到支付页面
let viewController = PaymentViewController()
viewController.popAction = {
MalaIsPaymentIn = false
}
self.navigationController?.pushViewController(viewController, animated: true)
}
// MARK: - Delegate
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
guard let status = MalaOrderStatus(rawValue: models[indexPath.row].status ?? "c"), let isLiveCourse = models[indexPath.row].isLiveCourse else {
return 162
}
switch (status, isLiveCourse) {
// 待付款
case (.penging, true): return 213 // 支付 退款
case (.penging, false): return 240 // 支付 退款
// 已付款
case (.paid, true): return 162
case (.paid, false): return 240 // 再次购买
// 已关闭
case (.canceled, true): return 162
case (.canceled, false): return 240 // 再次购买
// 已退费
case (.refund, true): return 162
case (.refund, false): return 190
default: return 162
}
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let viewController = OrderFormInfoViewController()
let model = models[indexPath.row]
viewController.id = model.id
self.navigationController?.pushViewController(viewController, animated: true)
}
// MARK: - DataSource
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return models.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: OrderFormViewCellReuseId, for: indexPath) as! OrderFormViewCell
cell.selectionStyle = .none
cell.model = models[indexPath.row]
return cell
}
deinit {
NotificationCenter.default.removeObserver(self, name: MalaNotification_PushToPayment, object: nil)
NotificationCenter.default.removeObserver(self, name: MalaNotification_PushTeacherDetailView, object: nil)
NotificationCenter.default.removeObserver(self, name: MalaNotification_CancelOrderForm, object: nil)
}
}
extension OrderFormViewController {
public func emptyDataSet(_ scrollView: UIScrollView!, didTap button: UIButton!) {
self.loadOrderForm()
}
public func emptyDataSet(_ scrollView: UIScrollView!, didTap view: UIView!) {
self.loadOrderForm()
}
}
|
b76f11ffc3b645b8cd2fc4aa8c56dfae
| 32.738318 | 151 | 0.572484 | false | false | false | false |
maxoly/PulsarKit
|
refs/heads/master
|
PulsarKit/PulsarKitTests/Models/User.swift
|
mit
|
1
|
//
// User.swift
// PulsarKitTests
//
// Created by Massimo Oliviero on 14/08/2018.
// Copyright © 2019 Nacoon. All rights reserved.
//
import Foundation
struct User: Hashable {
let id: Int
let name: String
init(id: Int, name: String = "") {
self.id = id
self.name = name
}
static func == (lhs: User, rhs: User) -> Bool {
lhs.id == rhs.id
}
func hash(into hasher: inout Hasher) {
hasher.combine(id)
}
}
|
6c5b20e2e23af776b21042197e2b5e50
| 17.074074 | 51 | 0.55123 | false | false | false | false |
praxent/PRGalleryView
|
refs/heads/master
|
PRGalleryView.swift
|
mit
|
1
|
//
// PRGalleryView.swift
// ⌘ Praxent
//
// A single view type which accepts video, GIF and photo media for display in a gallery.
//
// Created by Albert Martin on 9/25/15.
// Copyright © 2015 Praxent. All rights reserved.
//
import AVFoundation
import AVKit
import MobileCoreServices
import FLAnimatedImage
public enum PRGalleryType {
case Image
case Animated
case Video
}
public class PRGalleryView: UIView {
public let imageView: FLAnimatedImageView = FLAnimatedImageView()
public let videoController: AVPlayerViewController = AVPlayerViewController()
public var type: PRGalleryType = .Image
public var shouldAllowPlayback: Bool = true
public var thumbnailInSeconds: Float64 = 5
public var branded: Bool = false
public var overlayLandscape: UIImage = UIImage()
public var overlayPortrait: UIImage = UIImage()
///
/// Load any supported media into the gallery view by URL.
///
public var media: NSURL! {
didSet {
if (self.media == nil || self.media.path == nil) {
image = UIImage()
return
}
type = typeForPath(self.media.path!)
switch type {
case .Video:
image = nil
animatedImage = nil
if (shouldAllowPlayback) {
player = AVPlayer(URL: self.media)
return
}
image = self.imageThumbnailFromVideo(self.media)
break
case .Animated:
if (shouldAllowPlayback) {
animatedImage = self.animatedImageFromPath(self.media.path!)
return
}
image = self.imageFromPath(self.media.path!)
break
default:
image = self.imageFromPath(self.media.path!)
}
}
}
///
/// Helper function to clean up the view stack after new media is loaded.
///
/// - parameter type: The type of loaded media; non-necessary views will be removed.
///
public func cleanupView(type: PRGalleryType) {
if (type == .Video) {
videoController.view.frame = bounds
imageView.removeFromSuperview()
addSubview(videoController.view)
return
}
imageView.frame = bounds
imageView.autoresizingMask = [.FlexibleHeight, .FlexibleWidth]
videoController.view.removeFromSuperview()
videoController.player = AVPlayer()
addSubview(imageView)
}
///
/// Determines the type of file being loaded in order to use the appropriate view.
///
/// - parameter path: The path to the file.
/// - returns: `video` for any media requiring playback controls or `gif`/`photo` for images.
///
public func typeForPath(path: NSString) -> PRGalleryType {
let utiTag = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, path.pathExtension, nil)!
let utiType = utiTag.takeRetainedValue() as String
if (AVURLAsset.audiovisualTypes().contains(String(utiType))) {
return .Video
}
if (String(utiType) == "com.compuserve.gif") {
return .Animated
}
return .Image
}
///
// MARK: Positioning and Measurement
///
public func sizeOfMedia() -> CGSize {
if (type == .Video) {
return videoController.view.frame.size
}
var scale: CGFloat = 1.0;
if (imageView.image!.size.width > imageView.image!.size.height) {
scale = imageView.frame.size.width / imageView.image!.size.width
} else {
scale = imageView.frame.size.height / imageView.image!.size.height
}
return CGSizeMake(imageView.image!.size.width * scale, imageView.image!.size.height * scale)
}
///
// MARK: Playback
///
///
/// Start playback of a video or animated GIF.
///
public func play() {
if (type != .Video && type != .Animated) {
return
}
switch type {
case .Video:
if (imageView.image != nil) {
player = AVPlayer(URL: self.media)
}
player!.play()
case .Animated:
if (imageView.animatedImage == nil) {
animatedImage = self.animatedImageFromPath(media!.path!)
image = nil
}
imageView.startAnimating()
default: break
}
}
///
/// Pause playback (resumable) of a video or animated GIF.
///
public func pause() {
if (type != .Video && type != .Animated) {
return
}
imageView.stopAnimating()
player!.pause()
}
///
/// Stop playback of a video or animated GIF. Returns the video to it's static
/// thumbnail representation if `shouldAllowPlayback` is `false`.
///
public func stop() {
if (type != .Video && type != .Animated) {
return
}
if (type == .Video && !shouldAllowPlayback && videoController.player?.currentItem != nil) {
image = self.imageThumbnailFromVideo(self.media)
}
imageView.stopAnimating()
player!.pause()
}
///
// MARK: Animated GIF
///
public var animatedImage: FLAnimatedImage? {
set {
imageView.animatedImage = newValue
cleanupView(.Image)
}
get {
return imageView.animatedImage
}
}
///
/// Creates an instance of FLAnimatedImage for animated GIF images.
///
/// - parameter path: The path to the file.
/// - returns: `FLAnimatedImage`
///
public func animatedImageFromPath(path: String) -> FLAnimatedImage {
let image = FLAnimatedImage(animatedGIFData: NSData(contentsOfFile: path))
if (image == nil) {
print("Unable to create animated image from path", path)
return FLAnimatedImage()
}
return image!
}
///
// MARK: Static Image
///
public var image: UIImage? {
set {
imageView.image = newValue
cleanupView(.Image)
}
get {
return imageView.image
}
}
///
/// Creates a UIImage for static images.
///
/// - parameter path: The path to the file.
/// - returns: `UIImage`
///
public func imageFromPath(path: String) -> UIImage {
let image = UIImage(contentsOfFile: path)
if (image == nil) {
print("Unable to create image from path", path)
return UIImage()
}
if (branded) {
return image!.branded(overlayLandscape, portrait: overlayPortrait)
}
return image!
}
///
// MARK: Video
///
public var player: AVPlayer? {
set {
videoController.player = newValue
cleanupView(.Video)
}
get {
return videoController.player
}
}
///
/// Returns a thumbnail image for display when playback is disabled.
///
/// - parameter url: The URL of the file.
/// - returns: `UIImage`
///
public func imageThumbnailFromVideo(url: NSURL) -> UIImage {
let video = AVURLAsset(URL: url)
let time = CMTimeMakeWithSeconds(thumbnailInSeconds, 60)
let thumbGenerator = AVAssetImageGenerator(asset: video)
thumbGenerator.appliesPreferredTrackTransform = true
do {
let thumbnail = try thumbGenerator.copyCGImageAtTime(time, actualTime: nil)
return UIImage(CGImage: thumbnail)
} catch {
print("Unable to generate thumbnail from video", url.path)
return UIImage()
}
}
}
|
626f2659dc553b43167198e21fec8ff4
| 24.960526 | 114 | 0.561581 | false | false | false | false |
BlurredSoftware/BSWInterfaceKit
|
refs/heads/develop
|
Tests/BSWInterfaceKitTests/Suite/Profiles/ClassicProfileViewController.swift
|
mit
|
1
|
//
// Created by Pierluigi Cifani on 03/05/16.
// Copyright © 2018 TheLeftBit SL. All rights reserved.
//
#if canImport(UIKit)
import UIKit
import Task
import BSWFoundation
import BSWInterfaceKit
public enum ClassicProfileEditKind {
case nonEditable
case editable(UIBarButtonItem)
public var isEditable: Bool {
switch self {
case .editable(_):
return true
default:
return false
}
}
}
open class ClassicProfileViewController: TransparentNavBarViewController, AsyncViewModelPresenter {
public init(dataProvider: Task<ClassicProfileViewModel>) {
self.dataProvider = dataProvider
super.init(nibName:nil, bundle:nil)
}
public init(viewModel: ClassicProfileViewModel) {
self.dataProvider = Task(success: viewModel)
super.init(nibName:nil, bundle:nil)
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
enum Constants {
static let SeparatorSize = CGSize(width: 30, height: 1)
static let LayoutMargins = UIEdgeInsets(uniform: 8)
static let PhotoGalleryRatio = CGFloat(0.78)
}
public var dataProvider: Task<ClassicProfileViewModel>!
open var editKind: ClassicProfileEditKind = .nonEditable
private let photoGallery = PhotoGalleryView()
private let titleLabel = UILabel.unlimitedLinesLabel()
private let detailsLabel = UILabel.unlimitedLinesLabel()
private let extraDetailsLabel = UILabel.unlimitedLinesLabel()
private let separatorView: UIView = {
let view = UIView()
NSLayoutConstraint.activate([
view.widthAnchor.constraint(equalToConstant: Constants.SeparatorSize.width),
view.heightAnchor.constraint(equalToConstant: Constants.SeparatorSize.height)
])
view.backgroundColor = UIColor.lightGray
return view
}()
open override func viewDidLoad() {
super.viewDidLoad()
//Add the photoGallery
photoGallery.delegate = self
scrollableStackView.addArrangedSubview(photoGallery)
NSLayoutConstraint.activate([
photoGallery.heightAnchor.constraint(equalTo: photoGallery.widthAnchor, multiplier: Constants.PhotoGalleryRatio),
photoGallery.widthAnchor.constraint(equalTo: scrollableStackView.widthAnchor)
])
scrollableStackView.addArrangedSubview(titleLabel, layoutMargins: Constants.LayoutMargins)
scrollableStackView.addArrangedSubview(detailsLabel, layoutMargins: Constants.LayoutMargins)
scrollableStackView.addArrangedSubview(separatorView, layoutMargins: Constants.LayoutMargins)
scrollableStackView.addArrangedSubview(extraDetailsLabel, layoutMargins: Constants.LayoutMargins)
//Add the rightBarButtonItem
switch editKind {
case .editable(let barButton):
navigationItem.rightBarButtonItem = barButton
default:
break
}
fetchData()
}
override open var preferredStatusBarStyle : UIStatusBarStyle {
return .lightContent
}
//MARK:- Private
open func fetchData() {
showLoader()
dataProvider.upon(.main) { [weak self] result in
guard let strongSelf = self else { return }
strongSelf.hideLoader()
switch result {
case .failure(let error):
strongSelf.showErrorMessage("Error fetching data", error: error)
case .success(let viewModel):
strongSelf.configureFor(viewModel: viewModel)
}
}
}
open func configureFor(viewModel: ClassicProfileViewModel) {
photoGallery.photos = viewModel.photos
titleLabel.attributedText = viewModel.titleInfo
detailsLabel.attributedText = viewModel.detailsInfo
extraDetailsLabel.attributedText = viewModel.extraInfo.joinedStrings()
}
}
//MARK:- PhotoGalleryViewDelegate
extension ClassicProfileViewController: PhotoGalleryViewDelegate {
public func didTapPhotoAt(index: Int, fromView: UIView) {
guard #available(iOS 13, *) else {
return
}
guard let viewModel = dataProvider.peek()?.value else { return }
let gallery = PhotoGalleryViewController(
photos: viewModel.photos,
initialPageIndex: index,
allowShare: false
)
gallery.modalPresentationStyle = .overFullScreen
gallery.delegate = self
present(gallery, animated: true, completion: nil)
}
}
//MARK:- PhotoGalleryViewControllerDelegate
@available(iOS 13, *)
extension ClassicProfileViewController: PhotoGalleryViewControllerDelegate {
public func photoGalleryController(_ photoGalleryController: PhotoGalleryViewController, willDismissAtPageIndex index: Int) {
photoGallery.scrollToPhoto(atIndex: index)
dismiss(animated: true, completion: nil)
}
}
#endif
|
7521d19505c2f946dd2c7fc5d8f08493
| 32.993289 | 129 | 0.676604 | false | false | false | false |
KosyanMedia/Aviasales-iOS-SDK
|
refs/heads/master
|
AviasalesSDKTemplate/Source/HotelsSource/HotelDetails/Tabs/HLHotelDetailPhotosTabCell.swift
|
mit
|
1
|
class HLHotelDetailPhotosTabCell: HLHotelDetailsTabCell, HLPhotoGridViewDelegate {
var photoGrid: HLPhotoGridView!
var hotel: HDKHotel! {
didSet {
setupContent()
}
}
override func createTabContentViewAndScrollView() -> (UIView, UIScrollView) {
let photoGrid = HLPhotoGridView(frame:CGRect.zero)
photoGrid.translatesAutoresizingMaskIntoConstraints = false
photoGrid.backgroundColor = UIColor.clear
photoGrid.delegate = self
photoGrid.collectionView.scrollsToTop = false
self.photoGrid = photoGrid
return (photoGrid, photoGrid.collectionView)
}
func setupContent() {
let thumbSize = HLPhotoManager.calculateThumbSizeForColumnsCount(delegate?.photosColumnsCount() ?? 1, containerWidth: bounds.width)
photoGrid.updateDataSource(withHotel: hotel, imageSize: thumbSize, thumbSize: thumbSize, useThumbs: true)
}
func setSelectedStyleForPhotoIndex(_ photoIndex: Int) {
photoGrid.collectionView.selectItem(at: IndexPath(item: photoIndex, section: 0), animated: false, scrollPosition: UICollectionView.ScrollPosition())
}
// MARK: - Public
func photoCellRect(_ indexPath: IndexPath) -> CGRect {
var rect = photoGrid.collectionView.layoutAttributesForItem(at: indexPath)?.frame ?? CGRect.zero
rect = convert(rect, from: photoGrid.collectionView)
return rect
}
// MARK: HLPhotoGridView delegate
func columnCount() -> Int {
return delegate?.photosColumnsCount() ?? 0
}
func columnInset() -> CGFloat {
return 1.0
}
func photoCollectionViewDidSelectPhotoAtIndex(_ index: Int) {
delegate?.showPhotoAtIndex(index)
}
func photoGridViewCellDidSelect(_ cell: HLPhotoScrollCollectionCell) {
delegate?.photoGridViewCellDidSelect?(cell)
}
func photoGridViewCellDidHighlight(_ cell: HLPhotoScrollCollectionCell) {
delegate?.photoGridViewCellDidHighlight?(cell)
}
}
|
6d24e7a1a442afe2e787c518774379df
| 31.596774 | 156 | 0.698664 | false | false | false | false |
sammyd/UnleashingSwift_bristech2015
|
refs/heads/master
|
UnleashingSwift.playground/Pages/GettingStarted.xcplaygroundpage/Contents.swift
|
mit
|
1
|
//: # Unleashing Swift
//: This page of the playground serves to get you up to speed with Swift concepts as quickly as possible
//: ## Mutability
let twelve = 12
//twelve = 13
var thirteen = 13
thirteen = 12
//thirteen = 13.0
//: ## Value / Reference types
var title = "This is a string"
var secondTitle = title
secondTitle += ", which has just got longer"
print(title)
print(secondTitle)
//: ## Functions
func square(value: Int) -> Int {
return value * value
}
square(4)
func exponentiate(value: Int, power: Int) -> Int {
return power > 0 ? value * exponentiate(value, power: power-1) : 1
}
exponentiate(2, power: 4)
func curryPower(power: Int)(_ value: Int) -> Int {
return exponentiate(value, power: power)
}
let cube = curryPower(3)
cube(3)
//: ## Extensions
extension Int {
func toThePower(power: Int) -> Int {
return exponentiate(self, power: power)
}
}
2.toThePower(5)
//: ## Closures
func asyncHello(name: String, callback: (reply: String) -> ()) {
callback(reply: "Hello \(name)")
}
asyncHello("sam") {
let shouty = $0.uppercaseString
print(shouty)
}
//: ## Functional Tinge
let scores = [1,2,4,5,3,5,7,2,2,6,8,2,3,6,2,3,5]
let cubedScores = scores.map { cube($0) }
cubedScores
let largeScores = scores.filter { $0 > 5 }
largeScores
let meanScore = scores.reduce(0) { $0 + Double($1) } / Double(scores.count)
meanScore
//: [Next](@next)
|
9c18a32a4c5777e6db740bfb541dd1f8
| 15.103448 | 104 | 0.655246 | false | false | false | false |
exyte/Macaw
|
refs/heads/master
|
MacawTests/TestUtils.swift
|
mit
|
1
|
import Foundation
#if os(OSX)
@testable import MacawOSX
#endif
#if os(iOS)
@testable import Macaw
#endif
class TestUtils {
class func compareWithReferenceObject(_ fileName: String, referenceObject: AnyObject) -> Bool {
// TODO: this needs to be replaced with SVG tests
return true
}
class func prepareParametersList(_ mirror: Mirror) -> [(String, String)] {
var result: [(String, String)] = []
for (_, attribute) in mirror.children.enumerated() {
if let label = attribute.label , (label == "_value" || label.first != "_") && label != "contentsVar" {
result.append((label, String(describing: attribute.value)))
result.append(contentsOf: prepareParametersList(Mirror(reflecting: attribute.value)))
}
}
return result
}
class func prettyFirstDifferenceBetweenStrings(s1: String, s2: String) -> String {
return prettyFirstDifferenceBetweenNSStrings(s1: s1 as NSString, s2: s2 as NSString) as String
}
}
/// Find first differing character between two strings
///
/// :param: s1 First String
/// :param: s2 Second String
///
/// :returns: .DifferenceAtIndex(i) or .NoDifference
fileprivate func firstDifferenceBetweenStrings(s1: NSString, s2: NSString) -> FirstDifferenceResult {
let len1 = s1.length
let len2 = s2.length
let lenMin = min(len1, len2)
for i in 0..<lenMin {
if s1.character(at: i) != s2.character(at: i) {
return .DifferenceAtIndex(i)
}
}
if len1 < len2 {
return .DifferenceAtIndex(len1)
}
if len2 < len1 {
return .DifferenceAtIndex(len2)
}
return .NoDifference
}
/// Create a formatted String representation of difference between strings
///
/// :param: s1 First string
/// :param: s2 Second string
///
/// :returns: a string, possibly containing significant whitespace and newlines
fileprivate func prettyFirstDifferenceBetweenNSStrings(s1: NSString, s2: NSString) -> NSString {
let firstDifferenceResult = firstDifferenceBetweenStrings(s1: s1, s2: s2)
return prettyDescriptionOfFirstDifferenceResult(firstDifferenceResult: firstDifferenceResult, s1: s1, s2: s2)
}
/// Create a formatted String representation of a FirstDifferenceResult for two strings
///
/// :param: firstDifferenceResult FirstDifferenceResult
/// :param: s1 First string used in generation of firstDifferenceResult
/// :param: s2 Second string used in generation of firstDifferenceResult
///
/// :returns: a printable string, possibly containing significant whitespace and newlines
fileprivate func prettyDescriptionOfFirstDifferenceResult(firstDifferenceResult: FirstDifferenceResult, s1: NSString, s2: NSString) -> NSString {
func diffString(index: Int, s1: NSString, s2: NSString) -> NSString {
let markerArrow = "\u{2b06}" // "⬆"
let ellipsis = "\u{2026}" // "…"
/// Given a string and a range, return a string representing that substring.
///
/// If the range starts at a position other than 0, an ellipsis
/// will be included at the beginning.
///
/// If the range ends before the actual end of the string,
/// an ellipsis is added at the end.
func windowSubstring(s: NSString, range: NSRange) -> String {
let validRange = NSMakeRange(range.location, min(range.length, s.length - range.location))
let substring = s.substring(with: validRange)
let prefix = range.location > 0 ? ellipsis : ""
let suffix = (s.length - range.location > range.length) ? ellipsis : ""
return "\(prefix)\(substring)\(suffix)"
}
// Show this many characters before and after the first difference
let windowPrefixLength = 10
let windowSuffixLength = 10
let windowLength = windowPrefixLength + 1 + windowSuffixLength
let windowIndex = max(index - windowPrefixLength, 0)
let windowRange = NSMakeRange(windowIndex, windowLength)
let sub1 = windowSubstring(s: s1, range: windowRange)
let sub2 = windowSubstring(s: s2, range: windowRange)
let markerPosition = min(windowSuffixLength, index) + (windowIndex > 0 ? 1 : 0)
let markerPrefix = String(repeating: " ", count: markerPosition)
let markerLine = "\(markerPrefix)\(markerArrow)"
return "Difference at index \(index):\n\(sub1)\n\(sub2)\n\(markerLine)" as NSString
}
switch firstDifferenceResult {
case .NoDifference: return "No difference"
case .DifferenceAtIndex(let index): return diffString(index: index, s1: s1, s2: s2)
}
}
/// Result type for firstDifferenceBetweenStrings()
public enum FirstDifferenceResult {
/// Strings are identical
case NoDifference
/// Strings differ at the specified index.
///
/// This could mean that characters at the specified index are different,
/// or that one string is longer than the other
case DifferenceAtIndex(Int)
}
extension FirstDifferenceResult: CustomStringConvertible {
/// Textual representation of a FirstDifferenceResult
public var description: String {
switch self {
case .NoDifference:
return "NoDifference"
case .DifferenceAtIndex(let index):
return "DifferenceAtIndex(\(index))"
}
}
/// Textual representation of a FirstDifferenceResult for debugging purposes
public var debugDescription: String {
return self.description
}
}
|
dbf0a4d3aaf2d68f04615d639c4b05b5
| 33.840764 | 145 | 0.678062 | false | false | false | false |
TLOpenSpring/TLTranstionLib-swift
|
refs/heads/master
|
Example/TLTranstionLib-swift/BaseTabController.swift
|
mit
|
1
|
//
// BaseTabController.swift
// TLTranstionLib-swift
//
// Created by Andrew on 16/7/22.
// Copyright © 2016年 CocoaPods. All rights reserved.
//
import UIKit
class BaseTabController: UIViewController,UINavigationControllerDelegate {
override func viewDidLoad() {
super.viewDidLoad()
let attr1 = getAttibutes()
let attr2 = getActiveAttibutes()
self.tabBarItem.setTitleTextAttributes(attr1, forState: .Normal)
self.tabBarItem.setTitleTextAttributes(attr2, forState: .Selected)
// Do any additional setup after loading the view.
}
func getAttibutes() -> [String:AnyObject] {
let font = UIFont.systemFontOfSize(18)
let attrs = [NSFontAttributeName:font,
NSForegroundColorAttributeName:UIColor.grayColor()]
return attrs
}
func getActiveAttibutes() -> [String:AnyObject] {
let font = UIFont.systemFontOfSize(18)
let attrs = [NSFontAttributeName:font,
NSForegroundColorAttributeName:UIColor.redColor()]
return attrs
}
}
|
41d6e83356b274f2123080452adfdd54
| 27.435897 | 74 | 0.651939 | false | false | false | false |
mcomella/prox
|
refs/heads/master
|
Prox/Prox/PlaceDetails/MapButton.swift
|
mpl-2.0
|
1
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import UIKit
class MapButton: UIButton {
private let shadowRadius: CGFloat = 3
override func draw(_ rect: CGRect) {
guard let context = UIGraphicsGetCurrentContext() else { return }
let shadow = NSShadow()
shadow.shadowColor = Colors.detailsViewMapButtonShadow
shadow.shadowOffset = CGSize(width: 0.5, height: 0.75)
shadow.shadowBlurRadius = shadowRadius
// Drawing code
let ovalPath = UIBezierPath(ovalIn: CGRect(x: (shadowRadius / 2) - shadow.shadowOffset.width, y: (shadowRadius / 2) - shadow.shadowOffset.height, width: rect.width - shadowRadius, height: rect.height - shadowRadius))
context.saveGState()
context.setShadow(offset: shadow.shadowOffset, blur: shadow.shadowBlurRadius, color: (shadow.shadowColor as! UIColor).cgColor)
Colors.detailsViewMapButtonBackground.setFill()
ovalPath.fill()
context.restoreGState()
}
}
|
35b7ce1706d5c0e150d31ec03724fa88
| 40.035714 | 225 | 0.693647 | false | false | false | false |
Derek-Chiu/Mr-Ride-iOS
|
refs/heads/master
|
Mr-Ride-iOS/Mr-Ride-iOS/HistoryTableViewController.swift
|
mit
|
1
|
//
// HistoryTableViewController.swift
// Mr-Ride-iOS
//
// Created by Derek on 6/6/16.
// Copyright © 2016 AppWorks School Derek. All rights reserved.
//
import UIKit
class HistoryTableViewController: UITableViewController {
let cellIdentifier = "HistoryCell"
var allRecord = [Run]()
var sectionByMonth = [NSDateComponents: [Run]]()
var keyOfMonth = [NSDateComponents]()
var currentSection = -1
weak var selectedDelegate: CellSelectedDelegate?
weak var chartDataSource: ChartDataSource?
override func viewDidLoad() {
super.viewDidLoad()
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
tableView.registerNib(UINib(nibName: "HistoryTableViewCell", bundle: nil), forCellReuseIdentifier: cellIdentifier)
tableView.frame = view.bounds
fetchData()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return keyOfMonth.count
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if let count = sectionByMonth[keyOfMonth[section]]?.count {
return count
}
print("error in section number")
return 0
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier) as! HistoryTableViewCell
let run = sectionByMonth[keyOfMonth[indexPath.section]]![indexPath.row]
if currentSection != indexPath.section {
print("section number == \(indexPath.section)")
chartDataSource!.setupChartData(sectionByMonth[keyOfMonth[indexPath.section]]!)
currentSection = indexPath.section
}
cell.backgroundColor = UIColor.mrDarkSlateBlue85Color()
cell.runID = run.id!
cell.labelDistance.text = String(format: "%.2f km", Double(run.distance!) / 1000)
cell.labelDate.text = String(format: "%2d", NSCalendar.currentCalendar().components(NSCalendarUnit.Day, fromDate: run.timestamp!).day)
if let counter = run.during as? Double{
let second = Int(counter) % 60
let minutes = Int(counter / 60) % 60
let hours = Int(counter / 60 / 60) % 99
// print(minuteSecond)
cell.labelTime.text = String(format: "%02d:%02d:%02d", hours, minutes, second)
}
return cell
}
func fetchData() {
print("fetchData")
if LocationRecorder.getInstance().fetchData() != nil {
allRecord = LocationRecorder.getInstance().fetchData()!
} else {
print("no record")
}
for run in allRecord {
let currentComponents = NSCalendar.currentCalendar().components([NSCalendarUnit.Year, NSCalendarUnit.Month], fromDate: run.timestamp!)
if sectionByMonth[currentComponents] != nil {
sectionByMonth[currentComponents]?.append(run)
} else {
sectionByMonth[currentComponents] = [run]
keyOfMonth.append(currentComponents)
}
}
}
// MARK: - Header part
// override func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
// let header = UIView()
// header.layer.cornerRadius = 2.0
// header.backgroundColor = UIColor.whiteColor()
// header.tintColor = UIColor.mrDarkSlateBlueColor()
// }
override func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
// "MMM yyyy"
return "\(keyOfMonth[section].month), \(keyOfMonth[section].year) "
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
// open statistic page
print(indexPath.row)
guard let runID = sectionByMonth[keyOfMonth[indexPath.section]]?[indexPath.row].id else {
return
}
selectedDelegate?.cellDidSelected(runID)
}
}
|
a88a01bd1a29a216d160bd8ba517dcb1
| 33.734848 | 146 | 0.627481 | false | false | false | false |
Pluto-Y/SwiftyEcharts
|
refs/heads/master
|
SwiftyEcharts/Models/Graphic/TextGraphic.swift
|
mit
|
1
|
//
// TextGraphic.swift
// SwiftyEcharts
//
// Created by Pluto Y on 11/02/2017.
// Copyright © 2017 com.pluto-y. All rights reserved.
//
/// 文本类型的 `Graphic`
public final class TextGraphic: Graphic {
/// 文本样式
public final class Style: GraphicStyle {
/// 文本块文字。可以使用 \n 来换行。
public var text: String?
/// 图形元素的左上角在父节点坐标系(以父节点左上角为原点)中的横坐标值。
public var x: Float?
/// 图形元素的左上角在父节点坐标系(以父节点左上角为原点)中的纵坐标值。
public var y: Float?
/// 字体大小、字体类型、粗细、字体样式。格式参见 css font。
/// 例如:
/// // size | family
/// font: '2em "STHeiti", sans-serif'
///
/// // style | weight | size | family
/// font: 'italic bolder 16px cursive'
///
/// // weight | size | family
/// font: 'bolder 2em "Microsoft YaHei", sans-serif'
public var font: String?
/// 水平对齐方式,取值:'left', 'center', 'right'。
/// 如果为 'left',表示文本最左端在 x 值上。如果为 'right',表示文本最右端在 x 值上。
public var textAlign: Align?
/// 垂直对齐方式,取值:'top', 'middle', 'bottom'。
public var textVertical: VerticalAlign?
/// MARK: GraphicStyle
public var fill: Color?
public var stroke: Color?
public var lineWidth: Float?
public var shadowBlur: Float?
public var shadowOffsetX: Float?
public var shadowOffsetY: Float?
public var shadowColor: Color?
public init() {}
}
/// MARK: Graphic
public var type: GraphicType {
return .text
}
public var id: String?
public var action: GraphicAction?
public var left: Position?
public var right: Position?
public var top: Position?
public var bottom: Position?
public var bounding: GraphicBounding?
public var z: Float?
public var zlevel: Float?
public var silent: Bool?
public var invisible: Bool?
public var cursor: String?
public var draggable: Bool?
public var progressive: Bool?
/// 文本样式
public var style: Style?
public init() {}
}
extension TextGraphic.Style: Enumable {
public enum Enums {
case text(String), x(Float), y(Float), font(String), textAlign(Align), textVertical(VerticalAlign), fill(Color), stroke(Color), lineWidth(Float), shadowBlur(Float), shadowOffsetX(Float), shadowOffsetY(Float), shadowColor(Color)
}
public typealias ContentEnum = Enums
public convenience init(_ elements: Enums...) {
self.init()
for ele in elements {
switch ele {
case let .text(text):
self.text = text
case let .x(x):
self.x = x
case let .y(y):
self.y = y
case let .font(font):
self.font = font
case let .textAlign(textAlign):
self.textAlign = textAlign
case let .textVertical(textVertical):
self.textVertical = textVertical
case let .fill(fill):
self.fill = fill
case let .stroke(stroke):
self.stroke = stroke
case let .lineWidth(lineWidth):
self.lineWidth = lineWidth
case let .shadowBlur(shadowBlur):
self.shadowBlur = shadowBlur
case let .shadowOffsetX(shadowOffsetX):
self.shadowOffsetX = shadowOffsetX
case let .shadowOffsetY(shadowOffsetY):
self.shadowOffsetY = shadowOffsetY
case let .shadowColor(shadowColor):
self.shadowColor = shadowColor
}
}
}
}
extension TextGraphic.Style: Mappable {
public func mapping(_ map: Mapper) {
map["text"] = text
map["x"] = x
map["y"] = y
map["font"] = font
map["textAlign"] = textAlign
map["textVertical"] = textVertical
map["fill"] = fill
map["stroke"] = stroke
map["lineWidth"] = lineWidth
map["shadowBlur"] = shadowBlur
map["shadowOffsetX"] = shadowOffsetX
map["shadowOffsetY"] = shadowOffsetY
map["shadowColor"] = shadowColor
}
}
extension TextGraphic: Enumable {
public enum Enums {
case id(String), action(GraphicAction), left(Position), right(Position), top(Position), bottom(Position), bounding(GraphicBounding), z(Float), zlevel(Float), silent(Bool), invisible(Bool), cursor(String), draggable(Bool), progressive(Bool), style(Style)
}
public typealias ContentEnum = Enums
public convenience init(_ elements: Enums...) {
self.init()
for ele in elements {
switch ele {
case let .id(id):
self.id = id
case let .action(action):
self.action = action
case let .left(left):
self.left = left
case let .right(right):
self.right = right
case let .top(top):
self.top = top
case let .bottom(bottom):
self.bottom = bottom
case let .bounding(bounding):
self.bounding = bounding
case let .z(z):
self.z = z
case let .zlevel(zlevel):
self.zlevel = zlevel
case let .silent(silent):
self.silent = silent
case let .invisible(invisible):
self.invisible = invisible
case let .cursor(cursor):
self.cursor = cursor
case let .draggable(draggable):
self.draggable = draggable
case let .progressive(progressive):
self.progressive = progressive
case let .style(style):
self.style = style
}
}
}
}
extension TextGraphic: Mappable {
public func mapping(_ map: Mapper) {
map["type"] = type
map["id"] = id
map["$action"] = action
map["left"] = left
map["right"] = right
map["top"] = top
map["bottom"] = bottom
map["bounding"] = bounding
map["z"] = z
map["zlevel"] = zlevel
map["silent"] = silent
map["invisible"] = invisible
map["cursor"] = cursor
map["draggable"] = draggable
map["progressive"] = progressive
map["style"] = style
}
}
|
ad0f8aff4f9039cadf4db42c750697e6
| 31.110553 | 261 | 0.543036 | false | false | false | false |
lvillani/theine
|
refs/heads/master
|
Chai/State.swift
|
gpl-3.0
|
1
|
// SPDX-License-Identifier: GPL-3.0-only
//
// Chai - Don't let your Mac fall asleep, like a sir
// Copyright (C) 2021 Chai authors
//
// This program 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, version 3 of the License.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
import Dispatch
//
// Our stuff
//
enum Action {
case initialize
case activate(ActivationSpec?)
case deactivate
case setDisableAfterSuspendEnabled(Bool)
case setLoginItemEnabled(Bool)
}
struct State {
var active: Bool = false
var activeSpec: ActivationSpec? = nil
var isDisableAfterSuspendEnabled: Bool = false
var isLoginItemEnabled: Bool = false
}
func appReducer(state: State, action: Action) -> State {
switch action {
case .initialize:
let defaults = Defaults()
var state = State()
state.isDisableAfterSuspendEnabled = defaults.isDisableAfterSuspendEnabled
state.isLoginItemEnabled = defaults.isLoginItemEnabled
return state
case .activate(let activationSpec):
var newState = state
newState.active = true
newState.activeSpec = activationSpec
return newState
case .deactivate:
var newState = state
newState.active = false
newState.activeSpec = nil
return newState
case .setDisableAfterSuspendEnabled(let enabled):
Defaults().isDisableAfterSuspendEnabled = enabled
var newState = state
newState.isDisableAfterSuspendEnabled = enabled
return newState
case .setLoginItemEnabled(let enabled):
Defaults().isLoginItemEnabled = enabled
var newState = state
newState.isLoginItemEnabled = enabled
return newState
}
}
let globalStore = Store(reducer: appReducer, initialState: State())
//
// Infrastructure
//
typealias Reducer = (State, Action) -> State
protocol StoreDelegate: AnyObject {
func stateChanged(state: State)
}
class Store {
private let queue = DispatchQueue(label: "StoreDispatchQueue")
private let reducer: Reducer
private var _state: State
private var subscribers: [StoreDelegate] = []
public var state: State { return queue.sync { _state } }
public init(reducer: @escaping Reducer, initialState: State) {
self.reducer = reducer
self._state = initialState
}
public func dispatch(action: Action) {
queue.sync {
_state = reducer(_state, action)
for subscriber in subscribers {
subscriber.stateChanged(state: _state)
}
}
}
public func subscribe(storeDelegate: StoreDelegate) {
queue.sync {
if !subscribers.contains(where: { $0 === storeDelegate }) {
subscribers.append(storeDelegate)
storeDelegate.stateChanged(state: _state)
}
}
}
public func unsubscribe(storeDelegate: StoreDelegate) {
queue.sync {
subscribers.removeAll(where: { $0 === storeDelegate })
}
}
}
|
f43be6d990addc4537be8f014f55b36e
| 25.495935 | 78 | 0.713716 | false | false | false | false |
skedgo/tripkit-ios
|
refs/heads/main
|
Sources/TripKitUI/helper/TKUICardActionsViewLayoutHelper.swift
|
apache-2.0
|
1
|
//
// TKUICardActionsViewLayoutHelper.swift
// TripKitUI-iOS
//
// Created by Brian Huang on 6/4/20.
// Copyright © 2020 SkedGo Pty Ltd. All rights reserved.
//
import Foundation
import UIKit
protocol TKUICardActionsViewLayoutHelperDelegate: AnyObject {
func numberOfActionsToDisplay(in collectionView: UICollectionView) -> Int
func actionCellToDisplay(at indexPath: IndexPath, in collectionView: UICollectionView) -> UICollectionViewCell?
func size(for cell: UICollectionViewCell, at indexPath: IndexPath) -> CGSize?
}
class TKUICardActionsViewLayoutHelper: NSObject {
weak var delegate: TKUICardActionsViewLayoutHelperDelegate!
weak var collectionView: UICollectionView!
private let sectionInset = UIEdgeInsets(top: 8, left: 8, bottom: 8, right: 8)
private let sizingCell = TKUICompactActionCell.newInstance()
init(collectionView: UICollectionView) {
self.collectionView = collectionView
super.init()
collectionView.dataSource = self
collectionView.delegate = self
collectionView.backgroundColor = .clear
collectionView.register(TKUICompactActionCell.nib, forCellWithReuseIdentifier: TKUICompactActionCell.identifier)
}
}
// MARK: -
extension TKUICardActionsViewLayoutHelper: UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return delegate.numberOfActionsToDisplay(in: collectionView)
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
return delegate.actionCellToDisplay(at: indexPath, in: collectionView) ?? UICollectionViewCell()
}
}
// MARK: -
extension TKUICardActionsViewLayoutHelper: UICollectionViewDelegate {
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
#if targetEnvironment(macCatalyst)
// Ignore, we'll use highlight instead
#else
guard
let cell = collectionView.cellForItem(at: indexPath) as? TKUICompactActionCell,
let onTapHandler = cell.onTap
else { return }
if onTapHandler(cell) {
collectionView.reloadData()
}
#endif
}
func collectionView(_ collectionView: UICollectionView, didHighlightItemAt indexPath: IndexPath) {
#if targetEnvironment(macCatalyst)
guard
let cell = collectionView.cellForItem(at: indexPath) as? TKUICompactActionCell,
let onTapHandler = cell.onTap
else { return }
if onTapHandler(cell) {
collectionView.reloadData()
}
#else
// Ignore, we'll use selected instead
#endif
}
}
// MARK: -
extension TKUICardActionsViewLayoutHelper: UICollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return delegate.size(for: sizingCell, at: indexPath) ?? .zero
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
return sectionInset
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
return sectionInset.left
}
}
|
eaed094ba7f4b26db054ff64e08fe873
| 29.827273 | 168 | 0.751696 | false | false | false | false |
HackerEdu/pengtian
|
refs/heads/master
|
d1_PrimeOrNot/PrimeOrNot/PrimeOrNot/ViewController.swift
|
mit
|
1
|
//
// ViewController.swift
// PrimeOrNot
//
// Created by PENG Tian on 2/1/15.
// Copyright (c) 2015 PENG Tian. All rights reserved.
//
//第一个作业:做一个app,此app要能够判断用户输入的某个数是不是质数
//测试的时候随手按了个4829384712637竟然被告知是质数!真的吗??
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var userInput: UITextField! //用户输入
@IBOutlet weak var feedback: UILabel! //用户得到的反馈
@IBAction func usrButton(sender: AnyObject) { /*按钮*/
var inputNum = userInput.text.toInt()
println(inputNum)
if inputNum == nil { //如果不是数
feedback.text = "not a prime"
} else {
for i in 2...inputNum!-1 {
if inputNum! % i == 0 { //笨办法,把所有从2到用户输入-1的数都取模一次
feedback.text = "not a prime"
break
} else {
feedback.text = "prime!"
}
}
}
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
|
5b507f1bbd78a0b1b0d08abde91e8591
| 25.933333 | 76 | 0.575908 | false | false | false | false |
ello/ello-ios
|
refs/heads/master
|
Sources/Model/UserAvatarCellModel.swift
|
mit
|
1
|
////
/// UserAvatarCellModel.swift
//
let UserAvatarCellModelVersion = 2
@objc(UserAvatarCellModel)
final class UserAvatarCellModel: Model {
enum EndpointType {
case lovers
case reposters
}
let endpointType: EndpointType
var seeMoreTitle: String {
switch endpointType {
case .lovers: return InterfaceString.Post.LovedByList
case .reposters: return InterfaceString.Post.RepostedByList
}
}
var icon: InterfaceImage {
switch endpointType {
case .lovers: return .heart
case .reposters: return .repost
}
}
var endpoint: ElloAPI {
switch endpointType {
case .lovers: return .postLovers(postId: postParam)
case .reposters: return .postReposters(postId: postParam)
}
}
var users: [User] = []
var postParam: String
var hasUsers: Bool {
return users.count > 0
}
init(
type endpointType: EndpointType,
users: [User],
postParam: String
) {
self.endpointType = endpointType
self.users = users
self.postParam = postParam
super.init(version: UserAvatarCellModelVersion)
}
required init(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func belongsTo(post: Post, type: EndpointType) -> Bool {
guard type == endpointType else { return false }
return post.id == postParam || ("~" + post.token == postParam)
}
func append(user: User) {
guard !users.any({ $0.id == user.id }) else { return }
users.append(user)
}
func remove(user: User) {
users = users.filter { $0.id != user.id }
}
}
|
300e03037ffb1dcee92b4bfc5e6c4529
| 23.913043 | 70 | 0.602094 | false | false | false | false |
sarvex/SwiftRecepies
|
refs/heads/master
|
AddressBook/Adding Persons to Groups/Adding Persons to Groups/AppDelegate.swift
|
isc
|
1
|
//
// AppDelegate.swift
// Adding Persons to Groups
//
// Created by Vandad Nahavandipoor on 7/27/14.
// Copyright (c) 2014 Pixolity Ltd. All rights reserved.
//
// These example codes are written for O'Reilly's iOS 8 Swift Programming Cookbook
// If you use these solutions in your apps, you can give attribution to
// Vandad Nahavandipoor for his work. Feel free to visit my blog
// at http://vandadnp.wordpress.com for daily tips and tricks in Swift
// and Objective-C and various other programming languages.
//
// You can purchase "iOS 8 Swift Programming Cookbook" from
// the following URL:
// http://shop.oreilly.com/product/0636920034254.do
//
// If you have any questions, you can contact me directly
// at [email protected]
// Similarly, if you find an error in these sample codes, simply
// report them to O'Reilly at the following URL:
// http://www.oreilly.com/catalog/errata.csp?isbn=0636920034254
import UIKit
import AddressBook
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
lazy var addressBook: ABAddressBookRef = {
var error: Unmanaged<CFError>?
return ABAddressBookCreateWithOptions(nil,
&error).takeRetainedValue() as ABAddressBookRef
}()
func newPersonWithFirstName(firstName: String,
lastName: String,
inAddressBook: ABAddressBookRef) -> ABRecordRef?{
let person: ABRecordRef = ABPersonCreate().takeRetainedValue()
let couldSetFirstName = ABRecordSetValue(person,
kABPersonFirstNameProperty,
firstName as CFTypeRef,
nil)
let couldSetLastName = ABRecordSetValue(person,
kABPersonLastNameProperty,
lastName as CFTypeRef,
nil)
var error: Unmanaged<CFErrorRef>? = nil
let couldAddPerson = ABAddressBookAddRecord(inAddressBook, person, &error)
if couldAddPerson{
println("Successfully added the person")
} else {
println("Failed to add the person.")
return nil
}
if ABAddressBookHasUnsavedChanges(inAddressBook){
var error: Unmanaged<CFErrorRef>? = nil
let couldSaveAddressBook = ABAddressBookSave(inAddressBook, &error)
if couldSaveAddressBook{
println("Successfully saved the address book")
} else {
println("Failed to save the address book.")
}
}
if couldSetFirstName && couldSetLastName{
println("Successfully set the first name " +
"and the last name of the person")
} else {
println("Failed to set the first name and/or " +
"the last name of the person")
}
return person
}
func newGroupWithName(name: String, inAddressBook: ABAddressBookRef) ->
ABRecordRef?{
let group: ABRecordRef = ABGroupCreate().takeRetainedValue()
var error: Unmanaged<CFError>?
let couldSetGroupName = ABRecordSetValue(group,
kABGroupNameProperty, name, &error)
if couldSetGroupName{
error = nil
let couldAddRecord = ABAddressBookAddRecord(inAddressBook,
group,
&error)
if couldAddRecord{
println("Successfully added the new group")
if ABAddressBookHasUnsavedChanges(inAddressBook){
error = nil
let couldSaveAddressBook =
ABAddressBookSave(inAddressBook, &error)
if couldSaveAddressBook{
println("Successfully saved the address book")
} else {
println("Failed to save the address book")
return nil
}
} else {
println("No unsaved changes")
return nil
}
} else {
println("Could not add a new group")
return nil
}
} else {
println("Failed to set the name of the group")
return nil
}
return group
}
func addPerson(person: ABRecordRef,
toGroup: ABRecordRef,
saveToAddressBook: ABAddressBookRef) -> Bool{
var error: Unmanaged<CFErrorRef>? = nil
var added = false
/* Now attempt to add the person entry to the group */
added = ABGroupAddMember(toGroup,
person,
&error)
if added == false{
println("Could not add the person to the group")
return false
}
/* Make sure we save any unsaved changes */
if ABAddressBookHasUnsavedChanges(saveToAddressBook){
error = nil
let couldSaveAddressBook = ABAddressBookSave(saveToAddressBook,
&error)
if couldSaveAddressBook{
println("Successfully added the person to the group")
added = true
} else {
println("Failed to save the address book")
}
} else {
println("No changes were saved")
}
return added
}
func addPersonsAndGroupsToAddressBook(addressBook: ABAddressBookRef){
let richardBranson: ABRecordRef? = newPersonWithFirstName("Richard",
lastName: "Branson",
inAddressBook: addressBook)
if let richard: ABRecordRef = richardBranson{
let entrepreneursGroup: ABRecordRef? = newGroupWithName("Entrepreneurs",
inAddressBook: addressBook)
if let group: ABRecordRef = entrepreneursGroup{
if addPerson(richard, toGroup: group, saveToAddressBook: addressBook){
println("Successfully added Richard Branson to the group")
} else {
println("Failed to add Richard Branson to the group")
}
} else {
println("Failed to create the group")
}
} else {
println("Failed to create an entity for Richard Branson")
}
}
func application(application: UIApplication,
didFinishLaunchingWithOptions launchOptions: [NSObject : AnyObject]?) -> Bool {
switch ABAddressBookGetAuthorizationStatus(){
case .Authorized:
println("Already authorized")
addPersonsAndGroupsToAddressBook(addressBook)
case .Denied:
println("You are denied access to address book")
case .NotDetermined:
ABAddressBookRequestAccessWithCompletion(addressBook,
{[weak self] (granted: Bool, error: CFError!) in
if granted{
let strongSelf = self!
println("Access is granted")
strongSelf.addPersonsAndGroupsToAddressBook(
strongSelf.addressBook)
} else {
println("Access is not granted")
}
})
case .Restricted:
println("Access is restricted")
default:
println("Unhandled")
}
return true
}
}
|
de716ef3666e63a9b4363518ada761c3
| 28.321888 | 83 | 0.62178 | false | false | false | false |
timsawtell/SwiftAppStarter
|
refs/heads/master
|
App/Utility/Constants/Constants.swift
|
mit
|
1
|
//
// constants.swift
// TSBoilerplateSwift
//
// Created by Tim Sawtell on 5/06/2014.
// Copyright (c) 2014 Sawtell Software. All rights reserved.
//
import Foundation
import UIKit
let kModelFileName = "model.dat"
let kModelArchiveKey = "model"
let kReverseDomainName = "au.com.sawtellsoftware.tsboilerplateswift"
let kUnableToParseMessageText = "Unable to parse results";
let kNoResultsText = "No results found"
var deviceOrientation: UIInterfaceOrientation = UIApplication.sharedApplication().statusBarOrientation
var isPortrait = deviceOrientation == UIInterfaceOrientation.Portrait || deviceOrientation == UIInterfaceOrientation.PortraitUpsideDown
var isLandscape = deviceOrientation == UIInterfaceOrientation.LandscapeLeft || deviceOrientation == UIInterfaceOrientation.LandscapeRight
let kBaseURL = "www.example.com"
let kPathForModelFile: String = pathForModel()!
func pathForModel() -> String? {
let paths = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.ApplicationSupportDirectory, NSSearchPathDomainMask.UserDomainMask, true)
if paths.count > 0 {
var path = paths[0]
let fm = NSFileManager()
if !fm.fileExistsAtPath(path) {
do {
try fm.createDirectoryAtPath(path, withIntermediateDirectories: true, attributes: nil)
} catch {
return nil
}
}
path = path.stringByAppendingString("/\(kModelFileName)")
return path
}
return nil
}
|
f5f8efc7b7fada1b8e68b145be3aa7d2
| 33.790698 | 147 | 0.725753 | false | false | false | false |
CosmicMind/Material
|
refs/heads/develop
|
Pods/Material/Sources/iOS/Button/BaseIconLayerButton.swift
|
gpl-3.0
|
3
|
/*
* The MIT License (MIT)
*
* Copyright (C) 2019, CosmicMind, Inc. <http://cosmicmind.com>.
* 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 Motion
/// Implements common logic for CheckButton and RadioButton
open class BaseIconLayerButton: Button {
class var iconLayer: BaseIconLayer { fatalError("Has to be implemented by subclasses") }
lazy var iconLayer: BaseIconLayer = type(of: self).iconLayer
/// A Boolean value indicating whether the button is in the selected state
///
/// Use `setSelected(_:, animated:)` if the state change needs to be animated
open override var isSelected: Bool {
didSet {
iconLayer.setSelected(isSelected, animated: false)
updatePulseColor()
}
}
/// A Boolean value indicating whether the control is enabled.
open override var isEnabled: Bool {
didSet {
iconLayer.isEnabled = isEnabled
}
}
/// Sets the color of the icon to use for the specified state.
///
/// - Parameters:
/// - color: The color of the icon to use for the specified state.
/// - state: The state that uses the specified color. Supports only (.normal, .selected, .disabled)
open func setIconColor(_ color: UIColor, for state: UIControl.State) {
switch state {
case .normal:
iconLayer.normalColor = color
case .selected:
iconLayer.selectedColor = color
case .disabled:
iconLayer.disabledColor = color
default:
fatalError("unsupported state")
}
}
/// Returns the icon color used for a state.
///
/// - Parameter state: The state that uses the icon color. Supports only (.normal, .selected, .disabled)
/// - Returns: The color of the title for the specified state.
open func iconColor(for state: UIControl.State) -> UIColor {
switch state {
case .normal:
return iconLayer.normalColor
case .selected:
return iconLayer.selectedColor
case .disabled:
return iconLayer.disabledColor
default:
fatalError("unsupported state")
}
}
/// A Boolean value indicating whether the button is being animated
open var isAnimating: Bool { return iconLayer.isAnimating }
/// Sets the `selected` state of the button, optionally animating the transition.
///
/// - Parameters:
/// - isSelected: A Boolean value indicating new `selected` state
/// - animated: true if the state change should be animated, otherwise false.
open func setSelected(_ isSelected: Bool, animated: Bool) {
guard !isAnimating else { return }
iconLayer.setSelected(isSelected, animated: animated)
self.isSelected = isSelected
}
open override func prepare() {
super.prepare()
layer.addSublayer(iconLayer)
iconLayer.prepare()
contentHorizontalAlignment = .left // default was .center
reloadImage()
}
open override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
// pulse.animation set to .none so that when we call `super.touchesBegan`
// pulse will not expand as there is a `guard` against .none case
pulse.animation = .none
super.touchesBegan(touches, with: event)
pulse.animation = .point
// expand pulse from the center of iconLayer/visualLayer (`point` is relative to self.view/self.layer)
pulse.expand(point: iconLayer.frame.center)
}
open override func layoutSubviews() {
super.layoutSubviews()
// positioning iconLayer
let insets = iconEdgeInsets
iconLayer.frame.size = CGSize(width: iconSize, height: iconSize)
iconLayer.frame.origin = CGPoint(x: imageView!.frame.minX + insets.left, y: imageView!.frame.minY + insets.top)
// visualLayer is the layer where pulse layer is expanding.
// So we position it at the center of iconLayer, and make it
// small circle, so that the expansion of pulse layer is clipped off
let w = iconSize + insets.left + insets.right
let h = iconSize + insets.top + insets.bottom
let pulseSize = min(w, h)
visualLayer.bounds.size = CGSize(width: pulseSize, height: pulseSize)
visualLayer.frame.center = iconLayer.frame.center
visualLayer.cornerRadius = pulseSize / 2
}
/// Size of the icon
///
/// This property affects `intrinsicContentSize` and `sizeThatFits(_:)`
/// Use `iconEdgeInsets` to set margins.
open var iconSize: CGFloat = 18 {
didSet {
reloadImage()
}
}
/// The *outset* margins for the rectangle around the button’s icon.
///
/// You can specify a different value for each of the four margins (top, left, bottom, right)
/// This property affects `intrinsicContentSize` and `sizeThatFits(_:)` and position of the icon
/// within the rectangle.
///
/// You can use `iconSize` and this property, or `titleEdgeInsets` and `contentEdgeInsets` to position
/// the icon however you want.
/// For negative values, behavior is undefined. Default is `8.0` for all four margins
open var iconEdgeInsets = UIEdgeInsets(top: 8, left: 8, bottom: 8, right: 8) {
didSet {
reloadImage()
}
}
open override func apply(theme: Theme) {
super.apply(theme: theme)
setIconColor(theme.secondary, for: .selected)
setIconColor(theme.onSurface.withAlphaComponent(0.38), for: .normal)
titleColor = theme.onSurface.withAlphaComponent(0.60)
selectedPulseColor = theme.secondary
normalPulseColor = theme.onSurface
updatePulseColor()
}
/// This might be considered as a hackish way, but it's just manipulation
/// UIButton considers size of the `currentImage` to determine `intrinsicContentSize`
/// and `sizeThatFits(_:)`, and to position `titleLabel`.
/// So, we make use of this property (by setting transparent image) to make room for our icon
/// without making much effort (like playing with `titleEdgeInsets` and `contentEdgeInsets`)
/// Size of the image equals to `iconSize` plus corresponsing `iconEdgeInsets` values
private func reloadImage() {
let insets = iconEdgeInsets
let w = iconSize + insets.left + insets.right
let h = iconSize + insets.top + insets.bottom
UIGraphicsBeginImageContext(CGSize(width: w, height: h))
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
self.image = image
}
/// Pulse color for selected state.
open var selectedPulseColor = Color.white
/// Pulse color for normal state.
open var normalPulseColor = Color.white
}
private extension BaseIconLayerButton {
func updatePulseColor() {
pulseColor = isSelected ? selectedPulseColor : normalPulseColor
}
}
// MARK: - BaseIconLayer
internal class BaseIconLayer: CALayer {
var selectedColor = Color.blue.base
var normalColor = Color.lightGray
var disabledColor = Color.gray
func prepareForFirstAnimation() {}
func firstAnimation() {}
func prepareForSecondAnimation() {}
func secondAnimation() {}
private(set) var isAnimating = false
private(set) var isSelected = false
var isEnabled = true {
didSet {
selectedColor = { selectedColor }()
normalColor = { normalColor }()
disabledColor = { disabledColor }()
}
}
func prepare() {
normalColor = { normalColor }() // calling didSet
selectedColor = { selectedColor }() // calling didSet
}
func setSelected(_ isSelected: Bool, animated: Bool) {
guard self.isSelected != isSelected, !isAnimating else { return }
self.isSelected = isSelected
if animated {
animate()
} else {
Motion.disable {
prepareForFirstAnimation()
firstAnimation()
prepareForSecondAnimation()
secondAnimation()
}
}
}
private func animate() {
guard !isAnimating else { return }
prepareForFirstAnimation()
Motion.animate(duration: Constants.partialDuration, timingFunction: .easeInOut, animations: {
self.isAnimating = true
self.firstAnimation()
}, completion: {
Motion.disable {
self.prepareForSecondAnimation()
}
Motion.delay(Constants.partialDuration * Constants.delayFactor) {
Motion.animate(duration: Constants.partialDuration, timingFunction: .easeInOut, animations: {
self.secondAnimation()
}, completion: { self.isAnimating = false })
}
})
}
var sideLength: CGFloat { return frame.height }
struct Constants {
static let totalDuration = 0.5
static let delayFactor = 0.33
static let partialDuration = totalDuration / (1.0 + delayFactor + 1.0)
}
}
// MARK: - Helper extension
private extension CGRect {
var center: CGPoint {
get {
return CGPoint(x: minX + width / 2 , y: minY + height / 2)
}
set {
origin = CGPoint(x: newValue.x - width / 2, y: newValue.y - height / 2)
}
}
}
internal extension CALayer {
/// Animates the propery of CALayer from current value to the specified value
/// and does not reset to the initial value after the animation finishes
///
/// - Parameters:
/// - keyPath: Keypath to the animatable property of the layer
/// - to: Final value of the property
/// - dur: Duration of the animation in seconds. Defaults to 0, which results in taking the duration from enclosing CATransaction, or .25 seconds
func animate(_ keyPath: String, to: CGFloat, dur: TimeInterval = 0) {
let animation = CABasicAnimation(keyPath: keyPath)
animation.timingFunction = .easeIn
animation.fromValue = self.value(forKeyPath: keyPath) // from current value
animation.duration = dur
setValue(to, forKeyPath: keyPath)
self.add(animation, forKey: nil)
}
}
internal extension CATransform3D {
static var identity: CATransform3D {
return CATransform3DIdentity
}
}
|
44168b32de73569f8f0b22375f8bb604
| 32.949686 | 149 | 0.691089 | false | false | false | false |
spotify/HubFramework
|
refs/heads/master
|
demo/sources/LabelComponent.swift
|
apache-2.0
|
1
|
/*
* Copyright (c) 2016 Spotify AB.
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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 HubFramework
/**
* A component that renders a text label
*
* This component is compatible with the following model data:
*
* - title
*/
class LabelComponent: HUBComponent {
var view: UIView?
private lazy var label = UILabel()
private var font: UIFont { return .systemFont(ofSize: 20) }
var layoutTraits: Set<HUBComponentLayoutTrait> {
return [.compactWidth]
}
func loadView() {
label.numberOfLines = 0
label.font = font
view = label
}
func preferredViewSize(forDisplaying model: HUBComponentModel, containerViewSize: CGSize) -> CGSize {
guard let text = model.title else {
return CGSize()
}
let size = (text as NSString).size(withAttributes: [NSAttributedStringKey.font: font])
return CGSize(width: ceil(size.width), height: ceil(size.height))
}
func prepareViewForReuse() {
// No-op
}
func configureView(with model: HUBComponentModel, containerViewSize: CGSize) {
label.text = model.title
}
}
|
c43e5c67e7d561c45dcb7595209734c6
| 29.484375 | 105 | 0.681189 | false | false | false | false |
tamaki-shingo/SoraKit
|
refs/heads/master
|
SoraKit/Classes/Sora.swift
|
mit
|
1
|
//
// Sora.swift
// Pods
//
// Created by tamaki on 7/1/17.
//
//
import Foundation
import APIKit
public class Sora {
public class func cours(success: @escaping ([Cour]) -> Void, failure: @escaping (Error) -> Void) {
let request = CoursRequest()
Session.send(request) { (result) in
switch result {
case .success(let cours):
success(cours)
case .failure(let error):
print("error: \(error)")
failure(error)
}
}
}
public class func animeTitles(OfYear year: Int, success: @escaping ([AnimeTitle]) -> Void, failure: @escaping (Error) -> Void) {
var request = AnimeTitleRequest()
request.year = String(year)
Session.send(request) { (result) in
switch result {
case .success(let years):
success(years)
case .failure(let error):
print("error: \(error)")
failure(error)
}
}
}
public class func animeInfo(OfYear year: Int, season: SoraSeason, success: @escaping ([AnimeInfo]) -> Void, failure: @escaping (Error) -> Void) {
var request = AnimeInfoRequest()
request.year = String(year)
request.season = season
Session.send(request) { (result) in
switch result {
case .success(let yearDetails):
success(yearDetails)
case .failure(let error):
print("error: \(error)")
failure(error)
}
}
}
}
|
4e65f3ca7e013b72de3a929032f1aef1
| 29.576923 | 149 | 0.524528 | false | false | false | false |
mendesbarreto/IOS
|
refs/heads/master
|
Bike 2 Work/Bike 2 Work/VariablesNameConsts.swift
|
mit
|
1
|
//
// Constans.swift
// Bike 2 Work
//
// Created by Douglas Barreto on 1/27/16.
// Copyright © 2016 Douglas Mendes. All rights reserved.
//
import Foundation
public let kHourStartName = "$hourStart";
public let kHourEndName = "$hourEnd";
public let kTemperatureStartName = "$temperatureStart";
public let kTemperatureEndName = "$temperatureEnd";
public let kHumidityStartName = "$humidityStart";
public let kHumidityEndName = "$humidityEnd";
public let kCityVariableName = "$city";
|
8d11129a42f95f0db6064bc8fec6dc9b
| 27.764706 | 57 | 0.747951 | false | false | false | false |
justindarc/firefox-ios
|
refs/heads/master
|
XCUITests/ScreenGraphTest.swift
|
mpl-2.0
|
1
|
/* 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 MappaMundi
import XCTest
class ScreenGraphTest: XCTestCase {
var navigator: MMNavigator<TestUserState>!
var app: XCUIApplication!
override func setUp() {
app = XCUIApplication()
navigator = createTestGraph(for: self, with: app).navigator()
app.terminate()
app.launchArguments = [LaunchArguments.Test, LaunchArguments.ClearProfile, LaunchArguments.SkipIntro, LaunchArguments.SkipWhatsNew]
app.activate()
}
}
extension XCTestCase {
func wait(forElement element: XCUIElement, timeout: TimeInterval) {
let predicate = NSPredicate(format: "exists == 1")
expectation(for: predicate, evaluatedWith: element)
waitForExpectations(timeout: timeout)
}
}
extension ScreenGraphTest {
// Temoporary disable since it is failing intermittently on BB
func testUserStateChanges() {
XCTAssertNil(navigator.userState.url, "Current url is empty")
navigator.userState.url = "https://mozilla.org"
navigator.performAction(TestActions.LoadURLByTyping)
// The UserState is mutated in BrowserTab.
navigator.goto(BrowserTab)
navigator.nowAt(BrowserTab)
XCTAssertTrue(navigator.userState.url?.starts(with: "www.mozilla.org") ?? false, "Current url recorded by from the url bar is \(navigator.userState.url ?? "nil")")
}
func testBackStack() {
// We'll go through the browser tab, through the menu.
navigator.goto(SettingsScreen)
// Going back, there is no explicit way back to the browser tab,
// and the menu will have dismissed. We should be detecting the existence of
// elements as we go through each screen state, so if there are errors, they'll be
// reported in the graph below.
navigator.goto(BrowserTab)
}
func testSimpleToggleAction() {
// Switch night mode on, by toggling.
navigator.performAction(TestActions.ToggleNightMode)
XCTAssertTrue(navigator.userState.nightMode)
navigator.back()
XCTAssertEqual(navigator.screenState, BrowserTab)
// Nothing should happen here, because night mode is already on.
navigator.toggleOn(navigator.userState.nightMode, withAction: TestActions.ToggleNightMode)
XCTAssertTrue(navigator.userState.nightMode)
XCTAssertEqual(navigator.screenState, BrowserTab)
// Switch night mode off.
navigator.toggleOff(navigator.userState.nightMode, withAction: TestActions.ToggleNightMode)
XCTAssertFalse(navigator.userState.nightMode)
navigator.back()
XCTAssertEqual(navigator.screenState, BrowserTab)
}
func testChainedActionPerf1() {
let navigator = self.navigator!
measure {
navigator.userState.url = defaultURL
navigator.performAction(TestActions.LoadURLByPasting)
XCTAssertEqual(navigator.screenState, WebPageLoading)
}
}
func testChainedActionPerf2() {
let navigator = self.navigator!
measure {
navigator.userState.url = defaultURL
navigator.performAction(TestActions.LoadURLByTyping)
XCTAssertEqual(navigator.screenState, WebPageLoading)
}
navigator.userState.url = defaultURL
navigator.performAction(TestActions.LoadURL)
XCTAssertEqual(navigator.screenState, WebPageLoading)
}
func testConditionalEdgesSimple() {
XCTAssertTrue(navigator.can(goto: PasscodeSettingsOff))
XCTAssertFalse(navigator.can(goto: PasscodeSettingsOn))
navigator.goto(PasscodeSettingsOff)
XCTAssertEqual(navigator.screenState, PasscodeSettingsOff)
}
func testConditionalEdgesRerouting() {
// The navigator should dynamically reroute to the target screen
// if the userState changes.
// This test adds to the graph a passcode setting screen. In that screen,
// there is a noop action that fatalErrors if it is taken.
//
let map = createTestGraph(for: self, with: app)
func typePasscode(_ passCode: String) {
passCode.forEach { char in
app.keys["\(char)"].tap()
}
}
map.addScreenState(SetPasscodeScreen) { screenState in
// This is a silly way to organize things here,
// and is an artifical way to show that the navigator is re-routing midway through
// a goto.
screenState.onEnter() { userState in
typePasscode(userState.newPasscode)
typePasscode(userState.newPasscode)
userState.passcode = userState.newPasscode
}
screenState.noop(forAction: "FatalError", transitionTo: PasscodeSettingsOn, if: "passcode == nil") { _ in fatalError() }
screenState.noop(forAction: "Very", "Long", "Path", "Of", "Actions", transitionTo: PasscodeSettingsOn, if: "passcode != nil") { _ in }
}
navigator = map.navigator()
XCTAssertTrue(navigator.can(goto: PasscodeSettingsOn))
XCTAssertTrue(navigator.can(goto: PasscodeSettingsOff))
XCTAssertTrue(navigator.can(goto: "FatalError"))
navigator.goto(PasscodeSettingsOn)
XCTAssertTrue(navigator.can(goto: PasscodeSettingsOn))
XCTAssertFalse(navigator.can(goto: PasscodeSettingsOff))
XCTAssertFalse(navigator.can(goto: "FatalError"))
XCTAssertEqual(navigator.screenState, PasscodeSettingsOn)
}
}
private let defaultURL = "https://example.com"
@objcMembers
class TestUserState: MMUserState {
required init() {
super.init()
initialScreenState = FirstRun
}
var url: String? = nil
var nightMode = false
var passcode: String? = nil
var newPasscode: String = "111111"
}
let PasscodeSettingsOn = "PasscodeSettingsOn"
let PasscodeSettingsOff = "PasscodeSettingsOff"
let WebPageLoading = "WebPageLoading"
fileprivate class TestActions {
static let ToggleNightMode = "menu-NightMode"
static let LoadURL = "LoadURL"
static let LoadURLByTyping = "LoadURLByTyping"
static let LoadURLByPasting = "LoadURLByPasting"
}
var isTablet: Bool {
// There is more value in a variable having the same name,
// so it can be used in both predicates and in code
// than avoiding the duplication of one line of code.
return UIDevice.current.userInterfaceIdiom == .pad
}
fileprivate func createTestGraph(for test: XCTestCase, with app: XCUIApplication) -> MMScreenGraph<TestUserState> {
let map = MMScreenGraph(for: test, with: TestUserState.self)
map.addScreenState(FirstRun) { screenState in
screenState.noop(to: BrowserTab)
screenState.tap(app.textFields["url"], to: URLBarOpen)
}
map.addScreenState(WebPageLoading) { screenState in
screenState.dismissOnUse = true
// Would like to use app.otherElements.deviceStatusBars.networkLoadingIndicators.element
// but this means exposing some of SnapshotHelper to another target.
// screenState.onEnterWaitFor("exists != true",
// element: app.progressIndicators.element(boundBy: 0))
screenState.noop(to: BrowserTab)
}
map.addScreenState(BrowserTab) { screenState in
screenState.onEnter { userState in
userState.url = app.textFields["url"].value as? String
}
screenState.tap(app.buttons["TabToolbar.menuButton"], to: BrowserTabMenu)
screenState.tap(app.textFields["url"], to: URLBarOpen)
screenState.gesture(forAction: TestActions.LoadURLByPasting, TestActions.LoadURL) { userState in
UIPasteboard.general.string = userState.url ?? defaultURL
app.textFields["url"].press(forDuration: 1.0)
app.tables["Context Menu"].cells["menu-PasteAndGo"].firstMatch.tap()
}
}
map.addScreenState(URLBarOpen) { screenState in
screenState.gesture(forAction: TestActions.LoadURLByTyping, TestActions.LoadURL) { userState in
let urlString = userState.url ?? defaultURL
app.textFields["address"].typeText("\(urlString)\r")
}
}
map.addScreenAction(TestActions.LoadURL, transitionTo: WebPageLoading)
map.addScreenState(BrowserTabMenu) { screenState in
screenState.dismissOnUse = true
screenState.onEnterWaitFor(element: app.tables["Context Menu"])
screenState.tap(app.tables.cells["Settings"], to: SettingsScreen)
screenState.tap(app.cells["menu-NightMode"], forAction: TestActions.ToggleNightMode, transitionTo: BrowserTabMenu) { userState in
userState.nightMode = !userState.nightMode
}
screenState.backAction = {
if isTablet {
// There is no Cancel option in iPad.
app.otherElements["PopoverDismissRegion"].tap()
} else {
app.buttons["PhotonMenu.close"].tap()
}
}
}
let navigationControllerBackAction = {
app.navigationBars.element(boundBy: 0).buttons.element(boundBy: 0).tap()
}
map.addScreenState(SettingsScreen) { screenState in
let table = app.tables["AppSettingsTableViewController.tableView"]
screenState.onEnterWaitFor(element: table)
screenState.tap(table.cells["TouchIDPasscode"], to: PasscodeSettingsOff, if: "passcode == nil")
screenState.tap(table.cells["TouchIDPasscode"], to: PasscodeSettingsOn, if: "passcode != nil")
screenState.backAction = navigationControllerBackAction
}
map.addScreenState(PasscodeSettingsOn) { screenState in
screenState.backAction = navigationControllerBackAction
}
map.addScreenState(PasscodeSettingsOff) { screenState in
screenState.tap(app.staticTexts["Turn Passcode On"], to: SetPasscodeScreen)
screenState.backAction = navigationControllerBackAction
}
map.addScreenState(SetPasscodeScreen) { screenState in
screenState.backAction = navigationControllerBackAction
}
return map
}
|
2892a242bee309e62202c08de8fe6d90
| 37.935606 | 171 | 0.679833 | false | true | false | false |
cp3hnu/PrivacyManager
|
refs/heads/master
|
PrivacySpeech/PrivacyManager+Speech.swift
|
mit
|
1
|
//
// PrivacyManager+Speech.swift
// PrivacySpeech
//
// Created by CP3 on 11/22/19.
// Copyright © 2019 CP3. All rights reserved.
//
import Foundation
import UIKit
import RxSwift
import Speech
import PrivacyManager
/// Photo
public extension PrivacyManager {
/// 获取照片访问权限的状态
var speechStatus: PermissionStatus {
let status = SFSpeechRecognizer.authorizationStatus()
switch status {
case .notDetermined:
return .unknown
case .authorized:
return .authorized
case .denied:
return .unauthorized
case .restricted:
return .disabled
@unknown default:
return .unknown
}
}
/// 获取照片访问权限的状态 - Observable
var rxSpeechPermission: Observable<Bool> {
return Observable.create{ observer -> Disposable in
let status = self.speechStatus
switch status {
case .unknown:
SFSpeechRecognizer.requestAuthorization { status in
onMainThread {
observer.onNext(status == .authorized)
observer.onCompleted()
}
}
case .authorized:
observer.onNext(true)
observer.onCompleted()
default:
observer.onNext(false)
observer.onCompleted()
}
return Disposables.create()
}
}
/// Present alert view controller for photo
func speechPermission(presenting: UIViewController, desc: String? = nil, authorized authorizedAction: @escaping PrivacyClosure, canceled cancelAction: PrivacyClosure? = nil, setting settingAction: PrivacyClosure? = nil) {
return privacyPermission(type: PermissionType.speech, rxPersission: rxSpeechPermission, desc: desc, presenting: presenting, authorized: authorizedAction, canceled: cancelAction, setting: settingAction)
}
}
|
52f36fc3db0e9e81574d551691e4d318
| 31.080645 | 225 | 0.602313 | false | false | false | false |
curtclifton/generic-state-machine-in-swift
|
refs/heads/master
|
StateMachine/AsyncEventSimulator.swift
|
mit
|
1
|
//
// AsyncEventSimulator.swift
// StateMachine
//
// Created by Curt Clifton on 11/9/15.
// Copyright © 2015 curtclifton.net. All rights reserved.
//
import Foundation
private func makeBackgroundQueue() -> NSOperationQueue {
let opQueue = NSOperationQueue()
opQueue.qualityOfService = .Background
opQueue.maxConcurrentOperationCount = 2
return opQueue
}
private let backgroundQueue = makeBackgroundQueue()
func afterDelayOfTimeInterval(delay: NSTimeInterval, performBlockOnMainQueue block: () -> ()) {
backgroundQueue.addOperationWithBlock {
NSThread.sleepForTimeInterval(delay)
NSOperationQueue.mainQueue().addOperationWithBlock {
block()
}
}
}
private let asyncSimulationProgressGranularity = Float(1.0 / 50.0)
func simulateAsyncOperationLastingSeconds<State: StateMachineState>(seconds: Int, forStateMachine stateMachine: StateMachine<State>, completionEventGenerator completionEvent: () -> State.EventType, progressEventGenerator progressEvent: (Float) -> State.EventType) {
let durationInSeconds = Double(seconds)
let progressInterval = durationInSeconds * Double(asyncSimulationProgressGranularity)
let startTime = NSDate()
func rescheduleProgress() {
afterDelayOfTimeInterval(progressInterval) {
let currentTime = NSDate()
let elapsedTimeInterval = currentTime.timeIntervalSinceDate(startTime)
let progress = Float(elapsedTimeInterval / durationInSeconds)
stateMachine.processEvent(progressEvent(progress))
// schedule another update unless it would put us past 100%
if progress + asyncSimulationProgressGranularity < 1.0 {
rescheduleProgress()
}
}
}
rescheduleProgress()
afterDelayOfTimeInterval(durationInSeconds) {
stateMachine.processEvent(completionEvent())
}
}
|
feeca7649f9335e8f95ec7ad86238d88
| 36.45098 | 265 | 0.716754 | false | false | false | false |
evgenyneu/walk-to-circle-ios
|
refs/heads/master
|
walk to circle/Utils/iiSoundPlayer.swift
|
mit
|
1
|
import UIKit
import AVFoundation
class iiSoundPlayer {
var player: AVAudioPlayer?
var fader: iiFaderForAvAudioPlayer?
init(fileName: String) {
setAudioSessionToAmbient()
let error: NSErrorPointer = nil
let soundURL = CFBundleCopyResourceURL(CFBundleGetMainBundle(), fileName as NSString, nil, nil)
do {
player = try AVAudioPlayer(contentsOfURL: soundURL)
} catch let error1 as NSError {
error.memory = error1
player = nil
}
}
convenience init(soundType: iiSoundType) {
self.init(fileName: soundType.rawValue)
}
func prepareToPlay() {
if let currentPlayer = player {
currentPlayer.prepareToPlay()
}
}
// Allows the sounds to be played with sounds from other apps
func setAudioSessionToAmbient() {
do {
try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryAmbient)
} catch _ {
}
do {
try AVAudioSession.sharedInstance().setActive(true)
} catch _ {
}
}
func play(atVolume volume: Float = 1.0) {
if let currentPlayer = player {
currentPlayer.currentTime = 0
currentPlayer.volume = volume
currentPlayer.play()
}
}
func playAsync(atVolume volume: Float = 1.0) {
iiQ.async {
self.play(atVolume: volume)
}
}
func fadeOut() {
if let currentPlayer = player {
if let currentFader = fader {
currentFader.stop()
}
let newFader = iiFaderForAvAudioPlayer(player: currentPlayer)
fader = newFader
newFader.fadeOut()
}
}
}
|
eb06abe651ddc1c5fe215578733b20a1
| 21.449275 | 99 | 0.657198 | false | false | false | false |
sztoth/PodcastChapters
|
refs/heads/develop
|
PodcastChapters/Utilities/Player/MediaLoader.swift
|
mit
|
1
|
//
// MediaLoader.swift
// PodcastChapters
//
// Created by Szabolcs Toth on 2016. 02. 11..
// Copyright © 2016. Szabolcs Toth. All rights reserved.
//
import Foundation
import RxSwift
protocol MediaLoaderType {
func URLFor(identifier: String) -> Observable<URL>
}
class MediaLoader {
fileprivate let library: MediaLibraryType
init(library: MediaLibraryType) {
self.library = library
}
}
// MARK: - MediaLoaderType
extension MediaLoader: MediaLoaderType {
func URLFor(identifier: String) -> Observable<URL> {
return Observable.create { observer in
if let identifierNumber = NSNumber.pch_number(from: identifier) {
if self.library.reloadData() {
let item = self.library.allMediaItems.filter({ $0.persistentID == identifierNumber }).first
if let location = item?.location {
observer.onNext(location)
observer.onCompleted()
}
else {
observer.on(.error(LibraryError.itemNotFound))
}
}
else {
observer.on(.error(LibraryError.libraryNotReloaded))
}
}
else {
observer.on(.error(LibraryError.persistentIDInvalid))
}
return Disposables.create()
}
}
}
// MARK: - LibraryError
extension MediaLoader {
enum LibraryError: Error {
case libraryNotReloaded
case itemNotFound
case persistentIDInvalid
}
}
|
d46c410a62caf2552fb527e5cc1a1705
| 25.442623 | 111 | 0.566026 | false | false | false | false |
keshavvishwkarma/KVConstraintKit
|
refs/heads/master
|
KVConstraintKit/KVConstraintKit+Pin.swift
|
mit
|
1
|
//
// KVConstraintKit+Pin.swift
// https://github.com/keshavvishwkarma/KVConstraintKit.git
//
// Distributed under the MIT License.
//
// Copyright © 2016-2017 Keshav Vishwkarma <[email protected]>. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
// of the Software, and to permit persons to whom the Software is furnished to do
// so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
//
#if os(iOS) || os(tvOS)
import UIKit
#else
import AppKit
#endif
// MARK : - TO APPLIED PREPARED CONSTRAINTS
extension View
{
// All the below methods of this category are used to applied\add constraints in supreview of receiver view (self)
/// A receiver view is aligned from the left with padding.
/// - Parameter padding: A CGFloat value to the left side padding.
@discardableResult public final func applyLeft(_ padding: CGFloat = 0) -> View {
(self +== .left).constant = padding ; return self
}
/// A receiver view is aligned from the right with padding.
/// - Parameter padding: A CGFloat value to the right side padding.
@discardableResult public final func applyRight(_ padding: CGFloat = 0) -> View {
(self +== .right).constant = padding ; return self
}
/// A receiver view is aligned from the top with padding.
/// - Parameter padding: A CGFloat value to the top side padding.
@discardableResult public final func applyTop(_ padding: CGFloat = 0) -> View {
(self +== .top).constant = padding ; return self
}
/// A receiver view is aligned from the bottom with padding.
/// - Parameter padding: A CGFloat value to the bottom side padding.
@discardableResult public final func applyBottom(_ padding: CGFloat = 0) -> View {
(self +== .bottom).constant = padding ; return self
}
/// A receiver view is aligned from the left with padding.
/// - Parameter padding: A CGFloat value to the left side padding.
@discardableResult public final func applyLeading(_ padding: CGFloat = 0) -> View {
(self +== .leading).constant = padding ; return self
}
/// A receiver view is aligned from the right with padding.
/// - Parameter padding: A CGFloat value to the right side padding.
@discardableResult public final func applyTrailing(_ padding: CGFloat = 0) -> View {
(self +== .trailing).constant = padding ; return self
}
/// To horizontally Center a receiver view in it's superview with an offset value.
/// - Parameter offsetX: A CGFloat value for the offset along the x axis.
@discardableResult public final func applyCenterX(_ offsetX: CGFloat = 0) -> View {
(self +== .centerX).constant = offsetX ; return self
}
/// To vertically Center a receiver view in it's superview with an offset value.
/// - Parameter offsetY: A CGFloat value for the offset along the y axis.
@discardableResult public final func applyCenterY(_ offsetY: CGFloat = 0) -> View {
(self +== .centerY).constant = offsetY ; return self
}
}
|
3a69bcee83460156e0ebc792cc9b0526
| 41.478723 | 118 | 0.687703 | false | false | false | false |
xwu/swift
|
refs/heads/master
|
test/Distributed/distributed_actor_isolation.swift
|
apache-2.0
|
1
|
// RUN: %target-typecheck-verify-swift -enable-experimental-distributed -disable-availability-checking -verify-ignore-unknown
// REQUIRES: concurrency
// REQUIRES: distributed
// TODO(distributed): rdar://82419661 remove -verify-ignore-unknown here, no warnings should be emitted for our
// generated code but right now a few are, because of Sendability checks -- need to track it down more.
import _Distributed
struct ActorAddress: ActorIdentity {
let address: String
init(parse address : String) {
self.address = address
}
}
actor LocalActor_1 {
let name: String = "alice"
var mutable: String = ""
distributed func nope() {
// expected-error@-1{{'distributed' function can only be declared within 'distributed actor'}}
}
}
struct NotCodableValue { }
distributed actor DistributedActor_1 {
let name: String = "alice" // expected-note{{distributed actor state is only available within the actor instance}}
var mutable: String = "alice" // expected-note{{distributed actor state is only available within the actor instance}}
var computedMutable: String {
get {
"hey"
}
set {
_ = newValue
}
}
distributed let letProperty: String = "" // expected-error{{'distributed' modifier cannot be applied to this declaration}}
distributed var varProperty: String = "" // expected-error{{'distributed' modifier cannot be applied to this declaration}}
distributed var computedProperty: String { // expected-error{{'distributed' modifier cannot be applied to this declaration}}
""
}
distributed static func distributedStatic() {} // expected-error{{'distributed' functions cannot be 'static'}}
func hello() {} // expected-note{{only 'distributed' functions can be called from outside the distributed actor}}
func helloAsync() async {} // expected-note{{only 'distributed' functions can be called from outside the distributed actor}}
func helloAsyncThrows() async throws {} // expected-note{{only 'distributed' functions can be called from outside the distributed actor}}
distributed func distHello() { } // ok
distributed func distHelloAsync() async { } // ok
distributed func distHelloThrows() throws { } // ok
distributed func distHelloAsyncThrows() async throws { } // ok
distributed func distInt() async throws -> Int { 42 } // ok
distributed func distInt(int: Int) async throws -> Int { int } // ok
distributed func distIntString(int: Int, two: String) async throws -> (String) { "\(int) + \(two)" } // ok
distributed func dist(notCodable: NotCodableValue) async throws {
// expected-error@-1 {{distributed function parameter 'notCodable' of type 'NotCodableValue' does not conform to 'Codable'}}
}
distributed func distBadReturn(int: Int) async throws -> NotCodableValue {
// expected-error@-1 {{distributed function result type 'NotCodableValue' does not conform to 'Codable'}}
fatalError()
}
distributed func distReturnGeneric<T: Codable & Sendable>(item: T) async throws -> T { // ok
item
}
distributed func distReturnGenericWhere<T: Sendable>(item: Int) async throws -> T where T: Codable { // ok
fatalError()
}
distributed func distBadReturnGeneric<T: Sendable>(int: Int) async throws -> T {
// expected-error@-1 {{distributed function result type 'T' does not conform to 'Codable'}}
fatalError()
}
distributed func distGenericParam<T: Codable & Sendable>(value: T) async throws { // ok
fatalError()
}
distributed func distGenericParamWhere<T: Sendable>(value: T) async throws -> T where T: Codable { // ok
value
}
distributed func distBadGenericParam<T: Sendable>(int: T) async throws {
// expected-error@-1 {{distributed function parameter 'int' of type 'T' does not conform to 'Codable'}}
fatalError()
}
static func staticFunc() -> String { "" } // ok
@MainActor
static func staticMainActorFunc() -> String { "" } // ok
static distributed func staticDistributedFunc() -> String {
// expected-error@-1{{'distributed' functions cannot be 'static'}}{10-21=}
fatalError()
}
func test_inside() async throws {
_ = self.name
_ = self.computedMutable
_ = try await self.distInt()
_ = try await self.distInt(int: 42)
self.hello()
_ = await self.helloAsync()
_ = try await self.helloAsyncThrows()
self.distHello()
await self.distHelloAsync()
try self.distHelloThrows()
try await self.distHelloAsyncThrows()
// Hops over to the global actor.
_ = await DistributedActor_1.staticMainActorFunc()
}
}
func test_outside(
local: LocalActor_1,
distributed: DistributedActor_1
) async throws {
// ==== properties
_ = distributed.id // ok
distributed.id = AnyActorIdentity(ActorAddress(parse: "mock://1.1.1.1:8080/#123121")) // expected-error{{cannot assign to property: 'id' is immutable}})
_ = local.name // ok, special case that let constants are okey
let _: String = local.mutable // ok, special case that let constants are okey
_ = distributed.name // expected-error{{distributed actor-isolated property 'name' can only be referenced inside the distributed actor}}
_ = distributed.mutable // expected-error{{distributed actor-isolated property 'mutable' can only be referenced inside the distributed actor}}
// ==== special properties (nonisolated, implicitly replicated)
// the distributed actor's special fields may always be referred to
_ = distributed.id
_ = distributed.actorTransport
// ==== static functions
_ = distributed.staticFunc() // expected-error{{static member 'staticFunc' cannot be used on instance of type 'DistributedActor_1'}}
_ = DistributedActor_1.staticFunc()
// ==== non-distributed functions
distributed.hello() // expected-error{{only 'distributed' functions can be called from outside the distributed actor}}
_ = await distributed.helloAsync() // expected-error{{only 'distributed' functions can be called from outside the distributed actor}}
_ = try await distributed.helloAsyncThrows() // expected-error{{only 'distributed' functions can be called from outside the distributed actor}}
}
// ==== Protocols and static (non isolated functions)
protocol P {
static func hello() -> String
}
extension P {
static func hello() -> String { "" }
}
distributed actor ALL: P {
}
// ==== Codable parameters and return types ------------------------------------
func test_params(
distributed: DistributedActor_1
) async throws {
_ = try await distributed.distInt() // ok
_ = try await distributed.distInt(int: 42) // ok
_ = try await distributed.dist(notCodable: .init())
}
|
0194618109943a701982bff5ab5c3739
| 37.614035 | 154 | 0.702257 | false | false | false | false |
swilliams/pathway
|
refs/heads/master
|
PathwayExampleApp/PathwayExampleApp/PersonStateMachine.swift
|
mit
|
1
|
//
// PersonStateMachine.swift
// PathwayExampleApp
//
// Created by Scott Williams on 2/23/15.
// Copyright (c) 2015 Scott Williams. All rights reserved.
//
import UIKit
// This combines both the app's state and the navigation states into a single class. Since the state is simple (2 fields) that's ok, but you'll want to split that out as things start to get a little more complex.
class PersonStateMachine: ViewControllerStateMachine {
var firstName: String = ""
var lastName: String = ""
init() {
let del = UIApplication.sharedApplication().delegate as? AppDelegate
let nav = del?.window?.rootViewController as UINavigationController
let firstnameState = NavigationState(identifier: HomeViewController.self) {
return HomeViewController(nibName: "HomeViewController", bundle: nil)
}
let lastnameState = NavigationState(identifier: LastNameViewController.self) {
return LastNameViewController(nibName: "LastNameViewController", bundle: nil)
}
let finalState = NavigationState(identifier: EndViewController.self) {
return EndViewController(nibName: "EndViewController", bundle: nil)
}
let linearDecider = LinearStateMachineLogic(states: [firstnameState, lastnameState, finalState])
super.init(navController: nav, stateMachineLogic: linearDecider)
}
}
|
61eb66035c79783f7823e7d47accf174
| 42.5 | 212 | 0.715517 | false | false | false | false |
quadro5/swift3_L
|
refs/heads/master
|
swift_question.playground/Pages/UnionFind - email entry.xcplaygroundpage/Contents.swift
|
unlicense
|
1
|
//: [Previous](@previous)
import Foundation
var str = "Hello, playground"
//: [Next](@next)
// Union find - model,
// o(n) find
// o(n) union
class UnionFind1 {
var dict = Dictionary<Int, Int>()
/// search for top father
///
/// - Parameter key: serach key
/// - Returns: top father
func find(key: Int) -> Int {
// key existed in the father
// we add one into
guard var parent = dict[key] else {
dict[key] = key
return key
}
while dict[parent] != nil {
// if fatherOfparent point to other
if let fatherOfParent = dict[parent],
parent != fatherOfParent {
parent = fatherOfParent
// if fatherOfparent point to itself
// we find the top father
} else {
break
}
}
return parent
}
/// connect left and right
///
/// - Parameters:
/// - left: left key
/// - right: right key
func union(left: Int, right: Int) {
let leftFather = self.find(key: left)
let rightFather = self.find(key: right)
// if top father is not equal
// we let rightFather as the new top father of left/right
if leftFather != rightFather {
dict[leftFather] = rightFather
}
}
}
/// UnionFind - improved model, compressed path
/// o(1) avg find
/// o(1) avg union
class UnionFind2 {
var dict = Dictionary<Int, Int>()
/// search for top father
///
/// - Parameter key: serach key
/// - Returns: top father
func find(key: Int) -> Int {
// key existed in the father
// we add one into
guard var topFather = dict[key] else {
dict[key] = key
return key
}
// find top father
while dict[topFather] != nil {
// if fatherOfparent point to other
if let fatherOfParent = dict[topFather],
topFather != fatherOfParent {
topFather = fatherOfParent
// if fatherOfparent point to itself
// we find the top father
} else {
break
}
}
// compress path
// refind all path of key's father
// change all dict[path] = topFather
var father = key
while dict[father] != nil {
if let fatherOfFather = dict[father],
father != fatherOfFather {
dict[father] = topFather
father = fatherOfFather
} else {
break
}
}
return topFather
}
/// connect left and right
///
/// - Parameters:
/// - left: left key
/// - right: right key
func union(left: Int, right: Int) {
let leftFather = self.find(key: left)
let rightFather = self.find(key: right)
// if top father is not equal
// we let rightFather as the new top father of left/right
if leftFather != rightFather {
dict[leftFather] = rightFather
}
}
}
/* Email problem - combine related entry
input:
name: "c1", emails: ["e1", "e2"]
name: "c2", emails: ["e3", "e4"]
name: "c3", emails: ["e5", "e6"]
name: "c4", emails: ["e1", "e3"]
return: [c1, c2, c4], [c3]
*/
struct EmailEntry {
var name: String
var emails: Array<String>
init(name: String, emails: Array<String>) {
self.name = name
self.emails = emails
}
init() {
self.name = ""
self.emails = Array<String>()
}
}
class UnionFind {
// child email, parent email
var dict = Dictionary<String, String>()
// email, [userName]
var emailBooks = Dictionary<String, Set<String>>()
func add(entry: EmailEntry) -> Void {
// combine with the same email
combine(entry: entry)
// find all related parents
var fathers = Set<String>()
for email in entry.emails {
// if can find final father
if let parent = dict[email] {
let father = getFather(from: parent)
fathers.insert(father)
}
}
// if no fathers find / first entry
if fathers.isEmpty {
if let father = entry.emails.first {
dict[father] = father
for child in entry.emails {
if child != father {
dict[child] = father
add(user: entry.name, toFatherEmail: father)
}
}
}
// all parents point to fahter
} else {
if let father = fathers.first {
//print("final father: \(father)\n")
for parent in fathers {
if parent != father {
dict[parent] = father
combine(from: parent, to: father)
}
}
for email in entry.emails {
dict[email] = father
add(user: entry.name, toFatherEmail: father)
}
}
}
}
// print userList
func userList() -> Array<Array<String>>? {
if dict.isEmpty {
return nil
}
var res = Array<Array<String>>()
var usedEmailSet = Set<String>()
for email in dict {
// if cur email has parent
if let parent = dict[email.key] {
let father = getFather(from: parent)
if usedEmailSet.contains(father) == false {
let userSet = emailBooks[father]!
res.append(Array(userSet))
usedEmailSet.insert(father)
}
} else {
// if cur email has not parent
if let userSet = emailBooks[email.key] {
res.append(Array(userSet))
}
}
}
return res
}
/// combine entry's email in to emailBooks
///
/// - Parameter entry: input email entry
private func combine(entry: EmailEntry) {
// combine with the same email
for email in entry.emails {
if emailBooks[email] != nil {
emailBooks[email]?.insert(entry.name)
} else {
emailBooks[email] = Set<String>([entry.name])
}
}
}
/// add userName to the father
///
/// - Parameters:
/// - user: userName
/// - father: father
private func add(user: String, toFatherEmail father: String) {
if emailBooks[father] == nil {
emailBooks[father] = Set<String>([user])
} else {
emailBooks[father]?.insert(user)
}
}
/// combine userSet from child to father
///
/// - Parameters:
/// - child: child name
/// - father: father name
private func combine(from child: String, to father: String) {
if let childSet = emailBooks[child] {
emailBooks[father]?.formUnion(childSet)
}
}
/// get final father
///
/// - Parameter child: input child name
/// - Returns: final father name
private func getFather(from child: String) -> String {
var father = child
while (dict[father] != nil && dict[father] != father) {
father = dict[father]!
}
return father
}
}
// test
let emailUnion = UnionFind()
var entrys = Array<EmailEntry>()
entrys.append(EmailEntry(name: "c1", emails: ["e1", "e2"]))
entrys.append(EmailEntry(name: "c2", emails: ["e3", "e4"]))
entrys.append(EmailEntry(name: "c3", emails: ["e5", "e6"]))
entrys.append(EmailEntry(name: "c4", emails: ["e1", "e3"]))
for entry in entrys {
emailUnion.add(entry: entry)
}
print("input: \n\(entrys)\n")
print("dict: \n\(emailUnion.dict)\n")
print("emailBooks: \n\(emailUnion.emailBooks)\n")
if let res = emailUnion.userList() {
print("res: \(res)")
} else {
print("nil")
}
|
39e57f33e10aae622230609ba0d34fdd
| 23.661677 | 68 | 0.496783 | false | false | false | false |
BurlApps/latch
|
refs/heads/master
|
Framework/LTPasscodeKey.swift
|
gpl-2.0
|
2
|
//
// LTPasscodeKey.swift
// Latch
//
// Created by Brian Vallelunga on 10/25/14.
// Copyright (c) 2014 Brian Vallelunga. All rights reserved.
//
import UIKit
protocol LTPasscodeKeyDelegate {
func keyPressed(number: Int)
}
class LTPasscodeKey: UIButton {
// MARK: Instance Variable
var delegate: LTPasscodeKeyDelegate!
var parentView: UIView!
var background: UIColor!
var border: UIColor!
var backgroundTouch: UIColor!
var borderTouch: UIColor!
var numberLabel: UILabel!
// MARK: Private Instance Variable
var number: Int!
private var row: CGFloat!
private var column: CGFloat!
// MARK: Instance Method
convenience init(number: Int, alpha: String!, row: CGFloat, column: CGFloat) {
self.init()
// Assign Instance Variables
self.row = row
self.column = column
self.number = number
// Create Number Label
self.numberLabel = UILabel()
self.numberLabel.textAlignment = NSTextAlignment.Center
if number >= 0 {
self.numberLabel.font = UIFont(name: "HelveticaNeue-Thin", size: 28)
self.numberLabel.numberOfLines = 2
if alpha != nil {
var attributedText = NSMutableAttributedString(string: "\(number)")
var alphaText = NSMutableAttributedString(string: "\n\(alpha)")
alphaText.addAttribute(NSFontAttributeName, value: UIFont(name: "HelveticaNeue-Thin", size: 12)!, range: NSMakeRange(0, alphaText.length))
attributedText.appendAttributedString(alphaText)
self.numberLabel.attributedText = attributedText
} else {
self.numberLabel.text = "\(number)"
}
} else {
self.numberLabel.text = "Delete"
self.numberLabel.font = UIFont(name: "HelveticaNeue", size: 18)
}
self.addSubview(self.numberLabel)
// Attach Event Listner
self.addTarget(self, action: Selector("holdHandle:"), forControlEvents: UIControlEvents.TouchDown)
self.addTarget(self, action: Selector("tapHandle:"), forControlEvents: UIControlEvents.TouchUpInside)
}
// MARK: Gesture Handler
@IBAction func holdHandle(gesture: UIPanGestureRecognizer) {
if self.number >= 0 {
self.backgroundColor = self.backgroundTouch
self.layer.borderColor = self.borderTouch.CGColor
self.numberLabel.textColor = self.borderTouch
} else {
self.numberLabel.alpha = 0.4
}
}
@IBAction func tapHandle(gesture: UIPanGestureRecognizer) {
self.delegate!.keyPressed(self.number)
UIView.animateWithDuration(0.4, delay: 0.05, options: UIViewAnimationOptions.CurveEaseOut, animations: { () -> Void in
if self.number >= 0 {
self.backgroundColor = self.background
self.layer.borderColor = self.border.CGColor
self.numberLabel.textColor = self.border
} else {
self.numberLabel.alpha = 1
}
}, completion: nil)
}
// MARK: Instance Methods
func configureKey() {
// Create Frame
var keyWidth: CGFloat = 65
var keyHeight: CGFloat = 65
var keyPadding: CGFloat = 18
var keyCenterX = self.parentView.frame.width/2 - (keyWidth/2)
var keyX = keyCenterX + ((keyWidth + keyPadding) * (self.column - 1))
var keyY = (keyHeight + keyPadding) * self.row
self.frame = CGRectMake(keyX, keyY, keyWidth, keyHeight)
// Update View Styling
if self.number >= 0 {
self.backgroundColor = self.background
self.layer.borderColor = self.border.CGColor
self.layer.borderWidth = 1
self.layer.cornerRadius = keyWidth/2
self.layer.masksToBounds = true
}
// Update Label Styling
self.numberLabel.frame = CGRectMake(0, 0, keyWidth, keyHeight)
self.numberLabel.textColor = self.border
}
}
|
35b8f94954fb7a49929aaca29b9dd5fb
| 33.53719 | 154 | 0.601819 | false | false | false | false |
Aioria1314/WeiBo
|
refs/heads/master
|
WeiBo/WeiBo/Classes/Views/Home/ZXCHomeController.swift
|
mit
|
1
|
//
// ZXCHomeController.swift
// WeiBo
//
// Created by Aioria on 2017/3/26.
// Copyright © 2017年 Aioria. All rights reserved.
//
import UIKit
import YYModel
class ZXCHomeController: ZXCVistorViewController {
// lazy var statusList: [ZXCStatus] = [ZXCStatus]()
fileprivate lazy var pullUpView: UIActivityIndicatorView = {
let indicatorView = UIActivityIndicatorView(activityIndicatorStyle: .whiteLarge)
indicatorView.color = UIColor.red
return indicatorView
}()
// fileprivate lazy var pullDownView: UIRefreshControl = {
//
// let refresh = UIRefreshControl()
//
// refresh.addTarget(self, action: #selector(pullDownrefreshAction), for: .valueChanged)
//
// return refresh
// }()
fileprivate lazy var pullDownView: ZXCRefreshControl = {
let refresh = ZXCRefreshControl()
refresh.addTarget(self, action: #selector(pullDownrefreshAction), for: .valueChanged)
return refresh
}()
fileprivate lazy var labTip: UILabel = {
let lab = UILabel()
lab.text = "没有加载到最新数据"
lab.isHidden = true
lab.textColor = UIColor.white
lab.backgroundColor = UIColor.orange
lab.font = UIFont.systemFont(ofSize: 15)
lab.textAlignment = .center
return lab
}()
fileprivate lazy var homeViewModel: ZXCHomeViewModel = ZXCHomeViewModel()
override func viewDidLoad()
{
super.viewDidLoad()
if !isLogin {
visitorView?.updateVisitorInfo(imgName: nil, message: nil)
}
else {
loadData()
setupUI()
}
}
fileprivate func setupUI() {
setupTableView()
if let nav = self.navigationController {
nav.view.insertSubview(labTip, belowSubview: nav.navigationBar)
labTip.frame = CGRect(x: 0, y: nav.navigationBar.frame.maxY - 35, width: nav.navigationBar.width, height: 35)
}
}
fileprivate func setupTableView() {
tableView.register(ZXCHomeTableViewCell.self, forCellReuseIdentifier: homeReuseID)
tableView.rowHeight = UITableViewAutomaticDimension
tableView.estimatedRowHeight = 200
tableView.separatorStyle = .none
tableView.tableFooterView = pullUpView
// self.refreshControl = pullDownView
tableView.addSubview(pullDownView)
}
fileprivate func loadData() {
// ZXCNetworkTools.sharedTools.requestHomeData(accessToken: ZXCUserAccountViewModel.sharedViewModel.accessToken!) { (response, error) in
//
// if error != nil {
// }
//
// guard let dict = response as? [String: Any] else {
// return
// }
//
// let statusDic = dict["statuses"] as? [[String: Any]]
//
// let statusArray = NSArray.yy_modelArray(with: ZXCStatus.self, json: statusDic!) as! [ZXCStatus]
//
// self.statusList = statusArray
//
// self.tableView.reloadData()
// }
homeViewModel.requestHomeData(isPullup: pullUpView.isAnimating) { (isSuccess, message) in
if self.pullUpView.isAnimating == false {
if self.labTip.isHidden == false {
return
}
self.tipAnimation(message: message)
}
self.endRefreshing()
if isSuccess {
self.tableView.reloadData()
}
}
}
fileprivate func endRefreshing() {
pullUpView.stopAnimating()
pullDownView.endRefreshing()
}
// MARK: DataSource
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.homeViewModel.statusList.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell: ZXCHomeTableViewCell = tableView.dequeueReusableCell(withIdentifier: homeReuseID, for: indexPath) as! ZXCHomeTableViewCell
cell.statusViewModel = homeViewModel.statusList[indexPath.row]
// cell.textLabel?.text = homeViewModel.statusList[indexPath.row].user?.screen_name
return cell
}
override func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
if indexPath.row == homeViewModel.statusList.count - 1 && !pullUpView.isAnimating{
pullUpView.startAnimating()
loadData()
}
}
@objc fileprivate func pullDownrefreshAction () {
loadData()
}
fileprivate func tipAnimation(message: String) {
labTip.text = message
labTip.isHidden = false
UIView.animate(withDuration: 1, animations: {
self.labTip.transform = CGAffineTransform(translationX: 0, y: self.labTip.height)
}) { (_) in
UIView.animate(withDuration: 1, animations: {
self.labTip.transform = CGAffineTransform.identity
}, completion: { (_) in
self.labTip.isHidden = true
})
}
}
}
|
54249e99eda0eae96f0e8daed92c33a6
| 27.405941 | 143 | 0.554549 | false | false | false | false |
rolson/arcgis-runtime-samples-ios
|
refs/heads/master
|
arcgis-ios-sdk-samples/Content Display Logic/Controllers/ContentCollectionViewController.swift
|
apache-2.0
|
1
|
// Copyright 2016 Esri.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import UIKit
private let reuseIdentifier = "CategoryCell"
class ContentCollectionViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate, CustomSearchHeaderViewDelegate {
@IBOutlet private var collectionView:UICollectionView!
private var headerView:CustomSearchHeaderView!
var nodesArray:[Node]!
private var transitionSize:CGSize!
override func viewDidLoad() {
super.viewDidLoad()
//hide suggestions
self.hideSuggestions()
self.populateTree()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func populateTree() {
let path = NSBundle.mainBundle().pathForResource("ContentPList", ofType: "plist")
let content = NSArray(contentsOfFile: path!)
self.nodesArray = self.populateNodesArray(content! as [AnyObject])
self.collectionView?.reloadData()
}
func populateNodesArray(array:[AnyObject]) -> [Node] {
var nodesArray = [Node]()
for object in array {
let node = self.populateNode(object as! [String:AnyObject])
nodesArray.append(node)
}
return nodesArray
}
func populateNode(dict:[String:AnyObject]) -> Node {
let node = Node()
if let displayName = dict["displayName"] as? String {
node.displayName = displayName
}
if let descriptionText = dict["descriptionText"] as? String {
node.descriptionText = descriptionText
}
if let storyboardName = dict["storyboardName"] as? String {
node.storyboardName = storyboardName
}
if let children = dict["children"] as? [AnyObject] {
node.children = self.populateNodesArray(children)
}
return node
}
//MARK: - Suggestions related
func showSuggestions() {
// if !self.isSuggestionsTableVisible() {
self.collectionView.performBatchUpdates({ [weak self] () -> Void in
(self?.collectionView.collectionViewLayout as! UICollectionViewFlowLayout).headerReferenceSize = CGSize(width: self!.collectionView.bounds.width, height: self!.headerView.expandedViewHeight)
}, completion: nil)
//show suggestions
// }
}
func hideSuggestions() {
// if self.isSuggestionsTableVisible() {
self.collectionView.performBatchUpdates({ [weak self] () -> Void in
(self?.collectionView.collectionViewLayout as! UICollectionViewFlowLayout).headerReferenceSize = CGSize(width: self!.collectionView.bounds.width, height: self!.headerView.shrinkedViewHeight)
}, completion: nil)
//hide suggestions
// }
}
//TODO: implement this
// func isSuggestionsTableVisible() -> Bool {
// return (self.headerView?.suggestionsTableHeightConstraint?.constant == 0 ? false : true) ?? false
// }
//MARK: - samples lookup by name
func nodesByDisplayNames(names:[String]) -> [Node] {
var nodes = [Node]()
for node in self.nodesArray {
let children = node.children
let matchingNodes = children.filter({ return names.contains($0.displayName) })
nodes.appendContentsOf(matchingNodes)
}
return nodes
}
// MARK: UICollectionViewDataSource
func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
return 1
}
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return self.nodesArray?.count ?? 0
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as! CategoryCell
let node = self.nodesArray[indexPath.item]
//mask to bounds
cell.layer.masksToBounds = false
//name
cell.nameLabel.text = node.displayName.uppercaseString
//icon
let image = UIImage(named: "\(node.displayName)_icon")
cell.iconImageView.image = image
//background image
let bgImage = UIImage(named: "\(node.displayName)_bg")
cell.backgroundImageView.image = bgImage
//cell shadow
cell.layer.cornerRadius = 5
cell.layer.masksToBounds = true
return cell
}
//supplementary view as search bar
func collectionView(collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, atIndexPath indexPath: NSIndexPath) -> UICollectionReusableView {
if self.headerView == nil {
self.headerView = collectionView.dequeueReusableSupplementaryViewOfKind(kind, withReuseIdentifier: "CollectionHeaderView", forIndexPath: indexPath) as! CustomSearchHeaderView
self.headerView.delegate = self
}
return self.headerView
}
//size for item
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
if self.transitionSize != nil {
return self.transitionSize
}
return self.itemSizeForCollectionViewSize(collectionView.frame.size)
}
//MARK: - UICollectionViewDelegate
func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
//hide keyboard if visible
self.view.endEditing(true)
let node = self.nodesArray[indexPath.item]
let controller = self.storyboard!.instantiateViewControllerWithIdentifier("ContentTableViewController") as! ContentTableViewController
controller.nodesArray = node.children
controller.title = node.displayName
self.navigationController?.showViewController(controller, sender: self)
}
//MARK: - Transition
//get the size of the new view to be transitioned to
override func viewWillTransitionToSize(size: CGSize, withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator) {
let newFlowLayout = UICollectionViewFlowLayout()
newFlowLayout.itemSize = self.itemSizeForCollectionViewSize(size)
newFlowLayout.sectionInset = UIEdgeInsets(top: 5, left: 10, bottom: 10, right: 10)
newFlowLayout.headerReferenceSize = CGSize(width: size.width, height: (self.headerView.isShowingSuggestions ? self.headerView.expandedViewHeight : self.headerView.shrinkedViewHeight))
self.transitionSize = newFlowLayout.itemSize
self.collectionView?.setCollectionViewLayout(newFlowLayout, animated: false)
self.transitionSize = nil
}
//item width based on the width of the collection view
func itemSizeForCollectionViewSize(size:CGSize) -> CGSize {
//first try for 3 items in a row
var width = (size.width - 4*10)/3
if width < 150 { //if too small then go for 2 in a row
width = (size.width - 3*10)/2
}
return CGSize(width: width, height: width)
}
//MARK: - CustomSearchHeaderViewDelegate
func customSearchHeaderView(customSearchHeaderView: CustomSearchHeaderView, didFindSamples sampleNames: [String]?) {
if let sampleNames = sampleNames {
let resultNodes = self.nodesByDisplayNames(sampleNames)
if resultNodes.count > 0 {
//show the results
let controller = self.storyboard!.instantiateViewControllerWithIdentifier("ContentTableViewController") as! ContentTableViewController
controller.nodesArray = resultNodes
controller.title = "Search results"
controller.containsSearchResults = true
self.navigationController?.showViewController(controller, sender: self)
return
}
}
SVProgressHUD.showErrorWithStatus("No match found", maskType: .Gradient)
}
func customSearchHeaderViewWillHideSuggestions(customSearchHeaderView: CustomSearchHeaderView) {
self.hideSuggestions()
}
func customSearchHeaderViewWillShowSuggestions(customSearchHeaderView: CustomSearchHeaderView) {
self.showSuggestions()
}
}
|
dcb6254550cf52e179268023048ac8ec
| 38.343348 | 206 | 0.669139 | false | false | false | false |
googlearchive/science-journal-ios
|
refs/heads/master
|
ScienceJournal/UI/LicenseViewController.swift
|
apache-2.0
|
1
|
/*
* Copyright 2019 Google LLC. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import UIKit
import WebKit
class LicenseViewController: MaterialHeaderViewController {
// MARK: - Properties
private let license: LicenseData
private let webView = WKWebView()
override var trackedScrollView: UIScrollView? { return webView.scrollView }
// MARK: - Public
init(license: LicenseData, analyticsReporter: AnalyticsReporter) {
self.license = license
super.init(analyticsReporter: analyticsReporter)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) is not supported")
}
override func viewDidLoad() {
super.viewDidLoad()
view.addSubview(webView)
view.isAccessibilityElement = false
webView.translatesAutoresizingMaskIntoConstraints = false
webView.pinToEdgesOfView(view)
if isPresented {
appBar.hideStatusBarOverlay()
}
title = license.title
let backMenuItem = MaterialBackBarButtonItem(target: self, action: #selector(backButtonPressed))
navigationItem.leftBarButtonItem = backMenuItem
if let licenseFile =
Bundle.currentBundle.path(forResource: license.filename, ofType: nil) {
do {
let licenseString = try String(contentsOfFile: licenseFile,
encoding: String.Encoding.utf8)
webView.loadHTMLString(licenseString, baseURL: nil)
} catch {
print("Could not read license file: \(license.filename).html, error: " +
error.localizedDescription)
}
}
}
// MARK: - User Actions
@objc private func backButtonPressed() {
navigationController?.popViewController(animated: true)
}
}
|
1ca703dc00332ef774051de9702d2285
| 28.866667 | 100 | 0.705357 | false | false | false | false |
vapor/node
|
refs/heads/master
|
Sources/Node/Convertibles/Date+Convertible.swift
|
mit
|
1
|
import Foundation
extension Date: NodeConvertible {
internal static let lock = NSLock()
/**
If a date receives a numbered node, it will use this closure
to convert that number into a Date as a timestamp
By default, this timestamp uses seconds via timeIntervalSince1970.
Override for custom implementations
*/
public static var incomingTimestamp: (Node.Number) throws -> Date = {
return Date(timeIntervalSince1970: $0.double)
}
/**
In default scenarios where a timestamp should be represented as a
Number, this closure will be used.
By default, uses seconds via timeIntervalSince1970.
Override for custom implementations.
*/
public static var outgoingTimestamp: (Date) throws -> Node.Number = {
return Node.Number($0.timeIntervalSince1970)
}
/**
A prioritized list of date formatters to use when attempting
to parse a String into a Date.
Override for custom implementations, or to remove supported formats
*/
public static var incomingDateFormatters: [DateFormatter] = [
.iso8601,
.mysql,
.rfc1123
]
/**
A default formatter to use when serializing a Date object to
a String.
Defaults to ISO 8601
Override for custom implementations.
For complex scenarios where various string representations must be used,
the user is responsible for handling their date formatting manually.
*/
public static var outgoingDateFormatter: DateFormatter = .iso8601
/**
Initializes a Date object with another Node.date, a number representing a timestamp,
or a formatted date string corresponding to one of the `incomingDateFormatters`.
*/
public init(node: Node) throws {
switch node.wrapped {
case let .date(date):
self = date
case let .number(number):
self = try Date.incomingTimestamp(number)
case let .string(string):
Date.lock.lock()
defer { Date.lock.unlock() }
guard
let date = Date.incomingDateFormatters
.lazy
.flatMap({ $0.date(from: string) })
.first
else { fallthrough }
self = date
default:
throw NodeError.unableToConvert(
input: node,
expectation: "\(Date.self), formatted time string, or timestamp",
path: []
)
}
}
/// Creates a node representation of the date
public func makeNode(in context: Context?) throws -> Node {
return .date(self, in: context)
}
}
extension StructuredData {
public var date: Date? {
return try? Date(node: self, in: nil)
}
}
extension DateFormatter {
/**
ISO8601 Date Formatter -- preferred in JSON
http://stackoverflow.com/a/28016692/2611971
*/
@nonobjc public static let iso8601: DateFormatter = {
let formatter = DateFormatter()
formatter.locale = Locale(identifier: "en_US_POSIX")
formatter.timeZone = TimeZone(secondsFromGMT: 0)
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSXXXXX"
return formatter
}()
}
extension DateFormatter {
/**
A date formatter for mysql formatted types
*/
@nonobjc public static let mysql: DateFormatter = {
let formatter = DateFormatter()
formatter.timeZone = TimeZone(secondsFromGMT: 0)
formatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
return formatter
}()
}
extension DateFormatter {
/**
A date formatter conforming to RFC 1123 spec
*/
@nonobjc public static let rfc1123: DateFormatter = {
let formatter = DateFormatter()
formatter.dateFormat = "EEE, dd MMM yyyy HH:mm:ss z"
return formatter
}()
}
|
f6203330a3958abdbaecbbbcab54060a
| 29.143939 | 92 | 0.60769 | false | false | false | false |
csnu17/My-Swift-learning
|
refs/heads/master
|
collection-data-structures-swift/DataStructures.playground/Contents.swift
|
mit
|
1
|
import Foundation
let cats = [ "Ellen" : "Chaplin", "Lilia" : "George Michael", "Rose" : "Friend", "Bettina" : "Pai Mei"]
cats["Ellen"] //returns Chaplin as an optional
cats["Steve"] //Returns nil
if let ellensCat = cats["Ellen"] {
print("Ellen's cat is named \(ellensCat).")
} else {
print("Ellen's cat's name not found!")
}
let names = ["John", "Paul", "George", "Ringo", "Mick", "Keith", "Charlie", "Ronnie"]
var stringSet = Set<String>() // 1
var loopsCount = 0
while stringSet.count < 4 {
let randomNumber = arc4random_uniform(UInt32(names.count)) // 2
let randomName = names[Int(randomNumber)] // 3
print(randomName) // 4
stringSet.insert(randomName) // 5
loopsCount += 1 // 6
}
// 7
print("Loops: " + loopsCount.description + ", Set contents: " + stringSet.description)
let countedMutable = NSCountedSet()
for name in names {
countedMutable.add(name)
countedMutable.add(name)
}
let ringos = countedMutable.count(for: "Ringo")
print("Counted Mutable set: \(countedMutable)) with count for Ringo: \(ringos)")
let items : NSArray = ["one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten"]
let indexSet = NSMutableIndexSet()
indexSet.add(3)
indexSet.add(8)
indexSet.add(9)
items.objects(at: indexSet as IndexSet) // returns ["four", "nine", "ten"]
|
c9573e1e3699aacd5945185c042880e9
| 29 | 103 | 0.657316 | false | false | false | false |
ReiVerdugo/uikit-fundamentals
|
refs/heads/master
|
step4.8-roshamboWithHistory-solution/RockPaperScissors/RockPaperScissorsViewController.swift
|
mit
|
1
|
//
// RockPaperScissorsViewController.swift
// RockPaperScissors
//
// Created by Gabrielle Miller-Messner on 10/30/14.
// Copyright (c) 2014 Gabrielle Miller-Messner. All rights reserved.
//
import UIKit
// MARK: - RockPaperScissorsViewController: UIViewController
class RockPaperScissorsViewController: UIViewController {
// MARK: Properties
var history = [RPSMatch]()
// MARK: Outlets
@IBOutlet weak var rockButton: UIButton!
@IBOutlet weak var paperButton: UIButton!
@IBOutlet weak var scissorsButton: UIButton!
// MARK: Actions
@IBAction func makeYourMove(sender: UIButton) {
switch (sender) {
case self.rockButton:
throwDown(RPS.Rock)
case self.paperButton:
throwDown(RPS.Paper)
case self.scissorsButton:
throwDown(RPS.Scissors)
default:
assert(false, "An unknown button is invoking makeYourMove()")
}
}
@IBAction func showHistory(sender: AnyObject) {
let storyboard = self.storyboard
let controller = storyboard?.instantiateViewControllerWithIdentifier("HistoryViewController")as! HistoryViewController
controller.history = self.history
self.presentViewController(controller, animated: true, completion: nil)
}
// MARK: Play!
func throwDown(playersMove: RPS) {
let computersMove = RPS()
let match = RPSMatch(p1: playersMove, p2: computersMove)
// Add match to the history
history.append(match)
// Get the Storyboard and ResultViewController
let storyboard = UIStoryboard (name: "Main", bundle: nil)
let resultVC = storyboard.instantiateViewControllerWithIdentifier("ResultViewController") as! ResultViewController
// Communicate the match to the ResultViewController
resultVC.match = match
self.presentViewController(resultVC, animated: true, completion: nil)
}
}
|
079a20cea342947fd815c60fe0255ab6
| 27.861111 | 126 | 0.641001 | false | false | false | false |
CPRTeam/CCIP-iOS
|
refs/heads/master
|
Pods/thenPromise/Source/PromiseState.swift
|
gpl-3.0
|
3
|
//
// PromiseState.swift
// then
//
// Created by Sacha Durand Saint Omer on 08/08/16.
// Copyright © 2016 s4cha. All rights reserved.
//
import Foundation
public enum PromiseState<T> {
case dormant
case pending(progress: Float)
case fulfilled(value: T)
case rejected(error: Error)
}
extension PromiseState {
var value: T? {
if case let .fulfilled(value) = self {
return value
}
return nil
}
var error: Error? {
if case let .rejected(error) = self {
return error
}
return nil
}
var isDormant: Bool {
if case .dormant = self {
return true
}
return false
}
var isPendingOrDormant: Bool {
return !isFulfilled && !isRejected
}
var isFulfilled: Bool {
if case .fulfilled = self {
return true
}
return false
}
var isRejected: Bool {
if case .rejected = self {
return true
}
return false
}
}
|
ad394e02cb395f3ee3689a4b5e2a223d
| 17.517241 | 51 | 0.52514 | false | false | false | false |
mindforce/Projector
|
refs/heads/master
|
Projector/LoginViewController.swift
|
gpl-2.0
|
1
|
//
// LoginViewController.swift
// RedmineProject-3.0
//
// Created by Volodymyr Tymofiychuk on 14.01.15.
// Copyright (c) 2015 Volodymyr Tymofiychuk. All rights reserved.
//
import UIKit
import Alamofire
class LoginViewController: UIViewController {
@IBOutlet weak var txtLink: UITextField!
@IBOutlet weak var txtUsername: UITextField!
@IBOutlet weak var txtPassword: UITextField!
@IBOutlet weak var switchRememberMe: UISwitch!
@IBAction func btnLogin(sender: UIButton) {
var username = txtUsername.text
var password = txtPassword.text
var defaultData : NSUserDefaults = NSUserDefaults.standardUserDefaults()
if (username != "" && password != "") {
var baseUrl = txtLink.text
defaultData.setObject(baseUrl, forKey: "BASE_URL")
var urlPath = baseUrl + "/users/current.json"
urlPath = urlPath.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)!
var url: NSURL = NSURL(string: urlPath)!
println("Start login '\(username)'")
Alamofire.request(.GET, url)
.authenticate(user: username, password: password)
.validate(statusCode: 200..<300)
.validate(contentType: ["application/json"])
.responseJSON { (request, response, json, error) in
if error == nil {
var json = JSON(json!)
var api_key = json["user"]["api_key"]
defaultData.setObject(username, forKey: "USERNAME")
defaultData.setObject(api_key.stringValue, forKey: "API_KEY")
if self.switchRememberMe.on {
defaultData.setBool(true, forKey: "REMEMBER_ME")
} else {
defaultData.setBool(false, forKey: "REMEMBER_ME")
}
defaultData.synchronize()
self.dismissViewControllerAnimated(true, completion: nil)
}
}
}
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// 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.
}
*/
}
|
12612998a6f1d563ce1d1a6fa5a8bf50
| 34.204819 | 106 | 0.562971 | false | false | false | false |
pfvernon2/swiftlets
|
refs/heads/master
|
iOSX/iOS/UIColor+Utilities.swift
|
apache-2.0
|
1
|
//
// UIColor+Utilities.swift
// swiftlets
//
// Created by Frank Vernon on 4/30/16.
// Copyright © 2016 Frank Vernon. All rights reserved.
//
import UIKit
extension UIColor {
/**
Convenience initializer for creating UIColor from HTML hex formats: #RRGGBB
- parameters:
- htmlHex: HTML style hex description of RGB color: [#]RRGGBB[AA]
- note: The leading # and trailing alpha values are optional.
- returns: The color specified by the hex string or nil in the event parsing fails.
*/
public convenience init?(htmlHex:String) {
guard let color = htmlHex.colorForHex() else {
return nil
}
self.init(cgColor: color.cgColor)
}
}
//Custom Colors
extension UIColor {
public static var random: UIColor = { UIColor(red: CGFloat.random(in: 0.0...1.0),
green: CGFloat.random(in: 0.0...1.0),
blue: CGFloat.random(in: 0.0...1.0),
alpha: 1.0) }()
public static var eigengrau: UIColor = { UIColor(red: 0.09, green: 0.09, blue: 0.11, alpha: 1.00) }()
}
//Color operations
public extension UIColor {
func lightenColor(removeSaturation val: CGFloat, resultAlpha alpha: CGFloat = -1) -> UIColor {
var h: CGFloat = .zero
var s: CGFloat = .zero
var b: CGFloat = .zero
var a: CGFloat = .zero
guard getHue(&h, saturation: &s, brightness: &b, alpha: &a) else {
return self
}
return UIColor(hue: h,
saturation: max(s - val, 0.0),
brightness: b,
alpha: alpha == -1 ? a : alpha)
}
}
extension String {
/**
Convenience method for creating UIColor from HTML hex formats: [#]RRGGBB[AA]
- note: The leading # and trailing alpha values are optional.
- returns: The color specified by the hex string or nil in the event parsing fails.
*/
public func colorForHex() -> UIColor? {
//creating temp string so we can manipulate as necessary
var working = self
//remove leading # if present
if working.hasPrefix("#") {
working.remove(at: startIndex)
}
//ensure string fits length requirements
switch working.count {
case 6:
//RRGGBB
//add default alpha for ease of processing below
working.append("FF")
case 8:
//RRGGBBAA
break
default:
//ilegal lengths
return nil
}
guard let rgbaInt:UInt32 = UInt32(working, radix: 16) else {
return nil
}
let bytes: [UInt8] = [
UInt8(rgbaInt.bigEndian & 0xFF),
UInt8(rgbaInt.bigEndian >> 8 & 0xFF),
UInt8(rgbaInt.bigEndian >> 16 & 0xFF),
UInt8(rgbaInt.bigEndian >> 24 & 0xFF)
]
return UIColor(red: CGFloat(bytes[0])/255.0,
green: CGFloat(bytes[1])/255.0,
blue: CGFloat(bytes[2])/255.0,
alpha: CGFloat(bytes[3])/255.0)
}
}
|
05c2fc9e03719ee0471d4637207069c9
| 29.62037 | 105 | 0.52404 | false | false | false | false |
pandazheng/Spiral
|
refs/heads/master
|
Spiral/OrdinaryHelpScene.swift
|
mit
|
1
|
//
// HelpScene.swift
// Spiral
//
// Created by 杨萧玉 on 14/10/19.
// Copyright (c) 2014年 杨萧玉. All rights reserved.
//
import SpriteKit
class OrdinaryHelpScene: SKScene {
func lightWithFinger(point:CGPoint){
if let light = self.childNodeWithName("light") as? SKLightNode {
light.lightColor = SKColor.whiteColor()
light.position = self.convertPointFromView(point)
}
}
func turnOffLight() {
(self.childNodeWithName("light") as? SKLightNode)?.lightColor = SKColor.blackColor()
}
func back() {
Data.sharedData.gameOver = false
let scene = OrdinaryModeScene(size: self.size)
let push = SKTransition.pushWithDirection(SKTransitionDirection.Right, duration: 1)
push.pausesIncomingScene = false
self.scene?.view?.presentScene(scene, transition: push)
}
override func didMoveToView(view: SKView) {
let bg = childNodeWithName("background") as! SKSpriteNode
let w = bg.size.width
let h = bg.size.height
let scale = max(view.frame.width/w, view.frame.height/h)
bg.xScale = scale
bg.yScale = scale
}
}
|
a0370521098d9c84a49567c4e384dc1b
| 28.55 | 92 | 0.634518 | false | false | false | false |
keyOfVv/Cusp
|
refs/heads/master
|
Cusp/Sources/Extensions.swift
|
mit
|
1
|
//
// Extensions.swift
// Pods
//
// Created by Ke Yang on 2/20/16.
//
//
import Foundation
import CoreBluetooth
public typealias UUID = CBUUID
public typealias CentralManager = CBCentralManager
//public typealias Peripheral = CBPeripheral
public typealias Service = CBService
public typealias Characteristic = CBCharacteristic
public typealias Descriptor = CBDescriptor
public typealias CharacteristicWriteType = CBCharacteristicWriteType
// MARK: - CBUUID
extension Foundation.UUID {
public var hash: Int {
return uuidString.hashValue
}
public func isEqual(_ object: Any?) -> Bool {
if let other = object as? Foundation.UUID {
return self.hashValue == other.hashValue
}
return false
}
}
// MARK: - CBUUID
extension CBUUID {
open override var hash: Int {
return uuidString.hashValue
}
open override func isEqual(_ object: Any?) -> Bool {
if let other = object as? CBUUID {
return self.hashValue == other.hashValue
}
return false
}
}
// MARK: - CBPeripheral
extension CBPeripheral {
open override var hash: Int {
return identifier.hashValue
}
open override func isEqual(_ object: Any?) -> Bool {
if let other = object as? CBPeripheral {
return self.hashValue == other.hashValue
}
return false
}
/// 根据UUID字符串获取对应的服务
@available(*, deprecated, message: "use Peripheral's -serviceWith(UUIDString:) method instead")
private func serviceWith(UUIDString: String) -> CBService? {
if let services = self.services {
for aService in services {
if (aService.uuid.uuidString == UUIDString) {
return aService
}
}
}
return nil
}
/// 根据UUID字符串获取对应的特征
@available(*, deprecated, message: "use Peripheral's -characteristicWith(UUIDString:) method instead")
private func characteristicWith(UUIDString: String) -> CBCharacteristic? {
if let services = self.services {
for aService in services {
if let characteristics = aService.characteristics {
for aCharacteristics in characteristics {
if (aCharacteristics.uuid.uuidString == UUIDString) {
return aCharacteristics
}
}
}
}
}
return nil
}
}
// MARK: - CBService
extension CBService {
open override var hash: Int {
return uuid.hashValue
}
open override func isEqual(_ object: Any?) -> Bool {
if let other = object as? CBService {
return self.hashValue == other.hashValue
}
return false
}
}
// MARK: - CBCharacteristic
extension CBCharacteristic {
open override var hash: Int {
return uuid.hashValue
}
open override func isEqual(_ object: Any?) -> Bool {
if let other = object as? CBCharacteristic {
return self.hashValue == other.hashValue
}
return false
}
}
// MARK: - CBDescriptor
extension CBDescriptor {
open override var hash: Int {
return uuid.hashValue
}
open override func isEqual(_ object: Any?) -> Bool {
if let other = object as? CBDescriptor {
return self.hashValue == other.hashValue
}
return false
}
}
// MARK: - String
extension String {
var isValidUUID: Bool {
do {
// check with short pattern
let shortP = "^[A-F0-9]{4}$"
let shortRegex = try NSRegularExpression(pattern: shortP, options: NSRegularExpression.Options.caseInsensitive)
let shortMatchNum = shortRegex.matches(in: self, options: NSRegularExpression.MatchingOptions.reportProgress, range: NSMakeRange(0, self.characters.count))
if shortMatchNum.count == 1 {
return true
}
// check with full pattern
let fullP = "^[A-F0-9\\-]{36}$"
let fullRegex = try NSRegularExpression(pattern: fullP, options: NSRegularExpression.Options.caseInsensitive)
let fullMatchNum = fullRegex.matches(in: self, options: NSRegularExpression.MatchingOptions.reportProgress, range: NSMakeRange(0, self.characters.count))
if fullMatchNum.count == 1 {
return true
}
} catch {
}
return false
}
}
|
9cfef8d8c75f0eb51a82bf8175c0785e
| 21.074286 | 158 | 0.701786 | false | false | false | false |
narner/AudioKit
|
refs/heads/master
|
Playgrounds/AudioKitPlaygrounds/Playgrounds/Synthesis.playground/Pages/Morphing Oscillator.xcplaygroundpage/Contents.swift
|
mit
|
1
|
//: ## Morphing Oscillator
//: Oscillator with four different waveforms built in.
import AudioKitPlaygrounds
import AudioKit
import AudioKitUI
var morph = AKMorphingOscillator(waveformArray: [AKTable(.sine),
AKTable(.triangle),
AKTable(.sawtooth),
AKTable(.square)])
morph.frequency = 400
morph.amplitude = 0.1
morph.index = 0.8
AudioKit.output = morph
AudioKit.start()
morph.start()
class LiveView: AKLiveViewController {
var frequencyLabel: AKLabel?
var amplitudeLabel: AKLabel?
var morphIndexLabel: AKLabel?
override func viewDidLoad() {
addTitle("Morphing Oscillator")
addView(AKButton(title: "Stop Oscillator") { button in
morph.isStarted ? morph.stop() : morph.play()
button.title = morph.isStarted ? "Stop Oscillator" : "Start Oscillator"
})
addView(AKSlider(property: "Frequency",
value: morph.frequency,
range: 220 ... 880,
format: "%0.2f Hz"
) { frequency in
morph.frequency = frequency
})
addView(AKSlider(property: "Amplitude", value: morph.amplitude) { amplitude in
morph.amplitude = amplitude
})
addLabel("Index: Sine = 0, Triangle = 1, Sawtooth = 2, Square = 3")
addView(AKSlider(property: "Morph Index", value: morph.index, range: 0 ... 3) { index in
morph.index = index
})
addView(AKOutputWaveformPlot.createView(width: 440, height: 400))
}
func start() {
morph.play()
}
func stop() {
morph.stop()
}
}
import PlaygroundSupport
PlaygroundPage.current.needsIndefiniteExecution = true
PlaygroundPage.current.liveView = LiveView()
|
3c3f07cda5d8ef15a5b98c5d46ecdbac
| 28.046154 | 96 | 0.57786 | false | false | false | false |
A-Kod/vkrypt
|
refs/heads/master
|
Pods/SwiftyVK/Library/Sources/Errors/ApiErrorHandler.swift
|
apache-2.0
|
2
|
protocol ApiErrorHandler {
func handle(error: ApiError) throws -> ApiErrorHandlerResult
}
final class ApiErrorHandlerImpl: ApiErrorHandler {
private let executor: ApiErrorExecutor
init(executor: ApiErrorExecutor) {
self.executor = executor
}
func handle(error: ApiError) throws -> ApiErrorHandlerResult {
switch error.code {
case 5:
_ = try executor.logIn(revoke: false)
return .none
case 14:
guard
let sid = error.otherInfo["captcha_sid"],
let imgRawUrl = error.otherInfo["captcha_img"]
else {
throw VKError.api(error)
}
let key = try executor.captcha(rawUrlToImage: imgRawUrl, dismissOnFinish: false)
return .captcha(Captcha(sid, key))
case 17:
guard
let rawUrl = error.otherInfo["redirect_uri"],
let url = URL(string: rawUrl)
else {
throw VKError.api(error)
}
try executor.validate(redirectUrl: url)
return .none
default:
throw VKError.api(error)
}
}
}
enum ApiErrorHandlerResult {
case captcha(Captcha)
case none
}
|
de60b63bc1bef33cbb5d018aef525f3a
| 27.042553 | 92 | 0.538695 | false | false | false | false |
didisouzacosta/ASAlertViewController
|
refs/heads/master
|
ASAlertViewController/Classes/AlertController/ASHandlerButton.swift
|
mit
|
1
|
//
// ASHandlerButton.swift
// Pods
//
// Created by Adriano Souza Costa on 4/1/17.
//
//
import Foundation
import UIKit
class ASHandlerButton: UIButton {
// MARK: - Variables
var onAction: (()->())?
var closeOnAction: Bool = true
fileprivate var alertHandler: ASAlertHandler?
// MARK: - Lifecircle Class
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
init(frame: CGRect, handler: ASAlertHandler? = nil) {
super.init(frame: frame)
alertHandler = handler
closeOnAction = handler?.closeOnAction ?? true
updateUI()
setupAction()
}
// MARK: - Private Methods
fileprivate func updateUI() {
setTitle(alertHandler?.title, for: .normal)
setTitleColor(alertHandler?.type.fontStyle.color, for: .normal)
titleLabel?.font = alertHandler?.type.fontStyle.font
backgroundColor = .white
translatesAutoresizingMaskIntoConstraints = false;
heightAnchor.constraint(equalToConstant: 45).isActive = true
}
fileprivate func setupAction() {
addTarget(self, action: #selector(callHandler), for: .touchUpInside)
addTarget(self, action: #selector(drag), for: .touchDown)
addTarget(self, action: #selector(drag), for: .touchDragEnter)
addTarget(self, action: #selector(exitDrag), for: .touchDragExit)
}
@objc fileprivate func callHandler() {
onAction?()
alertHandler?.handler?()
exitDrag()
}
@objc fileprivate func drag() {
UIView.animate(withDuration: 0.26) {
self.backgroundColor = UIColor(red: 234/255, green: 234/255, blue: 234/255, alpha: 1)
}
}
@objc fileprivate func exitDrag() {
UIView.animate(withDuration: 0.26) {
self.backgroundColor = .white
}
}
}
|
996ff65a2689e065f5c69e4333e59b8b
| 24.22973 | 97 | 0.627209 | false | false | false | false |
rlisle/Patriot-iOS
|
refs/heads/master
|
PatriotTests/MockHwManager.swift
|
bsd-3-clause
|
1
|
//
// MockHwManager.swift
// Patriot
//
// Created by Ron Lisle on 5/5/17.
// Copyright © 2017 Ron Lisle. All rights reserved.
//
import Foundation
import PromiseKit
class MockHwManager: HwManager
{
var deviceDelegate: DeviceNotifying?
var activityDelegate: ActivityNotifying?
var photons: [String: Photon] = [: ]
var eventName: String = "unspecified"
var deviceNames: Set<String> = []
var supportedNames = Set<String>()
var currentActivities: [String: Int] = [: ]
func login(user: String, password: String) -> Promise<Void>
{
return Promise(value: ())
}
func discoverDevices() -> Promise<Void>
{
return Promise(value: ())
}
func sendCommand(activity: String, percent: Int)
{
}
}
//MARK: Testing Methods
extension MockHwManager
{
func sendDelegateSupportedListChanged(names: Set<String>)
{
supportedNames = names
activityDelegate?.supportedListChanged()
}
}
|
cdf1e204af7dbe850e8af514c937eb3c
| 19.660377 | 67 | 0.580822 | false | false | false | false |
PureSwift/Bluetooth
|
refs/heads/master
|
Sources/BluetoothGATT/GATTAge.swift
|
mit
|
1
|
//
// GATTAge.swift
// Bluetooth
//
// Created by Carlos Duclos on 6/13/18.
// Copyright © 2018 PureSwift. All rights reserved.
//
import Foundation
/**
Age
Age of the User.
- SeeAlso: [ Age](https://www.bluetooth.com/specifications/gatt/viewer?attributeXmlFile=org.bluetooth.characteristic.age.xml)
*/
@frozen
public struct GATTAge: GATTCharacteristic, Equatable {
internal static var length: Int { return MemoryLayout<UInt8>.size }
public static var uuid: BluetoothUUID { return .age }
public var year: Year
public init(year: Year) {
self.year = year
}
public init?(data: Data) {
guard data.count == type(of: self).length
else { return nil }
let year = Year(rawValue: data[0])
self.init(year: year)
}
public var data: Data {
return Data([year.rawValue])
}
}
public extension GATTAge {
struct Year: BluetoothUnit, Equatable {
public static var unitType: UnitIdentifier { return .year }
public var rawValue: UInt8
public init(rawValue: UInt8) {
self.rawValue = rawValue
}
}
}
extension GATTAge.Year: CustomStringConvertible {
public var description: String {
return rawValue.description
}
}
extension GATTAge.Year: ExpressibleByIntegerLiteral {
public init(integerLiteral value: UInt8) {
self.init(rawValue: value)
}
}
extension GATTAge: CustomStringConvertible {
public var description: String {
return year.description
}
}
|
9e9c0c37f431e9dc0d66b6617d29ddc9
| 19.180723 | 126 | 0.598209 | false | false | false | false |
blockchain/My-Wallet-V3-iOS
|
refs/heads/master
|
Modules/CryptoAssets/Sources/EthereumKit/Models/Transactions/EthereumJsonRpcTransaction.swift
|
lgpl-3.0
|
1
|
// Copyright © Blockchain Luxembourg S.A. All rights reserved.
import Foundation
/// A representation of a transaction that can be passed to Ethereum JSON RPC methods.
///
/// All parameters are hexadecimal String values.
public struct EthereumJsonRpcTransaction: Codable {
/// from: DATA, 20 Bytes - The address the transaction is send from.
let from: String
/// to: DATA, 20 Bytes - (optional when creating new contract) The address the transaction is directed to.
let to: String?
/// data: DATA - The compiled code of a contract OR the hash of the invoked method signature and encoded parameters. For details see Ethereum Contract ABI
let data: String
/// gas: QUANTITY - (optional, default: 90000) Integer of the gas provided for the transaction execution. It will return unused gas.
let gas: String?
/// gasPrice: QUANTITY - (optional, default: To-Be-Determined) Integer of the gasPrice used for each paid gas
let gasPrice: String?
/// value: QUANTITY - (optional) Integer of the value sent with this transaction
let value: String?
/// nonce: QUANTITY - (optional) Integer of a nonce. This allows to overwrite your own pending transactions that use the same nonce.
let nonce: String?
public init(
from: String,
to: String?,
data: String,
gas: String?,
gasPrice: String?,
value: String?,
nonce: String?
) {
self.from = from
self.to = to
self.data = data
self.gas = gas
self.gasPrice = gasPrice
self.value = value
self.nonce = nonce
}
}
|
239e61d06dc894c5851db7d0a53e17ab
| 32.979167 | 158 | 0.662784 | false | false | false | false |
WhatsTaste/WTImagePickerController
|
refs/heads/master
|
Vendor/Controllers/WTImagePickerController.swift
|
mit
|
1
|
//
// WTImagePickerController.swift
// WTImagePickerController
//
// Created by Jayce on 2017/2/8.
// Copyright © 2017年 WhatsTaste. All rights reserved.
//
import UIKit
public typealias WTImagePickerControllerDidFinishHandler = (_ picker: WTImagePickerController, _ images: [UIImage]) -> Void
public typealias WTImagePickerControllerDidCancelHandler = (_ picker: WTImagePickerController) -> Void
public let WTImagePickerControllerDisableAlphaComponent: CGFloat = 0.3
private let pickLimitDefault: Int = 0
@objc public protocol WTImagePickerControllerDelegate: NSObjectProtocol {
@objc optional func imagePickerController(_ picker: WTImagePickerController, didFinishWithImages images: [UIImage])
@objc optional func imagePickerControllerDidCancel(_ picker: WTImagePickerController)
}
open class WTImagePickerController: UIViewController, WTAlbumViewControllerDelegate {
convenience init() {
self.init(nibName: nil, bundle: nil)
}
// MARK: - Life cycle
override open func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
self.addChildViewController(contentViewController)
self.view.addSubview(contentViewController.view)
contentViewController.view.frame = self.view.bounds
contentViewController.view.autoresizingMask = [.flexibleWidth, .flexibleHeight]
contentViewController.didMove(toParentViewController: self)
}
open override var preferredStatusBarStyle: UIStatusBarStyle {
return contentViewController.preferredStatusBarStyle
}
open override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
return .portrait
}
open override var childViewControllerForStatusBarHidden: UIViewController? {
let topViewController = contentViewController.topViewController
return topViewController
}
open override var childViewControllerForStatusBarStyle: UIViewController? {
let topViewController = contentViewController.topViewController
return topViewController
}
// MARK: - WTAlbumViewControllerDelegate
func albumViewController(_ controller: WTAlbumViewController, didFinishWithImages images: [UIImage]) {
delegate?.imagePickerController?(self, didFinishWithImages: images)
didFinishHandler?(self, images)
}
func albumViewControllerDidCancel(_ controller: WTAlbumViewController) {
delegate?.imagePickerControllerDidCancel?(self)
didCancelHandler?(self)
}
// MARK: - Properties
@objc weak public var delegate: WTImagePickerControllerDelegate?
@objc public var didFinishHandler: WTImagePickerControllerDidFinishHandler?
@objc public var didCancelHandler: WTImagePickerControllerDidCancelHandler?
@objc public var tintColor: UIColor = .init(red: 0, green: 122 / 255, blue: 255 / 255, alpha: 1)
@objc public var pickLimit: Int = pickLimitDefault //Default is 0, which means no limit
lazy private var contentViewController: UINavigationController = {
let rootViewController = WTAlbumViewController(style: .plain)
rootViewController.delegate = self
rootViewController.tintColor = tintColor
rootViewController.pickLimit = self.pickLimit
let navigationController = UINavigationController(rootViewController: rootViewController)
navigationController.isToolbarHidden = true
navigationController.navigationBar.isTranslucent = false
return navigationController
}()
}
// MARK: - Localization
public extension NSObject {
func WTIPLocalizedString(_ key: String) -> String {
return NSLocalizedString(key, tableName: "WTImagePickerController", bundle: Bundle(path: Bundle.main.path(forResource: "WTImagePickerController", ofType: "bundle")!)!, value: "", comment: "")
}
}
public extension UIView {
func WTIPLayoutGuide() -> Any {
if #available(iOS 11.0, *) {
return safeAreaLayoutGuide
} else {
return self
}
}
}
public extension UIColor {
func WTIPReverse(alpha: CGFloat?) -> UIColor {
var localAlpha: CGFloat = 0
var white: CGFloat = 0
if getWhite(&white, alpha: &localAlpha) {
return UIColor(white: 1 - white, alpha: alpha ?? localAlpha)
}
var hue: CGFloat = 0
var saturation: CGFloat = 0
var brightness: CGFloat = 0
if getHue(&hue, saturation: &saturation, brightness: &brightness, alpha: &localAlpha) {
return UIColor(hue: 1 - hue, saturation: 1 - saturation, brightness: 1 - brightness, alpha: alpha ?? localAlpha)
}
var red: CGFloat = 0
var green: CGFloat = 0
var blue: CGFloat = 0
if getRed(&red, green: &green, blue: &blue, alpha: &localAlpha) {
return UIColor(red: 1 - red, green: 1 - green, blue: 1 - blue, alpha: alpha ?? localAlpha)
}
return UIColor.clear
}
}
|
b75bb0d426fd49ec9ee3f6a7e925ef60
| 36.592593 | 199 | 0.696749 | false | false | false | false |
honishi/Hakumai
|
refs/heads/main
|
Hakumai/Managers/HandleNameManager/DatabaseValueCacher.swift
|
mit
|
1
|
//
// DatabaseValueCacher.swift
// Hakumai
//
// Created by Hiroyuki Onishi on 2021/12/28.
// Copyright © 2021 Hiroyuki Onishi. All rights reserved.
//
import Foundation
class DatabaseValueCacher<T: Equatable> {
enum CacheStatus: Equatable {
case cached(T?) // `.cached(nil)` means the value is cached as `nil`.
case notCached
}
private var cache: [String: CacheStatus] = [:]
func update(value: T?, for userId: String, in communityId: String) {
objc_sync_enter(self)
defer { objc_sync_exit(self) }
let key = cacheKey(userId, communityId)
let _value: CacheStatus = {
guard let value = value else { return .cached(nil) }
return .cached(value)
}()
cache[key] = _value
}
func updateValueAsNil(for userId: String, in communityId: String) {
update(value: nil, for: userId, in: communityId)
}
func cachedValue(for userId: String, in communityId: String) -> CacheStatus {
objc_sync_enter(self)
defer { objc_sync_exit(self) }
let key = cacheKey(userId, communityId)
return cache[key] ?? .notCached
}
private func cacheKey(_ userId: String, _ communityId: String) -> String {
return "\(userId):\(communityId)"
}
}
|
b455da932b598d73702384eec0ac0a3e
| 28.431818 | 81 | 0.615444 | false | false | false | false |
rugheid/Swift-MathEagle
|
refs/heads/master
|
MathEagleTests/Protocols/ExtensionsTests.swift
|
mit
|
1
|
//
// ExtensionsTests.swift
// SwiftMath
//
// Created by Rugen Heidbuchel on 27/01/15.
// Copyright (c) 2015 Jorestha Solutions. All rights reserved.
//
import Cocoa
import XCTest
import MathEagle
class ExtensionsTests: XCTestCase {
func testIsNegative() {
XCTAssertFalse(2.0.isNegative)
XCTAssertFalse(0.0.isNegative)
XCTAssertFalse(1023432.0.isNegative)
XCTAssertFalse(1.4532.isNegative)
XCTAssertTrue((-1.4532).isNegative)
XCTAssertTrue((-1.0).isNegative)
}
func testIsPositive() {
XCTAssertTrue(2.0.isPositive)
XCTAssertFalse(0.0.isPositive)
XCTAssertTrue(1023432.0.isPositive)
XCTAssertTrue(1.4532.isPositive)
XCTAssertFalse((-1.4532).isPositive)
XCTAssertFalse((-1.0).isPositive)
}
func testIsNatural() {
XCTAssertTrue(2.0.isNatural)
XCTAssertTrue(0.0.isNatural)
XCTAssertTrue(1023432.0.isNatural)
XCTAssertFalse(1.4532.isNatural)
XCTAssertFalse((-1.4532).isNatural)
XCTAssertFalse((-1.0).isNatural)
}
func testIsInteger() {
XCTAssertTrue(2.0.isInteger)
XCTAssertTrue(0.0.isInteger)
XCTAssertTrue((-2.0).isInteger)
XCTAssertFalse(2.12.isInteger)
XCTAssertFalse((-2.12).isInteger)
}
func testExtensionsDouble() {
do {
let x : Double = 1.0
XCTAssertFalse(x.isNegative)
XCTAssertTrue(x.isPositive)
XCTAssertTrue(x.isInteger)
XCTAssertTrue(x.isNatural)
}
do {
let x : Double = -1.0
XCTAssertTrue(x.isNegative)
XCTAssertFalse(x.isPositive)
XCTAssertTrue(x.isInteger)
XCTAssertFalse(x.isNatural)
}
do {
let x : Double = 3.14159
XCTAssertFalse(x.isNegative)
XCTAssertTrue(x.isPositive)
XCTAssertFalse(x.isInteger)
XCTAssertFalse(x.isNatural)
}
do {
let x : Double = 0.0
XCTAssertFalse(x.isNegative)
XCTAssertFalse(x.isPositive)
XCTAssertTrue(x.isInteger)
XCTAssertTrue(x.isNatural)
}
}
func testExtensionsFloat() {
do {
let x : Float = 1.0
XCTAssertFalse(x.isNegative)
XCTAssertTrue(x.isPositive)
XCTAssertTrue(x.isInteger)
XCTAssertTrue(x.isNatural)
}
do {
let x : Float = -1.0
XCTAssertTrue(x.isNegative)
XCTAssertFalse(x.isPositive)
XCTAssertTrue(x.isInteger)
XCTAssertFalse(x.isNatural)
}
do {
let x : Float = 3.14159
XCTAssertFalse(x.isNegative)
XCTAssertTrue(x.isPositive)
XCTAssertFalse(x.isInteger)
XCTAssertFalse(x.isNatural)
}
do {
let x : Float = 0.0
XCTAssertFalse(x.isNegative)
XCTAssertFalse(x.isPositive)
XCTAssertTrue(x.isInteger)
XCTAssertTrue(x.isNatural)
}
}
func testExtensionsCGFloat() {
do {
let x : CGFloat = 1.0
XCTAssertFalse(x.isNegative)
XCTAssertTrue(x.isPositive)
XCTAssertTrue(x.isInteger)
XCTAssertTrue(x.isNatural)
}
do {
let x : CGFloat = -1.0
XCTAssertTrue(x.isNegative)
XCTAssertFalse(x.isPositive)
XCTAssertTrue(x.isInteger)
XCTAssertFalse(x.isNatural)
}
do {
let x : CGFloat = 3.14159
XCTAssertFalse(x.isNegative)
XCTAssertTrue(x.isPositive)
XCTAssertFalse(x.isInteger)
XCTAssertFalse(x.isNatural)
}
do {
let x : CGFloat = 0.0
XCTAssertFalse(x.isNegative)
XCTAssertFalse(x.isPositive)
XCTAssertTrue(x.isInteger)
XCTAssertTrue(x.isNatural)
}
}
func testExtensionsInt() {
do {
let x : Int = 1
XCTAssertFalse(x.isNegative)
XCTAssertTrue(x.isPositive)
XCTAssertTrue(x.isInteger)
XCTAssertTrue(x.isNatural)
}
do {
let x : Int = -1
XCTAssertTrue(x.isNegative)
XCTAssertFalse(x.isPositive)
XCTAssertTrue(x.isInteger)
XCTAssertFalse(x.isNatural)
}
do {
let x : Int = 0
XCTAssertFalse(x.isNegative)
XCTAssertFalse(x.isPositive)
XCTAssertTrue(x.isInteger)
XCTAssertTrue(x.isNatural)
}
}
func testExtensionsInt8() {
do {
let x : Int8 = 1
XCTAssertFalse(x.isNegative)
XCTAssertTrue(x.isPositive)
XCTAssertTrue(x.isInteger)
XCTAssertTrue(x.isNatural)
}
do {
let x : Int8 = -1
XCTAssertTrue(x.isNegative)
XCTAssertFalse(x.isPositive)
XCTAssertTrue(x.isInteger)
XCTAssertFalse(x.isNatural)
}
do {
let x : Int8 = 0
XCTAssertFalse(x.isNegative)
XCTAssertFalse(x.isPositive)
XCTAssertTrue(x.isInteger)
XCTAssertTrue(x.isNatural)
}
}
func testExtensionsInt16() {
do {
let x : Int16 = 1
XCTAssertFalse(x.isNegative)
XCTAssertTrue(x.isPositive)
XCTAssertTrue(x.isInteger)
XCTAssertTrue(x.isNatural)
}
do {
let x : Int16 = -1
XCTAssertTrue(x.isNegative)
XCTAssertFalse(x.isPositive)
XCTAssertTrue(x.isInteger)
XCTAssertFalse(x.isNatural)
}
do {
let x : Int16 = 0
XCTAssertFalse(x.isNegative)
XCTAssertFalse(x.isPositive)
XCTAssertTrue(x.isInteger)
XCTAssertTrue(x.isNatural)
}
}
func testExtensionsInt32() {
do {
let x : Int32 = 1
XCTAssertFalse(x.isNegative)
XCTAssertTrue(x.isPositive)
XCTAssertTrue(x.isInteger)
XCTAssertTrue(x.isNatural)
}
do {
let x : Int32 = -1
XCTAssertTrue(x.isNegative)
XCTAssertFalse(x.isPositive)
XCTAssertTrue(x.isInteger)
XCTAssertFalse(x.isNatural)
}
do {
let x : Int32 = 0
XCTAssertFalse(x.isNegative)
XCTAssertFalse(x.isPositive)
XCTAssertTrue(x.isInteger)
XCTAssertTrue(x.isNatural)
}
}
func testExtensionsInt64() {
do {
let x : Int64 = 1
XCTAssertFalse(x.isNegative)
XCTAssertTrue(x.isPositive)
XCTAssertTrue(x.isInteger)
XCTAssertTrue(x.isNatural)
}
do {
let x : Int64 = -1
XCTAssertTrue(x.isNegative)
XCTAssertFalse(x.isPositive)
XCTAssertTrue(x.isInteger)
XCTAssertFalse(x.isNatural)
}
do {
let x : Int64 = 0
XCTAssertFalse(x.isNegative)
XCTAssertFalse(x.isPositive)
XCTAssertTrue(x.isInteger)
XCTAssertTrue(x.isNatural)
}
}
func testExtensionsUInt() {
do {
let x : UInt = 1
XCTAssertFalse(x.isNegative)
XCTAssertTrue(x.isPositive)
XCTAssertTrue(x.isInteger)
XCTAssertTrue(x.isNatural)
}
do {
let x : UInt = 0
XCTAssertFalse(x.isNegative)
XCTAssertFalse(x.isPositive)
XCTAssertTrue(x.isInteger)
XCTAssertTrue(x.isNatural)
}
}
func testExtensionsUInt8() {
do {
let x : UInt8 = 1
XCTAssertFalse(x.isNegative)
XCTAssertTrue(x.isPositive)
XCTAssertTrue(x.isInteger)
XCTAssertTrue(x.isNatural)
}
do {
let x : UInt8 = 0
XCTAssertFalse(x.isNegative)
XCTAssertFalse(x.isPositive)
XCTAssertTrue(x.isInteger)
XCTAssertTrue(x.isNatural)
}
}
func testExtensionsUInt16() {
do {
let x : UInt16 = 1
XCTAssertFalse(x.isNegative)
XCTAssertTrue(x.isPositive)
XCTAssertTrue(x.isInteger)
XCTAssertTrue(x.isNatural)
}
do {
let x : UInt16 = 0
XCTAssertFalse(x.isNegative)
XCTAssertFalse(x.isPositive)
XCTAssertTrue(x.isInteger)
XCTAssertTrue(x.isNatural)
}
}
func testExtensionsUInt32() {
do {
let x : UInt32 = 1
XCTAssertFalse(x.isNegative)
XCTAssertTrue(x.isPositive)
XCTAssertTrue(x.isInteger)
XCTAssertTrue(x.isNatural)
}
do {
let x : UInt32 = 0
XCTAssertFalse(x.isNegative)
XCTAssertFalse(x.isPositive)
XCTAssertTrue(x.isInteger)
XCTAssertTrue(x.isNatural)
}
}
func testExtensionsUInt64() {
do {
let x : UInt64 = 1
XCTAssertFalse(x.isNegative)
XCTAssertTrue(x.isPositive)
XCTAssertTrue(x.isInteger)
XCTAssertTrue(x.isNatural)
}
do {
let x : UInt64 = 0
XCTAssertFalse(x.isNegative)
XCTAssertFalse(x.isPositive)
XCTAssertTrue(x.isInteger)
XCTAssertTrue(x.isNatural)
}
}
}
|
36ba1993350536b9a88a59e873789a86
| 28.527273 | 63 | 0.531507 | false | true | false | false |
AnnMic/FestivalArchitect
|
refs/heads/master
|
FestivalArchitect/Classes/Systems/PhysicalNeedSystem.swift
|
mit
|
1
|
//
// UpdateNeedSystem.swift
// FestivalArchitect
//
// Created by Ann Michelsen on 12/11/14.
// Copyright (c) 2014 AnnMi. All rights reserved.
//
import Foundation
class PhysicalNeedSystem : System { //TODO rename to something better
let environment:Environment
init (env:Environment) {
environment = env
}
func update(dt: Float) {
let entites:[Entity] = environment.entitiesWithComponent(AIComponent.self)
if entites.count == 0 {
return
}
for entity in entites {
decreaseVisitorNeeds(entity)
}
}
func decreaseVisitorNeeds(entity:Entity){
var visitor:PhysicalNeedComponent = entity.component(PhysicalNeedComponent)!
if visitor.hunger > -100 {
visitor.hunger--
}
if visitor.fatigue > -100 {
visitor.fatigue--
}
if visitor.thirst > -100 {
visitor.thirst--
}
println("hunger \(visitor.hunger) thirst \(visitor.thirst) fatigue \(visitor.fatigue)")
}
}
|
d4a0bb6ae72c6cc4ef5789777388d5ce
| 19.722222 | 95 | 0.572833 | false | false | false | false |
Aishwarya-Ramakrishnan/sparkios
|
refs/heads/master
|
Source/Auth/AccessToken.swift
|
mit
|
1
|
// 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
import ObjectMapper
class AccessToken: NSObject, NSCoding, Mappable {
var accessTokenString: String?
var accessTokenExpiration: TimeInterval?
var refreshTokenString: String?
var refreshTokenExpiration: TimeInterval?
var accessTokenCreation: TimeInterval?
var accessTokenExpirationDate: Date {
return Date(timeInterval: accessTokenExpiration!, since: accessTokenCreationDate)
}
var accessTokenCreationDate: Date {
return Date(timeIntervalSinceReferenceDate: accessTokenCreation!)
}
private let accessTokenKey = "accessTokenKey"
private let accessTokenExpirationKey = "accessTokenExpirationKey"
private let refreshTokenKey = "refreshTokenKey"
private let refreshTokenExpirationKey = "refreshTokenExpirationKey"
private let accessTokenCreationKey = "accessTokenCreationKey"
init(accessToken: String) {
self.accessTokenString = accessToken
}
// MARK:- Mappable
required init?(map: Map) {
accessTokenCreation = Date().timeIntervalSinceReferenceDate
}
func mapping(map: Map) {
accessTokenString <- map["access_token"]
accessTokenExpiration <- map["expires_in"]
refreshTokenString <- map["refresh_token"]
refreshTokenExpiration <- map["refresh_token_expires_in"]
}
// MARK:- NSCoding
required init?(coder aDecoder: NSCoder) {
accessTokenString = aDecoder.decodeObject(forKey: accessTokenKey) as? String
accessTokenExpiration = aDecoder.decodeDouble(forKey: accessTokenExpirationKey)
refreshTokenString = aDecoder.decodeObject(forKey: refreshTokenKey) as? String
refreshTokenExpiration = aDecoder.decodeDouble(forKey: refreshTokenExpirationKey)
accessTokenCreation = aDecoder.decodeDouble(forKey: accessTokenCreationKey)
}
func encode(with aCoder: NSCoder) {
encodeObject(accessTokenString, forKey: accessTokenKey, aCoder: aCoder)
encodeDouble(accessTokenExpiration, forKey: accessTokenExpirationKey, aCoder: aCoder)
encodeObject(refreshTokenString, forKey: refreshTokenKey, aCoder: aCoder)
encodeDouble(refreshTokenExpiration, forKey: refreshTokenExpirationKey, aCoder: aCoder)
encodeDouble(accessTokenCreation, forKey: accessTokenCreationKey, aCoder: aCoder)
}
private func encodeObject(_ objv: Any?, forKey key: String, aCoder: NSCoder) {
guard objv != nil else {
return
}
aCoder.encode(objv, forKey: key)
}
private func encodeDouble(_ realv: Double?, forKey key: String, aCoder: NSCoder) {
guard let realValue = realv else {
return
}
aCoder.encode(realValue, forKey: key)
}
}
|
65cd8406f891ba81575920b077fc5ecd
| 39.854167 | 95 | 0.718001 | false | false | false | false |
oacastefanita/PollsFramework
|
refs/heads/master
|
Example/PollsFramework-watch Extension/PollsInterfaceController.swift
|
mit
|
1
|
//
// InterfaceController.swift
// PollsFramework-watch Extension
//
// Created by Stefanita Oaca on 10/09/2017.
// Copyright © 2017 CocoaPods. All rights reserved.
//
import WatchKit
import Foundation
import PollsFramework
class PollsInterfaceController: WKInterfaceController {
@IBOutlet var lblNoData: WKInterfaceLabel!
@IBOutlet var pollsTable: WKInterfaceTable!
var array: [Poll]!
override func awake(withContext context: Any?) {
super.awake(withContext: context)
array = PollsFrameworkController.sharedInstance.dataController().getAllObjectsFor(entityName: "Poll") as! [Poll]
pollsTable.setNumberOfRows(array.count, withRowType: "pollsRow")
for index in 0..<array.count {
if let controller = pollsTable.rowController(at: index) as? PollsRowController {
controller.poll = array[index]
}
}
lblNoData.setHidden(array.count != 0)
// Configure interface objects here.
}
override func willActivate() {
// This method is called when watch view controller is about to be visible to user
super.willActivate()
}
override func didDeactivate() {
// This method is called when watch view controller is no longer visible
super.didDeactivate()
}
override func table(_ table: WKInterfaceTable, didSelectRowAt rowIndex: Int) {
let poll = array[rowIndex]
if poll.pollTypeId == PollTypes.singleText.rawValue{
pushController(withName: "SingleTextPoll", context: poll)
}else if poll.pollTypeId == PollTypes.bestText.rawValue{
pushController(withName: "BestTextPoll", context: poll)
}else if poll.pollTypeId == PollTypes.singleImage.rawValue{
pushController(withName: "SingleImagePoll", context: poll)
}else if poll.pollTypeId == PollTypes.bestImage.rawValue{
pushController(withName: "BestImagePoll", context: poll)
}
}
}
|
1adaf3e69772e13a2ae18b937c9fc309
| 34.385965 | 120 | 0.667824 | false | false | false | false |
scotlandyard/expocity
|
refs/heads/master
|
expocity/Test/Model/Home/TMHome.swift
|
mit
|
1
|
import XCTest
@testable import expocity
class TMHome:XCTestCase
{
private var mHome:MHome?
private let kRoomName:String = "MyWeirdRoomName with space"
override func setUp()
{
super.setUp()
mHome = MHome()
}
override func tearDown()
{
mHome = nil
super.tearDown()
}
//MARK: -
func testRoomOwner()
{
let firebaseRoom:FDatabaseModelRoom = mHome!.room()
let userId:String = firebaseRoom.owner
XCTAssertFalse(userId.isEmpty, "Room has no owner")
}
func testEmptyRoomName()
{
let firebaseRoom:FDatabaseModelRoom = mHome!.room()
let roomName:String = firebaseRoom.name
XCTAssertFalse(roomName.isEmpty, "Room name is empty")
}
func testRoomName()
{
mHome!.itemTitle.title = kRoomName
let firebaseRoom:FDatabaseModelRoom = mHome!.room()
let roomName:String = firebaseRoom.name
XCTAssertEqual(roomName, kRoomName, "Room name mismatch")
}
func testAccessInvitationOnly()
{
let accessInvitationOnly:FDatabaseModelRoom.Access = FDatabaseModelRoom.Access.invitationOnly
mHome!.itemAccess.access = accessInvitationOnly
let firebaseRoom:FDatabaseModelRoom = mHome!.room()
let roomAccess:FDatabaseModelRoom.Access = firebaseRoom.access
XCTAssertEqual(roomAccess, accessInvitationOnly, "Room access mismatch")
}
func testAccessFreeJoin()
{
let accessFreeJoin:FDatabaseModelRoom.Access = FDatabaseModelRoom.Access.freeJoin
mHome!.itemAccess.access = accessFreeJoin
let firebaseRoom:FDatabaseModelRoom = mHome!.room()
let roomAccess:FDatabaseModelRoom.Access = firebaseRoom.access
XCTAssertEqual(roomAccess, accessFreeJoin, "Room access mismatch")
}
}
|
f632cb289e3af8212bdb45a1b97f22b0
| 26.884058 | 101 | 0.644491 | false | true | false | false |
studyYF/YueShiJia
|
refs/heads/master
|
YueShiJia/YueShiJia/Classes/Tools/YFHttpRequest.swift
|
apache-2.0
|
1
|
//
// YFHttpRequest.swift
// YueShiJia
//
// Created by YangFan on 2017/5/9.
// Copyright © 2017年 YangFan. All rights reserved.
//网络请求工具
/**
首页
https://interface.yueshichina.com/?act=app&op=index1&app_id=1002&channel=APPSTORE&client=ios&curpage=1&imei=B2624433-81D9-4205-AF20-892FDBB80EE8&net_type=WIFI&page=10&push_id=4627676201928478325&req_time=1494315520869&token=&v=2.1.3&version=10.3.1
轮播图详情
https://interface.yueshichina.com/?act=app&op=goods_special_new&app_id=1002&channel=APPSTORE&client=ios&imei=B2624433-81D9-4205-AF20-892FDBB80EE8&key=898774d9eee50eacaf72470122975d8b&net_type=WIFI&push_id=4627676201928478325&req_time=1494572577981&special_id=578&token=&v=2.1.3&version=10.3.1
*/
import Foundation
import Alamofire
import SVProgressHUD
import SwiftyJSON
class YFHttpRequest {
/// 单例
static let shareInstance = YFHttpRequest()
/// 定义首页数据请求返回的类型
typealias homeData = ([YFHomeItem],[Banner],[YFHomeHeaderItem])
/// 网络请求基本方法
///
/// - Parameters:
/// - method: 请求方式
/// - url: 地址
/// - param: 参数
/// - completion: 完成后回调
private func baseRequest(_ method: HTTPMethod = .get, url: String, param: [String: Any]? = nil, completion: @escaping(Any) -> ()) {
Alamofire.request(url, method: method, parameters: param).responseJSON { (response) in
//如果请求失败,则直接返回,并提示加载失败
guard response.result.isSuccess else {
SVProgressHUD.showError(withStatus: "加载失败!")
return
}
//如果有返回值,则回调
if let value = response.result.value {
completion(value)
}
}
}
/// 获取首页数据
///
/// - Parameters:
/// - page: 页数
/// - completion: 完成回调
public func loadHomeData(_ page: Int, completion: @escaping (homeData) -> ()) {
let url = "https://interface.yueshichina.com/?act=app&op=index1&app_id=1002&channel=APPSTORE&client=ios&curpage=\(page)&imei=B2624433-81D9-4205-AF20-892FDBB80EE8&net_type=WIFI&page=10&push_id=4627676201928478325&req_time=1494315520869&token=&v=2.1.3&version=10.3.1"
baseRequest(url: url) { (response) in
let dict = JSON(response)
let code = dict["code"].intValue
guard code == kSuccessCode else {
SVProgressHUD.showError(withStatus: "请求失败")
return
}
if let dict = dict["datas"].dictionary {
//商品数组
var homeItems = [YFHomeItem]()
//广告
var banners = [Banner]()
//四个分类
var headItems = [YFHomeHeaderItem]()
if let home = dict["data_type"]?.arrayObject {
for item in home {
homeItems.append(YFHomeItem(dict: item as! [String : Any]))
}
}
if let banner = dict["banner"]?.arrayObject {
for item in banner {
banners.append(Banner(dict: item as! [String : Any]))
}
}
if let four = dict["relation_good_four"]?.arrayObject {
for item in four {
headItems.append(YFHomeHeaderItem(dict: item as! [String : Any]))
}
}
completion((homeItems, banners, headItems))
}
}
}
/// 请求专题详情数据
///
/// - Parameters:
/// - special_id: 专题id
/// - completion: 返回专题数据
public func loadSpecialGoodsData(_ special_id: String, completion: @escaping(YFSpecialGoodsItem) -> ()) {
let url = "https://interface.yueshichina.com/?act=app&op=goods_special_new&app_id=1002&channel=APPSTORE&client=ios&imei=B2624433-81D9-4205-AF20-892FDBB80EE8&key=898774d9eee50eacaf72470122975d8b&net_type=WIFI&push_id=4627676201928478325&req_time=1494572577981&special_id=\(special_id)&token=&v=2.1.3&version=10.3.1"
baseRequest(url: url) { (response) in
let dict = JSON(response)
let code = dict["code"].intValue
guard code == kSuccessCode else {
SVProgressHUD.showError(withStatus: "请求失败")
return
}
if let dict = dict["datas"].dictionaryObject {
completion(YFSpecialGoodsItem(dict: dict))
}
}
}
/// 获取专题数据
///
/// - Parameters:
/// - special_type: 专题id
/// - completion: 返回专题数据
public func loadSubjectData(_ special_type: String, completion: @escaping ([NSObject]) -> ()) {
let url = "https://interface.yueshichina.com/?act=app&op=special_programa&app_id=1002&channel=APPSTORE&client=ios&curpage=1&imei=B2624433-81D9-4205-AF20-892FDBB80EE8&key=898774d9eee50eacaf72470122975d8b&net_type=WIFI&page=10&push_id=4627676201928478325&req_time=1494992191249&special_type=\(special_type)&token=&v=2.1.3&version=10.3.1"
baseRequest(url: url) { (response) in
let data = JSON(response)
let code = data["code"].intValue
guard code == kSuccessCode else {
SVProgressHUD.showError(withStatus: "请求失败")
return
}
let dict = data["datas"].dictionary
if let items = dict?["article_list"]?.arrayObject {
var arr = [YFSubjectItem]()
for item in items {
arr.append(YFSubjectItem(dict: item as! [String : Any]))
}
completion(arr)
}
if let items = dict?["virtual"]?.arrayObject {
var arr = [YFActiveItem]()
for item in items {
arr.append(YFActiveItem(dict: item as! [String : Any]))
}
completion(arr)
}
}
}
/// 获取店铺数据
///
/// - Parameter completion: 返回
public func loadShopData(_ completion: @escaping (ShopData) -> ()) {
let url = "https://interface.yueshichina.com/?act=goods_cms_special&op=cms_special&app_id=1002&channel=APPSTORE&client=ios&curpage=1&imei=B2624433-81D9-4205-AF20-892FDBB80EE8&key=898774d9eee50eacaf72470122975d8b&net_type=WIFI&push_id=4627676201928478325&req_time=1495435589585&token=&v=2.1.3&version=10.3.1"
baseRequest(url: url) { (response) in
let data = JSON(response)
let code = data["code"].intValue
guard code == kSuccessCode else {
SVProgressHUD.showInfo(withStatus: "")
return
}
if let dict = data["datas"].dictionary {
var shopArr = [YFShopItem]()
var bannerArr = [Banner]()
var classifyArr = [ClassifyItem]()
var channerItem: Channer?
if let shopItems = dict["query"]?.arrayObject {
for item in shopItems {
shopArr.append(YFShopItem(dict: item as! [String : Any]))
}
}
if let bannerItems = dict["banner"]?.arrayObject {
for item in bannerItems {
bannerArr.append(Banner(dict: item as! [String : Any]))
}
}
if let classifyItems = dict["tag_classify"]?.arrayObject {
for item in classifyItems {
classifyArr.append(ClassifyItem(dict: item as! [String : Any]))
}
}
if let channer = dict["channel"]?.dictionaryObject {
channerItem = Channer(dict: channer)
}
completion((shopArr,bannerArr,classifyArr,channerItem!))
}
}
}
}
|
712bf1a484afecd0fbcc22bcd39d582e
| 40.253968 | 343 | 0.552648 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.