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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
JohnnyIsHereNow/POCA
|
refs/heads/master
|
poca/FirstApp/FirstApp/RetrieveUserWithId.swift
|
gpl-2.0
|
1
|
//
// RetrieveUserWithId.swift
// POCA
//
// Created by Alexandru Draghi on 10/06/16.
// Copyright © 2016 Alex. All rights reserved.
//
import UIKit
class RetrieveUserWithId: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
public func retriveUser(userID:Int) -> User
{
let user = User()
var newString = ""
do {
let post:NSString = "userID=\(userID)"
NSLog("PostData: %@",post);
let url:NSURL = NSURL(string:"http://angelicapp.com/POCA/jsonGetUserById.php")!
let postData:NSData = post.dataUsingEncoding(NSASCIIStringEncoding)!
let postLength:NSString = String( postData.length )
let request:NSMutableURLRequest = NSMutableURLRequest(URL: url)
request.HTTPMethod = "POST"
request.cachePolicy = NSURLRequestCachePolicy.ReloadIgnoringCacheData
request.HTTPBody = postData
request.setValue(postLength as String, forHTTPHeaderField: "Content-Length")
request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
request.setValue("application/json", forHTTPHeaderField: "Accept")
var reponseError: NSError?
var response: NSURLResponse?
var urlData: NSData?
do
{
urlData = try NSURLConnection.sendSynchronousRequest(request, returningResponse:&response)
}
catch let error as NSError
{
reponseError = error
urlData = nil
}
if ( urlData != nil )
{
let res = response as! NSHTTPURLResponse!;
//NSLog("Response code: %ld", res.statusCode);
if (res.statusCode >= 200 && res.statusCode < 300)
{
let responseData:NSString = NSString(data:urlData!, encoding:NSUTF8StringEncoding)!
NSLog("Response ==> %@", responseData);
newString = responseData.substringFromIndex(0)
let newStringArr = newString.componentsSeparatedByString("+")
print(newStringArr)
if newStringArr.count != 0
{
user.Name = newStringArr[0]
user.Email = newStringArr[1]
user.Username = newStringArr[2]
user.passion1 = Int(newStringArr[4]) as Int!
user.passion2 = Int(newStringArr[5]) as Int!
user.passion3 = Int(newStringArr[6]) as Int!
}
}
else
{
let alertView:UIAlertView = UIAlertView()
alertView.title = "Update Failed!"
alertView.message = "Connection Failed"
alertView.delegate = self
alertView.addButtonWithTitle("OK")
alertView.show()
}
}
else
{
let alertView:UIAlertView = UIAlertView()
alertView.title = "Update Failed!"
alertView.message = "Connection Failure"
if let error = reponseError
{
alertView.message = (error.localizedDescription)
}
alertView.delegate = self
alertView.addButtonWithTitle("OK")
alertView.show()
}
}
return user;
}
}
|
204342cbb1890fd37132ce0306fb2061
| 35.236364 | 106 | 0.508028 | false | false | false | false |
JosephNK/SwiftyIamport
|
refs/heads/master
|
SwiftyIamportDemo/Controller/WKRemoteViewController.swift
|
mit
|
1
|
//
// WKRemoteViewController.swift
// SwiftyIamportDemo
//
// Created by JosephNK on 29/11/2018.
// Copyright © 2018 JosephNK. All rights reserved.
//
import UIKit
import SwiftyIamport
import WebKit
class WKRemoteViewController: UIViewController {
lazy var wkWebView: WKWebView = {
var view = WKWebView()
view.backgroundColor = UIColor.clear
view.navigationDelegate = self
return view
}()
override func viewDidLoad() {
super.viewDidLoad()
self.view.addSubview(wkWebView)
self.wkWebView.frame = self.view.bounds
// 결제 환경 설정
IAMPortPay.sharedInstance.configure(scheme: "iamporttest") // info.plist에 설정한 scheme
IAMPortPay.sharedInstance
.setWKWebView(self.wkWebView) // 현재 Controller에 있는 WebView 지정
.setRedirectUrl(nil) // m_redirect_url 주소
// ISP 취소시 이벤트 (NicePay만 가능)
IAMPortPay.sharedInstance.setCancelListenerForNicePay { [weak self] in
DispatchQueue.main.async {
let alert = UIAlertController(title: nil, message: "ISP 결제 취소", preferredStyle: UIAlertController.Style.alert)
alert.addAction(UIAlertAction(title: "OK", style: UIAlertAction.Style.default, handler: nil))
self?.present(alert, animated: true, completion: nil)
}
}
// 결제 웹페이지(Remote) 호출
if let url = URL(string: "http://www.iamport.kr/demo") {
let request = URLRequest(url: url)
self.wkWebView.load(request)
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
extension WKRemoteViewController: WKNavigationDelegate {
func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
let request = navigationAction.request
IAMPortPay.sharedInstance.requestRedirectUrl(for: request, parser: { (data, response, error) -> Any? in
// Background Thread 처리
var resultData: [String: Any]?
if let httpResponse = response as? HTTPURLResponse {
let statusCode = httpResponse.statusCode
switch statusCode {
case 200:
resultData = [
"isSuccess": "OK"
]
break
default:
break
}
}
return resultData
}) { (pasingData) in
// Main Thread 처리
}
let result = IAMPortPay.sharedInstance.requestAction(for: request)
decisionHandler(result ? .allow : .cancel)
}
func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
// 결제 환경으로 설정에 의한 웹페이지(Local) 호출 결과
IAMPortPay.sharedInstance.requestIAMPortPayWKWebViewDidFinishLoad(webView) { (error) in
if error != nil {
switch error! {
case .custom(let reason):
print("error: \(reason)")
break
}
}else {
print("OK")
}
}
}
func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) {
print("didFail")
}
func webView(_ webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: Error) {
print("didFailProvisionalNavigation \(error.localizedDescription)")
}
}
|
765d1d4e530f4664ec7233b1d8fd30ab
| 32.290909 | 157 | 0.578099 | false | false | false | false |
SusanDoggie/Doggie
|
refs/heads/main
|
Sources/DoggieGraphics/ApplePlatform/Graphic/CGPattern.swift
|
mit
|
1
|
//
// CGPattern.swift
//
// The MIT License
// Copyright (c) 2015 - 2022 Susan Cheng. 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 canImport(CoreGraphics)
public func CGPatternCreate(
version: UInt32,
bounds: CGRect,
matrix: CGAffineTransform,
xStep: CGFloat,
yStep: CGFloat,
tiling: CGPatternTiling,
isColored: Bool,
callbacks: @escaping (CGContext) -> Void
) -> CGPattern? {
typealias CGPatternCallback = (CGContext) -> Void
let info = UnsafeMutablePointer<CGPatternCallback>.allocate(capacity: 1)
info.initialize(to: callbacks)
let callback = CGPatternCallbacks(version: version, drawPattern: { (info, context) in
guard let callbacks = info?.assumingMemoryBound(to: CGPatternCallback.self).pointee else { return }
callbacks(context)
}, releaseInfo: { info in
guard let info = info?.assumingMemoryBound(to: CGPatternCallback.self) else { return }
info.deinitialize(count: 1)
info.deallocate()
})
return CGPattern(info: info, bounds: bounds, matrix: matrix, xStep: xStep, yStep: yStep, tiling: tiling, isColored: isColored, callbacks: [callback])
}
#endif
|
cef5c0ea27251206d77ee814474be73c
| 37.2 | 153 | 0.70637 | false | false | false | false |
GuiminChu/HishowZone-iOS
|
refs/heads/master
|
HiShow/General/View/ImageViewingController.swift
|
mit
|
1
|
import UIKit
import Kingfisher
class ImageViewingController: UIViewController, UIScrollViewDelegate, UIGestureRecognizerDelegate {
private lazy var scrollView: UIScrollView = {
let view = UIScrollView(frame: self.view.bounds)
view.autoresizingMask = [.flexibleWidth, .flexibleHeight]
view.delegate = self
view.showsHorizontalScrollIndicator = false
view.zoomScale = 1.0
view.maximumZoomScale = 8.0
view.isScrollEnabled = false
return view
}()
private let duration = 0.3
private let zoomScale: CGFloat = 3.0
private let dismissDistance: CGFloat = 100.0
private var image: UIImage!
private var imageView: AnimatedImageView!
private var imageInfo: ImageInfo!
private var startFrame: CGRect!
private var snapshotView: UIView!
private var originalScrollViewCenter: CGPoint = .zero
private var singleTapGestureRecognizer: UITapGestureRecognizer!
private var panGestureRecognizer: UIPanGestureRecognizer!
private var longPressGestureRecognizer: UILongPressGestureRecognizer!
private var doubleTapGestureRecognizer: UITapGestureRecognizer!
init(imageInfo: ImageInfo) {
super.init(nibName: nil, bundle: nil)
self.imageInfo = imageInfo
image = imageInfo.image
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
view.addSubview(scrollView)
let referenceFrameCurrentView = imageInfo.referenceView.convert(imageInfo.referenceRect, to: view)
imageView = AnimatedImageView(frame: referenceFrameCurrentView)
imageView.isUserInteractionEnabled = true
imageView.image = image
// imageView.originalData = imageInfo.originalData // used for gif image
imageView.contentMode = .scaleAspectFill // reset content mode
imageView.backgroundColor = .clear
setupGestureRecognizers()
view.backgroundColor = .black
}
func presented(by viewController: UIViewController) {
view.isUserInteractionEnabled = false
snapshotView = snapshotParentmostViewController(of: viewController)
snapshotView.alpha = 0.1
view.insertSubview(snapshotView, at: 0)
let referenceFrameInWindow = imageInfo.referenceView.convert(imageInfo.referenceRect, to: nil)
view.addSubview(imageView) // will move to scroll view after transition finishes
viewController.present(self, animated: false) {
self.imageView.frame = referenceFrameInWindow
self.startFrame = referenceFrameInWindow
UIView.animate(withDuration: self.duration, delay: 0, options: .beginFromCurrentState, animations: {
self.imageView.frame = self.resizedFrame(forImageSize: self.image.size)
self.imageView.center = CGPoint(x: self.view.bounds.width / 2.0, y: self.view.bounds.height / 2.0)
}, completion: { (_) in
self.scrollView.addSubview(self.imageView)
self.updateScrollViewAndImageView()
self.view.isUserInteractionEnabled = true
})
}
}
private func dismiss() {
view.isUserInteractionEnabled = false
let imageFrame = view.convert(imageView.frame, from: scrollView)
imageView.removeFromSuperview()
imageView.frame = imageFrame
view.addSubview(imageView)
scrollView.removeFromSuperview()
UIView.animate(withDuration: duration, delay: 0, options: .beginFromCurrentState, animations: {
self.imageView.frame = self.startFrame
}) { (_) in
self.dismiss(animated: false, completion: nil)
}
}
// MARK: - Private
private func cancelImageDragging() {
UIView.animate(withDuration: duration, delay: 0, usingSpringWithDamping: 0.7, initialSpringVelocity: 0, options: [.allowUserInteraction, .beginFromCurrentState], animations: {
self.imageView.center = CGPoint(x: self.scrollView.contentSize.width / 2.0, y: self.scrollView.contentSize.height / 2.0)
self.updateScrollViewAndImageView()
self.snapshotView.alpha = 0.1
}, completion: nil)
}
private func setupGestureRecognizers() {
doubleTapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(doubleTap(_:)))
doubleTapGestureRecognizer.numberOfTapsRequired = 2
doubleTapGestureRecognizer.delegate = self
longPressGestureRecognizer = UILongPressGestureRecognizer(target: self, action: #selector(longPress))
longPressGestureRecognizer.delegate = self
singleTapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(singleTap))
singleTapGestureRecognizer.require(toFail: doubleTapGestureRecognizer)
singleTapGestureRecognizer.require(toFail: longPressGestureRecognizer)
singleTapGestureRecognizer.delegate = self
view.addGestureRecognizer(singleTapGestureRecognizer)
view.addGestureRecognizer(longPressGestureRecognizer)
view.addGestureRecognizer(doubleTapGestureRecognizer)
panGestureRecognizer = UIPanGestureRecognizer(target: self, action: #selector(pan(_:)))
panGestureRecognizer.maximumNumberOfTouches = 1
panGestureRecognizer.delegate = self
scrollView.addGestureRecognizer(panGestureRecognizer)
}
private func snapshotParentmostViewController(of viewController: UIViewController) -> UIView {
var snapshot = viewController.view
if var presentingViewController = viewController.view.window!.rootViewController {
while presentingViewController.presentedViewController != nil {
presentingViewController = presentingViewController.presentedViewController!
}
snapshot = presentingViewController.view.snapshotView(afterScreenUpdates: true)
}
return snapshot ?? UIView()
}
private func updateScrollViewAndImageView() {
scrollView.frame = view.bounds
imageView.frame = resizedFrame(forImageSize: image.size)
scrollView.contentSize = imageView.frame.size
scrollView.contentInset = contentInsetForScrollView(withZoomScale: scrollView.zoomScale)
}
private func contentInsetForScrollView(withZoomScale zoomScale: CGFloat) -> UIEdgeInsets {
let boundsWidth = scrollView.bounds.width
let boundsHeight = scrollView.bounds.height
let contentWidth = image.size.width
let contentHeight = image.size.height
var minContentHeight: CGFloat!
var minContentWidth: CGFloat!
if (contentHeight / contentWidth) < (boundsHeight / boundsWidth) {
minContentWidth = boundsWidth
minContentHeight = minContentWidth * (contentHeight / contentWidth)
} else {
minContentHeight = boundsHeight
minContentWidth = minContentHeight * (contentWidth / contentHeight)
}
minContentWidth = minContentWidth * zoomScale
minContentHeight = minContentHeight * zoomScale
let hDiff = max(boundsWidth - minContentWidth, 0)
let vDiff = max(boundsHeight - minContentHeight, 0)
let inset = UIEdgeInsets(top: vDiff / 2.0, left: hDiff / 2.0, bottom: vDiff / 2.0, right: hDiff / 2.0)
return inset
}
private func resizedFrame(forImageSize size: CGSize) -> CGRect {
guard size.width > 0, size.height > 0 else {
return .zero
}
var frame = view.bounds
let nativeWidth = size.width
let nativeHeight = size.height
var targetWidth = frame.width * scrollView.zoomScale
var targetHeight = frame.height * scrollView.zoomScale
if (targetHeight / targetWidth) < (nativeHeight / nativeWidth) {
targetWidth = targetHeight * (nativeWidth / nativeHeight)
} else {
targetHeight = targetWidth * (nativeHeight / nativeWidth)
}
frame = CGRect(x: 0, y: 0, width: targetWidth, height: targetHeight)
return frame
}
// MARK: - Gesture Recognizer Actions
@objc
private func singleTap() {
dismiss()
}
@objc
private func pan(_ sender: UIPanGestureRecognizer) {
let translation = sender.translation(in: sender.view)
let translationDistance = sqrt(pow(translation.x, 2) + pow(translation.y, 2))
switch sender.state {
case .began:
originalScrollViewCenter = scrollView.center
case .changed:
scrollView.center = CGPoint(x: originalScrollViewCenter.x + translation.x, y: originalScrollViewCenter.y + translation.y)
snapshotView.alpha = min(max(translationDistance / dismissDistance * 0.5, 0.1), 0.6)
default:
if translationDistance > dismissDistance {
dismiss()
} else {
cancelImageDragging()
}
}
}
@objc
private func longPress() {
let activityViewController = UIActivityViewController(activityItems: [image], applicationActivities: nil)
present(activityViewController, animated: true, completion: nil)
}
@objc
private func doubleTap(_ sender: UITapGestureRecognizer) {
let rawLocation = sender.location(in: sender.view)
let point = scrollView.convert(rawLocation, from: sender.view)
var targetZoomRect: CGRect
var targetInsets: UIEdgeInsets
if scrollView.zoomScale == 1.0 {
let zoomWidth = view.bounds.width / zoomScale
let zoomHeight = view.bounds.height / zoomScale
targetZoomRect = CGRect(x: point.x - zoomWidth * 0.5, y: point.y - zoomHeight * 0.5, width: zoomWidth, height: zoomHeight)
targetInsets = contentInsetForScrollView(withZoomScale: zoomScale)
} else {
let zoomWidth = view.bounds.width * scrollView.zoomScale
let zoomHeight = view.bounds.height * scrollView.zoomScale
targetZoomRect = CGRect(x: point.x - zoomWidth * 0.5, y: point.y - zoomHeight * 0.5, width: zoomWidth, height: zoomHeight)
targetInsets = contentInsetForScrollView(withZoomScale: 1.0)
}
view.isUserInteractionEnabled = false
CATransaction.begin()
CATransaction.setCompletionBlock {
self.scrollView.contentInset = targetInsets
self.view.isUserInteractionEnabled = true
}
scrollView.zoom(to: targetZoomRect, animated: true)
CATransaction.commit()
}
// MARK: - UIGestureRecognizerDelegate
func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool {
if gestureRecognizer == panGestureRecognizer, scrollView.zoomScale != 1.0 {
return false
}
return true
}
// MARK: - UIScrollViewDelegate
func viewForZooming(in scrollView: UIScrollView) -> UIView? {
return imageView
}
func scrollViewDidZoom(_ scrollView: UIScrollView) {
scrollView.contentInset = contentInsetForScrollView(withZoomScale: scrollView.zoomScale)
scrollView.isScrollEnabled = true
}
func scrollViewDidEndZooming(_ scrollView: UIScrollView, with view: UIView?, atScale scale: CGFloat) {
scrollView.isScrollEnabled = (scale > 1)
scrollView.contentInset = contentInsetForScrollView(withZoomScale: scale)
}
}
struct ImageInfo {
var image: UIImage!
var originalData: Data?
var referenceRect: CGRect!
var referenceView: UIView!
}
|
26b4ad05387287494bcae6a879df9015
| 42.568266 | 183 | 0.672567 | false | false | false | false |
RizanHa/RHImgPicker
|
refs/heads/master
|
RHImgPicker/Classes/Models/AlbumTableViewDataSource.swift
|
mit
|
1
|
// The MIT License (MIT)
//
// Copyright (c) 2016 Rizan Hamza
//
// 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.
//
// AlbumTableViewDataSource.swift
// Pods
//
// Created by rizan on 27/08/2016.
//
//
import UIKit
import Photos
fileprivate enum AlbumPreviewImageIndex : Int {
case imgNotFound = -1
case img1 = 0
case img2 = 1
case img3 = 2
}
final class AlbumTableViewDataSource : NSObject, UITableViewDataSource {
class func registerCellIdentifiersForTableView(_ tableView: UITableView?) {
tableView?.register(AlbumCell.self, forCellReuseIdentifier: AlbumCell.IDENTIFIER)
}
fileprivate struct AlbumData {
var albumTitle : String?
var img1 : UIImage?
var img2 : UIImage?
var img3 : UIImage?
}
let fetchResults: [PHFetchResult<AnyObject>]
let settings: RHImgPickerSettings?
fileprivate var DATACach : [AlbumData] = []
fileprivate func dataCachIndexForAlbum(_ albumTitle : String?) -> AlbumPreviewImageIndex {
var ObjIndex : AlbumPreviewImageIndex = .imgNotFound
for (idx,data) in DATACach.enumerated() {
if data.albumTitle == albumTitle {
let index = min(idx, AlbumPreviewImageIndex.img3.rawValue)
if let oj = AlbumPreviewImageIndex(rawValue: idx) {
ObjIndex = oj
}
break
}
}
return ObjIndex
}
fileprivate func updataDATACach(_ albumTitle : String?, img : UIImage?, imgIndex : AlbumPreviewImageIndex) {
if albumTitle == nil {
return
}
let objIndex = dataCachIndexForAlbum(albumTitle)
if (objIndex != .imgNotFound ) {
var data = DATACach[objIndex.rawValue]
DATACach.remove(at: objIndex.rawValue)
switch imgIndex {
case .img1:
data.img1 = img
break
case .img2:
data.img2 = img
break
case .img3:
data.img3 = img
break
default:
break
}
DATACach.append(data)
}
}
init(fetchResults: [PHFetchResult<AnyObject>], settings: RHImgPickerSettings?) {
self.fetchResults = fetchResults
self.settings = settings
super.init()
}
func numberOfSections(in tableView: UITableView) -> Int {
return fetchResults.count
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return fetchResults[section].count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
UIView.setAnimationsEnabled(false)
let cell = tableView.dequeueReusableCell(withIdentifier: AlbumCell.IDENTIFIER, for: indexPath) as! AlbumCell
cell.layoutCell()
let cachingManager = PHCachingImageManager.default() as? PHCachingImageManager
cachingManager?.allowsCachingHighQualityImages = false
// Fetch album
if let album = fetchResults[(indexPath as NSIndexPath).section][(indexPath as NSIndexPath).row] as? PHAssetCollection {
// Title
cell.albumTitleLabel.text = album.localizedTitle
// check for album preview cash DATA
let objIndex = dataCachIndexForAlbum(album.localizedTitle)
if (objIndex != .imgNotFound ) {
let data = DATACach[objIndex.rawValue]
cell.albumTitleLabel.text = data.albumTitle
cell.firstImageView.image = data.img1
cell.secondImageView.image = data.img2
cell.thirdImageView.image = data.img3
UIView.setAnimationsEnabled(true)
return cell
}
// request Album preview DATA
let fetchOptions = PHFetchOptions()
fetchOptions.sortDescriptors = [
NSSortDescriptor(key: "creationDate", ascending: false)
]
fetchOptions.predicate = NSPredicate(format: "mediaType = %d", PHAssetMediaType.image.rawValue)
let result = PHAsset.fetchAssets(in: album, options: fetchOptions)
result.enumerateObjects( { (object, idx, stop) in
if let asset = object as? PHAsset {
let imageSize = CGSize(width: 80, height: 80)
let imageContentMode: PHImageContentMode = .aspectFill
switch idx {
case AlbumPreviewImageIndex.img1.rawValue:
PHCachingImageManager.default().requestImage(for: asset, targetSize: imageSize, contentMode: imageContentMode, options: nil) { (result, _) in
cell.firstImageView.image = result
self.updataDATACach(album.localizedTitle, img: cell.firstImageView.image, imgIndex: .img1)
}
case AlbumPreviewImageIndex.img2.rawValue:
PHCachingImageManager.default().requestImage(for: asset, targetSize: imageSize, contentMode: imageContentMode, options: nil) { (result, _) in
cell.secondImageView.image = result
self.updataDATACach(album.localizedTitle, img: cell.secondImageView.image, imgIndex: .img2)
}
case AlbumPreviewImageIndex.img3.rawValue:
PHCachingImageManager.default().requestImage(for: asset, targetSize: imageSize, contentMode: imageContentMode, options: nil) { (result, _) in
cell.thirdImageView.image = result
self.updataDATACach(album.localizedTitle, img: cell.thirdImageView.image, imgIndex: .img3)
}
default:
// Stop enumeration
stop.initialize(to: true)
}
}
})
}
let newData : AlbumData = AlbumData(albumTitle: cell.albumTitleLabel.text, img1: cell.firstImageView.image, img2: cell.secondImageView.image, img3: cell.thirdImageView.image)
self.DATACach.append(newData)
UIView.setAnimationsEnabled(true)
return cell
}
}
|
27baf31dde1cfac38c07a857d8df2fc3
| 31.595142 | 182 | 0.564154 | false | false | false | false |
tensorflow/examples
|
refs/heads/master
|
lite/examples/pose_estimation/ios/PoseEstimation/Camera/CameraFeedManager.swift
|
apache-2.0
|
1
|
// Copyright 2021 The TensorFlow Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// =============================================================================
import AVFoundation
import Accelerate.vImage
import UIKit
/// Delegate to receive the frames captured from the device's camera.
protocol CameraFeedManagerDelegate: AnyObject {
/// Callback method that receives frames from the camera.
/// - Parameters:
/// - cameraFeedManager: The CameraFeedManager instance which calls the delegate.
/// - pixelBuffer: The frame received from the camera.
func cameraFeedManager(
_ cameraFeedManager: CameraFeedManager, didOutput pixelBuffer: CVPixelBuffer)
}
/// Manage the camera pipeline.
final class CameraFeedManager: NSObject, AVCaptureVideoDataOutputSampleBufferDelegate {
/// Delegate to receive the frames captured by the device's camera.
var delegate: CameraFeedManagerDelegate?
override init() {
super.init()
configureSession()
}
/// Start capturing frames from the camera.
func startRunning() {
captureSession.startRunning()
}
/// Stop capturing frames from the camera.
func stopRunning() {
captureSession.stopRunning()
}
let captureSession = AVCaptureSession()
/// Initialize the capture session.
private func configureSession() {
captureSession.sessionPreset = AVCaptureSession.Preset.photo
guard
let backCamera = AVCaptureDevice.default(
.builtInWideAngleCamera, for: .video, position: .back)
else {
return
}
do {
let input = try AVCaptureDeviceInput(device: backCamera)
captureSession.addInput(input)
} catch {
return
}
let videoOutput = AVCaptureVideoDataOutput()
videoOutput.videoSettings = [
(kCVPixelBufferPixelFormatTypeKey as String): NSNumber(value: kCVPixelFormatType_32BGRA)
]
videoOutput.alwaysDiscardsLateVideoFrames = true
let dataOutputQueue = DispatchQueue(
label: "video data queue",
qos: .userInitiated,
attributes: [],
autoreleaseFrequency: .workItem)
if captureSession.canAddOutput(videoOutput) {
captureSession.addOutput(videoOutput)
videoOutput.connection(with: .video)?.videoOrientation = .portrait
captureSession.startRunning()
}
videoOutput.setSampleBufferDelegate(self, queue: dataOutputQueue)
}
// MARK: Methods of the AVCaptureVideoDataOutputSampleBufferDelegate
func captureOutput(
_ output: AVCaptureOutput, didOutput sampleBuffer: CMSampleBuffer,
from connection: AVCaptureConnection
) {
guard let pixelBuffer = CMSampleBufferGetImageBuffer(sampleBuffer) else {
return
}
CVPixelBufferLockBaseAddress(pixelBuffer, CVPixelBufferLockFlags.readOnly)
delegate?.cameraFeedManager(self, didOutput: pixelBuffer)
CVPixelBufferUnlockBaseAddress(pixelBuffer, CVPixelBufferLockFlags.readOnly)
}
}
|
985dbaed69b8cb7f1a68f6d7ba8c910c
| 32.980198 | 94 | 0.722028 | false | false | false | false |
CodaFi/swift-compiler-crashes
|
refs/heads/master
|
crashes-fuzzing/22685-no-stacktrace.swift
|
mit
|
11
|
// Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
class A {
init("cd"A<T: (v: c> U)
class a {
class A<T : A {
typealias f : where g<T
func f: e: a {
{
}
}
{
{
class A {
{
}
}
struct B<b() -> ( )
}
}
}
{
struct c : T
func a
let h == b
-> = b
{
}
class c<T : T: d: A<I : d {
let : a = B)
{
}
enum A {
struct Q<T: A<T where g
enum S {
{
let h = b
class a
let i: A {
"
class B {
struct B : T) {
{
A {
struct Q<T.g = b(c<T) {
{
{
e {
}
protocol A {
}
var d = 1
struct Q<T : B<T where g: B)
println(f<T where g
}
class B : where h> ()
var a<T : T where g
class d>
}
}
var d {
func a
}
let : C {
struct B {
A ) -> {
class A {
struct c : c<T) {
}
{
}
{
struct B {
class c
}
init(object2: e.B<T) -> {
init(f: T: e
{
class a {
}
}
println(T! {
{
{
{
println() -> ( ( ) -> {
{
init("])
struct Q<T where g<T.h
class A ) {
}
class b {
class B {
class c<b
}
}
v
class C(a
var d = {
init < {
func b<d: a {
init(A
typealias f : B<h: A {
{
var d = b> U>
{
}
}
}
}
var d {
struct B {
enum a<T: a {
}
}
{
let h = b("
let h = 1
class B<T: T where g: A : T) {
init() -> {
struct B {
{
{
func f<T where H : c> ( )
class d<T where g: a {
}
}
-> = [T where k : A {
let i: d {
{
{
{
enum A {
{
protocol a {
}
var f : C {
class a<T : A {
extension {
}
let a {
}
{
class a: A {
typealias e {
}
class B? {
typealias b {
}
class d: C {
class B<b() {
let i( )
}
class B {
}
class B<b(f<T where g: C {
}
class d
class B : (A
init(f<T where h
}
class c<T where g
let i: d {
enum S : a {
struct B<T where g
struct B<T where h
var f : b<T) {
{
}
{
init(f<T.h == e: a {
enum A {
enum A {
func c<S : a {
}
A {
let : T>
typealias b {
struct Q<d
var f : A<T : A {
{
struct Q<b> {
struct B<U>])
class d>
println(a: A {
class B<T where g
var e
{
class B<T) -> {
func i: NSObject {
init() -> {
struct g: T, A {
let start = c
class d
enum S : e
{
init < {
}
{
}
class A {
class B : a {
init(f<T where g
func a
protocol a = b(T) -> {
}
class b : (f: d<h: a = B<T where g
{
{
"
let h = b<d: (
|
095467328801638cd0096e3014b40bac
| 8.70892 | 87 | 0.523694 | false | false | false | false |
OctMon/OMExtension
|
refs/heads/master
|
OMExtension/OMExtension/Source/Foundation/OMInt.swift
|
mit
|
1
|
//
// OMInt.swift
// OMExtension
//
// The MIT License (MIT)
//
// Copyright (c) 2016 OctMon
//
// 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
#if !os(macOS)
import UIKit
#endif
public extension Int {
struct OM {
public static func random(_ range: Range<Int>) -> Int {
return random(range.lowerBound, range.upperBound - 1)
}
public static func random(_ range: ClosedRange<Int>) -> Int {
return random(range.lowerBound, range.upperBound)
}
public static func random(_ lower: Int = 0, _ upper: Int = 9) -> Int {
return lower + Int(arc4random_uniform(UInt32(upper - lower + 1)))
}
}
}
public extension Int {
var omToString: String {
return String(self)
}
var omToDouble: Double {
return Double(self)
}
var omToFloat: Float {
return Float(self)
}
var omToCGFloat: CGFloat {
return CGFloat(self)
}
var omIsEven: Bool {
return (self % 2 == 0)
}
var omIsOdd: Bool {
return !omIsEven
}
var omAbs: Int {
return abs(self)
}
var omLocaleCurrency: String {
let formatter = NumberFormatter()
formatter.numberStyle = .currency
formatter.locale = Locale.current
return formatter.string(from: self as NSNumber)!
}
}
|
4d4ec38b1886ea75372bae804040f745
| 25.323232 | 82 | 0.610898 | false | false | false | false |
xilosada/TravisViewerIOS
|
refs/heads/master
|
TVModel/RepositoryEntity.swift
|
mit
|
1
|
//
// RepositoryEntity.swift
// TravisViewerIOS
//
// Created by X.I. Losada on 04/02/16.
// Copyright © 2016 XiLosada. All rights reserved.
//
import Foundation
public struct RepositoryEntity {
public let id: Int
public let slug: String
public let description: String
public var builds = [BuildEntity]()
init(id: Int, slug: String, description: String) {
self.id = id
self.slug = slug
self.description = description
}
}
extension RepositoryEntity {
init?(dictionary: NSDictionary) {
guard let id = dictionary["id"] as? Int,
slug = dictionary["slug"] as? String,
description = dictionary["description"] as? String
else{
return nil
}
self.id = id
self.slug = slug
if description.isEmpty {
self.description = "Description not provided"
}else {
self.description = description
}
}
struct Mapper{
static func parseJSONArray(jsonArray: [AnyObject]) throws -> [RepositoryEntity] {
var repos = [RepositoryEntity]()
print(jsonArray)
try jsonArray.forEach { jsonObject in
if let repoDictionary = jsonObject as? NSDictionary {
if let repo = RepositoryEntity(dictionary: repoDictionary){
repos.append(repo)
}
} else {
throw NSError(domain: "repo mapper", code: 0, userInfo: nil)
}
}
return repos
}
}
}
|
ed1a90289be412903a982e9a414bdb5a
| 26.338983 | 89 | 0.549007 | false | false | false | false |
jigneshsheth/Datastructures
|
refs/heads/master
|
DataStructure/DataStructure/Cards/Card.swift
|
mit
|
1
|
//
// Card.swift
// DataStructure
//
// Created by Jigs Sheth on 3/21/16.
// Copyright © 2016 jigneshsheth.com. All rights reserved.
//
import Foundation
public class Card {
class public func shuffle<T>(input:[T]) -> [T]{
var input:[T] = input
let len = input.count
for i in 0..<len{
let index = Int(arc4random_uniform((UInt32(len - i))))
let temp = input[i]
input[i] = input[index]
input[index] = temp
}
return input
}
}
|
fdce6db3d8c6d849d329faaf21d7a209
| 16.814815 | 60 | 0.592516 | false | false | false | false |
wjk930726/weibo
|
refs/heads/master
|
weiBo/weiBo/iPhone/Modules/Compose/EmotionKeyboard/WBEmotionKeyboardCell.swift
|
mit
|
1
|
//
// WBEmotionKeyboardCell.swift
// weiBo
//
// Created by 王靖凯 on 2016/12/5.
// Copyright © 2016年 王靖凯. All rights reserved.
//
import UIKit
fileprivate let basetag: Int = 4526
class WBEmotionKeyboardCell: UICollectionViewCell {
var model: [WBEmotionModel]? {
didSet {
guard let emotions = model else {
return
}
for item in emotions.enumerated() {
let tag = item.offset + basetag
let model = item.element
guard let btn = viewWithTag(tag) as? UIButton else {
print("tag is error")
return
}
if model.type == 0 {
guard let png = model.fullPath else {
print("png is error")
return
}
btn.setTitle(nil, for: .normal)
btn.setImage(UIImage(named: png), for: .normal)
} else {
guard let emoji = model.code else {
print("emoji is error")
return
}
btn.setTitle(String.emoji(stringCode: emoji), for: .normal)
// let str = String.emoji(stringCode: emoji)
// print(str,emoji)
btn.setImage(nil, for: .normal)
}
}
}
}
override init(frame: CGRect) {
super.init(frame: frame)
setupView()
}
required init?(coder _: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
extension WBEmotionKeyboardCell {
fileprivate func setupView() {
let witdhHeight = (screenWidth / 7)
let space = (bounds.size.height - 3 * witdhHeight) / 2
let frame = CGRect(x: 0, y: 0, width: witdhHeight, height: witdhHeight)
for i in 0 ..< 21 {
let btn = UIButton(title: nil, target: self, action: #selector(insertOrDelete(sender:)))
let dx = CGFloat(i % 7)
let dy = CGFloat(i / 7)
btn.frame = frame.offsetBy(dx: dx * witdhHeight, dy: dy * (witdhHeight + space))
if i == 20 {
btn.setImage(#imageLiteral(resourceName: "compose_emotion_delete"), for: .normal)
btn.setImage(#imageLiteral(resourceName: "compose_emotion_delete_highlighted"), for: .highlighted)
}
btn.tag = basetag + i
btn.titleLabel?.font = UIFont.systemFont(ofSize: 34)
contentView.addSubview(btn)
}
}
}
extension WBEmotionKeyboardCell {
@objc fileprivate func insertOrDelete(sender: UIButton) {
let index = sender.tag - basetag
var isDelete: Bool = false
var userInfo: [String: Any] = [:]
if index == 20 {
isDelete = true
userInfo = ["isDelete": isDelete]
} else {
isDelete = false
let emotion = model![index]
userInfo = ["isDelete": isDelete, "emotion": emotion]
}
let notification = Notification(name: addOrDeleteNotification, object: nil, userInfo: userInfo)
NotificationCenter.default.post(notification)
}
}
|
909c68f7c0b36ffe1375eb78102356ce
| 32.854167 | 114 | 0.521846 | false | false | false | false |
humberaquino/bufpeek
|
refs/heads/master
|
Bufpeek/BufpeekError.swift
|
mit
|
1
|
import Foundation
// Error domains, codes and utility functions
public class BufpeekError {
struct Code {
// OAuth
static let FailedOAuth = 1000
static let OAuthMissingAccessToken = 1001
static let OAuthInvalidResponse = 1002
static let TokenNotAvailable = 1003
// Mapping
static let MappingError = 2000
// Fetching
static let MultipleFetchError = 3000
}
struct Domain {
static let OAuth = "OAuth"
static let Mapping = "Mapping"
static let Fetching = "Fetching"
}
public class func authErrorWithMessage(msg: String) -> NSError {
let userInfo = [NSLocalizedDescriptionKey: msg]
let error = NSError(domain: Domain.OAuth, code: Code.FailedOAuth, userInfo: userInfo)
return error
}
public class func accessTokenNotFoundInResponse(json: NSDictionary) -> NSError {
let msg = "JSON response does not contain 'access_token' element"
let userInfo = [NSLocalizedDescriptionKey: msg]
let error = NSError(domain: Domain.OAuth, code: Code.OAuthMissingAccessToken, userInfo: userInfo)
return error
}
public class func responseDataNotJSON(obj: AnyObject?) -> NSError {
let msg = "Response is not a dictionary: \(obj)"
let userInfo = [NSLocalizedDescriptionKey: msg]
let error = NSError(domain: Domain.OAuth, code: Code.OAuthInvalidResponse, userInfo: userInfo)
return error
}
public class func mappingError(json: String, className: String) -> NSError {
let msg = "Error while trying to map \(className)"
let userInfo = [NSLocalizedDescriptionKey: msg]
let error = NSError(domain: Domain.Mapping, code: Code.MappingError, userInfo: userInfo)
return error
}
public class func multipleFetchError(msg: String) -> NSError {
let userInfo = [NSLocalizedDescriptionKey: msg]
let error = NSError(domain: Domain.Fetching, code: Code.MultipleFetchError, userInfo: userInfo)
return error
}
public class func tokenNotAvailable() -> NSError {
let msg = "Token not available. Probably the user is not logged in"
let userInfo = [NSLocalizedDescriptionKey: msg]
let error = NSError(domain: Domain.OAuth, code: Code.TokenNotAvailable, userInfo: userInfo)
return error
}
}
|
6e64d5e9554945a007fc35a5a63052d5
| 34.882353 | 105 | 0.653137 | false | false | false | false |
JiongXing/PhotoBrowser
|
refs/heads/master
|
Example/Example/ImageSmoothZoomViewController.swift
|
mit
|
1
|
//
// LocalImageSmoothZoomViewController.swift
// Example
//
// Created by JiongXing on 2019/11/28.
// Copyright © 2019 JiongXing. All rights reserved.
//
import UIKit
import JXPhotoBrowser
class ImageSmoothZoomViewController: BaseCollectionViewController {
override class func name() -> String { "更丝滑的Zoom转场动画" }
override class func remark() -> String { "需要用户自己创建并提供转场视图,以及缩略图位置" }
override func makeDataSource() -> [ResourceModel] {
makeLocalDataSource()
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.jx.dequeueReusableCell(BaseCollectionViewCell.self, for: indexPath)
cell.imageView.image = self.dataSource[indexPath.item].localName.flatMap { UIImage(named: $0) }
// 等比拉伸,填满视图
cell.imageView.contentMode = .scaleAspectFill
return cell
}
override func openPhotoBrowser(with collectionView: UICollectionView, indexPath: IndexPath) {
let browser = JXPhotoBrowser()
browser.numberOfItems = {
self.dataSource.count
}
browser.reloadCellAtIndex = { context in
let browserCell = context.cell as? JXPhotoBrowserImageCell
let indexPath = IndexPath(item: context.index, section: indexPath.section)
browserCell?.imageView.image = self.dataSource[indexPath.item].localName.flatMap { UIImage(named: $0) }
}
// 更丝滑的Zoom动画
browser.transitionAnimator = JXPhotoBrowserSmoothZoomAnimator(transitionViewAndFrame: { (index, destinationView) -> JXPhotoBrowserSmoothZoomAnimator.TransitionViewAndFrame? in
let path = IndexPath(item: index, section: indexPath.section)
guard let cell = collectionView.cellForItem(at: path) as? BaseCollectionViewCell else {
return nil
}
let image = cell.imageView.image
let transitionView = UIImageView(image: image)
transitionView.contentMode = cell.imageView.contentMode
transitionView.clipsToBounds = true
let thumbnailFrame = cell.imageView.convert(cell.imageView.bounds, to: destinationView)
return (transitionView, thumbnailFrame)
})
browser.pageIndex = indexPath.item
browser.show(method: .push(inNC: nil))
}
}
|
e81e56bee213a17136b9c3c4a2136c7c
| 42.436364 | 183 | 0.68648 | false | false | false | false |
Diederia/project
|
refs/heads/master
|
Diederick-Calkoen-Project/CollectionViewController.swift
|
mit
|
1
|
//
// CollectionViewController.swift
// Diederick-Calkoen-Project
//
// Created by Diederick Calkoen on 12/01/17.
// Copyright © 2017 Diederick Calkoen. All rights reserved.
//
// This view controller shows the schedule of the calendar day. As stundent, teacher or admin user you could schedule yourself in the collection view. All the data of the collection view is saved in FireBase.
import UIKit
import Firebase
class CollectionViewController: UIViewController {
// MARK: - outlets
@IBOutlet weak var collectionView: UICollectionView!
@IBOutlet weak var dateLabel: UILabel!
// MARK: - Constants and variables
let dateCellIdentifier = "DateCellIdentifier"
let contentCellIdentifier = "ContentCellIdentifier"
let timeSlots:[String] = ["9:00","9:30","10:00","10:30","11:00","11:30","12:00","12:30","13:00",
"13:30","14:00","14:30","15:00","15:30","16:00","16:30","17:00","17:30",
"18:00","18:30","19:00","19:30","20:00","20:30","21:00","21:30","22:00"]
let hours:[String] = [" 1 uur ", " 1½ uur " , " 2 uur ", " 2½ uur "," 3 uur "," 3½ uur ",
" 4 uur", "4½ uur", " 5 uur ", " 5½ uur ", " 6 uur ", " 6½ uur ",
" 7 uur ", " 7½ uur ", " 8 uur ", " 8½ uur ", " 9 uur "]
var pickerMenu: UIPickerView = UIPickerView()
var sampleSegment: UISegmentedControl = UISegmentedControl ()
var alertController: UIAlertController = UIAlertController()
var selectedRow: Int = 2
var selectedItem = IndexPath()
var ref = FIRDatabase.database().reference()
var userId = String()
var userStatus = Int()
var userData = [String:AnyObject]()
// MARK: - Colors
let colorDictionary: [String:UIColor] = ["lightWhite": UIColor(red: 255/255.0, green: 255/255.0, blue: 255/255.0, alpha: 1),
"greyWhite": UIColor(red: 242/255.0, green: 242/255.0, blue: 242/255.0, alpha: 1),
"green": UIColor(red: 0/255.0, green: 240/255.0, blue: 20/255.0, alpha: 1),
"lightGreen": UIColor(red: 0/255.0, green: 200/255.0, blue: 20/255.0, alpha: 0.3),
"greyGreen": UIColor(red: 0/255.0, green: 200/255.0, blue: 20/255.0, alpha: 0.5),
"lightRed": UIColor(red: 230/255.0, green: 20/255.0, blue: 20/255.0, alpha: 0.3),
"greyRed": UIColor(red: 230/255.0, green: 20/255.0, blue: 20/255.0, alpha: 0.5)]
let white = UIColor(red: 255/255.0, green: 255/255.0, blue: 255/255.0, alpha: 1)
let black = UIColor(red: 0/255.0, green: 0/255.0, blue: 0/255.0, alpha: 1)
let pink = UIColor(red: 225/255.0, green: 0/255.0, blue: 122/255.0, alpha: 1.0)
// MARK: - Override functions
override func viewDidLoad()
{
super.viewDidLoad()
setupCollectionView()
setupPickerView()
}
override func encodeRestorableState(with coder: NSCoder) {
coder.encode(CalendarDay.dataOfDate, forKey: "data")
coder.encode(CalendarDay.calendarDayDate, forKey: "date")
super.encodeRestorableState(with: coder)
}
override func decodeRestorableState(with coder: NSCoder) {
CalendarDay.dataOfDate = coder.decodeObject(forKey: "data") as! [(String) : String]
dateLabel.text = coder.decodeObject(forKey: "date") as! String?
collectionView.reloadData()
super.decodeRestorableState(with: coder)
}
// MARk: - Functions
// Setup all items for the use of the collection view.
func setupCollectionView() {
dateLabel.text = CalendarDay.calendarDayDate
collectionView.layer.borderWidth = 2
collectionView.layer.borderColor = self.pink.cgColor
userData = UserDefaults.standard.value(forKey: "userData") as! [String : AnyObject]
self.userId = userData["id"] as! String
self.userStatus = userData["userStatus"] as! Int
self.collectionView .register(UINib(nibName: "DateCollectionViewCell", bundle: nil), forCellWithReuseIdentifier: dateCellIdentifier)
self.collectionView .register(UINib(nibName: "ContentCollectionViewCell", bundle: nil), forCellWithReuseIdentifier: contentCellIdentifier)
}
// Function to setup the picker view for the input of the user.
func setupPickerView () {
pickerMenu = UIPickerView(frame: CGRect(x: 10.0, y: 40.0, width: 250, height: 170))
pickerMenu.delegate = self;
pickerMenu.dataSource = self;
pickerMenu.showsSelectionIndicator = true
pickerMenu.tintColor = UIColor.red
pickerMenu.reloadAllComponents()
}
// Function to handle all the parameters to configurate the cell of the collection view.
func configurateCell(indexPath: IndexPath, contentCell: Bool, text: String, colorString: String) -> UICollectionViewCell {
if contentCell == true {
let cell = collectionView .dequeueReusableCell(withReuseIdentifier: contentCellIdentifier, for: indexPath) as! ContentCollectionViewCell
cell.contentLabel.textColor = self.black
cell.contentLabel.text = text
cell.backgroundColor = self.getColor(indexPath: indexPath, colorString: colorString)
return cell
} else {
let cell = collectionView .dequeueReusableCell(withReuseIdentifier: dateCellIdentifier, for: indexPath) as! DateCollectionViewCell
cell.dateLabel.textColor = self.black
cell.dateLabel.text = text
cell.backgroundColor = self.getColor(indexPath: indexPath, colorString: colorString)
return cell
}
}
// Function the get the right background color of the cell.
func getColor(indexPath: IndexPath, colorString: String) -> UIColor {
var color = UIColor()
if colorString == "green" || colorString == "white" {
color = self.colorDictionary[colorString]!
} else {
if indexPath.section % 2 != 0 {
color = self.colorDictionary["grey" + colorString]!
} else {
color = self.colorDictionary["light" + colorString]!
}
}
return color
}
func reloadCollectionView() {
self.collectionView.reloadData()
}
// Function to convert the index path to a string without brackets for FireBase.
func convertIndexPath (indexPath: IndexPath) -> String {
var stringIndexPath = String(describing: indexPath)
stringIndexPath = stringIndexPath.replacingOccurrences(of: "[", with: "")
stringIndexPath = stringIndexPath.replacingOccurrences(of: "]", with: "")
return stringIndexPath
}
// Function for an alert.
func alert(title: String, message: String) {
alertController = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.alert)
alertController.addAction(UIAlertAction(title: "Terug", style: UIAlertActionStyle.default,handler: nil))
self.present(alertController, animated: true, completion: nil)
}
// Function for an alert with a picker view.
func alertWithPickerMenu(title: String, message: String, user: Int) {
alertController = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.alert)
alertController.view.addSubview(pickerMenu)
alertController.addAction(UIAlertAction(title: "Terug", style: UIAlertActionStyle.default,handler: nil))
alertController.addAction(UIAlertAction(title: "Ja",style: UIAlertActionStyle.default, handler: {
(_)in
if user == 0 {
self.studentPickerView()
} else if user == 1 {
self.teacherPickerView()
} else {
self.adminPickerView()
}
}))
self.present(alertController, animated: true, completion: nil)
}
// Remove teacher id from the database when all hours are deleted.
func removeTeacherId(){
for i in 1...17 {
let indexPath = (String(i) + ", " + String(self.selectedItem.row))
if CalendarDay.dataOfDate[indexPath] != nil {
return
}
}
CalendarDay.dataOfDate.removeValue(forKey: String(0) + ", " + String(self.selectedItem.row))
}
// The picker view function when a teacher clicks on a cell.
func teacherPickerView() {
// check the request is within the schedule
guard self.selectedItem.section + self.selectedRow <= 28 else {
self.alert(title: "Error", message: "Plan de uren binnen de roostertijden.")
return
}
// place the use id in the cells
CalendarDay.dataOfDate["0, " + String(self.selectedItem.row)] = self.userId
for i in 0...self.selectedRow - 1 {
let indexPath = IndexPath(row: self.selectedItem.row, section: self.selectedItem.section + i)
let stringIndexPath = self.convertIndexPath(indexPath: indexPath)
CalendarDay.dataOfDate[stringIndexPath] = "Vrij"
}
// save the data of the day in FireBase
self.ref.child("data").child(CalendarDay.calendarDayDate).setValue(CalendarDay.dataOfDate)
self.collectionView.reloadData()
}
// The picker view function when a student clicks on a cell.
func studentPickerView() {
// check if the request is within the schedule
guard self.selectedItem.section + self.selectedRow <= 28 else {
self.alert(title: "Error", message: "Plan de uren binnen de roostertijden.")
return
}
let section = self.selectedItem.section + self.selectedRow - 1
let indexPath = IndexPath(row: self.selectedItem.row, section: section)
let cell = self.collectionView.cellForItem(at: indexPath) as! ContentCollectionViewCell
// check if teacher is avaible for the input of the student
guard cell.contentLabel.text == "Vrij" else {
self.alert(title: "Error", message: "De docent is niet beschikbaar op deze tijden. Check uw invoer.")
return
}
for i in 0...self.selectedRow - 1 {
let indexPath = String(self.selectedItem.section + i) + ", " + String(self.selectedItem.row)
CalendarDay.dataOfDate.updateValue(self.userId, forKey: indexPath)
}
self.ref.child("data").child(CalendarDay.calendarDayDate).setValue(CalendarDay.dataOfDate)
self.collectionView.reloadData()
}
func adminPickerView() {
guard self.selectedItem.section + self.selectedRow <= 28 else {
self.alert(title: "Foudmelding", message: "Verwijder binnen de uren van de roostertijden.")
return
}
let section = self.selectedItem.section + self.selectedRow - 1
let indexPath = IndexPath(row: self.selectedItem.row, section: section)
let cell = self.collectionView.cellForItem(at: indexPath) as! ContentCollectionViewCell
// check if teacher is avaible for the input of the student
guard cell.contentLabel.text != "_" else {
self.alert(title: "Foudmelding", message: "Deze uren kunnen niet verwijderd worden. Let op het aantal uren te verwijderen.")
return
}
for i in 0...self.selectedRow - 1 {
let indexPath = String(self.selectedItem.section + i) + ", " + String(self.selectedItem.row)
CalendarDay.dataOfDate.removeValue(forKey: indexPath)
}
removeTeacherId()
self.ref.child("data").child(CalendarDay.calendarDayDate).setValue(CalendarDay.dataOfDate)
self.collectionView.reloadData()
}
}
// MARK: - UICollectionView
extension CollectionViewController: UICollectionViewDataSource, UICollectionViewDelegate {
func numberOfSections(in collectionView: UICollectionView) -> Int
{
return 28
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int
{
return 8
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
if indexPath.section == 0 {
return
}
self.selectedItem = indexPath
let cell = collectionView.cellForItem(at: indexPath) as! ContentCollectionViewCell
// Check if it's an admin user and if the cell is not empty.
if self.userStatus == 2 && cell.contentLabel.text != "_" {
self.alertWithPickerMenu(title: " Wilt u " + timeSlots[self.selectedItem.section - 1] + " verwijderen? \n\n\n\n\n\n\n\n\n", message: " U moet minimaal 1 uur verwijderen.", user: self.userStatus)
}
guard cell.contentLabel.text == "Vrij" || cell.contentLabel.text == "_" else{
self.alert(title: "Foutmelding", message: "De sectie is al ingepland")
return
}
// Check if it's a student and setup picker view.
if cell.contentLabel.text == "Vrij" {
guard self.userStatus == 0 && indexPath.row != 0 else {
self.alert(title: "Foutmelding", message: "U kunt als docent geen docent reserveren.")
return
}
self.alertWithPickerMenu(title: " Wilt u " + timeSlots[self.selectedItem.section - 1] + " uur inplannen? \n\n\n\n\n\n\n\n\n", message: " U moet minimaal 1 uur inplannen.", user: self.userStatus)
// Check if it's a teacher and setup picker view.
} else if cell.contentLabel.text == "_" {
guard self.userStatus == 1 else {
self.alert(title: "Foutmelding", message: "U kunt als leerling geen beschikbare tijden invoeren.")
return
}
guard CalendarDay.dataOfDate.values.contains(self.userId) == false else {
self.alert(title: "Foutmelding", message: "U heeft deze dag al ingepland.")
return
}
self.alertWithPickerMenu(title: " Wilt u " + self.timeSlots[self.selectedItem.section - 1] + " uur inplannen? \n\n\n\n\n\n\n\n\n", message: "U moet minimaal 1 uur inplannen.", user: self.userStatus)
}
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
if indexPath.section == 0 {
if indexPath.row == 0 {
return configurateCell(indexPath: indexPath,
contentCell: false,
text: "Tijd",
colorString: "White")
} else {
if CalendarDay.dataOfDate[(self.convertIndexPath(indexPath: indexPath))] != nil {
return configurateCell(indexPath: indexPath,
contentCell: true,
text: CalendarDay.dataOfDate[(self.convertIndexPath(indexPath:indexPath))]!,
colorString: "green")
} else {
return configurateCell(indexPath: indexPath,
contentCell: true,
text: "Vrij",
colorString: "White")
}
}
} else {
if indexPath.row == 0 {
return configurateCell(indexPath: indexPath,
contentCell: false,
text: timeSlots[((indexPath as NSIndexPath).section) - 1],
colorString: "White")
} else {
if CalendarDay.dataOfDate[(self.convertIndexPath(indexPath:indexPath))] != nil {
var color = String()
if CalendarDay.dataOfDate[(self.convertIndexPath(indexPath:indexPath))] == "Vrij"{
color = "Green"
}
else {
color = "Red"
}
return configurateCell(indexPath: indexPath,
contentCell: true,
text: CalendarDay.dataOfDate[(self.convertIndexPath(indexPath:indexPath))]!,
colorString: color)
} else {
return configurateCell(indexPath: indexPath,
contentCell: true,
text: "_",
colorString: "White")
}
}
}
}
}
// MARK: - UIPickerView
extension CollectionViewController: UIPickerViewDataSource, UIPickerViewDelegate {
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 1
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return 17
}
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
return hours[row] as String
}
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
selectedRow = 2 + row
}
func pickerView(_ pickerView: UIPickerView, rowHeightForComponent component: Int) -> CGFloat {
return 36.0
}
}
|
7821d02db660e20a3dfdec9ea774cf5e
| 44.966057 | 211 | 0.598466 | false | false | false | false |
yar1vn/Swiftilities
|
refs/heads/master
|
Swiftilities/Swiftilities/Cache.swift
|
mit
|
1
|
//
// Cache.swift
// Switiflities
//
// Created by Yariv on 1/6/15.
// Copyright (c) 2015 Yariv. All rights reserved.
//
import Foundation
struct Cache {
var maxSize = 10
var count: Int { return _cache.count }
var first: String? { return _cache.first }
var last: String? { return _cache.last }
private var _cache = [String]()
init(objects: [String]? = nil) {
_cache = objects ?? []
}
subscript(index: Int) -> String {
get { return _cache[index] }
set { _cache[index] = newValue }
}
mutating func append(object: String) -> String {
// prevent duplicates
if let index = find(_cache, object) {
_cache.removeAtIndex(index)
}
_cache.insert(object, atIndex: 0)
// enforce max size
if _cache.count > maxSize {
_cache.removeLast()
}
return object
}
mutating func removeAll() {
_cache.removeAll()
}
}
extension Cache: Serializable {
func toJSON() -> JSON {
return _cache
}
static func fromJSON(json: JSON) -> Cache? {
if let objects = json as? [String] {
return Cache(objects: objects)
}
return nil
}
}
|
97a197c5a8f1f0b0bb2246965aa1f844
| 18.491525 | 50 | 0.590949 | false | false | false | false |
Adlai-Holler/RACReddit
|
refs/heads/master
|
RACReddit/SubredditEntriesViewController.swift
|
mit
|
1
|
//
// SubredditEntriesViewController.swift
// RACReddit
//
// Created by Adlai Holler on 10/31/15.
// Copyright © 2015 adlai. All rights reserved.
//
import UIKit
import SafariServices
import ReactiveCocoa
final class SubredditEntriesViewController: UITableViewController, UITextFieldDelegate {
var data: [RedditPost] = []
var currentSubredditName: String?
var currentFetchDisposable: Disposable?
@IBOutlet weak var titleTextField: UITextField!
deinit {
currentFetchDisposable?.dispose()
}
override func viewDidLoad() {
super.viewDidLoad()
titleTextField.becomeFirstResponder()
}
// MARK: - Table view data source
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return data.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("cellID", forIndexPath: indexPath)
cell.textLabel?.text = data[indexPath.item].title
return cell
}
// MARK: - Navigation
/// When they select a post, create a Safari view controller and push it.
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
let url = data[indexPath.row].url
let vc = SFSafariViewController(URL: url)
showViewController(vc, sender: self)
}
// MARK: - Handling the Text Field
/// If they tap the return key, dismiss the field.
func textFieldShouldReturn(textField: UITextField) -> Bool {
textField.endEditing(false)
return true
}
/// When they finish editing, if our subreddit name has changed, do a load.
func textFieldDidEndEditing(textField: UITextField) {
if textField.text != currentSubredditName {
currentSubredditName = textField.text
loadNewData()
}
}
/// Cancel any existing load and load the data for the current subreddit name.
private func loadNewData() {
// Make sure we have a current subreddit name
guard let currentSubredditName = currentSubredditName else { return }
// Dispose of our current fetch if needed.
currentFetchDisposable?.dispose()
RedditPost
// Create a signal producer.
.fetchPostsForSubredditName(currentSubredditName)
// Switch events onto UI scheduler (main thread).
.observeOn(UIScheduler())
// Start the signal producer – produce a signal and listen to its events.
.start {[weak self] event in
self?.handleFetchEventForSubredditName(currentSubredditName, event: event)
}
}
/// We will call this on the main thread for any fetch event that comes through
private func handleFetchEventForSubredditName(name: String, event: Event<[RedditPost], NSError>) {
switch event {
case let .Next(posts):
NSLog("View controller received posts: \(posts)")
data = posts
tableView.reloadData()
case let .Failed(error):
NSLog("Failed to fetch posts for subreddit: \(name) with error: \(error)")
default: ()
}
}
}
|
32fecbbe8538457523b6d60bc4f094a0
| 28.91 | 118 | 0.732197 | false | false | false | false |
arsonik/OrangeTv
|
refs/heads/master
|
OrangeTv/OrangeTv.swift
|
mit
|
1
|
//
// OrangeTv.swift
// OrangeTv
//
// Created by Florian Morello on 06/11/14.
// Copyright (c) 2014 Florian Morello. All rights reserved.
// http://lsm-rendezvous040413.orange.fr/API/?api_token=be906750a3cd20d6ddb47ec0b50e7a68&output=json&withChannels=1 ??
// http://ip_livebox_tv:8080/remoteControl/cmd?operation=09&epg_id=id_de_la_chaîne&uui=1
// http://wiki.queret.net/docs/multimedia/orangetv
//
import Foundation
import Alamofire
class OrangeTv {
let host:String
let remoteControlCmd:String
init(host:String){
self.host = host
self.remoteControlCmd = "http://\(self.host):8080/remoteControl/cmd"
}
func sendCommand(command:OrangeTv.Command){
return self.sendKey("\(command.code)")
}
func setChannel(channel:OrangeTv.Channel){
return self.send(["operation": "09", "epg_id": channel.epgId, "uui": 1])
}
private func sendKey(cmd:String){
return self.send(["operation": 10, "key": cmd, "mode": OrangeTv.Mode.Press.code])
}
private func send(params:[String:AnyObject]!){
Alamofire.request(.GET, self.remoteControlCmd, parameters: params).responseJSON { (request:NSURLRequest, response:NSHTTPURLResponse?, result:AnyObject?, error:NSError?) -> Void in
if let dico = result as? [String: AnyObject] {
if let result = dico["result"] as? [String: AnyObject] {
}
}
}
}
func tv() {
Alamofire.request(.GET, "http://lsm-rendezvous040413.orange.fr/API/", parameters: ["api_token": "be906750a3cd20d6ddb47ec0b50e7a68", "output": "json", "withChannels": 1]).responseJSON { (request:NSURLRequest, response:NSHTTPURLResponse?, result:AnyObject?, error:NSError?) -> Void in
if let dico = result as? [String: AnyObject] {
if let channels = dico["channels"]?["channel"] as? [[String: AnyObject]] {
for channelData in channels {
OrangeTv.Channel(data: channelData)
}
}
if let diffusions = dico["diffusions"]?["diffusion"] as? [[String: AnyObject]] {
println("Diffusions \(diffusions.count)")
}
}
}
}
func setChannel(code:Int){
for c in "\(code)" {
var key:OrangeTv.Command!
if c == "0" {
key = OrangeTv.Command.N0
}
else if c == "1" {
key = OrangeTv.Command.N1
}
else if c == "2" {
key = OrangeTv.Command.N2
}
else if c == "3" {
key = OrangeTv.Command.N3
}
else if c == "4" {
key = OrangeTv.Command.N4
}
else if c == "5" {
key = OrangeTv.Command.N5
}
else if c == "6" {
key = OrangeTv.Command.N6
}
else if c == "7" {
key = OrangeTv.Command.N7
}
else if c == "8" {
key = OrangeTv.Command.N8
}
else if c == "9" {
key = OrangeTv.Command.N9
}
self.sendCommand(key)
}
}
// MARK: Mode
enum Mode {
case Press
case LongPress
case Release
var code : Int {
switch self {
case .Press:
return 0
case .LongPress:
return 1
case .Release:
return 2
}
}
}
// MARK: Commands
enum Command {
case Power
case N0
case N1
case N2
case N3
case N4
case N5
case N6
case N7
case N8
case N9
case ChannelUp
case ChannelDown
case VolumeUp
case VolumeDown
case Mute
case Up
case Down
case Left
case Right
case Ok
case Back
case Menu
case PlayPause
case FastBackward
case FastForward
case Rec
case Vod
var code:Int {
switch self {
case .Power:
return 116
case .N0:
return 512
case .N1:
return 513
case .N2:
return 514
case .N3:
return 515
case .N4:
return 516
case .N5:
return 517
case .N6:
return 518
case .N7:
return 519
case .N8:
return 520
case .N9:
return 521
case .ChannelUp:
return 402
case .ChannelDown:
return 403
case .VolumeUp:
return 115
case .VolumeDown:
return 114
case .Mute:
return 113
case .Up:
return 103
case .Down:
return 108
case .Left:
return 105
case .Right:
return 116
case .Ok:
return 352
case .Back:
return 158
case .Menu:
return 139
case .PlayPause:
return 164
case .FastBackward:
return 168
case .FastForward:
return 159
case .Rec:
return 167
case .Vod:
return 393
}
}
}
// MARK: Channel
class Channel {
let id:Int! // 78,
let blendedTV:Bool // 0,
let imageUrl:NSURL // http://media.programme-tv.orange.fr/Images/Chaines/415.gif
let htag:String // #nauticalchannel
let image:String // nauticalchannel.png
let tvIndex:Int! // 95
let epgId:Int! // 415
let name:String // Nautical Channel
init(data:[String:AnyObject]){
self.blendedTV = data["blendedTV"] as String == "1"
self.imageUrl = NSURL(string: data["imageUrl"] as String)!
self.id = (data["id"] as String!)?.toInt()
self.htag = data["htag"] as String
self.image = data["image"] as String
self.tvIndex = (data["tvIndex"] as String!).toInt()
self.epgId = (data["epgId"] as String!)?.toInt()
self.name = data["name"] as String
}
}
}
|
73b165a06a598d62ae225e67f1d3e892
| 20.140426 | 284 | 0.629555 | false | false | false | false |
Ehrippura/firefox-ios
|
refs/heads/master
|
Client/Frontend/Browser/HistoryStateHelper.swift
|
mpl-2.0
|
8
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Foundation
import WebKit
protocol HistoryStateHelperDelegate: class {
func historyStateHelper(_ historyStateHelper: HistoryStateHelper, didPushOrReplaceStateInTab tab: Tab)
}
// This tab helper is needed for injecting a user script into the
// WKWebView that intercepts calls to `history.pushState()` and
// `history.replaceState()` so that the BrowserViewController is
// notified when the user navigates a single-page web application.
class HistoryStateHelper: TabHelper {
weak var delegate: HistoryStateHelperDelegate?
fileprivate weak var tab: Tab?
required init(tab: Tab) {
self.tab = tab
if let path = Bundle.main.path(forResource: "HistoryStateHelper", ofType: "js") {
if let source = try? NSString(contentsOfFile: path, encoding: String.Encoding.utf8.rawValue) as String {
let userScript = WKUserScript(source: source, injectionTime: WKUserScriptInjectionTime.atDocumentEnd, forMainFrameOnly: true)
tab.webView!.configuration.userContentController.addUserScript(userScript)
}
}
}
func scriptMessageHandlerName() -> String? {
return "historyStateHelper"
}
func userContentController(_ userContentController: WKUserContentController, didReceiveScriptMessage message: WKScriptMessage) {
if let tab = tab {
DispatchQueue.main.async {
self.delegate?.historyStateHelper(self, didPushOrReplaceStateInTab: tab)
}
}
}
class func name() -> String {
return "HistoryStateHelper"
}
}
|
509b428f017b46766ea8249b57376fea
| 39.222222 | 141 | 0.69558 | false | false | false | false |
athiercelin/Localizations
|
refs/heads/master
|
Localizations/Models/File.swift
|
mit
|
1
|
//
// File.swift
// Localizations
//
// Created by Arnaud Thiercelin on 2/4/16.
// Copyright © 2016 Arnaud Thiercelin. 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 Cocoa
class File: NSObject {
enum State {
case New
case Edit
case Obselete
case None
}
var state = State.None
var name = ""
var folder = ""
var path = ""
var rawContent = ""
var translations = [Translation] ()
var languageCode: String {
get {
let folderParts = folder.components(separatedBy: ".")
if folderParts.count > 0 {
return folderParts[0]
}
return ""
}
}
override var description: String {
get {
return self.debugDescription
}
}
override var debugDescription: String {
get {
return "Name: \(self.name)\n" +
"Folder: \(self.folder)\n" +
"Path: \(self.path)\n" +
"State: \(self.state)\n"
}
}
}
|
f1d9aea630cf2e91b8dc8a748ebcc16b
| 27.893939 | 112 | 0.703199 | false | false | false | false |
flypaper0/ethereum-wallet
|
refs/heads/release/1.1
|
ethereum-wallet/Classes/BusinessLayer/Core/Services/Gas/GasService.swift
|
gpl-3.0
|
1
|
// Copyright © 2018 Conicoin LLC. All rights reserved.
// Created by Artur Guseinov
import Geth
class GasService: GasServiceProtocol {
private let client: GethEthereumClient
private let context: GethContext
private let callMsgBuilder: GasCallMsgBuilder
init(core: EthereumCoreProtocol, callMsgBuilder: GasCallMsgBuilder) {
self.client = core.client
self.context = core.context
self.callMsgBuilder = callMsgBuilder
}
func getSuggestedGasLimit(from: String, to: String, amount: Decimal, settings: SendSettings, result: @escaping (Result<Decimal>) -> Void) {
Ethereum.syncQueue.async { [unowned self] in
do {
let msg = try self.callMsgBuilder.build(from: from, to: to, amount: amount, settings: settings)
var gasLimit: Int64 = 0
try self.client.estimateGas(self.context, msg: msg, gas: &gasLimit)
DispatchQueue.main.async {
result(.success(Decimal(gasLimit)))
}
} catch {
DispatchQueue.main.async {
result(.failure(error))
}
}
}
}
func getSuggestedGasPrice(result: @escaping (Result<Decimal>) -> Void) {
Ethereum.syncQueue.async {
do {
let gasPrice = try self.client.suggestGasPrice(self.context)
DispatchQueue.main.async {
result(.success(Decimal(gasPrice.getString(10))))
}
} catch {
DispatchQueue.main.async {
result(.failure(error))
}
}
}
}
}
|
8e27be526a1ca267061e67dd11380648
| 27.150943 | 141 | 0.640751 | false | false | false | false |
deuiore/mpv
|
refs/heads/master
|
video/out/mac/gl_layer.swift
|
gpl-2.0
|
13
|
/*
* This file is part of mpv.
*
* mpv is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* mpv 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 Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with mpv. If not, see <http://www.gnu.org/licenses/>.
*/
import Cocoa
import OpenGL.GL
import OpenGL.GL3
let glVersions: [CGLOpenGLProfile] = [
kCGLOGLPVersion_3_2_Core,
kCGLOGLPVersion_Legacy
]
let glFormatBase: [CGLPixelFormatAttribute] = [
kCGLPFAOpenGLProfile,
kCGLPFAAccelerated,
kCGLPFADoubleBuffer
]
let glFormatSoftwareBase: [CGLPixelFormatAttribute] = [
kCGLPFAOpenGLProfile,
kCGLPFARendererID,
CGLPixelFormatAttribute(UInt32(kCGLRendererGenericFloatID)),
kCGLPFADoubleBuffer
]
let glFormatOptional: [[CGLPixelFormatAttribute]] = [
[kCGLPFABackingStore],
[kCGLPFAAllowOfflineRenderers]
]
let glFormat10Bit: [CGLPixelFormatAttribute] = [
kCGLPFAColorSize,
_CGLPixelFormatAttribute(rawValue: 64),
kCGLPFAColorFloat
]
let glFormatAutoGPU: [CGLPixelFormatAttribute] = [
kCGLPFASupportsAutomaticGraphicsSwitching
]
let attributeLookUp: [UInt32:String] = [
kCGLOGLPVersion_3_2_Core.rawValue: "kCGLOGLPVersion_3_2_Core",
kCGLOGLPVersion_Legacy.rawValue: "kCGLOGLPVersion_Legacy",
kCGLPFAOpenGLProfile.rawValue: "kCGLPFAOpenGLProfile",
UInt32(kCGLRendererGenericFloatID): "kCGLRendererGenericFloatID",
kCGLPFARendererID.rawValue: "kCGLPFARendererID",
kCGLPFAAccelerated.rawValue: "kCGLPFAAccelerated",
kCGLPFADoubleBuffer.rawValue: "kCGLPFADoubleBuffer",
kCGLPFABackingStore.rawValue: "kCGLPFABackingStore",
kCGLPFAColorSize.rawValue: "kCGLPFAColorSize",
kCGLPFAColorFloat.rawValue: "kCGLPFAColorFloat",
kCGLPFAAllowOfflineRenderers.rawValue: "kCGLPFAAllowOfflineRenderers",
kCGLPFASupportsAutomaticGraphicsSwitching.rawValue: "kCGLPFASupportsAutomaticGraphicsSwitching",
]
class GLLayer: CAOpenGLLayer {
unowned var cocoaCB: CocoaCB
var libmpv: LibmpvHelper { get { return cocoaCB.libmpv } }
let displayLock = NSLock()
let cglContext: CGLContextObj
let cglPixelFormat: CGLPixelFormatObj
var needsFlip: Bool = false
var forceDraw: Bool = false
var surfaceSize: NSSize = NSSize(width: 0, height: 0)
var bufferDepth: GLint = 8
enum Draw: Int { case normal = 1, atomic, atomicEnd }
var draw: Draw = .normal
let queue: DispatchQueue = DispatchQueue(label: "io.mpv.queue.draw")
var needsICCUpdate: Bool = false {
didSet {
if needsICCUpdate == true {
update()
}
}
}
var inLiveResize: Bool = false {
didSet {
if inLiveResize {
isAsynchronous = true
}
update(force: true)
}
}
init(cocoaCB ccb: CocoaCB) {
cocoaCB = ccb
(cglPixelFormat, bufferDepth) = GLLayer.createPixelFormat(ccb)
cglContext = GLLayer.createContext(ccb, cglPixelFormat)
super.init()
autoresizingMask = [.layerWidthSizable, .layerHeightSizable]
backgroundColor = NSColor.black.cgColor
if #available(macOS 10.12, *), bufferDepth > 8 {
contentsFormat = .RGBA16Float
}
var i: GLint = 1
CGLSetParameter(cglContext, kCGLCPSwapInterval, &i)
CGLSetCurrentContext(cglContext)
libmpv.initRender()
libmpv.setRenderUpdateCallback(updateCallback, context: self)
libmpv.setRenderControlCallback(cocoaCB.controlCallback, context: cocoaCB)
}
// necessary for when the layer containing window changes the screen
override init(layer: Any) {
guard let oldLayer = layer as? GLLayer else {
fatalError("init(layer: Any) passed an invalid layer")
}
cocoaCB = oldLayer.cocoaCB
surfaceSize = oldLayer.surfaceSize
cglPixelFormat = oldLayer.cglPixelFormat
cglContext = oldLayer.cglContext
super.init()
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func canDraw(inCGLContext ctx: CGLContextObj,
pixelFormat pf: CGLPixelFormatObj,
forLayerTime t: CFTimeInterval,
displayTime ts: UnsafePointer<CVTimeStamp>?) -> Bool {
if inLiveResize == false {
isAsynchronous = false
}
return cocoaCB.backendState == .initialized &&
(forceDraw || libmpv.isRenderUpdateFrame())
}
override func draw(inCGLContext ctx: CGLContextObj,
pixelFormat pf: CGLPixelFormatObj,
forLayerTime t: CFTimeInterval,
displayTime ts: UnsafePointer<CVTimeStamp>?) {
needsFlip = false
forceDraw = false
if draw.rawValue >= Draw.atomic.rawValue {
if draw == .atomic {
draw = .atomicEnd
} else {
atomicDrawingEnd()
}
}
updateSurfaceSize()
libmpv.drawRender(surfaceSize, bufferDepth, ctx)
if needsICCUpdate {
needsICCUpdate = false
cocoaCB.updateICCProfile()
}
}
func updateSurfaceSize() {
var dims: [GLint] = [0, 0, 0, 0]
glGetIntegerv(GLenum(GL_VIEWPORT), &dims)
surfaceSize = NSSize(width: CGFloat(dims[2]), height: CGFloat(dims[3]))
if NSEqualSizes(surfaceSize, NSZeroSize) {
surfaceSize = bounds.size
surfaceSize.width *= contentsScale
surfaceSize.height *= contentsScale
}
}
func atomicDrawingStart() {
if draw == .normal {
NSDisableScreenUpdates()
draw = .atomic
}
}
func atomicDrawingEnd() {
if draw.rawValue >= Draw.atomic.rawValue {
NSEnableScreenUpdates()
draw = .normal
}
}
override func copyCGLPixelFormat(forDisplayMask mask: UInt32) -> CGLPixelFormatObj {
return cglPixelFormat
}
override func copyCGLContext(forPixelFormat pf: CGLPixelFormatObj) -> CGLContextObj {
contentsScale = cocoaCB.window?.backingScaleFactor ?? 1.0
return cglContext
}
let updateCallback: mpv_render_update_fn = { (ctx) in
let layer: GLLayer = unsafeBitCast(ctx, to: GLLayer.self)
layer.update()
}
override func display() {
displayLock.lock()
let isUpdate = needsFlip
super.display()
CATransaction.flush()
if isUpdate && needsFlip {
CGLSetCurrentContext(cglContext)
if libmpv.isRenderUpdateFrame() {
libmpv.drawRender(NSZeroSize, bufferDepth, cglContext, skip: true)
}
}
displayLock.unlock()
}
func update(force: Bool = false) {
if force { forceDraw = true }
queue.async {
if self.forceDraw || !self.inLiveResize {
self.needsFlip = true
self.display()
}
}
}
class func createPixelFormat(_ ccb: CocoaCB) -> (CGLPixelFormatObj, GLint) {
var pix: CGLPixelFormatObj?
var depth: GLint = 8
var err: CGLError = CGLError(rawValue: 0)
let swRender = ccb.libmpv.macOpts.cocoa_cb_sw_renderer
if swRender != 1 {
(pix, depth, err) = GLLayer.findPixelFormat(ccb)
}
if (err != kCGLNoError || pix == nil) && swRender != 0 {
(pix, depth, err) = GLLayer.findPixelFormat(ccb, software: true)
}
guard let pixelFormat = pix, err == kCGLNoError else {
ccb.log.sendError("Couldn't create any CGL pixel format")
exit(1)
}
return (pixelFormat, depth)
}
class func findPixelFormat(_ ccb: CocoaCB, software: Bool = false) -> (CGLPixelFormatObj?, GLint, CGLError) {
var pix: CGLPixelFormatObj?
var err: CGLError = CGLError(rawValue: 0)
var npix: GLint = 0
for ver in glVersions {
var glBase = software ? glFormatSoftwareBase : glFormatBase
glBase.insert(CGLPixelFormatAttribute(ver.rawValue), at: 1)
var glFormat = [glBase]
if (ccb.libmpv.macOpts.cocoa_cb_10bit_context == 1) {
glFormat += [glFormat10Bit]
}
glFormat += glFormatOptional
if (ccb.libmpv.macOpts.macos_force_dedicated_gpu == 0) {
glFormat += [glFormatAutoGPU]
}
for index in stride(from: glFormat.count-1, through: 0, by: -1) {
let format = glFormat.flatMap { $0 } + [_CGLPixelFormatAttribute(rawValue: 0)]
err = CGLChoosePixelFormat(format, &pix, &npix)
if err == kCGLBadAttribute || err == kCGLBadPixelFormat || pix == nil {
glFormat.remove(at: index)
} else {
let attArray = format.map({ (value: _CGLPixelFormatAttribute) -> String in
return attributeLookUp[value.rawValue] ?? String(value.rawValue)
})
ccb.log.sendVerbose("Created CGL pixel format with attributes: " +
"\(attArray.joined(separator: ", "))")
return (pix, glFormat.contains(glFormat10Bit) ? 16 : 8, err)
}
}
}
let errS = String(cString: CGLErrorString(err))
ccb.log.sendWarning("Couldn't create a " +
"\(software ? "software" : "hardware accelerated") " +
"CGL pixel format: \(errS) (\(err.rawValue))")
if software == false && ccb.libmpv.macOpts.cocoa_cb_sw_renderer == -1 {
ccb.log.sendWarning("Falling back to software renderer")
}
return (pix, 8, err)
}
class func createContext(_ ccb: CocoaCB, _ pixelFormat: CGLPixelFormatObj) -> CGLContextObj {
var context: CGLContextObj?
let error = CGLCreateContext(pixelFormat, nil, &context)
guard let cglContext = context, error == kCGLNoError else {
let errS = String(cString: CGLErrorString(error))
ccb.log.sendError("Couldn't create a CGLContext: " + errS)
exit(1)
}
return cglContext
}
}
|
209136532d07df0a1ba9a70bbe4136ca
| 32.701863 | 113 | 0.609289 | false | false | false | false |
Tuslareb/JBDatePicker
|
refs/heads/master
|
JBDatePicker/Classes/JBDatePickerEnums.swift
|
mit
|
2
|
//
// JBDatePickerEnums.swift
// JBDatePicker
//
// Created by Joost van Breukelen on 09-10-16.
// Copyright © 2016 Joost van Breukelen. All rights reserved.
//
import UIKit
enum MonthViewIdentifier: Int { case previous, presented, next }
enum JBScrollDirection { case none, toNext, toPrevious }
//In a calendar, day, week, weekday, month, and year numbers are generally 1-based. So Sunday is 1.
public enum JBWeekDay: Int { case sunday = 1, monday, tuesday, wednesday, thursday, friday, saturday }
public enum JBSelectionShape { case circle, square, roundedRect }
public enum JBFontSize { case verySmall, small, medium, large, veryLarge }
//only for debugging
func randomColor() -> UIColor{
let red = CGFloat(randomInt(min: 0, max: 255)) / 255
let green = CGFloat(randomInt(min: 0, max: 255)) / 255
let blue = CGFloat(randomInt(min: 0, max: 255)) / 255
let randomColor = UIColor(red: red, green: green, blue: blue, alpha: 1)
return randomColor
}
func randomInt(min: Int, max:Int) -> Int {
return min + Int(arc4random_uniform(UInt32(max - min + 1)))
}
func randomFloat(min: Int, max:Int) -> Int {
return min + Int(arc4random_uniform(UInt32(max - min + 1)))
}
|
2879ed980592330c773857b269c567c4
| 32.555556 | 102 | 0.694536 | false | false | false | false |
CoolCodeFactory/Antidote
|
refs/heads/master
|
AntidoteArchitectureExample/UIWindow+Extensions.swift
|
mit
|
1
|
//
// UIWindow+Extensions.swift
// AntidoteArchitectureExample
//
// Created by Dmitriy Utmanov on 16/09/16.
// Copyright © 2016 Dmitry Utmanov. All rights reserved.
//
import UIKit
extension UIWindow {
func setRootViewController(_ viewController: UIViewController, animated: Bool) {
if animated {
// NavBar Blink - http://stackoverflow.com/a/29235480/2640551
guard let rootViewController = rootViewController else { return }
let snapshotView = rootViewController.view.snapshotView(afterScreenUpdates: true)
self.rootViewController = viewController
viewController.view.addSubview(snapshotView!)
UIView.animate(withDuration: kDefaultAnimationDuration, delay: 0.0, options: [.curveEaseOut], animations: {
snapshotView?.alpha = 0.0
}, completion: { (finished) in
snapshotView?.removeFromSuperview()
})
} else {
self.rootViewController = viewController
}
}
}
|
b1c1cbdd26c19db192f27e00e297d3a4
| 31.666667 | 119 | 0.624304 | false | false | false | false |
lucdion/aide-devoir
|
refs/heads/master
|
sources/AideDevoir/Classes/Helpers/GeometryHelpers.swift
|
apache-2.0
|
1
|
//
// GeometryHelpers.swift
//
import UIKit
extension UIScrollView {
func insetSetTop(_ top: CGFloat) {
var inset = self.contentInset
inset.top = top
contentInset = inset
}
func insetSetBottom(_ bottom: CGFloat) {
var inset = self.contentInset
inset.bottom = bottom
contentInset = inset
}
}
|
623a88c240211a9554c99f2977156f27
| 18.888889 | 44 | 0.608939 | false | false | false | false |
huangboju/Moots
|
refs/heads/master
|
Examples/UIScrollViewDemo/UIScrollViewDemo/DayPickerView.swift
|
mit
|
1
|
//
// DayPickerView.swift
// UIScrollViewDemo
//
// Created by 伯驹 黄 on 2017/6/19.
// Copyright © 2017年 伯驹 黄. All rights reserved.
//
import UIKit
private let itemSide: CGFloat = 75
private let padding: CGFloat = 40
extension CGSize {
var rect: CGRect {
return CGRect(origin: .zero, size: self)
}
var flatted: CGSize {
return CGSize(width: flat(width), height: flat(height))
}
}
class DayPicker: UIView {
fileprivate var items: [String]!
private lazy var collectionView: UICollectionView = {
let layout = RulerLayout()
layout.scrollDirection = .horizontal
layout.itemSize = CGSize(width: itemSide, height: itemSide)
layout.minimumLineSpacing = padding
layout.usingScale = true
let collectionView = UICollectionView(frame: self.frame.size.rect, collectionViewLayout: layout)
collectionView.dataSource = self
collectionView.delegate = self
collectionView.showsHorizontalScrollIndicator = false
collectionView.backgroundColor = UIColor.white
return collectionView
}()
convenience init(origin: CGPoint, items: [String]) {
self.init(frame: CGRect(origin: origin, size: CGSize(width: UIScreen.main.bounds.width, height: 100)))
self.items = items
backgroundColor = UIColor.white
addSubview(collectionView)
collectionView.register(DayPickerCell.self, forCellWithReuseIdentifier: "cellID")
}
}
extension DayPicker: UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return items.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cellID", for: indexPath)
(cell as? DayPickerCell)?.text = items[indexPath.row]
return cell
}
}
extension DayPicker: UICollectionViewDelegate {}
class DayPickerCell: UICollectionViewCell {
private lazy var textLayer: CXETextLayer = {
let textLayer = CXETextLayer()
textLayer.frame = self.bounds
textLayer.bounds = self.bounds
textLayer.alignmentMode = .center
textLayer.foregroundColor = UIColor.white.cgColor
textLayer.backgroundColor = UIColor.red.cgColor
textLayer.cornerRadius = self.bounds.width / 2
return textLayer
}()
var text: String? {
didSet {
textLayer.string = text
}
}
override init(frame: CGRect) {
super.init(frame: frame)
contentView.layer.addSublayer(textLayer)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
class CXETextLayer: CATextLayer {
override init() {
super.init()
}
override init(layer: Any) {
super.init(layer: layer)
}
required init(coder aDecoder: NSCoder) {
super.init(layer: aDecoder)
}
override func draw(in ctx: CGContext) {
let height = bounds.height
let fontSize = self.fontSize
let yDiff = (height - fontSize) / 2 - fontSize / 10
ctx.saveGState()
ctx.translateBy(x: 0.0, y: yDiff)
super.draw(in: ctx)
ctx.restoreGState()
}
}
|
0f3c691b1049a43ff25875069517d4a5
| 27.91453 | 121 | 0.658883 | false | false | false | false |
coolster01/PokerTouch
|
refs/heads/master
|
PokerTouch/Hand.swift
|
apache-2.0
|
1
|
//
// Hand.swift
// PokerTouch
//
// Created by Subhi Sbahi on 5/21/17.
// Copyright © 2017 Rami Sbahi. All rights reserved.
//
import Foundation
class Hand {
var valuesInvolved: [Int] = [] // used to determine ties
/* royal flush
* just put in a zero
* straight flush / straight
* returns highest value in the straight - not other cards
* four/three of kind / one pair
* returns value involved in pair, then high --> low
* flush
* returns the five cards in flush from high --> low, then the last two values high --> low
* two pair
* higher pair, lower pair, remaining cards
* full house
* 3 of a kind, pair, remaining
* none (high card)
* organize high --> low
*/
var outOfIt: [Int] = []
var cardList: [Card] = []
var score: Int = 0
init(eCardList: [Card])
{
cardList = eCardList
self.sortCards()
let oldScore: Int = self.setScore()
var oldValues: [Int] = []
for current in valuesInvolved
{
oldValues.append(current)
}
for currentCard in cardList
{
currentCard.makeAceLow()
}
self.sortCards()
if(self.setScore() <= oldScore) // not any better
{
for currentCard in cardList
{
currentCard.makeAceHigh()
}
score = oldScore
valuesInvolved = oldValues
}
// if it was improved, it will stay that way
self.sortCards()
}
/**
* Insertion sort
*/
func sortCards()
{
var key: Int = 0
for index in 1..<cardList.count
{
let currentCard: Card = cardList[index]
key = index
while(key > 0 && cardList[key - 1].compareTo(otherCard: cardList[index]) < 0)
{
key -= 1
}
cardList.insert(currentCard, at: key)
cardList.remove(at: index + 1)
}
}
func setScore() -> Int
{
if(self.isRoyalFlush())
{
score = 9
}
else if(self.isStraightFlush())
{
score = 8
}
else if(self.isFourOfKind())
{
score = 7
}
else if(self.isFullHouse())
{
score = 6
}
else if(self.isFlush())
{
score = 5
}
else if(self.isStraight())
{
score = 4
}
else if(self.isThreeOfKind())
{
score = 3
}
else if(self.isTwoPair())
{
score = 2
}
else if(self.isPair())
{
score = 1
}
else
{
score = 0
valuesInvolved.removeAll() // should already be clear, but just double-checking
for current in cardList
{
valuesInvolved.append(current.myValue)
}
}
return score
}
func isPair() -> Bool
{
var cards = [Int](repeating: 0, count: 15)
for currentCard in cardList
{
cards[currentCard.myValue] += 1
}
for index in 1..<cards.count
{
if(cards[index] >= 2)
{
valuesInvolved.removeAll()
valuesInvolved.append(index) // add that value
for current in cardList
{
let currentValue: Int = current.myValue
if(currentValue != index)
{
valuesInvolved.append(currentValue)
}
}
return true
}
}
return false
}
func isFullHouse() -> Bool
{
if(isThreeOfKind() && isTwoPair()) // all full houses are a two pair and a three of kind
{
return true
}
return false
}
func isTwoPair() -> Bool
{
var cards = [Int](repeating: 0, count: 15)
for currentCard in cardList
{
cards[currentCard.myValue] += 1
}
var count: Int = 0
var values: [Int] = []
for index in (1...14).reversed()
{
if(cards[index] >= 2)
{
count += 1
if(cards[index] >= 3) // makes full house, needs priority
{
values.insert(index, at: 0)
}
else
{
values.append(index)
}
}
}
var numAdded: Int = 0
if(count >= 2) // at least 2 pairs
{
valuesInvolved.removeAll()
for value in values
{
if(numAdded <= 1) // 2 pairs have not been accounted for yet
{
valuesInvolved.append(value)
numAdded += 1
}
}
for current in cardList
{
let currentValue: Int = current.myValue;
if(!valuesInvolved.contains(currentValue))
{
valuesInvolved.append(currentValue)
}
}
return true
}
return false
}
func isThreeOfKind() -> Bool
{
var cards = [Int](repeating: 0, count: 15)
for currentCard in cardList
{
cards[currentCard.myValue] += 1
}
for index in 1..<cards.count
{
if(cards[index] >= 3)
{
valuesInvolved.removeAll()
valuesInvolved.append(index) // add that value
for current in cardList
{
let currentValue: Int = current.myValue
if(currentValue != index)
{
valuesInvolved.append(currentValue)
}
}
return true
}
}
return false
}
func isFourOfKind() -> Bool
{
var cards = [Int](repeating: 0, count: 15)
for currentCard in cardList
{
cards[currentCard.myValue] += 1
}
for index in 1..<cards.count
{
if(cards[index] == 4)
{
valuesInvolved.removeAll()
valuesInvolved.append(index) // add that value
for current in cardList
{
let currentValue: Int = current.myValue
if(currentValue != index)
{
valuesInvolved.append(currentValue)
}
}
return true
}
}
return false
}
func containsValue(_ val: Int) -> Bool
{
for current in cardList
{
if(current.myValue == val)
{
return true
}
}
return false
}
func containsCard(c: Card) -> Bool
{
for current in cardList
{
if(current.equals(otherCard: c))
{
return true
}
}
return false
}
func isStraightFlush() -> Bool
{
return self.isFlush() && self.isStraight() // will clear and put only highest value involved after flush
}
func isStraight() -> Bool
{
for start in (1...10).reversed()
{
if(self.containsValue(start) && self.containsValue(start+1) && self.containsValue(start+2) && self.containsValue(start+3) && self.containsValue(start+4))
{
valuesInvolved.removeAll()
valuesInvolved.append(start+4) // value of highest card in straight
return true
}
}
return false
}
func isFlush() -> Bool
{
var suits = [Int](repeating: 0, count: 5); // 1 = clubs, 2 = hearts, 3 = spades, 4 = diamonds
for i in 0..<cardList.count
{
suits[cardList[i].getSuitValue()] += 1
}
for j in 1...4
{
if(suits[j] >= 5) // this suit makes a flush
{
valuesInvolved.removeAll()
outOfIt.removeAll()
for index in 0..<cardList.count
{
if(cardList[index].getSuitValue() == j)
{
valuesInvolved.append(cardList[index].myValue) // will add high --> low of flush
}
else
{
outOfIt.append(cardList[index].myValue)
}
}
for out in outOfIt
{
valuesInvolved.append(out)
}
return true
}
}
return false
}
func isRoyalFlush() -> Bool
{
if(self.containsValue(10) && self.containsValue(11) && self.containsValue(12)
&& self.containsValue(13) && self.containsValue(14) && self.isFlush())
{
valuesInvolved.removeAll()
valuesInvolved.append(0)
return true
}
else
{
return false
}
}
func getImages() -> [String]
{
var images: [String] = []
for current in cardList
{
images.append(current.getImage())
}
return images
}
}
|
c6f5f51b1b169a3deb554b5c67472463
| 24.278351 | 165 | 0.433524 | false | false | false | false |
airbnb/lottie-ios
|
refs/heads/master
|
Sources/Private/CoreAnimation/Layers/InfiniteOpaqueAnimationLayer.swift
|
apache-2.0
|
2
|
// Created by Cal Stephens on 10/10/22.
// Copyright © 2022 Airbnb Inc. All rights reserved.
import QuartzCore
// MARK: - ExpandedAnimationLayer
/// A `BaseAnimationLayer` subclass that renders its background color
/// as if the layer is infinitely large, without affecting its bounds
/// or the bounds of its sublayers
final class InfiniteOpaqueAnimationLayer: BaseAnimationLayer {
// MARK: Lifecycle
override init() {
super.init()
addSublayer(additionalPaddingLayer)
}
required init?(coder _: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
/// Called by CoreAnimation to create a shadow copy of this layer
/// More details: https://developer.apple.com/documentation/quartzcore/calayer/1410842-init
override init(layer: Any) {
super.init(layer: layer)
}
// MARK: Internal
override func layoutSublayers() {
super.layoutSublayers()
masksToBounds = false
additionalPaddingLayer.backgroundColor = backgroundColor
// Scale `additionalPaddingLayer` to be larger than this layer
// by `additionalPadding` at each size, and centered at the center
// of this layer. Since `additionalPadding` is very large, this has
// the affect of making `additionalPaddingLayer` appear infinite.
let scaleRatioX = (bounds.width + (CALayer.veryLargeLayerPadding * 2)) / bounds.width
let scaleRatioY = (bounds.height + (CALayer.veryLargeLayerPadding * 2)) / bounds.height
additionalPaddingLayer.transform = CATransform3DScale(
CATransform3DMakeTranslation(-CALayer.veryLargeLayerPadding, -CALayer.veryLargeLayerPadding, 0),
scaleRatioX,
scaleRatioY,
1)
}
// MARK: Private
private let additionalPaddingLayer = CALayer()
}
|
a9647de802c2a26dff5484ca0f7f7aaa
| 30.035714 | 102 | 0.729574 | false | false | false | false |
fawadsuhail/weather-app
|
refs/heads/master
|
WeatherApp/Network/Router.swift
|
mit
|
1
|
//
// Router.swift
// WeatherApp
//
// Created by Fawad Suhail on 4/2/17.
// Copyright © 2017 Fawad Suhail. All rights reserved.
//
import Foundation
import Alamofire
enum Router: URLRequestConvertible {
static let baseURLString = K.Network.BASE_URL
case weather(city: String)
var method: HTTPMethod {
switch self {
case .weather:
return .get
}
}
var path: String {
switch self {
case .weather:
return K.Network.WEATHER_URL
}
}
func asURLRequest() throws -> URLRequest {
let url = try Router.baseURLString.asURL()
var urlRequest = URLRequest(url: url.appendingPathComponent(path))
urlRequest.httpMethod = method.rawValue
switch self {
case .weather(let cityName):
let params = ["q": cityName,
"key": K.Network.KEY,
"format": K.Network.FORMAT]
urlRequest = try URLEncoding.default.encode(urlRequest, with: params)
}
return urlRequest
}
}
|
5fdb032e4fc5fedf49030687ca0fd15e
| 19.117647 | 75 | 0.610136 | false | false | false | false |
AjayOdedara/CoreKitTest
|
refs/heads/master
|
CoreKit/Pods/SwiftDate/Sources/SwiftDate/TimeZoneName.swift
|
apache-2.0
|
16
|
//
// SwiftDate, Full featured Swift date library for parsing, validating, manipulating, and formatting dates and timezones.
// Created by: Daniele Margutti
// Main contributors: Jeroen Houtzager
//
//
// 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
/// MARK: - TimeZoneName Shortcut
/// This enum allows you set a valid timezone using swift's type safe support
public enum TimeZoneName: String {
/// Return a valid TimeZone instance from an enum
public var timeZone: TimeZone {
switch self {
case .current:
return TimeZone.current
case .currentAutoUpdating:
return TimeZone.autoupdatingCurrent
default:
return TimeZone(identifier: self.rawValue)!
}
}
/// Return a `TimeZone` instance with a fixed number of seconds from GMT zone
///
/// - parameter seconds: seconds from GMT
///
/// - returns: a new `TimeZone` instance
public static func secondsFromGMT(seconds: Int) -> TimeZone? {
return TimeZone(secondsFromGMT: seconds)
}
case current = "Current"
case currentAutoUpdating = "CurrentAutoUpdating"
case africaAbidjan = "Africa/Abidjan"
case africaAccra = "Africa/Accra"
case africaAddisAbaba = "Africa/Addis_Ababa"
case africaAlgiers = "Africa/Algiers"
case africaAsmara = "Africa/Asmara"
case africaBamako = "Africa/Bamako"
case africaBangui = "Africa/Bangui"
case africaBanjul = "Africa/Banjul"
case africaBissau = "Africa/Bissau"
case africaBlantyre = "Africa/Blantyre"
case africaBrazzaville = "Africa/Brazzaville"
case africaBujumbura = "Africa/Bujumbura"
case africaCairo = "Africa/Cairo"
case africaCasablanca = "Africa/Casablanca"
case africaCeuta = "Africa/Ceuta"
case africaConakry = "Africa/Conakry"
case africaDakar = "Africa/Dakar"
case africaDarEsSalaam = "Africa/Dar_es_Salaam"
case africaDjibouti = "Africa/Djibouti"
case africaDouala = "Africa/Douala"
case africaElAaiun = "Africa/El_Aaiun"
case africaFreetown = "Africa/Freetown"
case africaGaborone = "Africa/Gaborone"
case africaHarare = "Africa/Harare"
case africaJohannesburg = "Africa/Johannesburg"
case africaJuba = "Africa/Juba"
case africaKampala = "Africa/Kampala"
case africaKhartoum = "Africa/Khartoum"
case fricaKigali = "Africa/Kigali"
case africaKinshasa = "Africa/Kinshasa"
case africaLagos = "Africa/Lagos"
case africaLibreville = "Africa/Libreville"
case africaLome = "Africa/Lome"
case africaLuanda = "Africa/Luanda"
case africaLubumbashi = "Africa/Lubumbashi"
case africaLusaka = "Africa/Lusaka"
case africaMalabo = "Africa/Malabo"
case africaMaputo = "Africa/Maputo"
case africaMaseru = "Africa/Maseru"
case africaMbabane = "Africa/Mbabane"
case africaMogadishu = "Africa/Mogadishu"
case africaMonrovia = "Africa/Monrovia"
case africaNairobi = "Africa/Nairobi"
case africaNdjamena = "Africa/Ndjamena"
case africaNiamey = "Africa/Niamey"
case africaNouakchott = "Africa/Nouakchott"
case africaOuagadougou = "Africa/Ouagadougou"
case africaPortoNovo = "Africa/Porto-Novo"
case africaSaoTome = "Africa/Sao_Tome"
case africaTripoli = "Africa/Tripoli"
case africaTunis = "Africa/Tunis"
case africaWindhoek = "Africa/Windhoek"
case americaAdak = "America/Adak"
case americaAnchorage = "America/Anchorage"
case americaAnguilla = "America/Anguilla"
case americaAntigua = "America/Antigua"
case americaAraguaina = "America/Araguaina"
case americaArgentinaBuenosAires = "America/Argentina/Buenos_Aires"
case americaArgentinaCatamarca = "America/Argentina/Catamarca"
case americaArgentinaCordoba = "America/Argentina/Cordoba"
case americaArgentinaJujuy = "America/Argentina/Jujuy"
case americaArgentinaLaRioja = "America/Argentina/La_Rioja"
case americaArgentinaMendoza = "America/Argentina/Mendoza"
case americaArgentinaRioGallegos = "America/Argentina/Rio_Gallegos"
case americaArgentinaSalta = "America/Argentina/Salta"
case americaArgentinaSanJuan = "America/Argentina/San_Juan"
case americaArgentinaSanLuis = "America/Argentina/San_Luis"
case americaArgentinaTucuman = "America/Argentina/Tucuman"
case americaArgentinaUshuaia = "America/Argentina/Ushuaia"
case americaAruba = "America/Aruba"
case americaAsuncion = "America/Asuncion"
case americaAtikokan = "America/Atikokan"
case americaBahia = "America/Bahia"
case americaBahiaBanderas = "America/Bahia_Banderas"
case americaBarbados = "America/Barbados"
case americaBelem = "America/Belem"
case americaBelize = "America/Belize"
case americaBlancSablon = "America/Blanc-Sablon"
case americaBoaVista = "America/Boa_Vista"
case americaBogota = "America/Bogota"
case americaBoise = "America/Boise"
case americaCambridgeBay = "America/Cambridge_Bay"
case americaCampoGrande = "America/Campo_Grande"
case americaCancun = "America/Cancun"
case americaCaracas = "America/Caracas"
case americaCayenne = "America/Cayenne"
case americaCayman = "America/Cayman"
case americaChicago = "America/Chicago"
case americaChihuahua = "America/Chihuahua"
case americaCostaRica = "America/Costa_Rica"
case americaCreston = "America/Creston"
case americaCuiaba = "America/Cuiaba"
case americaCuracao = "America/Curacao"
case americaDanmarkshavn = "America/Danmarkshavn"
case americaDawson = "America/Dawson"
case americaDawsonCreek = "America/Dawson_Creek"
case americaDenver = "America/Denver"
case americaDetroit = "America/Detroit"
case americaDominica = "America/Dominica"
case americaEdmonton = "America/Edmonton"
case americaEirunepe = "America/Eirunepe"
case americaElSalvador = "America/El_Salvador"
case americaFortNelson = "America/Fort_Nelson"
case americaFortaleza = "America/Fortaleza"
case americaGlaceBay = "America/Glace_Bay"
case americaGodthab = "America/Godthab"
case americaGooseBay = "America/Goose_Bay"
case americaGrandTurk = "America/Grand_Turk"
case americaGrenada = "America/Grenada"
case americaGuadeloupe = "America/Guadeloupe"
case americaGuatemala = "America/Guatemala"
case americaGuayaquil = "America/Guayaquil"
case americaGuyana = "America/Guyana"
case americaHalifax = "America/Halifax"
case americaHavana = "America/Havana"
case americaHermosillo = "America/Hermosillo"
case americaIndianaIndianapolis = "America/Indiana/Indianapolis"
case americaIndianaKnox = "America/Indiana/Knox"
case americaIndianaMarengo = "America/Indiana/Marengo"
case americaIndianaPetersburg = "America/Indiana/Petersburg"
case americaIndianaTellCity = "America/Indiana/Tell_City"
case americaIndianaVevay = "America/Indiana/Vevay"
case americaIndianaVincennes = "America/Indiana/Vincennes"
case americaIndianaWinamac = "America/Indiana/Winamac"
case americaInuvik = "America/Inuvik"
case americaIqaluit = "America/Iqaluit"
case americaJamaica = "America/Jamaica"
case americaJuneau = "America/Juneau"
case americaKentuckyLouisville = "America/Kentucky/Louisville"
case americaKentuckyMonticello = "America/Kentucky/Monticello"
case americaKralendijk = "America/Kralendijk"
case americaLaPaz = "America/La_Paz"
case americaLima = "America/Lima"
case americaLosAngeles = "America/Los_Angeles"
case americaLowerPrinces = "America/Lower_Princes"
case americaMaceio = "America/Maceio"
case americaManagua = "America/Managua"
case americaManaus = "America/Manaus"
case americaMarigot = "America/Marigot"
case americaMartinique = "America/Martinique"
case americaMatamoros = "America/Matamoros"
case americaMazatlan = "America/Mazatlan"
case americaMenominee = "America/Menominee"
case americaMerida = "America/Merida"
case americaMetlakatla = "America/Metlakatla"
case americaMexicoCity = "America/Mexico_City"
case americaMiquelon = "America/Miquelon"
case americaMoncton = "America/Moncton"
case americaMonterrey = "America/Monterrey"
case americaMontevideo = "America/Montevideo"
case americaMontreal = "America/Montreal"
case americaMontserrat = "America/Montserrat"
case americaNassau = "America/Nassau"
case americaNewYork = "America/New_York"
case americaNipigon = "America/Nipigon"
case americaNome = "America/Nome"
case americaNoronha = "America/Noronha"
case americaNorthDakotaBeulah = "America/North_Dakota/Beulah"
case americaNorthDakotaCenter = "America/North_Dakota/Center"
case americaNorthDakotaNewSalem = "America/North_Dakota/New_Salem"
case americaOjinaga = "America/Ojinaga"
case americaPanama = "America/Panama"
case americaPangnirtung = "America/Pangnirtung"
case americaParamaribo = "America/Paramaribo"
case americaPhoenix = "America/Phoenix"
case americaPortAuPrince = "America/Port-au-Prince"
case americaPortOfSpain = "America/Port_of_Spain"
case americaPortoVelho = "America/Porto_Velho"
case americaPuertoRico = "America/Puerto_Rico"
case americaRainyRiver = "America/Rainy_River"
case americaRankinInlet = "America/Rankin_Inlet"
case americaRecife = "America/Recife"
case americaRegina = "America/Regina"
case americaResolute = "America/Resolute"
case americaRioBranco = "America/Rio_Branco"
case americaSantaIsabel = "America/Santa_Isabel"
case americaSantarem = "America/Santarem"
case americaSantiago = "America/Santiago"
case americaSantoDomingo = "America/Santo_Domingo"
case americaSaoPaulo = "America/Sao_Paulo"
case americaScoresbysund = "America/Scoresbysund"
case americaShiprock = "America/Shiprock"
case americaSitka = "America/Sitka"
case americaStBarthelemy = "America/St_Barthelemy"
case americaStJohns = "America/St_Johns"
case americaStKitts = "America/St_Kitts"
case americaStLucia = "America/St_Lucia"
case americaStThomas = "America/St_Thomas"
case americaStVincent = "America/St_Vincent"
case americaSwiftCurrent = "America/Swift_Current"
case americaTegucigalpa = "America/Tegucigalpa"
case americaThule = "America/Thule"
case americaThunderBay = "America/Thunder_Bay"
case americaTijuana = "America/Tijuana"
case americaToronto = "America/Toronto"
case americaTortola = "America/Tortola"
case americaVancouver = "America/Vancouver"
case americaWhitehorse = "America/Whitehorse"
case americaWinnipeg = "America/Winnipeg"
case americaYakutat = "America/Yakutat"
case americaYellowknife = "America/Yellowknife"
case antarcticaCasey = "Antarctica/Casey"
case antarcticaDavis = "Antarctica/Davis"
case antarcticaDumontdurville = "Antarctica/DumontDUrville"
case antarcticaMacquarie = "Antarctica/Macquarie"
case antarcticaMawson = "Antarctica/Mawson"
case antarcticaMcmurdo = "Antarctica/McMurdo"
case antarcticaPalmer = "Antarctica/Palmer"
case antarcticaRothera = "Antarctica/Rothera"
case antarcticaSouthPole = "Antarctica/South_Pole"
case antarcticaSyowa = "Antarctica/Syowa"
case antarcticaTroll = "Antarctica/Troll"
case antarcticaVostok = "Antarctica/Vostok"
case arcticLongyearbyen = "Arctic/Longyearbyen"
case asiaAden = "Asia/Aden"
case asiaAlmaty = "Asia/Almaty"
case asiaAmman = "Asia/Amman"
case asiaAnadyr = "Asia/Anadyr"
case asiaAqtau = "Asia/Aqtau"
case asiaAqtobe = "Asia/Aqtobe"
case asiaAshgabat = "Asia/Ashgabat"
case asiaBaghdad = "Asia/Baghdad"
case asiaBahrain = "Asia/Bahrain"
case asiaBaku = "Asia/Baku"
case asiaBangkok = "Asia/Bangkok"
case asiaBeirut = "Asia/Beirut"
case asiaBishkek = "Asia/Bishkek"
case asiaBrunei = "Asia/Brunei"
case asiaChita = "Asia/Chita"
case asiaChoibalsan = "Asia/Choibalsan"
case asiaChongqing = "Asia/Chongqing"
case asiaColombo = "Asia/Colombo"
case asiaDamascus = "Asia/Damascus"
case asiaDhaka = "Asia/Dhaka"
case asiaDili = "Asia/Dili"
case asiaDubai = "Asia/Dubai"
case asiaDushanbe = "Asia/Dushanbe"
case asiaGaza = "Asia/Gaza"
case asiaHarbin = "Asia/Harbin"
case asiaHebron = "Asia/Hebron"
case asiaHoChiMinh = "Asia/Ho_Chi_Minh"
case asiaHongKong = "Asia/Hong_Kong"
case asiaHovd = "Asia/Hovd"
case asiaIrkutsk = "Asia/Irkutsk"
case asiaJakarta = "Asia/Jakarta"
case asiaJayapura = "Asia/Jayapura"
case asiaJerusalem = "Asia/Jerusalem"
case asiaKabul = "Asia/Kabul"
case asiaKamchatka = "Asia/Kamchatka"
case asiaKarachi = "Asia/Karachi"
case asiaKashgar = "Asia/Kashgar"
case asiaKathmandu = "Asia/Kathmandu"
case asiaKatmandu = "Asia/Katmandu"
case asiaKhandyga = "Asia/Khandyga"
case asiaKolkata = "Asia/Kolkata"
case asiaKrasnoyarsk = "Asia/Krasnoyarsk"
case asiaKualaLumpur = "Asia/Kuala_Lumpur"
case asiaKuching = "Asia/Kuching"
case asiaKuwait = "Asia/Kuwait"
case asiaMacau = "Asia/Macau"
case asiaMagadan = "Asia/Magadan"
case asiaMakassar = "Asia/Makassar"
case asiaManila = "Asia/Manila"
case asiaMuscat = "Asia/Muscat"
case asiaNicosia = "Asia/Nicosia"
case asiaNovokuznetsk = "Asia/Novokuznetsk"
case asiaNovosibirsk = "Asia/Novosibirsk"
case asiaOmsk = "Asia/Omsk"
case asiaOral = "Asia/Oral"
case asiaPhnomPenh = "Asia/Phnom_Penh"
case asiaPontianak = "Asia/Pontianak"
case asiaPyongyang = "Asia/Pyongyang"
case asiaQatar = "Asia/Qatar"
case asiaQyzylorda = "Asia/Qyzylorda"
case asiaRangoon = "Asia/Rangoon"
case asiaRiyadh = "Asia/Riyadh"
case asiaSakhalin = "Asia/Sakhalin"
case asiaSamarkand = "Asia/Samarkand"
case asiaSeoul = "Asia/Seoul"
case asiaShanghai = "Asia/Shanghai"
case asiaSingapore = "Asia/Singapore"
case asiaSrednekolymsk = "Asia/Srednekolymsk"
case asiaTaipei = "Asia/Taipei"
case asiaTashkent = "Asia/Tashkent"
case asiaTbilisi = "Asia/Tbilisi"
case asiaTehran = "Asia/Tehran"
case asiaThimphu = "Asia/Thimphu"
case asiaTokyo = "Asia/Tokyo"
case asiaUlaanbaatar = "Asia/Ulaanbaatar"
case asiaUrumqi = "Asia/Urumqi"
case asiaUstNera = "Asia/Ust-Nera"
case asiaVientiane = "Asia/Vientiane"
case asiaVladivostok = "Asia/Vladivostok"
case asiaYakutsk = "Asia/Yakutsk"
case asiaYekaterinburg = "Asia/Yekaterinburg"
case asiaYerevan = "Asia/Yerevan"
case atlanticAzores = "Atlantic/Azores"
case atlanticBermuda = "Atlantic/Bermuda"
case atlanticCanary = "Atlantic/Canary"
case atlanticCapeVerde = "Atlantic/Cape_Verde"
case atlanticFaroe = "Atlantic/Faroe"
case atlanticMadeira = "Atlantic/Madeira"
case atlanticReykjavik = "Atlantic/Reykjavik"
case atlanticSouthGeorgia = "Atlantic/South_Georgia"
case atlanticStHelena = "Atlantic/St_Helena"
case atlanticStanley = "Atlantic/Stanley"
case australiaAdelaide = "Australia/Adelaide"
case australiaBrisbane = "Australia/Brisbane"
case australiaBrokenHill = "Australia/Broken_Hill"
case australiaCurrie = "Australia/Currie"
case australiaDarwin = "Australia/Darwin"
case australiaEucla = "Australia/Eucla"
case australiaHobart = "Australia/Hobart"
case australiaLindeman = "Australia/Lindeman"
case australiaLordHowe = "Australia/Lord_Howe"
case australiaMelbourne = "Australia/Melbourne"
case australiaPerth = "Australia/Perth"
case australiaSydney = "Australia/Sydney"
case europeAmsterdam = "Europe/Amsterdam"
case europeAndorra = "Europe/Andorra"
case europeAthens = "Europe/Athens"
case europeBelgrade = "Europe/Belgrade"
case europeBerlin = "Europe/Berlin"
case europeBratislava = "Europe/Bratislava"
case europeBrussels = "Europe/Brussels"
case europeBucharest = "Europe/Bucharest"
case europeBudapest = "Europe/Budapest"
case europeBusingen = "Europe/Busingen"
case europeChisinau = "Europe/Chisinau"
case europeCopenhagen = "Europe/Copenhagen"
case europeDublin = "Europe/Dublin"
case europeGibraltar = "Europe/Gibraltar"
case europeGuernsey = "Europe/Guernsey"
case europeHelsinki = "Europe/Helsinki"
case europeIsleOfMan = "Europe/Isle_of_Man"
case europeIstanbul = "Europe/Istanbul"
case europeJersey = "Europe/Jersey"
case europeKaliningrad = "Europe/Kaliningrad"
case europeKiev = "Europe/Kiev"
case europeLisbon = "Europe/Lisbon"
case europeLjubljana = "Europe/Ljubljana"
case europeLondon = "Europe/London"
case europeLuxembourg = "Europe/Luxembourg"
case europeMadrid = "Europe/Madrid"
case europeMalta = "Europe/Malta"
case europeMariehamn = "Europe/Mariehamn"
case europeMinsk = "Europe/Minsk"
case europeMonaco = "Europe/Monaco"
case europeMoscow = "Europe/Moscow"
case europeOslo = "Europe/Oslo"
case europeParis = "Europe/Paris"
case europePodgorica = "Europe/Podgorica"
case europePrague = "Europe/Prague"
case europeRiga = "Europe/Riga"
case europeRome = "Europe/Rome"
case europeSamara = "Europe/Samara"
case europeSanMarino = "Europe/San_Marino"
case europeSarajevo = "Europe/Sarajevo"
case europeSimferopol = "Europe/Simferopol"
case europeSkopje = "Europe/Skopje"
case europeSofia = "Europe/Sofia"
case europeStockholm = "Europe/Stockholm"
case europeTallinn = "Europe/Tallinn"
case europeTirane = "Europe/Tirane"
case europeUzhgorod = "Europe/Uzhgorod"
case europeVaduz = "Europe/Vaduz"
case europeVatican = "Europe/Vatican"
case europeVienna = "Europe/Vienna"
case europeVilnius = "Europe/Vilnius"
case europeVolgograd = "Europe/Volgograd"
case europeWarsaw = "Europe/Warsaw"
case europeZagreb = "Europe/Zagreb"
case europeZaporozhye = "Europe/Zaporozhye"
case europeZurich = "Europe/Zurich"
case gmt = "GMT"
case IndianAntananarivo = "Indian/Antananarivo"
case indianChagos = "Indian/Chagos"
case indianChristmas = "Indian/Christmas"
case indianCocos = "Indian/Cocos"
case indianComoro = "Indian/Comoro"
case indianKerguelen = "Indian/Kerguelen"
case indianMahe = "Indian/Mahe"
case indianMaldives = "Indian/Maldives"
case indianMauritius = "Indian/Mauritius"
case indianMayotte = "Indian/Mayotte"
case indianReunion = "Indian/Reunion"
case pacificApia = "Pacific/Apia"
case pacificAuckland = "Pacific/Auckland"
case pacificBougainville = "Pacific/Bougainville"
case pacificChatham = "Pacific/Chatham"
case pacificChuuk = "Pacific/Chuuk"
case pacificEaster = "Pacific/Easter"
case pacificEfate = "Pacific/Efate"
case pacificEnderbury = "Pacific/Enderbury"
case pacificFakaofo = "Pacific/Fakaofo"
case pacificFiji = "Pacific/Fiji"
case pacificFunafuti = "Pacific/Funafuti"
case pacificGalapagos = "Pacific/Galapagos"
case pacificGambier = "Pacific/Gambier"
case pacificGuadalcanal = "Pacific/Guadalcanal"
case pacificGuam = "Pacific/Guam"
case pacificHonolulu = "Pacific/Honolulu"
case pacificJohnston = "Pacific/Johnston"
case pacificKiritimati = "Pacific/Kiritimati"
case pacificKosrae = "Pacific/Kosrae"
case pacificKwajalein = "Pacific/Kwajalein"
case pacificMajuro = "Pacific/Majuro"
case pacificMarquesas = "Pacific/Marquesas"
case pacificMidway = "Pacific/Midway"
case pacificNauru = "Pacific/Nauru"
case pacificNiue = "Pacific/Niue"
case pacificNorfolk = "Pacific/Norfolk"
case pacificNoumea = "Pacific/Noumea"
case pacificPagoPago = "Pacific/Pago_Pago"
case pacificPalau = "Pacific/Palau"
case pacificPitcairn = "Pacific/Pitcairn"
case pacificPohnpei = "Pacific/Pohnpei"
case pacificPonape = "Pacific/Ponape"
case pacificPortMoresby = "Pacific/Port_Moresby"
case pacificRarotonga = "Pacific/Rarotonga"
case pacificSaipan = "Pacific/Saipan"
case pacificTahiti = "Pacific/Tahiti"
case pacificTarawa = "Pacific/Tarawa"
case pacificTongatapu = "Pacific/Tongatapu"
case pacificTruk = "Pacific/Truk"
case pacificWake = "Pacific/Wake"
case pacificWallis = "Pacific/Wallis"
}
|
80ca255ce70eb76277f93e33d5a2d9d7
| 40.363071 | 121 | 0.776446 | false | false | false | false |
linbin00303/Dotadog
|
refs/heads/master
|
DotaDog/DotaDog/Classes/Main/AppDelegate.swift
|
mit
|
1
|
//
// AppDelegate.swift
// DotaDog
//
// Created by 林彬 on 16/4/27.
// Copyright © 2016年 linbin. All rights reserved.
//
import UIKit
import FMDB
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
var leftView : UIView?
private var heroesInfo : NSDictionary?
private var heroesNameEN : NSArray?
private var abilitys : NSDictionary?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// 设置根控制器
window = UIWindow(frame: UIScreen.mainScreen().bounds)
let baseVC = DDogBaseViewController()
window?.rootViewController = baseVC
window?.backgroundColor = UIColor.blackColor()
window?.makeKeyAndVisible()
canConnectToNet { (result) in
if result == "no"{
let controller = getAlert("网络状态", message: "未能连接到服务器", doWhat: { (action) in
})
baseVC.presentViewController(controller, animated: true, completion: nil)
}
}
// 发送请求,保存数据到数据库
saveDataIntoSqlite()
// 非正常启动
if launchOptions != nil {
if launchOptions![UIApplicationLaunchOptionsLocalNotificationKey] != nil {
}
}
registerAuthor()
// 测试时间 1464551470
// let str = DDogTimeTransform.timeTransUTCtoDate(1464921390)
// print(str)
// let basePath = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true).first
// let fullPath = basePath! + "/dotadog.sqlite"
// print(fullPath)
return true
}
func application(application: UIApplication, didReceiveLocalNotification notification: UILocalNotification) {
let state = application.applicationState
if state == .Active {
// 前台
var dic = notification.userInfo
let str = dic!["key"] as! String
let alert = UIAlertView(title: "比赛通知", message: str, delegate: nil, cancelButtonTitle: "OK")
alert.show()
let navView = window?.rootViewController?.childViewControllers[1].childViewControllers[2] as? DDogNavController
let matchVC = navView?.childViewControllers[0] as? DDogMatchController
matchVC?.tableView.reloadData()
}
if state == .Inactive {
// 如果当前不在前台, 接收到通知, 要求, 用户点击通知之后, 跳转到会话详情
}
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// 如果应用程序的图标数字值为0, 就可以隐藏图标数字
UIApplication.sharedApplication().applicationIconBadgeNumber = 0
UIView.setAnimationBeginsFromCurrentState(true)
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
private func saveDataIntoSqlite() {
var herocount : Int32 = 0
var itemcount : Int32 = 0
var abilitycount : Int32 = 0
// print(isTableLive("hero"),isTableLive("items"),isTableLive("ability"))
// 开启子线程,进行网络请求和数据存储
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) {
// 如果表都存在,计算每一个表的列数
if isTableLive("hero")&&isTableLive("items")&&isTableLive("ability") {
DDogFMDBTool.shareInstance.columnsFromTable("hero") { (result) in
herocount = result
}
DDogFMDBTool.shareInstance.columnsFromTable("items") { (result) in
itemcount = result
}
DDogFMDBTool.shareInstance.columnsFromTable("ability") { (result) in
abilitycount = result
}
}
if herocount == 111 && itemcount == 189 && abilitycount == 503{
return
}
DDogFMDBTool.shareInstance.update_deleteData("hero")
DDogFMDBTool.shareInstance.update_deleteData("items")
DDogFMDBTool.shareInstance.update_deleteData("ability")
// 处理英雄数据,网络请求+存入数据库
DDogHeroesAndItemsDataSync.shareInstance.handleHeroesInfoData { (results) in
}
// 处理物品数据,网络请求+存入数据库
DDogHeroesAndItemsDataSync.shareInstance.handleItemsInfoData { (results) in
}
// 处理完毕,通知主线程
dispatch_async(dispatch_get_main_queue()) {
}
}
}
}
extension AppDelegate {
// 一般请求授权的方法, 写在应用程序启动的代理方法里面, 主要是为了刚启动, 就请求用户的权限(此处, 写在这里, 是方便查看代码)
func registerAuthor() -> () {
// 在ios8.0以后, 如果想要发送本地通知, 需要主动请求授权
// 另外, 做好版本适配(可以把项目的最低部署版本调低, 让他自动报错修复即可)
if #available(iOS 8.0, *) {
// 1. 指定需要请求的授权类型(哪些权限,比如弹框, 声音, 图标数字等等)
let typeValue = UIUserNotificationType.Alert.rawValue | UIUserNotificationType.Sound.rawValue | UIUserNotificationType.Badge.rawValue
let type = UIUserNotificationType(rawValue: typeValue)
// 2. 根据请求的授权类型, 创建一个通知设置对象
let setting = UIUserNotificationSettings(forTypes: type, categories: nil)
// 3. 注册通知设置对象(这时, 系统会自动弹出一个授权窗口, 让用户进行授权)
UIApplication.sharedApplication().registerUserNotificationSettings(setting)
}
}
}
|
ae00290047eb90c0a8ba8a36e8ae4cca
| 34.755102 | 285 | 0.608162 | false | false | false | false |
shanksyang/SwiftRegex
|
refs/heads/master
|
SwiftRegex/SwiftRegex.swift
|
bsd-3-clause
|
1
|
//
// SwiftRegex.swift
// SwiftRegex
//
// Created by Gregory Todd Williams on 6/7/14.
// Copyright (c) 2014 Gregory Todd Williams. All rights reserved.
//
import Foundation
//extension String {
// func rangeFromNSRange(nsRange : NSRange) -> Range<String.Index>? {
// let from16 = utf16.startIndex.advancedBy(nsRange.location, limit: utf16.endIndex)
// let to16 = from16.advancedBy(nsRange.length, limit: utf16.endIndex)
// if let from = String.Index(from16, within: self),
// let to = String.Index(to16, within: self) {
// return from ..< to
// }
// return nil
// }
//}
//
//
//extension String {
// func NSRangeFromRange(range : Range<String.Index>) -> NSRange {
// let utf16view = self.utf16
// let from = String.UTF16View.Index(range.startIndex, within: utf16view)
// let to = String.UTF16View.Index(range.endIndex, within: utf16view)
// return NSMakeRange(utf16view.startIndex.distanceTo(from), from.distanceTo(to))
// }
//}
infix operator =~ {}
func =~ (value : String, pattern : String) -> RegexMatchResult {
let nsstr = value as NSString // we use this to access the NSString methods like .length and .substringWithRange(NSRange)
let options : NSRegularExpressionOptions = []
do {
let re = try NSRegularExpression(pattern: pattern, options: options)
let all = NSRange(location: 0, length: nsstr.length)
var matches : Array<String> = []
var captureResult : [RegexCaptureResult] = [RegexCaptureResult]()
re.enumerateMatchesInString(value, options: [], range: all) { (result, flags, ptr) -> Void in
guard let result = result else { return }
var captureItems : [String] = []
for i in 0..<result.numberOfRanges
{
let range = result.rangeAtIndex(i)
print(range)
let string = nsstr.substringWithRange(range)
if(i > 0) {
captureItems.append(string)
continue
}
matches.append(string)
}
captureResult.append(RegexCaptureResult(items: captureItems))
print(matches)
}
return RegexMatchResult(items: matches, captureItems: captureResult)
} catch {
return RegexMatchResult(items: [], captureItems: [])
}
}
struct RegexMatchCaptureGenerator : GeneratorType {
var items: Array<String>
mutating func next() -> String? {
if items.isEmpty { return nil }
let ret = items[0]
items = Array(items[1..<items.count])
return ret
}
}
struct RegexMatchResult : SequenceType, BooleanType {
var items: Array<String>
var captureItems: [RegexCaptureResult]
func generate() -> RegexMatchCaptureGenerator {
print(items)
return RegexMatchCaptureGenerator(items: items)
}
var boolValue: Bool {
return items.count > 0
}
subscript (i: Int) -> String {
return items[i]
}
}
struct RegexCaptureResult {
var items: Array<String>
}
class SwiftRegex {
//是否包含
class func containsMatch(pattern: String, inString string: String) -> Bool {
let options : NSRegularExpressionOptions = []
let matchOptions : NSMatchingOptions = []
let regex = try! NSRegularExpression(pattern: pattern, options: options)
let range = NSMakeRange(0, string.characters.count)
return regex.firstMatchInString(string, options: matchOptions, range: range) != nil
}
//匹配
class func match(pattern: String, inString string: String) -> RegexMatchResult {
return string =~ pattern
}
//替换
class func replaceMatches(pattern: String, inString string: String, withString replacementString: String) -> String? {
let options : NSRegularExpressionOptions = []
let matchOptions : NSMatchingOptions = []
let regex = try! NSRegularExpression(pattern: pattern, options: options)
let range = NSMakeRange(0, string.characters.count)
return regex.stringByReplacingMatchesInString(string, options: matchOptions, range: range, withTemplate: replacementString)
}
}
|
5666a89041fe1285347feca186ff8492
| 32.648438 | 131 | 0.621082 | false | false | false | false |
imitationgame/pokemonpassport
|
refs/heads/master
|
pokepass/Model/Main/Transition/MMainTransitionReplace.swift
|
mit
|
1
|
import UIKit
class MMainTransitionReplace:MMainTransition
{
private let kAnimationDuration:TimeInterval = 0
init()
{
super.init(animationDuration:kAnimationDuration)
}
override func positionAfter()
{
let barHeight:CGFloat
if parent.bar == nil
{
barHeight = 0
}
else
{
barHeight = parent.kBarHeight
}
parent.layoutTopTemporal = NSLayoutConstraint(
item:next.view,
attribute:NSLayoutAttribute.top,
relatedBy:NSLayoutRelation.equal,
toItem:parent.view,
attribute:NSLayoutAttribute.top,
multiplier:1,
constant:barHeight)
parent.layoutBottomTemporal = NSLayoutConstraint(
item:next.view,
attribute:NSLayoutAttribute.bottom,
relatedBy:NSLayoutRelation.equal,
toItem:parent.view,
attribute:NSLayoutAttribute.bottom,
multiplier:1,
constant:0)
parent.layoutLeftTemporal = NSLayoutConstraint(
item:next.view,
attribute:NSLayoutAttribute.left,
relatedBy:NSLayoutRelation.equal,
toItem:parent.view,
attribute:NSLayoutAttribute.left,
multiplier:1,
constant:0)
parent.layoutRightTemporal = NSLayoutConstraint(
item:next.view,
attribute:NSLayoutAttribute.right,
relatedBy:NSLayoutRelation.equal,
toItem:parent.view,
attribute:NSLayoutAttribute.right,
multiplier:1,
constant:0)
parent.view.addConstraint(parent.layoutLeftTemporal!)
parent.view.addConstraint(parent.layoutRightTemporal!)
parent.view.addConstraint(parent.layoutTopTemporal!)
parent.view.addConstraint(parent.layoutBottomTemporal!)
parent.layoutTop = parent.layoutTopTemporal
parent.layoutBottom = parent.layoutBottomTemporal
parent.layoutRight = parent.layoutRightTemporal
parent.layoutLeft = parent.layoutLeftTemporal
}
}
|
735ee1db8a5a0d1e83be6b89e7c027b8
| 31.089552 | 63 | 0.617209 | false | false | false | false |
qualaroo/QualarooSDKiOS
|
refs/heads/master
|
Qualaroo/Filters/PropertyInjector.swift
|
mit
|
1
|
//
// TextConverter.swift
// Qualaroo
//
// Copyright (c) 2018, Qualaroo, Inc. All Rights Reserved.
//
// Please refer to the LICENSE.md file for the terms and conditions
// under which redistribution and use of this file is permitted.
//
import Foundation
protocol TextConverter: class {
func convert(_ text: String) -> String
}
class PropertyInjector {
let customProperties: CustomProperties
init(customProperties: CustomProperties) {
self.customProperties = customProperties
}
private func check(survey: Survey) -> Bool {
var missing = [String]()
for node in survey.nodeList {
missing.append(contentsOf: missingProperties(node: node))
}
if missing.count > 0 {
Qualaroo.log("""
Not showing survey with id: \(survey.surveyId).
Missing custom properties: \(missing.joined(separator: ", "))
""")
return false
}
return true
}
private func missingProperties(node: Node) -> [String] {
switch node {
case let question as Question:
var missing = missingProperties(question.title)
missing.append(contentsOf: missingProperties(question.description))
return missing
case let leadGen as LeadGenForm:
return missingProperties(leadGen.description)
case let message as Message:
return missingProperties(message.description)
default:
return []
}
}
private func missingProperties(_ text: String) -> [String] {
var properties = findAllProperties(in: text)
properties = properties.map { removeBrackets($0) }
return customProperties.checkForMissing(withKeywords: properties)
}
private func injectProperties(_ text: String) -> String {
var replacedText = text
let properties = findAllProperties(in: text)
for property in properties {
let value = customProperties.dictionary[removeBrackets(property)] ?? ""
replacedText = replacedText.replacingOccurrences(of: property,
with: value)
}
return replacedText
}
private func removeBrackets(_ text: String) -> String {
let start = text.index(text.startIndex, offsetBy: 2)
let end = text.index(before: text.endIndex)
let range = start..<end
return String(text[range])
}
private func findAllProperties(in text: String) -> [String] {
let pattern = "\\$\\{.*?\\}"
//swiftlint:disable:next force_try
let regex = try! NSRegularExpression(pattern: pattern, options: [])
let matches = regex.matches(in: text,
options: [],
range: NSRange(location: 0,
length: text.count))
return matches.map { String(text[text.range(from: $0.range)]) }
}
}
extension PropertyInjector: TextConverter {
func convert(_ text: String) -> String {
return injectProperties(text)
}
}
extension PropertyInjector: FilterProtocol {
func shouldShow(survey: Survey) -> Bool {
return check(survey: survey)
}
}
|
e5870b55cd5213290c9363598597190e
| 29.79798 | 77 | 0.646113 | false | false | false | false |
The9Labs/AudioMate
|
refs/heads/develop
|
AudioMate/PreferencesTabViewController.swift
|
mit
|
2
|
//
// PreferencesTabViewController.swift
// AudioMate
//
// Created by Ruben Nine on 12/15/16.
// Copyright © 2016 Ruben Nine. All rights reserved.
//
import Cocoa
class PreferencesTabViewController: NSTabViewController {
lazy var originalSizes = [NSTabViewItem : NSSize]()
override func viewDidLoad() {
super.viewDidLoad()
Utils.transformAppIntoForegroundMode()
// Activate (give focus to) our app
NSApplication.shared().activate(ignoringOtherApps: true)
transitionOptions = [.crossfade, .allowUserInteraction]
}
// MARK: - Lifecycle functions
deinit {
Utils.transformAppIntoUIElementMode()
}
// MARK: - NSViewController overrides
override func viewWillAppear() {
setOriginalSizeFor(tabViewItem: tabViewItems[selectedTabViewItemIndex])
animateTabViewTransitionTo(tabViewItem: tabViewItems[selectedTabViewItemIndex])
super.viewWillAppear()
}
// MARK: - NSTabViewDelegate
override func tabView(_ tabView: NSTabView, willSelect tabViewItem: NSTabViewItem?) {
super.tabView(tabView, willSelect: tabViewItem)
if let tabViewItem = tabViewItem {
setOriginalSizeFor(tabViewItem: tabViewItem)
}
}
override func tabView(_ tabView: NSTabView, didSelect tabViewItem: NSTabViewItem?) {
super.tabView(tabView, didSelect: tabViewItem)
if let tabViewItem = tabViewItem {
animateTabViewTransitionTo(tabViewItem: tabViewItem)
}
}
// MARK: - Private functions
private func setOriginalSizeFor(tabViewItem: NSTabViewItem) {
if (originalSizes[tabViewItem] == nil) {
originalSizes[tabViewItem] = tabViewItem.view?.frame.size
}
}
private func animateTabViewTransitionTo(tabViewItem: NSTabViewItem) {
guard let window = view.window else { return }
if let size = originalSizes[tabViewItem] {
window.title = tabViewItem.label
let contentFrame = window.frameRect(forContentRect: NSRect(origin: .zero, size: size))
var frame = window.frame
frame.origin.y += (frame.height - contentFrame.height)
frame.size = contentFrame.size
window.setFrame(frame, display: false, animate: true)
}
}
}
|
f1dd3d41ad2fcdaf06dcf89aab2e2e11
| 25.393258 | 98 | 0.661984 | false | false | false | false |
pinterest/PINRemoteImage
|
refs/heads/master
|
Examples/Swift-Example/Swift-Example/ScrollViewController.swift
|
apache-2.0
|
1
|
//
// ScrollViewController.swift
// Swift-Example
//
// Created by Marius Landwehr on 23.01.16.
// Copyright © 2016 Marius Landwehr. All rights reserved.
//
import UIKit
import PINRemoteImage
import PINCache
struct Kitten {
let imageUrl : URL
let size : CGSize
var dominantColor : UIColor?
init(urlString : String, size : CGSize) {
self.imageUrl = URL(string: urlString)!
self.size = size
}
}
class PinImageCell : UICollectionViewCell {
let imageView : UIImageView
override init(frame: CGRect) {
imageView = UIImageView()
super.init(frame: frame)
imageView.translatesAutoresizingMaskIntoConstraints = false
contentView.addSubview(imageView)
let view = ["imageView" : imageView]
let constraintsH = NSLayoutConstraint.constraints(withVisualFormat: "H:|-0-[imageView]-0-|", options: [], metrics: nil, views: view)
let constraintsV = NSLayoutConstraint.constraints(withVisualFormat: "V:|-0-[imageView]-0-|", options: [], metrics: nil, views: view)
contentView.addConstraints(constraintsH)
contentView.addConstraints(constraintsV)
layer.cornerRadius = 7
layer.masksToBounds = true
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func prepareForReuse() {
super.prepareForReuse()
imageView.image = nil
}
}
class ScrollViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout {
let kittens = [
Kitten(urlString: "https://i.pinimg.com/736x/92/5d/5a/925d5ac74db0dcfabc238e1686e31d16.jpg", size: CGSize(width: 503, height: 992)),
Kitten(urlString: "https://i.pinimg.com/736x/ff/b3/ae/ffb3ae40533b7f9463cf1c04d7ab69d1.jpg", size: CGSize(width: 500, height: 337)),
Kitten(urlString: "https://i.pinimg.com/736x/e4/b7/7c/e4b77ca06e1d4a401b1a49d7fadd90d9.jpg", size: CGSize(width: 522, height: 695)),
Kitten(urlString: "https://i.pinimg.com/736x/46/e1/59/46e159d76b167ed9211d662f95e7bf6f.jpg", size: CGSize(width: 557, height: 749)),
Kitten(urlString: "https://i.pinimg.com/736x/7a/72/77/7a72779329942c06f888c148eb8d7e34.jpg", size: CGSize(width: 710, height: 1069)),
Kitten(urlString: "https://i.pinimg.com/736x/60/21/8f/60218ff43257fb3b6d7c5b888f74a5bf.jpg", size: CGSize(width: 522, height: 676)),
Kitten(urlString: "https://i.pinimg.com/736x/90/e8/e4/90e8e47d53e71e0d97691dd13a5617fb.jpg", size: CGSize(width: 500, height: 688)),
Kitten(urlString: "https://i.pinimg.com/736x/96/ae/31/96ae31fbc52d96dd3308d2754a6ca37e.jpg", size: CGSize(width: 377, height: 700)),
Kitten(urlString: "https://i.pinimg.com/736x/9b/7b/99/9b7b99ff63be31bba8f9863724b3ebbc.jpg", size: CGSize(width: 334, height: 494)),
Kitten(urlString: "https://i.pinimg.com/736x/80/23/51/802351d953dd2a8b232d0da1c7ca6880.jpg", size: CGSize(width: 625, height: 469)),
Kitten(urlString: "https://i.pinimg.com/736x/f5/c4/f0/f5c4f04fa2686338dc3b08420d198484.jpg", size: CGSize(width: 625, height: 833)),
Kitten(urlString: "https://i.pinimg.com/736x/2b/06/4f/2b064f3e0af984a556ac94b251ff7060.jpg", size: CGSize(width: 625, height: 469)),
Kitten(urlString: "https://i.pinimg.com/736x/17/1f/c0/171fc02398143269d8a507a15563166a.jpg", size: CGSize(width: 625, height: 469)),
Kitten(urlString: "https://i.pinimg.com/736x/8a/35/33/8a35338bbf67c86a198ba2dd926edd82.jpg", size: CGSize(width: 625, height: 791)),
Kitten(urlString: "https://i.pinimg.com/736x/4d/6e/3c/4d6e3cf970031116c57486e85c2a4cab.jpg", size: CGSize(width: 625, height: 833)),
Kitten(urlString: "https://i.pinimg.com/736x/54/25/ee/5425eeccba78731cf7be70f0b8808bd2.jpg", size: CGSize(width: 605, height: 605)),
Kitten(urlString: "https://i.pinimg.com/736x/04/f1/3f/04f13fdb7580dcbe8c4d6b7d5a0a5ec2.jpg", size: CGSize(width: 504, height: 750)),
Kitten(urlString: "https://i.pinimg.com/736x/dc/16/4e/dc164ed33af9d899e5ed188e642f00e9.jpg", size: CGSize(width: 500, height: 500)),
Kitten(urlString: "https://i.pinimg.com/736x/c1/06/13/c106132936189b6cb654671f2a2183ed.jpg", size: CGSize(width: 640, height: 640)),
Kitten(urlString: "https://i.pinimg.com/736x/46/43/ed/4643eda4e1be4273721a76a370b90346.jpg", size: CGSize(width: 500, height: 473)),
]
var collectionKittens = [Kitten]()
var collectionView : UICollectionView?
override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
PINRemoteImageManager.shared().cache.removeAllObjects()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
PINRemoteImageManager.shared().cache.removeAllObjects()
}
override func viewDidLoad() {
super.viewDidLoad()
collectionView = UICollectionView(frame: view.bounds, collectionViewLayout: UICollectionViewFlowLayout())
collectionView?.register(PinImageCell.self, forCellWithReuseIdentifier: String(describing: PinImageCell.self))
collectionView?.delegate = self
collectionView?.dataSource = self
if let cView = collectionView {
view.addSubview(cView)
}
createRandomKittens()
}
func createRandomKittens() {
let dispatchGroup = DispatchGroup()
if let bounds = collectionView?.bounds {
var tmpKittens = [Kitten]()
DispatchQueue.global(qos: DispatchQoS.QoSClass.default).async(group: dispatchGroup) { () -> Void in
for _ in 1...500 {
let randGreen : CGFloat = CGFloat(drand48())
let randBlue : CGFloat = CGFloat(drand48())
let randRed : CGFloat = CGFloat(drand48())
let randomColor = UIColor(red: randRed, green: randGreen, blue: randBlue, alpha: 1)
let kittenIndex : Int = Int(arc4random() % 20)
let randKitten = self.kittens[kittenIndex]
var width = randKitten.size.width
var height = randKitten.size.height
if width > (bounds.size.width) {
height = height / (width / bounds.size.width)
width = bounds.size.width
}
var newKitten = Kitten(urlString: randKitten.imageUrl.absoluteString, size: CGSize(width: width, height: height))
newKitten.dominantColor = randomColor
DispatchQueue.main.sync(execute: { () -> Void in
tmpKittens.append(newKitten)
})
}
}
dispatchGroup.notify(queue: DispatchQueue.main, execute: { () -> Void in
self.collectionKittens += tmpKittens
self.collectionView?.reloadData()
})
}
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let kitten = collectionKittens[indexPath.row]
return kitten.size
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: String(describing: PinImageCell.self), for: indexPath)
if let pinCell = cell as? PinImageCell {
let kitten = collectionKittens[indexPath.row]
pinCell.backgroundColor = kitten.dominantColor
pinCell.alpha = 0
weak var weakPinCell = pinCell
pinCell.imageView.pin_setImage(from: kitten.imageUrl, completion: { (result) in
if result.requestDuration > 0.25 {
UIView.animate(withDuration: 0.3, animations: {
weakPinCell?.alpha = 1
})
} else {
weakPinCell?.alpha = 1
}
})
}
return cell
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return collectionKittens.count
}
func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
}
|
ca37fd152ce163901fda79ca790c98ef
| 45.178947 | 160 | 0.630157 | false | false | false | false |
gbuela/kanjiryokucha
|
refs/heads/master
|
KanjiRyokucha/LoginViewController.swift
|
mit
|
1
|
//
// LoginViewController.swift
// KanjiRyokucha
//
// Created by German Buela on 3/15/17.
// Copyright © 2017 German Buela. All rights reserved.
//
import UIKit
import ReactiveSwift
class LoginViewController: UIViewController {
@IBOutlet weak var loggingInLabel: UILabel!
@IBOutlet weak var errorMessageLabel: UILabel!
@IBOutlet weak var activityIndicator: UIActivityIndicatorView!
@IBOutlet weak var retryButton: UIButton!
@IBOutlet weak var manualLoginButton: UIButton!
let viewModel = LoginViewModel(sendLoginNotification: true)
var started = false
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .ryokuchaFaint
wireUp()
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
if !started {
started = true
viewModel.autologin()
}
}
private func wireUp() {
activityIndicator.reactive.isHidden <~ viewModel.state.map { !$0.isLoggingIn() }
loggingInLabel.reactive.isHidden <~ viewModel.state.map { !$0.isLoggingIn() }
activityIndicator.reactive.isAnimating <~ viewModel.state.map { $0.isLoggingIn() }
errorMessageLabel.reactive.isHidden <~ viewModel.state.map { !$0.isFailure() }
retryButton.reactive.isHidden <~ viewModel.state.map { !$0.isFailure() }
manualLoginButton.reactive.isHidden <~ viewModel.state.map { !$0.isFailure() }
errorMessageLabel.reactive.text <~ viewModel.state.map { (state: LoginState) -> String in
switch state {
case .failure(let message): return message
default: return ""
}
}
retryButton.reactive.controlEvents(.touchUpInside).react { [weak self] _ in
self?.viewModel.autologin()
}
manualLoginButton.reactive.controlEvents(.touchUpInside).react { [weak self] _ in
self?.viewModel.credentialsRequired.value = true
}
viewModel.credentialsRequired.uiReact { [weak self] required in
if required {
self?.promptForCredentials()
}
}
}
private func promptForCredentials() {
let credentialsVC = CredentialsViewController()
credentialsVC.enteredCredentialsCallback = { [weak self] (username: String, password: String) in
self?.viewModel.attemptLogin(withUsername: username, password: password)
}
present(credentialsVC, animated: true, completion: nil)
}
}
|
5e5e2aed2ae56a6207797cd812f79f5c
| 32.576923 | 104 | 0.633066 | false | false | false | false |
AmitaiB/AmazingAgeTrick
|
refs/heads/master
|
AmazingAgeTrick/CardID-enum.swift
|
mit
|
1
|
//
// CardID-enum.swift
// AmazingAgeTrick
//
// Created by Amitai Blickstein on 1/13/16.
// Copyright © 2016 Amitai Blickstein, LLC. All rights reserved.
//
import UIKit
import UIColor_Hex_Swift
//MARK: === CardID enum ===
/// CardID contains the 6 possible card values, and some convenience accessors.
enum CardID:Int {
case Card1 = 1, Card2 = 2, Card3 = 4, Card4 = 8, Card5 = 16, Card6 = 32
static let allValues = [Card1, Card2, Card3, Card4, Card5, Card6]
func cardInfoArray()->[Int] {
switch self {
case .Card1: return [1,3,5,7,9,11,13,15,17,19,21,23,25,27,29,31,33,35,37,39,41,43,45,47,49,51,53,55,57,59]
case .Card2: return [2,3,6,7,10,11,14,15,18,19,22,23,26,27,30,31,34,35,38,39,42,43,46,47,50,51,54,55,58,59]
case .Card3: return [4,5,6,7,12,13,14,15,20,21,22,23,28,29,30,31,36,37,38,39,44,45,46,47,52,53,54,55,60]
case .Card4: return [8,9,10,11,12,13,14,15,24,25,26,27,28,29,30,31,40,41,42,43,44,45,46,47,56,57,58,59,60]
case .Card5: return [16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,48,49,50,51,52,53,54,55,56,57,58,59,60]
case .Card6: return [32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60]
}
}
func altColorForCardID()->UIColor {
switch self {
case .Card1: return UIColor(red:0.74, green:0.16, blue:0.16, alpha:1)
case .Card2: return UIColor(red:0.13, green:0.52, blue:0.85, alpha:1)
case .Card3: return UIColor(red:0.96, green:0.95, blue:0.16, alpha:1)
case .Card4: return UIColor(red:0.37, green:0.63, blue:0.21, alpha:1)
case .Card5: return UIColor(red:0.77, green:0.41, blue:0.14, alpha:1)
case .Card6: return UIColor(red:0.45, green:0.13, blue:0.49, alpha:1)
}
}
func cellImageForCardID()->UIImage? {
switch self {
case .Card1: return UIImage(named: "Oval 24-red")
case .Card2: return UIImage(named: "Oval 24-orange")
case .Card3: return UIImage(named: "Oval 24-green")
case .Card4: return UIImage(named: "Oval 24-blue")
case .Card5: return UIImage(named: "Oval 24-violet")
case .Card6: return UIImage(named: "Oval 24-midnight")
}
}
}
|
3391397072f128b5a2df270a4a25b67d
| 40.392857 | 116 | 0.595772 | false | false | false | false |
LawrenceHan/iOS-project-playground
|
refs/heads/master
|
Swift_Algorithm/Swift_Algorithm/Edge.swift
|
mit
|
1
|
//
// Edge.swift
// Swift_Algorithm
//
// Created by Hanguang on 23/11/2016.
// Copyright © 2016 Hanguang. All rights reserved.
//
import Foundation
public struct Edge<T>: Equatable where T: Equatable, T: Hashable {
public let from: Vertex<T>
public let to: Vertex<T>
public let weight: Double?
}
extension Edge: CustomStringConvertible {
public var description: String {
get {
guard let unwrappedWeight = weight else {
return "\(from.description) -> \(to.description)"
}
return "\(from.description) -(\(unwrappedWeight))-> \(to.description)"
}
}
}
extension Edge: Hashable {
public var hashValue: Int {
get {
var string = "\(from.description)\(to.description)"
if weight != nil {
string.append("\(weight)")
}
return string.hashValue
}
}
}
public func == <T>(lhs: Edge<T>, rhs: Edge<T>) -> Bool {
guard lhs.from == rhs.from else {
return false
}
guard lhs.to == rhs.to else {
return false
}
guard lhs.weight == rhs.weight else {
return false
}
return true
}
|
ed509765f1184be41bf7d6e508abfa9e
| 19.932203 | 82 | 0.5417 | false | false | false | false |
MaartenBrijker/project
|
refs/heads/back
|
project/External/AudioKit-master/AudioKit/Common/Nodes/Generators/Oscillators/FM Oscillator/AKFMOscillatorPresets.swift
|
apache-2.0
|
1
|
//
// AKFMOscillatorPresets.swift
// AudioKit
//
// Created by Aurelius Prochazka on 4/12/16.
// Copyright © 2016 AudioKit. All rights reserved.
//
import Foundation
/// Preset for the AKFMOscillator
public extension AKFMOscillator {
/// Stun Ray Preset
public func presetStunRay() {
baseFrequency = 200
carrierMultiplier = 90
modulatingMultiplier = 10
modulationIndex = 25
}
/// Fog Horn Preset
public func presetFogHorn() {
baseFrequency = 25
carrierMultiplier = 10
modulatingMultiplier = 5
modulationIndex = 10
}
/// Buzzer Preset
public func presetBuzzer() {
baseFrequency = 400
carrierMultiplier = 28
modulatingMultiplier = 0.5
modulationIndex = 100
}
/// Spiral Preset
public func presetSpiral() {
baseFrequency = 5
carrierMultiplier = 280
modulatingMultiplier = 0.2
modulationIndex = 100
}
/// Wobble Preset
public func presetWobble() {
baseFrequency = 20
carrierMultiplier = 10
modulatingMultiplier = 0.9
modulationIndex = 20
}
}
|
cf1c4413de7a576be01de01101d9fbea
| 21.037037 | 51 | 0.603869 | false | false | false | false |
seanoshea/computer-science-in-swift
|
refs/heads/master
|
computer-science-in-swift/LinkedList.swift
|
mit
|
1
|
// Copyright (c) 2015-2016 Sean O'Shea. 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 Foundation
class LinkedListNode {
var data:Int = 0
var next:LinkedListNode?
}
class LinkedList: NSObject {
var head:LinkedListNode?
var length:Int = 0
func add(_ data:Int) {
let node = LinkedListNode()
node.data = data
var current:LinkedListNode
if self.head == nil {
self.head = node
} else {
current = self.head!
while current.next != nil {
current = current.next!
}
current.next = node
}
self.length = self.length + 1
}
func item(_ index:Int) -> Int? {
if index > -1 && index < self.length {
var current:LinkedListNode = self.head!
var i = 0
while i < index {
current = current.next!
i = i + 1
}
return current.data
}
return nil
}
func remove(_ index:Int) -> Int? {
if index > -1 && index < self.length {
var current:LinkedListNode = self.head!
var previous:LinkedListNode = LinkedListNode()
var i = 0
if index == 0 {
self.head = current.next
} else {
while i < index {
previous = current
current = current.next!
i = i + 1
}
previous.next = current.next
}
self.length = self.length - 1
return current.data
} else {
return nil
}
}
func size() -> Int {
return self.length
}
func toArray() -> [Int] {
var result = [Int]()
for i in 0..<self.length {
result.append(self.item(i)!)
}
return result
}
func clear() {
for i in 0..<self.length {
_ = self.remove(i)
}
self.head = nil
self.length = 0
}
}
|
90453a5756823796042dc1760543f1ff
| 29.221154 | 80 | 0.557747 | false | false | false | false |
DanielFulton/ImageLibraryTests
|
refs/heads/master
|
Pods/ImageLoader/ImageLoader/Loader.swift
|
mit
|
1
|
//
// Loader.swift
// ImageLoader
//
// Created by Hirohisa Kawasaki on 5/2/16.
// Copyright © 2016 Hirohisa Kawasaki. All rights reserved.
//
import UIKit
import Foundation
/**
Responsible for sending a request and receiving the response and calling blocks for the request.
*/
public class Loader {
unowned let delegate: Manager
let task: NSURLSessionDataTask
var receivedData = NSMutableData()
var blocks: [Block] = []
init (task: NSURLSessionDataTask, delegate: Manager) {
self.task = task
self.delegate = delegate
resume()
}
var state: NSURLSessionTaskState {
return task.state
}
public func completionHandler(completionHandler: CompletionHandler) -> Self {
let identifier = (blocks.last?.identifier ?? 0) + 1
return self.completionHandler(identifier, completionHandler: completionHandler)
}
public func completionHandler(identifier: Int, completionHandler: CompletionHandler) -> Self {
let block = Block(identifier: identifier, completionHandler: completionHandler)
return appendBlock(block)
}
func appendBlock(block: Block) -> Self {
blocks.append(block)
return self
}
// MARK: task
public func suspend() {
task.suspend()
}
public func resume() {
task.resume()
}
public func cancel() {
task.cancel()
}
func remove(identifier: Int) {
// needs to queue with sync
blocks = blocks.filter{ $0.identifier != identifier }
}
func receive(data: NSData) {
receivedData.appendData(data)
}
func complete(error: NSError?, completionHandler: () -> Void) {
if let URL = task.originalRequest?.URL {
if let error = error {
failure(URL, error: error, completionHandler: completionHandler)
return
}
dispatch_async(delegate.decompressingQueue) { [weak self] in
guard let wSelf = self else {
return
}
wSelf.success(URL, data: wSelf.receivedData, completionHandler: completionHandler)
}
}
}
private func success(URL: NSURL, data: NSData, completionHandler: () -> Void) {
let image = UIImage.decode(data)
_toCache(URL, data: data)
for block in blocks {
block.completionHandler(URL, image, nil, .None)
}
blocks = []
completionHandler()
}
private func failure(URL: NSURL, error: NSError, completionHandler: () -> Void) {
for block in blocks {
block.completionHandler(URL, nil, error, .None)
}
blocks = []
completionHandler()
}
private func _toCache(URL: NSURL, data: NSData?) {
if let data = data {
delegate.cache[URL] = data
}
}
}
|
74a6474d9c29250623abf7ee9155685b
| 24.866071 | 98 | 0.597376 | false | false | false | false |
JohnPJenkins/swift-t
|
refs/heads/master
|
stc/tests/291-chain-statements.swift
|
apache-2.0
|
4
|
import sys;
main {
// Check that declaration of y and z is visible in main block scope
int x = 1 =>
int y = 1 =>
int z = 1;
trace(x, y, z);
}
|
9184475c908f0b0a62cf76ffccd29603
| 16 | 71 | 0.517647 | false | false | false | false |
CPRTeam/CCIP-iOS
|
refs/heads/master
|
BeeFun/Pods/SwiftDate/Sources/SwiftDate/Supports/TimeStructures.swift
|
gpl-3.0
|
7
|
//
// SwiftDate
// Parse, validate, manipulate, and display dates, time and timezones in Swift
//
// Created by Daniele Margutti
// - Web: https://www.danielemargutti.com
// - Twitter: https://twitter.com/danielemargutti
// - Mail: [email protected]
//
// Copyright © 2019 Daniele Margutti. Licensed under MIT License.
//
import Foundation
// MARK: - Weekday
/// This define the weekdays for some functions.
public enum WeekDay: Int {
case sunday = 1, monday, tuesday, wednesday, thursday, friday, saturday
/// Returns the name of the day given a specific locale.
/// For example, for the `Friday` enum value, the en_AU locale would return "Friday" and fr_FR would return "samedi"
///
/// - Parameter locale: locale of the output, omit to use the `defaultRegion`'s locale.
/// - Returns: display name
public func name(style: SymbolFormatStyle = .`default`, locale: LocaleConvertible = SwiftDate.defaultRegion.locale) -> String {
let region = Region(calendar: SwiftDate.defaultRegion.calendar, zone: SwiftDate.defaultRegion.timeZone, locale: locale)
let formatter = DateFormatter.sharedFormatter(forRegion: region, format: nil)
let idx = (self.rawValue - 1)
switch style {
case .default: return formatter.weekdaySymbols[idx]
case .defaultStandalone: return formatter.standaloneWeekdaySymbols[idx]
case .short: return formatter.shortWeekdaySymbols[idx]
case .standaloneShort: return formatter.shortStandaloneWeekdaySymbols[idx]
case .veryShort: return formatter.veryShortWeekdaySymbols[idx]
case .standaloneVeryShort: return formatter.veryShortStandaloneWeekdaySymbols[idx]
}
}
/// Adds a number of days to the current weekday and returns the new weekday.
///
/// - Parameter months: number of months to add
/// - Returns: new month.
public func add(days: Int) -> WeekDay {
let normalized = days % 7
return WeekDay(rawValue: ((self.rawValue + normalized + 7 - 1) % 7) + 1)!
}
/// Subtracts a number of days from the current weekday and returns the new weekday.
///
/// - Parameter months: number of days to subtract. May be negative, in which case it will be added
/// - Returns: new weekday.
public func subtract(days: Int) -> WeekDay {
return add(days: -(days % 7))
}
}
// MARK: - Year
public struct Year: CustomStringConvertible, Equatable {
let year: Int
public var description: String {
return "\(self.year)"
}
/// Constructs a `Year` from the passed value.
///
/// - Parameter year: year value. Can be negative.
public init(_ year: Int) {
self.year = year
}
/// Returns whether this year is a leap year
///
/// - Returns: A boolean indicating whether this year is a leap year
public func isLeap() -> Bool {
return ((year & 3) == 0) && ((year % 100) != 0 || (year % 400) == 0)
}
/// Returns the number of days in this year
///
/// - Returns: The number of days in this year
public func numberOfDays() -> Int {
return self.isLeap() ? 366 : 365
}
}
// MARK: - Month
/// Defines months in a year
public enum Month: Int, CustomStringConvertible, Equatable {
case january = 0, february, march, april, may, june, july, august, september, october, november, december
public var description: String {
return self.name()
}
/// Returns the name of the month given a specific locale.
/// For example, for the `January` enum value, the en_AU locale would return "January" and fr_FR would return "janvier"
///
/// - Parameter locale: locale of the output, omit to use the `defaultRegion`'s locale.
/// - Returns: display name
public func name(style: SymbolFormatStyle = .`default`, locale: LocaleConvertible = SwiftDate.defaultRegion.locale) -> String {
let region = Region(calendar: SwiftDate.defaultRegion.calendar, zone: SwiftDate.defaultRegion.timeZone, locale: locale)
let formatter = DateFormatter.sharedFormatter(forRegion: region, format: nil)
switch style {
case .default: return formatter.monthSymbols[self.rawValue]
case .defaultStandalone: return formatter.standaloneMonthSymbols[self.rawValue]
case .short: return formatter.shortMonthSymbols[self.rawValue]
case .standaloneShort: return formatter.shortStandaloneMonthSymbols[self.rawValue]
case .veryShort: return formatter.veryShortMonthSymbols[self.rawValue]
case .standaloneVeryShort: return formatter.veryShortStandaloneMonthSymbols[self.rawValue]
}
}
/// Adds a number of months to the current month and returns the new month.
///
/// - Parameter months: number of months to add
/// - Returns: new month.
public func add(months: Int) -> Month {
let normalized = months % 12
return Month(rawValue: (self.rawValue + normalized + 12) % 12)!
}
/// Subtracts a number of months from the current month and returns the new month.
///
/// - Parameter months: number of months to subtract. May be negative, in which case it will be added
/// - Returns: new month.
public func subtract(months: Int) -> Month {
return add(months: -(months % 12))
}
/// Returns the number of days in a this month for a given year
///
/// - Parameter year: reference year.
/// - Returns: The number of days in this month.
public func numberOfDays(year: Int) -> Int {
switch self {
case .february:
return Year(year).isLeap() ? 29 : 28
case .april, .june, .september, .november:
return 30
default:
return 31
}
}
}
|
1314e65d4daeaf3c347bb163fb10dea9
| 34.184211 | 128 | 0.710172 | false | false | false | false |
noppoMan/aws-sdk-swift
|
refs/heads/main
|
Sources/Soto/Services/Braket/Braket_Paginator.swift
|
apache-2.0
|
1
|
//===----------------------------------------------------------------------===//
//
// This source file is part of the Soto for AWS open source project
//
// Copyright (c) 2017-2020 the Soto project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of Soto project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
// THIS FILE IS AUTOMATICALLY GENERATED by https://github.com/soto-project/soto/tree/main/CodeGenerator. DO NOT EDIT.
import SotoCore
// MARK: Paginators
extension Braket {
/// Searches for devices using the specified filters.
///
/// Provide paginated results to closure `onPage` for it to combine them into one result.
/// This works in a similar manner to `Array.reduce<Result>(_:_:) -> Result`.
///
/// Parameters:
/// - input: Input for request
/// - initialValue: The value to use as the initial accumulating value. `initialValue` is passed to `onPage` the first time it is called.
/// - logger: Logger used flot logging
/// - eventLoop: EventLoop to run this process on
/// - onPage: closure called with each paginated response. It combines an accumulating result with the contents of response. This combined result is then returned
/// along with a boolean indicating if the paginate operation should continue.
public func searchDevicesPaginator<Result>(
_ input: SearchDevicesRequest,
_ initialValue: Result,
logger: Logger = AWSClient.loggingDisabled,
on eventLoop: EventLoop? = nil,
onPage: @escaping (Result, SearchDevicesResponse, EventLoop) -> EventLoopFuture<(Bool, Result)>
) -> EventLoopFuture<Result> {
return client.paginate(
input: input,
initialValue: initialValue,
command: searchDevices,
tokenKey: \SearchDevicesResponse.nextToken,
on: eventLoop,
onPage: onPage
)
}
/// Provide paginated results to closure `onPage`.
///
/// - Parameters:
/// - input: Input for request
/// - logger: Logger used flot logging
/// - eventLoop: EventLoop to run this process on
/// - onPage: closure called with each block of entries. Returns boolean indicating whether we should continue.
public func searchDevicesPaginator(
_ input: SearchDevicesRequest,
logger: Logger = AWSClient.loggingDisabled,
on eventLoop: EventLoop? = nil,
onPage: @escaping (SearchDevicesResponse, EventLoop) -> EventLoopFuture<Bool>
) -> EventLoopFuture<Void> {
return client.paginate(
input: input,
command: searchDevices,
tokenKey: \SearchDevicesResponse.nextToken,
on: eventLoop,
onPage: onPage
)
}
/// Searches for tasks that match the specified filter values.
///
/// Provide paginated results to closure `onPage` for it to combine them into one result.
/// This works in a similar manner to `Array.reduce<Result>(_:_:) -> Result`.
///
/// Parameters:
/// - input: Input for request
/// - initialValue: The value to use as the initial accumulating value. `initialValue` is passed to `onPage` the first time it is called.
/// - logger: Logger used flot logging
/// - eventLoop: EventLoop to run this process on
/// - onPage: closure called with each paginated response. It combines an accumulating result with the contents of response. This combined result is then returned
/// along with a boolean indicating if the paginate operation should continue.
public func searchQuantumTasksPaginator<Result>(
_ input: SearchQuantumTasksRequest,
_ initialValue: Result,
logger: Logger = AWSClient.loggingDisabled,
on eventLoop: EventLoop? = nil,
onPage: @escaping (Result, SearchQuantumTasksResponse, EventLoop) -> EventLoopFuture<(Bool, Result)>
) -> EventLoopFuture<Result> {
return client.paginate(
input: input,
initialValue: initialValue,
command: searchQuantumTasks,
tokenKey: \SearchQuantumTasksResponse.nextToken,
on: eventLoop,
onPage: onPage
)
}
/// Provide paginated results to closure `onPage`.
///
/// - Parameters:
/// - input: Input for request
/// - logger: Logger used flot logging
/// - eventLoop: EventLoop to run this process on
/// - onPage: closure called with each block of entries. Returns boolean indicating whether we should continue.
public func searchQuantumTasksPaginator(
_ input: SearchQuantumTasksRequest,
logger: Logger = AWSClient.loggingDisabled,
on eventLoop: EventLoop? = nil,
onPage: @escaping (SearchQuantumTasksResponse, EventLoop) -> EventLoopFuture<Bool>
) -> EventLoopFuture<Void> {
return client.paginate(
input: input,
command: searchQuantumTasks,
tokenKey: \SearchQuantumTasksResponse.nextToken,
on: eventLoop,
onPage: onPage
)
}
}
extension Braket.SearchDevicesRequest: AWSPaginateToken {
public func usingPaginationToken(_ token: String) -> Braket.SearchDevicesRequest {
return .init(
filters: self.filters,
maxResults: self.maxResults,
nextToken: token
)
}
}
extension Braket.SearchQuantumTasksRequest: AWSPaginateToken {
public func usingPaginationToken(_ token: String) -> Braket.SearchQuantumTasksRequest {
return .init(
filters: self.filters,
maxResults: self.maxResults,
nextToken: token
)
}
}
|
cb294b8dfe1861ee4983f84565346f39
| 39.972028 | 168 | 0.63219 | false | false | false | false |
danthorpe/TaylorSource
|
refs/heads/development
|
Tests/Helpers.swift
|
mit
|
2
|
//
// Created by Daniel Thorpe on 19/04/2015.
// Copyright (c) 2015 Daniel Thorpe. All rights reserved.
//
import UIKit
import YapDatabase
import ValueCoding
import YapDatabaseExtensions
import TaylorSource
class StubbedTableView: UITableView {
override func dequeueCellWithIdentifier(id: String, atIndexPath indexPath: NSIndexPath) -> UITableViewCell {
return UITableViewCell(style: .Default, reuseIdentifier: id)
}
override func dequeueReusableHeaderFooterViewWithIdentifier(identifier: String) -> UITableViewHeaderFooterView? {
return UITableViewHeaderFooterView(reuseIdentifier: identifier)
}
}
class StubbedCollectionView: UICollectionView {
override func dequeueCellWithIdentifier(id: String, atIndexPath indexPath: NSIndexPath) -> UICollectionReusableView {
return UICollectionViewCell()
}
override func dequeueReusableSupplementaryViewOfKind(elementKind: String, withReuseIdentifier identifier: String, forIndexPath indexPath: NSIndexPath) -> UICollectionReusableView {
return UICollectionReusableView()
}
}
extension NSIndexPath {
static var first: NSIndexPath {
return NSIndexPath(forItem: 0, inSection: 0)
}
}
// MARK: - Fake Models
struct Person {
enum Gender: Int {
case Unknown = 1, Female, Male
}
let age: Int
let gender: Gender
let name: String
}
class PersonCoder: NSObject, NSCoding, CodingType {
let value: Person
required init(_ v: Person) {
value = v
}
required init?(coder aDecoder: NSCoder) {
if let gender = Person.Gender(rawValue: aDecoder.decodeIntegerForKey("gender")) {
let age = aDecoder.decodeIntegerForKey("age")
let name = aDecoder.decodeObjectForKey("name") as! String
value = Person(age: age, gender: gender, name: name)
}
else { fatalError("Person.Gender not encoded correctly") }
}
func encodeWithCoder(aCoder: NSCoder) {
aCoder.encodeInteger(value.age, forKey: "age")
aCoder.encodeInteger(value.gender.rawValue, forKey: "gender")
aCoder.encodeObject(value.name, forKey: "name")
}
}
extension Person: ValueCoding {
typealias Coder = PersonCoder
}
extension Person.Gender: CustomStringConvertible {
var description: String {
switch self {
case .Unknown: return "Unknown"
case .Female: return "Female"
case .Male: return "Male"
}
}
}
extension Person: Identifiable {
var identifier: Identifier {
return "\(name) - \(gender) - \(age)"
}
}
extension Person: Persistable {
static var collection: String {
return "People"
}
}
extension Person: CustomStringConvertible {
var description: String {
return "\(name), \(gender) \(age)"
}
}
func generateRandomPeople(count: Int) -> [Person] {
let possibleNames: [(Person.Gender, String)] = [
(.Male, "Tony"),
(.Male, "Thor"),
(.Male, "Bruce"),
(.Male, "Steve"),
(.Female, "Natasha"),
(.Male, "Clint"),
(.Unknown, "Ultron"),
(.Male, "Nick"),
(.Male, "James"),
(.Male, "Pietro"),
(.Female, "Wanda"),
(.Unknown, "Jarvis"),
(.Female, "Maria"),
(.Male, "Sam"),
(.Female, "Peggy")
]
func createRandomPerson(_: Int) -> Person {
let index = Int(arc4random_uniform(UInt32(possibleNames.endIndex)))
let rando = possibleNames[index]
let age = 25 + Int(arc4random_uniform(20))
return Person(age: age, gender: rando.0, name: rando.1)
}
return Array(0..<count).map(createRandomPerson)
}
func people(name: String, byGroup createGroup: (Person) -> String) -> YapDB.Fetch {
let grouping: YapDB.View.Grouping = .ByObject({ (_, collection, key, object) -> String! in
if collection == Person.collection {
if let person = Person.decode(object) {
return createGroup(person)
}
}
return .None
})
let sorting: YapDB.View.Sorting = .ByObject({ (_, group, collection1, key1, object1, collection2, key2, object2) -> NSComparisonResult in
if let person1 = Person.decode(object1),
let person2 = Person.decode(object2) {
let comparison = person1.name.caseInsensitiveCompare(person2.name)
switch comparison {
case .OrderedSame:
return person1.age < person2.age ? .OrderedAscending : .OrderedDescending
default:
return comparison
}
}
return .OrderedSame
})
let view = YapDB.View(name: name, grouping: grouping, sorting: sorting, collections: [Person.collection])
return .View(view)
}
func people(name: String, byGroup createGroup: (Person) -> String) -> YapDB.FetchConfiguration {
return YapDB.FetchConfiguration(fetch: people(name, byGroup: createGroup))
}
func people(name: String, byGroup createGroup: (Person) -> String) -> Configuration<Person> {
return Configuration(fetch: people(name, byGroup: createGroup), itemMapper: Person.decode)
}
|
8c38e0079c66ac5ad009ec8954dbf0e2
| 28.08427 | 184 | 0.637242 | false | false | false | false |
iAugux/iBBS-Swift
|
refs/heads/master
|
iBBS/IBBSFavoriteContainerViewController.swift
|
mit
|
1
|
//
// IBBSFavoriteContainerViewController.swift
// iBBS
//
// Created by Augus on 5/5/16.
// Copyright © 2016 iAugus. All rights reserved.
//
import UIKit
import SwiftyJSON
let postNewArticleInFavoriteVCSegueId = "favoriteControllerPresentEditingVC"
class IBBSFavoriteContainerViewController: IBBSBaseViewController {
override func viewDidLoad() {
super.viewDidLoad()
automaticPullingDownToRefresh()
configureTableView()
sendRequest()
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
/**
important: if present NavigationController's property of interactivePopGestureRecognizer is enable, we must set it to disable,
otherwise if we call UIScreenEdgePanGestureRecognizer on present ViewController it will crash.
*/
// navigationController?.interactivePopGestureRecognizer?.delegate = nil
navigationController?.interactivePopGestureRecognizer?.enabled = false
}
private func sendRequest() {
let key = IBBSLoginKey()
guard key.isValid else {
IBBSContext.loginIfNeeded(alertMessage: PLEASE_LOGIN, completion: nil)
return
}
APIClient.defaultClient.getFavoriteTopics(key.uid, token: key.token, success: { (json) -> Void in
DEBUGPrint(json)
if json == nil {
IBBSToast.make(NO_DATA, delay: 0, interval: TIME_OF_TOAST_OF_NO_MORE_DATA)
self.tableView.reloadData()
return
}
if json.type == Type.Array {
self.datasource = json.arrayValue
self.tableView.reloadData()
}
}, failure: { (error) -> Void in
DEBUGLog(error)
IBBSToast.make(SERVER_ERROR, delay: 0, interval: TIME_OF_TOAST_OF_SERVER_ERROR)
})
}
private func configureTableView() {
tableView.registerNib(UINib(nibName: String(IBBSTableViewCell), bundle: nil ), forCellReuseIdentifier: String(IBBSTableViewCell))
tableView.tableFooterView = UIView(frame: CGRectZero)
tableView.estimatedRowHeight = 100
tableView.rowHeight = UITableViewAutomaticDimension
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func cornerActionButtonDidTap() {
performPostNewArticleSegue(segueIdentifier: postNewArticleInFavoriteVCSegueId)
}
}
extension IBBSFavoriteContainerViewController {
// MARK: - Table view data source
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return datasource?.count ?? 0
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
if let cell = tableView.dequeueReusableCellWithIdentifier(String(IBBSTableViewCell)) as? IBBSTableViewCell {
let json = datasource[indexPath.row]
cell.loadDataToCell(json)
return cell
}
return UITableViewCell()
}
// MARK: - table view delegate
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
let json = datasource[indexPath.row]
let vc = IBBSDetailViewController()
vc.json = json
vc.navigationController?.navigationBar.hidden = true
navigationController?.pushViewController(vc, animated: true)
}
}
extension IBBSFavoriteContainerViewController {
override func automaticContentOffset() {
gearRefreshControl.beginRefreshing()
tableView.setContentOffset(CGPointMake(0, -125.0), animated: true)
executeAfterDelay(0.5) {
self.gearRefreshControl.endRefreshing()
}
}
// MARK: - refresh
override func refreshData() {
super.refreshData()
sendRequest()
// be sure to stop refreshing while there is an error with network or something else
let refreshInSeconds = 1.3
let popTime = dispatch_time(DISPATCH_TIME_NOW, Int64(refreshInSeconds * Double(NSEC_PER_SEC)));
dispatch_after(popTime, dispatch_get_main_queue()) { () -> Void in
self.page = 1
self.gearRefreshControl?.endRefreshing()
}
}
}
|
1e957d5e51e84bd1cbd544c4623a4a6b
| 31.384615 | 137 | 0.629454 | false | false | false | false |
JosephNK/SwiftyIamport
|
refs/heads/master
|
SwiftyIamportDemo/Controller/WKHtml5InicisViewController.swift
|
mit
|
1
|
//
// WKHtml5InicisViewController.swift
// SwiftyIamportDemo
//
// Created by JosephNK on 29/11/2018.
// Copyright © 2018 JosephNK. All rights reserved.
//
import UIKit
import SwiftyIamport
import WebKit
class WKHtml5InicisViewController: UIViewController {
lazy var wkWebView: WKWebView = {
var view = WKWebView()
view.backgroundColor = UIColor.clear
view.navigationDelegate = self
return view
}()
override func viewDidLoad() {
super.viewDidLoad()
self.view.addSubview(wkWebView)
self.wkWebView.frame = self.view.bounds
// 결제 환경 설정
IAMPortPay.sharedInstance.configure(scheme: "iamporttest", // info.plist에 설정한 scheme
storeIdentifier: "imp68124833") // iamport 에서 부여받은 가맹점 식별코드
IAMPortPay.sharedInstance
.setPGType(.html5_inicis) // PG사 타입
.setIdName(nil) // 상점아이디 ({PG사명}.{상점아이디}으로 생성시 사용)
.setPayMethod(.card) // 결제 형식
.setWKWebView(self.wkWebView) // 현재 Controller에 있는 WebView 지정
.setRedirectUrl(nil) // m_redirect_url 주소
// 결제 정보 데이타
let parameters: IAMPortParameters = [
"merchant_uid": String(format: "merchant_%@", String(Int(NSDate().timeIntervalSince1970 * 1000))),
"name": "결제테스트",
"amount": "1004",
"buyer_email": "[email protected]",
"buyer_name": "구매자",
"buyer_tel": "010-1234-5678",
"buyer_addr": "서울특별시 강남구 삼성동",
"buyer_postcode": "123-456",
"custom_data": ["A1": 123, "B1": "Hello"]
//"custom_data": "24"
]
IAMPortPay.sharedInstance.setParameters(parameters).commit()
// 결제 웹페이지(Local) 파일 호출
if let url = IAMPortPay.sharedInstance.urlFromLocalHtmlFile() {
let request = URLRequest(url: url)
self.wkWebView.load(request)
}
}
}
extension WKHtml5InicisViewController: WKNavigationDelegate {
func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
let request = navigationAction.request
IAMPortPay.sharedInstance.requestRedirectUrl(for: request, parser: { (data, response, error) -> Any? in
// Background Thread 처리
var resultData: [String: Any]?
if let httpResponse = response as? HTTPURLResponse {
let statusCode = httpResponse.statusCode
switch statusCode {
case 200:
resultData = [
"isSuccess": "OK"
]
break
default:
break
}
}
return resultData
}) { (pasingData) in
// Main Thread 처리
}
let result = IAMPortPay.sharedInstance.requestAction(for: request)
decisionHandler(result ? .allow : .cancel)
}
func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
// 결제 환경으로 설정에 의한 웹페이지(Local) 호출 결과
IAMPortPay.sharedInstance.requestIAMPortPayWKWebViewDidFinishLoad(webView) { (error) in
if error != nil {
switch error! {
case .custom(let reason):
print("error: \(reason)")
break
}
}else {
print("OK")
}
}
}
func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) {
print("didFail")
}
func webView(_ webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: Error) {
print("didFailProvisionalNavigation \(error.localizedDescription)")
}
}
|
1b0f5cca3df18975753ad7e25dd6dd2d
| 34.008621 | 157 | 0.544447 | false | false | false | false |
slepcat/mint-lisp
|
refs/heads/master
|
mint-lisp/mintlisp_env.swift
|
apache-2.0
|
1
|
//
// mintlisp_env.swift
// mint-lisp
//
// Created by NemuNeko on 2015/08/03.
// Copyright (c) 2015年 Taizo A. All rights reserved.
//
import Foundation
class Env {
var hash_table = [String: SExpr]()
var ext_env: Env?
init() {
ext_env = nil
}
/* debug print
deinit {
if hash_table.count > 10 {
print("deinit env, with \(hash_table.count) elements")
}
}
*/
func lookup(_ key : String) -> SExpr {
if let value = hash_table[key] {
return value
} else {
if let eenv = ext_env {
return eenv.lookup(key)
} else {
print("Unbouded symbol", terminator: "\n")
return MNull()
}
}
}
// todo: variable length of arguments
func extended_env(_ symbols: [SExpr], values: [SExpr]) -> Env? {
let _env = Env()
_env.ext_env = self
if symbols.count == values.count {
for i in 0..<symbols.count {
if let symbol = symbols[i] as? MSymbol {
_env.define_variable(symbol.key, val: values[i])
} else {
print("Unproper parameter values", terminator: "\n")
return nil
}
}
return _env
} else if symbols.count == 1 {
if let _ = symbols.last as? MNull {
return _env
}
}
print("Err. Number of Symbol and Value is unmatch.", terminator: "\n")
return nil
}
func clone() -> Env {
let cloned_env = Env()
cloned_env.ext_env = self.ext_env?.clone()
cloned_env.hash_table = self.hash_table
return cloned_env
}
func define_variable(_ key: String, val: SExpr) -> Bool {
if hash_table[key] == nil {
hash_table[key] = val
return true
} else {
return false
}
}
func set_variable(_ key: String, val: SExpr) -> Bool {
if hash_table[key] == nil {
return false
} else {
hash_table[key] = val
return true
}
}
func define_variable_force(_ key: String, val: SExpr) -> Bool {
hash_table[key] = val
return true
}
}
func global_environment() -> [String : SExpr] {
var primitives = [String : SExpr]()
///// basic operators /////
primitives["+"] = Plus()
primitives["-"] = Minus()
primitives["*"] = Multiply()
primitives["/"] = Divide()
primitives["="] = isEqual()
primitives[">"] = GreaterThan()
primitives["<"] = SmallerThan()
primitives[">="] = EqualOrGreaterThan()
primitives["<="] = EqualOrSmallerThan()
primitives["mod"] = Mod()
primitives["and"] = And()
primitives["or"] = Or()
primitives["not"] = Not()
primitives["pow"] = Power()
primitives["floor"] = Floor()
primitives["ceil"] = Ceil()
primitives["round"] = Round()
primitives["cos"] = Cos()
primitives["sin"] = Sin()
primitives["tan"] = Tan()
primitives["asin"] = ArcSin()
primitives["acos"] = ArcCos()
primitives["atan"] = ArcTan()
primitives["atan2"] = ArcTan2()
primitives["sinh"] = Sinh()
primitives["cosh"] = Cosh()
primitives["tanh"] = Tanh()
primitives["abs"] = Abs()
primitives["sqrt"] = Sqrt()
primitives["exp"] = Exp()
primitives["log"] = Log()
primitives["log10"] = Log10()
primitives["max"] = Max()
primitives["min"] = Min()
primitives["random"] = Random()
primitives["time"] = Time()
primitives["pi"] = MDouble(_value: M_1_PI)
///// conscell management /////
primitives["cons"] = Cons()
primitives["join"] = Join()
primitives["car"] = Car()
primitives["cdr"] = Cdr()
primitives["caar"] = Caar()
primitives["cadr"] = Cadr()
primitives["cdar"] = Cdar()
primitives["cddr"] = Cddr()
primitives["caaar"] = Caaar()
primitives["caadr"] = Caadr()
primitives["caddr"] = Caddr()
primitives["cdddr"] = Cdddr()
primitives["cdaar"] = Cdaar()
primitives["cddar"] = Cddar()
primitives["cdadr"] = Cdadr()
primitives["cadar"] = Cadar()
primitives["null"] = MNull()
///// array managemetn /////
primitives["array"] = NewArray()
primitives["at-index"] = ArrayAtIndex()
primitives["append"] = AppendArray()
primitives["joint"] = JointArray()
primitives["remove-at-index"] = RemoveAtIndex()
primitives["remove-last"] = RemoveLast()
primitives["remove-all"] = RemoveAll()
primitives["count"] = CountArray()
//primitives["list"] = isEqual()
//primitives["apply"] = isEqual()
//primitives["map"] = isEqual()
///// Type Casting /////
primitives["cast-double"] = CastDouble()
///// 3D data objects /////
primitives["vec"] = Vec()
primitives["vec.x"] = Vec_x()
primitives["vec.y"] = Vec_y()
primitives["vec.z"] = Vec_z()
primitives["vex"] = Vex()
primitives["vex.pos"] = Vex_Pos()
primitives["vex.normal"] = Vex_Normal()
primitives["vex.color"] = Vex_Color()
primitives["color"] = Color()
primitives["color.r"] = Color_r()
primitives["color.g"] = Color_g()
primitives["color.b"] = Color_b()
primitives["color.a"] = Color_a()
primitives["plane"] = Pln()
primitives["plane.normal"] = Pln_normal()
primitives["ln"] = Ln()
primitives["ln.pos"] = Ln_Pos()
primitives["ln.dir"] = Ln_Dir()
primitives["ln-seg"] = LnSeg()
primitives["poly"] = Poly()
primitives["poly.vex-at-index"] = Poly_VexAtIndex()
primitives["poly.vex-count"] = Poly_VexCount()
///// 3d primitives /////
primitives["cube"] = Cube()
primitives["sphere"] = Sphere()
primitives["cylinder"] = Cylinder()
///// 3d Transform /////
primitives["set-color"] = SetColor()
primitives["union"] = Union()
primitives["subtract"] = Subtract()
primitives["intersect"] = Intersect()
primitives["rotate"] = Rotate()
primitives["rotate-axis"] = RotateAxis()
primitives["move"] = Translate()
primitives["scale"] = Scale()
///// 2d data objects //////
primitives["shape"] = Shp()
///// IO /////
primitives["print"] = Print()
//primitives["display"] = Display()
primitives["quit"] = Quit()
return primitives
}
|
150d197af219182ceaed114caba83d65
| 26.329167 | 78 | 0.52325 | false | false | false | false |
PandaCoderSchool/Job4Students
|
refs/heads/master
|
Jobs4Students/JobDetailsViewController.swift
|
gpl-2.0
|
1
|
//
// JobDetailsViewController.swift
// Jobs4Students
//
// Created by Dan Tong on 9/21/15.
// Copyright © 2015 iOS Swift Course. All rights reserved.
//
import UIKit
import MapKit
class JobDetailsViewController: UIViewController, MKMapViewDelegate {
@IBOutlet weak var map: MKMapView!
@IBOutlet weak var jobDescription: UITextView!
var selectedJob: PFObject?
var localSearchRequest:MKLocalSearchRequest!
var localSearch:MKLocalSearch!
var localSearchResponse:MKLocalSearchResponse!
var pointAnnotation:MKPointAnnotation!
var pinAnnotationView:MKPinAnnotationView!
override func viewDidLoad() {
super.viewDidLoad()
// Update Map
localSearchRequest = MKLocalSearchRequest()
localSearchRequest.naturalLanguageQuery = selectedJob!["contactAddress"] as? String
localSearch = MKLocalSearch(request: localSearchRequest)
localSearch.startWithCompletionHandler { (localSearchResponse, error) -> Void in
if localSearchResponse == nil{
let alert = UIAlertView(title: nil, message: "Place not found", delegate: self, cancelButtonTitle: "Try again")
alert.show()
return
}
//3
self.pointAnnotation = MKPointAnnotation()
self.pointAnnotation.title = self.selectedJob!["contactAddress"] as? String
self.pointAnnotation.coordinate = CLLocationCoordinate2D(latitude: localSearchResponse!.boundingRegion.center.latitude, longitude: localSearchResponse!.boundingRegion.center.longitude)
self.pinAnnotationView = MKPinAnnotationView(annotation: self.pointAnnotation, reuseIdentifier: nil)
self.map.centerCoordinate = self.pointAnnotation.coordinate
self.map.addAnnotation(self.pinAnnotationView.annotation!)
let latitude: CLLocationDegrees = localSearchResponse!.boundingRegion.center.latitude
let longitue: CLLocationDegrees = localSearchResponse!.boundingRegion.center.longitude
let location: CLLocationCoordinate2D = CLLocationCoordinate2DMake(latitude, longitue)
let latDelta: CLLocationDegrees = 0.01
let lonDelta: CLLocationDegrees = 0.01
let span: MKCoordinateSpan = MKCoordinateSpanMake(latDelta, lonDelta)
let region: MKCoordinateRegion = MKCoordinateRegionMake(location, span)
self.map.setRegion(region, animated: true)
}
// Update Job info
self.title = selectedJob!["jobTitle"] as? String
jobDescription.text = selectedJob!["jobDetails"] as! String
}
@IBAction func onShareJob(sender: UIBarButtonItem) {
let textToShare = selectedJob!["jobDescription"] as! String // "Swift is awesome! Check out this website about it!"
let contactAddress = self.selectedJob!["contactAddress"] as! String
// if let myWebsite = NSURL(string: "http://www.codingexplorer.com/")
// {
let objectsToShare = [textToShare, contactAddress]
let activityVC = UIActivityViewController(activityItems: objectsToShare, applicationActivities: nil)
self.presentViewController(activityVC, animated: true, completion: nil)
// }
}
@IBAction func onApplyJob(sender: UIBarButtonItem) {
}
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.
}
*/
}
|
f80208a95eddc91fa6e7e9ba476fe184
| 34.84466 | 194 | 0.726436 | false | false | false | false |
KyoheiG3/ProtobufExample
|
refs/heads/master
|
ProtobufClient/ProtobufClient/ViewController.swift
|
mit
|
1
|
//
// ViewController.swift
// ProtobufClient
//
// Created by Kyohei Ito on 2016/11/19.
// Copyright © 2016年 Kyohei Ito. All rights reserved.
//
import UIKit
import RxSwift
import RxCocoa
import SwiftProtobuf
import Protobuf
private let stabJSON = "{\"id\":\"20\",\"name\":\"Swift\",\"books\":[{\"id\":\"10\",\"title\":\"Welcome to Swift\",\"author\":\"Apple Inc.\"}],\"keys\":{\"route\":\"66\"}}"
class TableViewCell: UITableViewCell {
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: .subtitle, reuseIdentifier: reuseIdentifier)
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
}
class ViewController: UIViewController {
@IBOutlet weak var tableView: UITableView!
@IBOutlet weak var typeLabel: UILabel!
@IBOutlet weak var acceptLabel: UILabel!
@IBOutlet weak var pathLabel: UILabel!
@IBOutlet weak var dataLabel: UILabel!
@IBOutlet weak var byteLabel: UILabel!
fileprivate let requests = [
RequestInfo(api: .go, type: .json, path: "/"),
RequestInfo(api: .go, type: .protobuf, path: "/"),
RequestInfo(api: .go, type: .protobuf, path: "/stab"),
RequestInfo(api: .swift, type: .json, path: "/"),
RequestInfo(api: .swift, type: .protobuf, path: "/"),
RequestInfo(api: .swift, type: .json, path: "/protobuf"),
RequestInfo(api: .swift, type: .protobuf, path: "/json"),
RequestInfo(api: .swift, type: .protobuf, path: "/stab"),
]
fileprivate let disposeBag = DisposeBag()
func data<T>(request: URLRequest) -> Observable<T> {
guard request.url?.path != "/stab" else {
self.typeLabel.text = "-"
self.byteLabel.text = "-"
self.typeLabel.text = "-"
// return stab data.
return .just(try! MyLibrary(json: stabJSON) as! T)
}
return URLSession.shared.rx.response(request: request)
.observeOn(MainScheduler.instance)
.map { [unowned self] (response, data) -> T in
if 200 ..< 300 ~= response.statusCode {
let contentType = response.allHeaderFields["Content-Type"] as? String
let accept = request.allHTTPHeaderFields?["Accept"]
self.byteLabel.text = "\(data)"
self.typeLabel.text = contentType
// This examples return serialized json string if json string needed. also return deserialized protobuf object if protobuf needed.
if let type = contentType, type == "application/protobuf" {
let library = try MyLibrary(protobuf: data)
if accept == "application/json" {
return try library.serializeJSON() as! T
} else {
return library as! T
}
} else {
let json = String(bytes: data, encoding: .utf8)
if accept == "application/protobuf" {
return try MyLibrary(json: json!) as! T
} else {
return json as! T
}
}
}
else {
throw RxCocoaURLError.httpRequestFailed(response: response, data: data)
}
}
.do(onError: { [unowned self] _ in
self.byteLabel.text = "-"
self.typeLabel.text = "-"
})
.catchError { error in
.just(error as! T)
}
}
func getRequest(url: String) -> URLRequest {
let url = URL(string: url)!
pathLabel.text = ":\(url.port!)\(url.path)"
var request = URLRequest(url: url)
request.httpMethod = "GET"
return request
}
override func viewDidLoad() {
super.viewDidLoad()
tableView.register(TableViewCell.self, forCellReuseIdentifier: "Cell")
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
extension ViewController: UITableViewDataSource, UITableViewDelegate {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return requests.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
let info = requests[indexPath.row]
cell.textLabel?.text = "\(info.api.port)\(info.path)"
cell.detailTextLabel?.text = info.type.description
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
let info = requests[indexPath.row]
acceptLabel.text = info.type.description
var request = getRequest(url: info.url)
request.setValue(info.type.description, forHTTPHeaderField: "Accept")
data(request: request)
.single()
.map { (data: CustomDebugStringConvertible) in data.debugDescription }
.bindTo(dataLabel.rx.text)
.addDisposableTo(disposeBag)
}
}
|
0f8c9487ce1da58d7c3844fc08ee7276
| 36.328947 | 172 | 0.547585 | false | false | false | false |
OpenKitten/MongoKitten
|
refs/heads/master/6.0
|
Sources/MongoKitten/CollectionHelpers/Collection+Update.swift
|
mit
|
2
|
import NIO
import MongoCore
extension MongoCollection {
public func updateOne(
where query: Document,
to document: Document
) -> EventLoopFuture<UpdateReply> {
return pool.next(for: .basic).flatMap { connection in
let request = UpdateCommand.UpdateRequest(where: query, to: document)
let command = UpdateCommand(updates: [request], inCollection: self.name)
return connection.executeCodable(
command,
namespace: self.database.commandNamespace,
in: self.transaction,
sessionId: self.sessionId ?? connection.implicitSessionId
)
}.decodeReply(UpdateReply.self)._mongoHop(to: hoppedEventLoop)
}
public func updateEncoded<E: Encodable>(
where query: Document,
to model: E
) -> EventLoopFuture<UpdateReply> {
do {
let document = try BSONEncoder().encode(model)
return updateOne(where: query, to: document)
} catch {
return eventLoop.makeFailedFuture(error)
}
}
public func updateOne<Query: MongoKittenQuery>(
where query: Query,
to document: Document
) -> EventLoopFuture<UpdateReply> {
return updateOne(
where: query.makeDocument(),
to: document
)
}
public func updateEncoded<Query: MongoKittenQuery, E: Encodable>(
where query: Query,
to model: E
) -> EventLoopFuture<UpdateReply> {
return updateEncoded(
where: query.makeDocument(),
to: model
)
}
public func updateMany(
where query: Document,
to document: Document
) -> EventLoopFuture<UpdateReply> {
return pool.next(for: .basic).flatMap { connection in
var request = UpdateCommand.UpdateRequest(where: query, to: document)
request.multi = true
let command = UpdateCommand(updates: [request], inCollection: self.name)
return connection.executeCodable(
command,
namespace: self.database.commandNamespace,
in: self.transaction,
sessionId: self.sessionId ?? connection.implicitSessionId
)
}.decodeReply(UpdateReply.self)._mongoHop(to: hoppedEventLoop)
}
public func updateManyEncoded<E: Encodable>(
where query: Document,
to model: E
) -> EventLoopFuture<UpdateReply> {
do {
let document = try BSONEncoder().encode(model)
return updateMany(where: query, to: document)
} catch {
return eventLoop.makeFailedFuture(error)
}
}
public func updateMany<Query: MongoKittenQuery>(
where query: Query,
to document: Document
) -> EventLoopFuture<UpdateReply> {
return updateMany(
where: query.makeDocument(),
to: document
)
}
public func updateManyEncoded<Query: MongoKittenQuery, E: Encodable>(
where query: Query,
to model: E
) -> EventLoopFuture<UpdateReply> {
return updateManyEncoded(
where: query.makeDocument(),
to: model
)
}
public func updateMany(
where query: Document,
setting: Document?,
unsetting: Document?
) -> EventLoopFuture<UpdateReply> {
return pool.next(for: .basic).flatMap { connection in
var request = UpdateCommand.UpdateRequest(where: query, setting: setting, unsetting: unsetting)
request.multi = true
let command = UpdateCommand(updates: [request], inCollection: self.name)
return connection.executeCodable(
command,
namespace: self.database.commandNamespace,
in: self.transaction,
sessionId: self.sessionId ?? connection.implicitSessionId
)
}.decodeReply(UpdateReply.self)._mongoHop(to: hoppedEventLoop)
}
public func upsert(_ document: Document, where query: Document) -> EventLoopFuture<UpdateReply> {
return pool.next(for: .basic).flatMap { connection in
var request = UpdateCommand.UpdateRequest(where: query, to: document)
request.multi = false
request.upsert = true
let command = UpdateCommand(updates: [request], inCollection: self.name)
return connection.executeCodable(
command,
namespace: self.database.commandNamespace,
in: self.transaction,
sessionId: self.sessionId ?? connection.implicitSessionId
)
}.decodeReply(UpdateReply.self)._mongoHop(to: hoppedEventLoop)
}
public func upsertEncoded<E: Encodable>(_ model: E, where query: Document) -> EventLoopFuture<UpdateReply> {
do {
let document = try BSONEncoder().encode(model)
return upsert(document, where: query)
} catch {
return eventLoop.makeFailedFuture(error)
}
}
public func upsert<Query: MongoKittenQuery>(_ document: Document, where query: Query) -> EventLoopFuture<UpdateReply> {
return upsert(document, where: query.makeDocument())
}
public func upsertEncoded<Query: MongoKittenQuery, E: Encodable>(_ model: E, where query: Query) -> EventLoopFuture<UpdateReply> {
return upsertEncoded(model, where: query.makeDocument())
}
}
|
80708f2e799000bbc25545cf0e3543ac
| 34.322785 | 134 | 0.597205 | false | false | false | false |
niw/meowatch
|
refs/heads/master
|
Meowatch WatchKit Extension/Meowatch.swift
|
mit
|
1
|
//
// Meowatch.swift
// Meowatch
//
// Created by Yoshimasa Niwa on 5/8/15.
// Copyright (c) 2015 Yoshimasa Niwa. All rights reserved.
//
import Accounts
import ImageIO
import Twitter
import UIKit
import WatchKit
extension UIImage {
class func animatedImageWithData(data: NSData) -> UIImage? {
if let source = CGImageSourceCreateWithData(data, nil) {
let count = CGImageSourceGetCount(source);
if count <= 1 {
return UIImage(data: data)
} else {
var images: [UIImage] = []
var duration = 0.0
for index in 0..<count {
if let cgImage = CGImageSourceCreateImageAtIndex(source, index, nil) {
if let frameProperties = CGImageSourceCopyPropertiesAtIndex(source, index, nil) as? NSDictionary,
gifProperties = frameProperties[kCGImagePropertyGIFDictionary as NSString] as? NSDictionary {
if let unclampedDelayTime = gifProperties[kCGImagePropertyGIFUnclampedDelayTime as NSString] as? NSNumber {
duration += unclampedDelayTime.doubleValue
} else if let delayTime = gifProperties[kCGImagePropertyGIFDelayTime as NSString] as? NSNumber {
duration += delayTime.doubleValue
}
}
let image = UIImage(CGImage: cgImage, scale: WKInterfaceDevice.currentDevice().screenScale, orientation: UIImageOrientation.Up)
images.append(image)
}
}
return UIImage.animatedImageWithImages(images, duration: duration);
}
} else {
return nil
}
}
func optimizedAnimatedImage(fitSize: CGSize, maxFrame: Int) -> UIImage? {
if let images = self.images {
if CGSizeEqualToSize(self.size, fitSize) || CGSizeEqualToSize(fitSize, CGSizeZero) {
return self;
}
let widthFactor = fitSize.width / self.size.width
let heightFactor = fitSize.height / self.size.height
let scaleFactor = min(widthFactor, heightFactor)
let scaledSize = CGSizeMake(self.size.width * scaleFactor, self.size.height * scaleFactor)
let increment: Int
if (maxFrame > 0) {
increment = images.count / maxFrame
} else {
increment = 0
}
var scaledImages: [UIImage] = []
UIGraphicsBeginImageContextWithOptions(scaledSize, false, WKInterfaceDevice.currentDevice().screenScale)
for var index = 0; index < images.count; index += increment {
let image = images[index]
image.drawInRect(CGRectMake(0.0, 0.0, scaledSize.width, scaledSize.height))
let newImage = UIGraphicsGetImageFromCurrentImageContext()
if let data = UIImageJPEGRepresentation(newImage, 0.5),
jpegImage = UIImage(data: data) {
scaledImages.append(jpegImage)
}
}
UIGraphicsEndImageContext();
return UIImage.animatedImageWithImages(scaledImages, duration:self.duration);
} else {
return self;
}
}
}
struct ArchivedAnimatedImage {
let data: NSData
let count: Int
let duration: NSTimeInterval
init(image: UIImage) {
self.data = NSKeyedArchiver.archivedDataWithRootObject(image)
if let count = image.images?.count {
self.count = count
} else {
self.count = 1
}
self.duration = image.duration
}
}
struct AnimatedImageFetchResult {
let originalData: NSData
let archivedAniamtedImage: ArchivedAnimatedImage
// Bluetooth 4.0 LE's data rate is, by measureing in stable environment,
// about 420 Kbps and could be worser.
private let bytesPerSeconds = 840 * 1024 / 8;
func estimatedLoadingTime() -> Double {
return Double(self.archivedAniamtedImage.data.length) / Double(self.bytesPerSeconds);
}
func formattedLodingSize() -> String {
let kiloBytes = self.archivedAniamtedImage.data.length / 1024;
let formatter = NSNumberFormatter()
formatter.numberStyle = NSNumberFormatterStyle.DecimalStyle
if let formattedString = formatter.stringFromNumber(NSNumber(integer: kiloBytes)) {
return formattedString
} else {
return "\(kiloBytes)"
}
}
}
func fetchAnimatedImage(completion: (AnimatedImageFetchResult?) -> Void) {
// FIXME: Find a feasible way to get cats from the internet.
let theCatApiEndpoint = "http://thecatapi.com/api/images/get?format=src&type=gif"
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0), {
if let url = NSURL(string: theCatApiEndpoint),
data = NSData(contentsOfURL: url),
image = UIImage.animatedImageWithData(data)?.optimizedAnimatedImage(CGSizeMake(120.0, 120.0), maxFrame: 6) {
let archivedAnimatedImage = ArchivedAnimatedImage(image: image)
let fetchResult = AnimatedImageFetchResult(originalData: data, archivedAniamtedImage: archivedAnimatedImage)
dispatch_async(dispatch_get_main_queue(), {
completion(fetchResult)
})
} else {
dispatch_async(dispatch_get_main_queue(), {
completion(nil)
})
}
})
}
struct ProgressBarHelper {
private let numberOfFrames = 40
private let cachedImageName = "ProgressBar"
weak var progressBarImage: WKInterfaceImage? {
didSet {
self.progressBarImage?.setImageNamed(self.cachedImageName)
self.progressBarImage?.stopAnimating()
}
}
init() {
if let image = progressBarAnimatedImage(self.numberOfFrames) {
WKInterfaceDevice.currentDevice().addCachedImage(image, name: self.cachedImageName)
}
}
// See https://developer.apple.com/watch/human-interface-guidelines/specifications/
private let progressBarColor = UIColor(red: 255.0/255.0, green: 230.0/255.0, blue: 32.0/255.0, alpha: 1.0)
private func progressBarImageAtProgress(progress: Double) -> UIImage? {
let progress = min(1.0, max(0.0, progress))
let barSize = CGSizeMake(WKInterfaceDevice.currentDevice().screenBounds.width - 12.0, 2.0)
UIGraphicsBeginImageContextWithOptions(barSize, false, WKInterfaceDevice.currentDevice().screenScale)
UIGraphicsGetCurrentContext()
self.progressBarColor.setFill()
UIBezierPath(roundedRect: CGRectMake(0.0, 0.0, ceil(barSize.width * CGFloat(progress)), barSize.height), cornerRadius: 1.0).fill()
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext();
return image
}
private func progressBarAnimatedImage(numberOfFrames: Int) -> UIImage? {
var images: [UIImage] = []
for index in 0..<numberOfFrames {
if let image = progressBarImageAtProgress(Double(index) / Double(numberOfFrames - 1)) {
images.append(image)
} else {
return nil
}
}
return UIImage.animatedImageWithImages(images, duration: 10.0)
}
func reset() {
self.progressBarImage?.startAnimatingWithImagesInRange(NSMakeRange(0, 1), duration: 0.0, repeatCount: 1)
}
func startInDuration(duration: NSTimeInterval) {
self.progressBarImage?.startAnimatingWithImagesInRange(NSMakeRange(0, self.numberOfFrames), duration: duration, repeatCount: 1)
}
}
class RequestTag {
}
struct SocialAccount {
let type: String
private func serviceType() -> String? {
switch self.type {
case ACAccountTypeIdentifierTwitter:
return SLServiceTypeTwitter
case ACAccountTypeIdentifierFacebook:
return SLServiceTypeFacebook
case ACAccountTypeIdentifierSinaWeibo:
return SLServiceTypeSinaWeibo
case ACAccountTypeIdentifierTencentWeibo:
return SLServiceTypeTencentWeibo
default:
return nil
}
}
func check(completion: ([ACAccount]?) -> Void) {
if let serviceType = self.serviceType() {
if SLComposeViewController.isAvailableForServiceType(serviceType) {
let accountStore = ACAccountStore();
if let accountType = accountStore.accountTypeWithAccountTypeIdentifier(self.type),
accounts = accountStore.accountsWithAccountType(accountType) as? [ACAccount]
{
if (accounts.count == 0) {
// Not Authorized.
completion(nil)
} else {
// Authorized.
completion(accounts)
}
} else {
completion([])
}
} else {
// No accounts.
completion([])
}
}
}
func request(completion: ([ACAccount]?) -> Void) {
let accountStore = ACAccountStore();
if let accountType = accountStore.accountTypeWithAccountTypeIdentifier(ACAccountTypeIdentifierTwitter) {
accountStore.requestAccessToAccountsWithType(accountType, options: nil, completion: { (granted, error) in
if granted {
if let accounts = accountStore.accountsWithAccountType(accountType) as? [ACAccount] {
completion(accounts)
} else {
completion([])
}
} else {
completion(nil)
}
})
}
}
}
class AnimatedImageFetchInterfaceController: WKInterfaceController {
@IBOutlet weak var loadingGroup: WKInterfaceGroup?
@IBOutlet weak var loadingLabel: WKInterfaceLabel?
@IBOutlet weak var contentImage: WKInterfaceImage?
private var progressBarHelper = ProgressBarHelper()
@IBOutlet weak var progressBarImage: WKInterfaceImage? {
get {
return self.progressBarHelper.progressBarImage
}
set {
self.progressBarHelper.progressBarImage = newValue
}
}
private var currenrRequestTag: RequestTag?
private var lastFetchResult: AnimatedImageFetchResult?
func fetch() {
self.loadingGroup?.setHidden(false)
self.contentImage?.setHidden(true)
self.progressBarHelper.reset()
self.loadingLabel?.setText("Loading...")
self.clearAllMenuItems()
let requestTag = RequestTag()
self.currenrRequestTag = requestTag
fetchAnimatedImage { [weak self] fetchResultOpt in
if let strongSelf = self {
if let currentRequstTag = strongSelf.currenrRequestTag, fetchResult = fetchResultOpt {
if currentRequstTag === requestTag {
strongSelf.loadingLabel?.setText("\(fetchResult.formattedLodingSize()) KB in \(Int(fetchResult.estimatedLoadingTime())) s")
strongSelf.progressBarHelper.startInDuration(fetchResult.estimatedLoadingTime())
dispatch_async(dispatch_get_main_queue(), { [weak self] in
if let strongSelf = self, currentRequstTag = strongSelf.currenrRequestTag {
if (currentRequstTag === requestTag) {
strongSelf.lastFetchResult = fetchResult;
strongSelf.loadingGroup?.setHidden(true)
strongSelf.contentImage?.setHidden(false)
strongSelf.contentImage?.setImageData(fetchResult.archivedAniamtedImage.data)
strongSelf.contentImage?.startAnimatingWithImagesInRange(NSMakeRange(0, fetchResult.archivedAniamtedImage.count), duration: fetchResult.archivedAniamtedImage.duration, repeatCount: 0)
strongSelf.addMenuItemWithItemIcon(WKMenuItemIcon.Share, title: "Share", action: "didTapShare:");
}
}
})
}
} else {
strongSelf.loadingLabel?.setText("Failed.")
}
}
}
}
private func requestTwitterAccount(completion: (ACAccount) -> Void) {
// FIXME: support account selection
let socialAccount = SocialAccount(type: ACAccountTypeIdentifierTwitter)
socialAccount.check { (accountsOpt) -> Void in
if let accounts = accountsOpt {
if let account = accounts.first {
completion(account)
} else {
self.presentControllerWithName("ModalAlert", context: ModalAlertInterfaceController.Context(text: "No Twitter accounts."))
}
} else {
self.presentControllerWithName("ModalAlert", context: ModalAlertInterfaceController.Context(text: "Meowatch needs access to your Twitter accounts. Tap Authorize to request access on the iPhone screen.", buttonTitle: "Authorize", didTapButton: { [weak self] in
self?.dismissController()
socialAccount.request({ (accounts) -> Void in
if let account = accounts?.first {
completion(account)
}
})
}))
}
}
}
private func share() {
let uploadWithMediaAPIEndpoint = "https://upload.twitter.com/1/statuses/update_with_media.json"
let status = "🐱 #Meowatch"
if let lastFetchResult = self.lastFetchResult {
requestTwitterAccount({ (account) in
let url = NSURL(string: uploadWithMediaAPIEndpoint)
let parameters = ["status": status]
let request = SLRequest(forServiceType: SLServiceTypeTwitter, requestMethod: SLRequestMethod.POST, URL: url, parameters: parameters)
request.account = account
request.addMultipartData(lastFetchResult.originalData, withName: "media", type: "image/gif", filename: "cat.gif")
request.performRequestWithHandler({ (data, response, error) in
})
})
}
}
@IBAction func didTapShare(sender: AnyObject) {
share();
}
}
class MainInterfaceController: AnimatedImageFetchInterfaceController {
override func awakeWithContext(context: AnyObject?) {
super.awakeWithContext(context)
fetch()
}
@IBAction func shuffle() {
fetch();
}
}
class ModalAlertInterfaceController: WKInterfaceController {
class Context {
let attributedText: NSAttributedString?
let text: String?
let buttonTitle: String?
let didTapButton: (() -> Void)?
init(text: String) {
self.attributedText = nil
self.text = text
self.buttonTitle = nil
self.didTapButton = nil
}
init(text: String, buttonTitle: String, didTapButton: () -> Void) {
self.attributedText = nil
self.text = text
self.buttonTitle = buttonTitle
self.didTapButton = didTapButton
}
init(attributedText: NSAttributedString?, buttonTitle: String, didTapButton: () -> Void) {
self.attributedText = attributedText
self.text = nil
self.buttonTitle = buttonTitle
self.didTapButton = didTapButton
}
}
@IBOutlet weak var label: WKInterfaceLabel?
@IBOutlet weak var button: WKInterfaceButton?
private var context: Context?
override func awakeWithContext(context: AnyObject?) {
super.awakeWithContext(context)
if let modalAlertContext = context as? Context {
self.context = modalAlertContext
if let attributedText = modalAlertContext.attributedText {
label?.setAttributedText(attributedText)
} else if let text = modalAlertContext.text {
label?.setText(text)
}
if let buttonTitle = modalAlertContext.buttonTitle {
button?.setTitle(buttonTitle)
} else {
button?.setHidden(true)
}
}
}
@IBAction func didTapButton(sender: AnyObject?) {
self.context?.didTapButton?()
}
}
|
0fabc11aa96103b9eb63e8ad79fe1e63
| 37.415525 | 275 | 0.59622 | false | false | false | false |
crazypoo/PTools
|
refs/heads/master
|
Pods/CollectionViewPagingLayout/Lib/Scale/ScaleTransformView.swift
|
mit
|
1
|
//
// ScaleTransformView.swift
// CollectionViewPagingLayout
//
// Created by Amir on 15/02/2020.
// Copyright © 2020 Amir Khorsandi. All rights reserved.
//
import UIKit
/// A protocol for adding scale transformation to `TransformableView`
public protocol ScaleTransformView: TransformableView {
/// Options for controlling scale effect, see `ScaleTransformViewOptions.swift`
var scaleOptions: ScaleTransformViewOptions { get }
/// The view to apply scale effect on
var scalableView: UIView { get }
/// The view to apply blur effect on
var scaleBlurViewHost: UIView { get }
/// the main function for applying transforms
func applyScaleTransform(progress: CGFloat)
}
public extension ScaleTransformView {
/// The default value is the super view of `scalableView`
var scaleBlurViewHost: UIView {
scalableView.superview ?? scalableView
}
}
public extension ScaleTransformView where Self: UICollectionViewCell {
/// Default `scalableView` for `UICollectionViewCell` is the first subview of
/// `contentView` or the content view itself if there is no subview
var scalableView: UIView {
contentView.subviews.first ?? contentView
}
}
public extension ScaleTransformView {
// MARK: Properties
var scaleOptions: ScaleTransformViewOptions {
.init()
}
// MARK: TransformableView
func transform(progress: CGFloat) {
applyScaleTransform(progress: progress)
}
// MARK: Public functions
func applyScaleTransform(progress: CGFloat) {
applyStyle(progress: progress)
applyScaleAndTranslation(progress: progress)
applyCATransform3D(progress: progress)
if #available(iOS 10, *) {
applyBlurEffect(progress: progress)
}
}
// MARK: Private functions
private func applyStyle(progress: CGFloat) {
guard scaleOptions.shadowEnabled else {
return
}
let layer = scalableView.layer
layer.shadowColor = scaleOptions.shadowColor.cgColor
let offset = CGSize(
width: max(scaleOptions.shadowOffsetMin.width, (1 - abs(progress)) * scaleOptions.shadowOffsetMax.width),
height: max(scaleOptions.shadowOffsetMin.height, (1 - abs(progress)) * scaleOptions.shadowOffsetMax.height)
)
layer.shadowOffset = offset
layer.shadowRadius = max(scaleOptions.shadowRadiusMin, (1 - abs(progress)) * scaleOptions.shadowRadiusMax)
layer.shadowOpacity = max(scaleOptions.shadowOpacityMin, (1 - abs(Float(progress))) * scaleOptions.shadowOpacityMax)
}
private func applyScaleAndTranslation(progress: CGFloat) {
var transform = CGAffineTransform.identity
var xAdjustment: CGFloat = 0
var yAdjustment: CGFloat = 0
let scaleProgress = scaleOptions.scaleCurve.computeFromLinear(progress: abs(progress))
var scale = 1 - scaleProgress * scaleOptions.scaleRatio
scale = max(scale, scaleOptions.minScale)
scale = min(scale, scaleOptions.maxScale)
if scaleOptions.keepHorizontalSpacingEqual {
xAdjustment = ((1 - scale) * scalableView.bounds.width) / 2
if progress > 0 {
xAdjustment *= -1
}
}
if scaleOptions.keepVerticalSpacingEqual {
yAdjustment = ((1 - scale) * scalableView.bounds.height) / 2
}
let translateProgress = scaleOptions.translationCurve.computeFromLinear(progress: abs(progress))
var translateX = scalableView.bounds.width * scaleOptions.translationRatio.x * (translateProgress * (progress < 0 ? -1 : 1)) - xAdjustment
var translateY = scalableView.bounds.height * scaleOptions.translationRatio.y * abs(translateProgress) - yAdjustment
if let min = scaleOptions.minTranslationRatio {
translateX = max(translateX, scalableView.bounds.width * min.x)
translateY = max(translateY, scalableView.bounds.height * min.y)
}
if let max = scaleOptions.maxTranslationRatio {
translateX = min(translateX, scalableView.bounds.width * max.x)
translateY = min(translateY, scalableView.bounds.height * max.y)
}
transform = transform
.translatedBy(x: translateX, y: translateY)
.scaledBy(x: scale, y: scale)
scalableView.transform = transform
}
private func applyCATransform3D(progress: CGFloat) {
var transform = CATransform3DMakeAffineTransform(scalableView.transform)
if let options = self.scaleOptions.rotation3d {
var angle = options.angle * progress
angle = max(angle, options.minAngle)
angle = min(angle, options.maxAngle)
transform.m34 = options.m34
transform = CATransform3DRotate(transform, angle, options.x, options.y, options.z)
scalableView.layer.isDoubleSided = options.isDoubleSided
}
if let options = self.scaleOptions.translation3d {
var x = options.translateRatios.0 * progress * scalableView.bounds.width
var y = options.translateRatios.1 * abs(progress) * scalableView.bounds.height
var z = options.translateRatios.2 * abs(progress) * scalableView.bounds.width
x = max(x, options.minTranslateRatios.0 * scalableView.bounds.width)
x = min(x, options.maxTranslateRatios.0 * scalableView.bounds.width)
y = max(y, options.minTranslateRatios.1 * scalableView.bounds.height)
y = min(y, options.maxTranslateRatios.1 * scalableView.bounds.height)
z = max(z, options.minTranslateRatios.2 * scalableView.bounds.width)
z = min(z, options.maxTranslateRatios.2 * scalableView.bounds.width)
transform = CATransform3DTranslate(transform, x, y, z)
}
scalableView.layer.transform = transform
}
private func applyBlurEffect(progress: CGFloat) {
guard scaleOptions.blurEffectRadiusRatio > 0, scaleOptions.blurEffectEnabled else {
scaleBlurViewHost.subviews.first(where: { $0 is BlurEffectView })?.removeFromSuperview()
return
}
let blurView: BlurEffectView
if let view = scaleBlurViewHost.subviews.first(where: { $0 is BlurEffectView }) as? BlurEffectView {
blurView = view
} else {
blurView = BlurEffectView(effect: UIBlurEffect(style: scaleOptions.blurEffectStyle))
scaleBlurViewHost.fill(with: blurView)
}
blurView.setBlurRadius(radius: abs(progress) * scaleOptions.blurEffectRadiusRatio)
blurView.transform = CGAffineTransform.identity.translatedBy(x: scalableView.transform.tx, y: scalableView.transform.ty)
}
}
|
9fb6642d072b0d421b834840ec196d86
| 38.571429 | 146 | 0.65935 | false | false | false | false |
joerocca/GitHawk
|
refs/heads/master
|
Classes/View Controllers/UIViewController+Safari.swift
|
mit
|
1
|
//
// UIViewController+Safari.swift
// Freetime
//
// Created by Ryan Nystrom on 7/5/17.
// Copyright © 2017 Ryan Nystrom. All rights reserved.
//
import UIKit
import SafariServices
extension UIViewController {
func presentSafari(url: URL) {
guard let safariViewController = try? SFSafariViewController.configured(with: url) else { return }
present(safariViewController, animated: trueUnlessReduceMotionEnabled)
}
func presentProfile(login: String) {
present(CreateProfileViewController(login: login), animated: trueUnlessReduceMotionEnabled)
}
func presentCommit(owner: String, repo: String, hash: String) {
guard let url = URL(string: "https://github.com/\(owner)/\(repo)/commit/\(hash)") else { return }
presentSafari(url: url)
}
func presentLabels(owner: String, repo: String, label: String) {
guard let url = URL(string: "https://github.com/\(owner)/\(repo)/labels/\(label)") else { return }
presentSafari(url: url)
}
func presentMilestone(owner: String, repo: String, milestone: Int) {
guard let url = URL(string: "https://github.com/\(owner)/\(repo)/milestone/\(milestone)") else { return }
presentSafari(url: url)
}
}
extension SFSafariViewController {
static func configured(with url: URL) throws -> SFSafariViewController {
let http = "http"
let schemedURL: URL
// handles http and https
if url.scheme?.hasPrefix(http) == true {
schemedURL = url
} else {
guard let u = URL(string: http + "://" + url.absoluteString) else { throw URL.Error.failedToCreateURL }
schemedURL = u
}
let safariViewController = SFSafariViewController(url: schemedURL)
safariViewController.preferredControlTintColor = Styles.Colors.Blue.medium.color
return safariViewController
}
}
extension URL {
enum Error: Swift.Error {
case failedToCreateURL
}
}
|
4c738e86a37afa0210a3ac1e44af5e67
| 28.904762 | 113 | 0.696391 | false | false | false | false |
apple/swift
|
refs/heads/main
|
test/attr/attr_override.swift
|
apache-2.0
|
4
|
// RUN: %target-typecheck-verify-swift -swift-version 5
@override // expected-error {{'override' can only be specified on class members}} {{1-11=}} expected-error {{'override' is a declaration modifier, not an attribute}} {{1-2=}}
func virtualAttributeCanNotBeUsedInSource() {}
class MixedKeywordsAndAttributes { // expected-note {{in declaration of 'MixedKeywordsAndAttributes'}}
// expected-error@+1 {{expected declaration}} expected-error@+1 {{consecutive declarations on a line must be separated by ';'}} {{11-11=;}}
override @inline(never) func f1() {}
}
class DuplicateOverrideBase {
func f1() {}
class func cf1() {}
class func cf2() {}
class func cf3() {}
class func cf4() {}
}
class DuplicateOverrideDerived : DuplicateOverrideBase {
override override func f1() {} // expected-error {{duplicate modifier}} expected-note {{modifier already specified here}}
override override class func cf1() {} // expected-error {{duplicate modifier}} expected-note {{modifier already specified here}}
override class override func cf2() {} // expected-error {{duplicate modifier}} expected-note {{modifier already specified here}}
class override override func cf3() {} // expected-error {{duplicate modifier}} expected-note {{modifier already specified here}}
override class override func cf4() {} // expected-error {{duplicate modifier}} expected-note {{modifier already specified here}}
}
class A {
func f0() { }
func f1() { } // expected-note{{overridden declaration is here}}
var v1: Int { return 5 }
var v2: Int { return 5 } // expected-note{{overridden declaration is here}}
internal var v21: Int { return 5 } // expected-note{{overridden declaration is here}}
var v4: String { return "hello" }// expected-note{{attempt to override property here}}
var v5: A { return self }
var v6: A { return self }
var v7: A { // expected-note{{attempt to override property here}}
get { return self }
set { }
}
var v8: Int = 0 // expected-note {{attempt to override property here}}
var v9: Int { return 5 } // expected-note{{attempt to override property here}}
var v10: Int { return 5 } // expected-note{{attempt to override property here}}
subscript (i: Int) -> String { // expected-note{{potential overridden subscript 'subscript(_:)' here}}
get {
return "hello"
}
set {
}
}
subscript (d: Double) -> String { // expected-note{{overridden declaration is here}} expected-note{{potential overridden subscript 'subscript(_:)' here}}
get {
return "hello"
}
set {
}
}
class subscript (i: String) -> String { // expected-note{{overridden declaration is here}} expected-note{{potential overridden class subscript 'subscript(_:)' here}}
get {
return "hello"
}
set {
}
}
class subscript (typeInSuperclass a: [Int]) -> String {
get {
return "hello"
}
set {
}
}
subscript (i: Int8) -> A { // expected-note{{potential overridden subscript 'subscript(_:)' here}}
get { return self }
}
subscript (i: Int16) -> A { // expected-note{{attempt to override subscript here}} expected-note{{potential overridden subscript 'subscript(_:)' here}}
get { return self }
set { }
}
func overriddenInExtension() {} // expected-note {{overr}}
}
class B : A {
override func f0() { }
func f1() { } // expected-error{{overriding declaration requires an 'override' keyword}}{{3-3=override }}
override func f2() { } // expected-error{{method does not override any method from its superclass}}
override var v1: Int { return 5 }
var v2: Int { return 5 } // expected-error{{overriding declaration requires an 'override' keyword}}{{3-3=override }}
internal var v21: Int { return 5 } // expected-error{{overriding declaration requires an 'override' keyword}}{{12-12=override }}
override var v3: Int { return 5 } // expected-error{{property does not override any property from its superclass}}
override var v4: Int { return 5 } // expected-error{{property 'v4' with type 'Int' cannot override a property with type 'String'}}
// Covariance
override var v5: B { return self }
override var v6: B {
get { return self }
set { }
}
override var v7: B { // expected-error{{cannot override mutable property 'v7' of type 'A' with covariant type 'B'}}
get { return self }
set { }
}
// Stored properties
override var v8: Int { return 5 } // expected-error {{cannot override mutable property with read-only property 'v8'}}
override var v9: Int // expected-error{{cannot override with a stored property 'v9'}}
lazy override var v10: Int = 5 // expected-error{{cannot override with a stored property 'v10'}}
override subscript (i: Int) -> String {
get {
return "hello"
}
set {
}
}
subscript (d: Double) -> String { // expected-error{{overriding declaration requires an 'override' keyword}} {{3-3=override }}
get {
return "hello"
}
set {
}
}
override subscript (f: Float) -> String { // expected-error{{subscript does not override any subscript from its superclass}}
get {
return "hello"
}
set {
}
}
override class subscript (i: Int) -> String { // expected-error{{subscript does not override any subscript from its superclass}}
get {
return "hello"
}
set {
}
}
static subscript (i: String) -> String { // expected-error{{overriding declaration requires an 'override' keyword}} {{10-10=override }}
get {
return "hello"
}
set {
}
}
static subscript (i: Double) -> String {
get {
return "hello"
}
set {
}
}
override class subscript (typeInSuperclass a: [Int]) -> String {
get {
return "hello"
}
set {
}
}
override subscript (typeInSuperclass a: [Int]) -> String { // expected-error{{subscript does not override any subscript from its superclass}}
get {
return "hello"
}
set {
}
}
// Covariant
override subscript (i: Int8) -> B {
get { return self }
}
override subscript (i: Int16) -> B { // expected-error{{cannot override mutable subscript of type '(Int16) -> B' with covariant type '(Int16) -> A'}}
get { return self }
set { }
}
override init() { }
override deinit { } // expected-error{{'override' modifier cannot be applied to this declaration}} {{3-12=}}
override typealias Inner = Int // expected-error{{'override' modifier cannot be applied to this declaration}} {{3-12=}}
}
extension B {
override func overriddenInExtension() {} // expected-error{{overr}}
}
struct S {
override func f() { } // expected-error{{'override' can only be specified on class members}} {{3-12=}}
}
extension S {
override func ef() {} // expected-error{{'override' can only be specified on class members}} {{3-12=}}
}
enum E {
override func f() { } // expected-error{{'override' can only be specified on class members}} {{3-12=}}
}
protocol P {
override func f() // expected-error{{method does not override any method from its parent protocol}}
override var g: Int { get } // expected-error{{property does not override any property from its parent protocol}}
override subscript(h: Int) -> Bool { get } // expected-error{{subscript does not override any subscript from its parent protocol}}
override init(i: Int) // expected-error{{initializer does not override a designated initializer from its parent protocol}}
}
override func f() { } // expected-error{{'override' can only be specified on class members}} {{1-10=}}
// Invalid 'override' on declarations inside closures.
var rdar16654075a = {
override func foo() {} // expected-error{{'override' can only be specified on class members}} {{3-12=}}
}
var rdar16654075b = {
class A {
override func foo() {} // expected-error{{method does not override any method from its superclass}}
}
}
var rdar16654075c = { () -> () in
override func foo() {} // expected-error {{'override' can only be specified on class members}} {{3-12=}}
()
}
var rdar16654075d = { () -> () in
class A {
override func foo() {} // expected-error {{method does not override any method from its superclass}}
}
A().foo()
}
var rdar16654075e = { () -> () in
class A {
func foo() {}
}
class B : A {
override func foo() {}
}
A().foo()
}
class C {
init(string: String) { } // expected-note{{overridden declaration is here}}
required init(double: Double) { } // expected-note 3{{overridden required initializer is here}}
convenience init() { self.init(string: "hello") } // expected-note{{attempt to override convenience initializer here}}
}
class D1 : C {
override init(string: String) { super.init(string: string) }
required init(double: Double) { }
convenience init() { self.init(string: "hello") }
}
class D2 : C {
init(string: String) { super.init(string: string) } // expected-error{{overriding declaration requires an 'override' keyword}}{{3-3=override }}
// FIXME: Would like to remove the space after 'override' as well.
required override init(double: Double) { } // expected-warning{{'override' is implied when overriding a required initializer}} {{12-21=}}
override convenience init() { self.init(string: "hello") } // expected-error{{initializer does not override a designated initializer from its superclass}}
}
class D3 : C {
override init(string: String) { super.init(string: string) }
override init(double: Double) { } // expected-error{{use the 'required' modifier to override a required initializer}}{{3-11=required}}
}
class D4 : C {
// "required override" only when we're overriding a non-required
// designated initializer with a required initializer.
required override init(string: String) { super.init(string: string) }
required init(double: Double) { }
}
class D5 : C {
// "required override" only when we're overriding a non-required
// designated initializer with a required initializer.
required convenience override init(string: String) { self.init(double: 5.0) }
required init(double: Double) { }
}
class D6 : C {
init(double: Double) { } // expected-error{{'required' modifier must be present on all overrides of a required initializer}} {{3-3=required }}
}
// rdar://problem/18232867
class C_empty_tuple {
init() { }
}
class D_empty_tuple : C_empty_tuple {
override init(foo:()) { } // expected-error{{initializer does not override a designated initializer from its superclass}}
}
class C_with_let {
let x = 42 // expected-note {{attempt to override property here}}
}
class D_with_let : C_with_let {
override var x : Int { get { return 4 } set {} } // expected-error {{cannot override immutable 'let' property 'x' with the getter of a 'var'}}
}
// <rdar://problem/21311590> QoI: Inconsistent diagnostics when no constructor is available
class C21311590 {
override init() {} // expected-error {{initializer does not override a designated initializer from its superclass}}
}
class B21311590 : C21311590 {}
_ = C21311590()
_ = B21311590()
class MismatchOptionalBase {
func param(_: Int?) {}
func paramIUO(_: Int!) {}
func result() -> Int { return 0 }
func fixSeveralTypes(a: Int?, b: Int!) -> Int { return 0 }
func functionParam(x: ((Int) -> Int)?) {}
func tupleParam(x: (Int, Int)?) {}
func compositionParam(x: (P1 & P2)?) {}
func nameAndTypeMismatch(label: Int?) {}
func ambiguousOverride(a: Int, b: Int?) {} // expected-note 2 {{overridden declaration is here}} expected-note {{potential overridden instance method 'ambiguousOverride(a:b:)' here}}
func ambiguousOverride(a: Int?, b: Int) {} // expected-note 2 {{overridden declaration is here}} expected-note {{potential overridden instance method 'ambiguousOverride(a:b:)' here}}
var prop: Int = 0 // expected-note {{attempt to override property here}}
var optProp: Int? // expected-note {{attempt to override property here}}
var getProp: Int { return 0 } // expected-note {{attempt to override property here}}
var getOptProp: Int? { return nil }
init(param: Int?) {}
init() {} // expected-note {{non-failable initializer 'init()' overridden here}}
subscript(a: Int?) -> Void { // expected-note {{attempt to override subscript here}}
get { return () }
set {}
}
subscript(b: Void) -> Int { // expected-note {{attempt to override subscript here}}
get { return 0 }
set {}
}
subscript(get a: Int?) -> Void {
return ()
}
subscript(get b: Void) -> Int {
return 0
}
subscript(ambiguous a: Int, b: Int?) -> Void { // expected-note {{overridden declaration is here}} expected-note {{potential overridden subscript 'subscript(ambiguous:_:)' here}}
return ()
}
subscript(ambiguous a: Int?, b: Int) -> Void { // expected-note {{overridden declaration is here}} expected-note {{potential overridden subscript 'subscript(ambiguous:_:)' here}}
return ()
}
}
protocol P1 {}
protocol P2 {}
class MismatchOptional : MismatchOptionalBase {
override func param(_: Int) {} // expected-error {{cannot override instance method parameter of type 'Int?' with non-optional type 'Int'}} {{29-29=?}}
override func paramIUO(_: Int) {} // expected-error {{cannot override instance method parameter of type 'Int?' with non-optional type 'Int'}} {{32-32=?}}
override func result() -> Int? { return nil } // expected-error {{cannot override instance method result type 'Int' with optional type 'Int?'}} {{32-33=}}
override func fixSeveralTypes(a: Int, b: Int) -> Int! { return nil }
// expected-error@-1 {{cannot override instance method parameter of type 'Int?' with non-optional type 'Int'}} {{39-39=?}}
// expected-error@-2 {{cannot override instance method parameter of type 'Int?' with non-optional type 'Int'}} {{47-47=?}}
// expected-error@-3 {{cannot override instance method result type 'Int' with optional type 'Int?'}} {{55-56=}}
override func functionParam(x: @escaping (Int) -> Int) {} // expected-error {{cannot override instance method parameter of type '((Int) -> Int)?' with non-optional type '(Int) -> Int'}} {{34-34=(}} {{56-56=)?}}
override func tupleParam(x: (Int, Int)) {} // expected-error {{cannot override instance method parameter of type '(Int, Int)?' with non-optional type '(Int, Int)'}} {{41-41=?}}
override func compositionParam(x: P1 & P2) {} // expected-error {{cannot override instance method parameter of type '(any P1 & P2)?' with non-optional type 'any P1 & P2'}} {{37-37=(}} {{44-44=)?}}
override func nameAndTypeMismatch(_: Int) {}
// expected-error@-1 {{argument labels for method 'nameAndTypeMismatch' do not match those of overridden method 'nameAndTypeMismatch(label:)'}} {{37-37=label }}
// expected-error@-2 {{cannot override instance method parameter of type 'Int?' with non-optional type 'Int'}} {{43-43=?}}
override func ambiguousOverride(a: Int?, b: Int?) {} // expected-error {{declaration 'ambiguousOverride(a:b:)' cannot override more than one superclass declaration}} {{none}}
override func ambiguousOverride(a: Int, b: Int) {} // expected-error {{method does not override any method from its superclass}} {{none}}
override var prop: Int? { // expected-error {{property 'prop' with type 'Int?' cannot override a property with type 'Int'}} {{none}}
get { return nil }
set {}
}
override var optProp: Int { // expected-error {{cannot override mutable property 'optProp' of type 'Int?' with covariant type 'Int'}} {{none}}
get { return 0 }
set {}
}
override var getProp: Int? { return nil } // expected-error {{property 'getProp' with type 'Int?' cannot override a property with type 'Int'}} {{none}}
override var getOptProp: Int { return 0 } // okay
override init(param: Int) {} // expected-error {{cannot override initializer parameter of type 'Int?' with non-optional type 'Int'}}
override init?() {} // expected-error {{failable initializer 'init()' cannot override a non-failable initializer}} {{none}}
override subscript(a: Int) -> Void { // expected-error {{cannot override mutable subscript of type '(Int) -> Void' with covariant type '(Int?) -> Void'}}
get { return () }
set {}
}
override subscript(b: Void) -> Int? { // expected-error {{cannot override mutable subscript of type '(Void) -> Int?' with covariant type '(Void) -> Int'}}
get { return nil }
set {}
}
override subscript(get a: Int) -> Void { // expected-error {{cannot override subscript index of type 'Int?' with non-optional type 'Int'}} {{32-32=?}}
return ()
}
override subscript(get b: Void) -> Int? { // expected-error {{cannot override subscript element type 'Int' with optional type 'Int?'}} {{41-42=}}
return nil
}
override subscript(ambiguous a: Int?, b: Int?) -> Void { // expected-error {{declaration 'subscript(ambiguous:_:)' cannot override more than one superclass declaration}}
return ()
}
override subscript(ambiguous a: Int, b: Int) -> Void { // expected-error {{subscript does not override any subscript from its superclass}}
return ()
}
}
class MismatchOptional2 : MismatchOptionalBase {
override func result() -> Int! { return nil } // expected-error {{cannot override instance method result type 'Int' with optional type 'Int?'}} {{32-33=}}
// None of these are overrides because we didn't say 'override'. Since they're
// not exact matches, they shouldn't result in errors.
func param(_: Int) {}
func ambiguousOverride(a: Int, b: Int) {}
// This is covariant, so we still assume it's meant to override.
func ambiguousOverride(a: Int?, b: Int?) {} // expected-error {{declaration 'ambiguousOverride(a:b:)' cannot override more than one superclass declaration}}
}
class MismatchOptional3 : MismatchOptionalBase {
override func result() -> Optional<Int> { return nil } // expected-error {{cannot override instance method result type 'Int' with optional type 'Optional<Int>'}} {{none}}
}
// Make sure we remap the method's innermost generic parameters
// to the correct depth
class GenericBase<T> {
func doStuff<U>(t: T, u: U) {}
init<U>(t: T, u: U) {}
}
class ConcreteSub : GenericBase<Int> {
override func doStuff<U>(t: Int, u: U) {}
override init<U>(t: Int, u: U) {}
}
class ConcreteBase {
init<U>(t: Int, u: U) {}
func doStuff<U>(t: Int, u: U) {}
}
class GenericSub<T> : ConcreteBase {
override init<U>(t: Int, u: U) {}
override func doStuff<U>(t: Int, u: U) {}
}
// Issue with generic parameter index
class MoreGenericSub1<T, TT> : GenericBase<T> {
override func doStuff<U>(t: T, u: U) {}
}
class MoreGenericSub2<TT, T> : GenericBase<T> {
override func doStuff<U>(t: T, u: U) {}
}
// Issue with insufficient canonicalization when
// comparing types
protocol SI {}
protocol CI {}
protocol Sequence {
associatedtype I : SI // expected-note{{declared here}}
}
protocol Collection : Sequence {
associatedtype I : CI // expected-warning{{redeclaration of associated type 'I'}}
}
class Index<F, T> {
func map(_ f: F) -> T {}
}
class CollectionIndex<C : Collection> : Index<C, C.I> {
override func map(_ f: C) -> C.I {}
}
// https://github.com/apple/swift/issues/46789
// Overrides with different generic signatures
protocol Protocol1 {}
protocol Protocol2 {}
// Base class is generic, derived class is concrete.
class Base1<T> {
func foo<T: Protocol1>(arg: T) {}
}
class Derived1: Base1<Protocol2> {
override func foo<T>(arg: T) {} // Ok?
}
// Base class is concrete, derived class is generic.
class Base2 {
func foo() {}
}
class Derived2<T>: Base2 {
override func foo<T>(arg: T) {} // expected-error {{method does not override any method from its superclass}}
}
// Base class generic w/ method generic, derived class generic w/ method not
// generic.
class Base3<T> {
func foo<T>(arg: T) {}
}
class Derived3<T>: Base3<T> {
override func foo() {} // expected-error {{method does not override any method from its superclass}}
}
// Base class generic w/ method generic, derived class generic w/ method generic
// but different requirement.
class Base4<T> {
func foo<T>(arg: T) {}
}
class Derived4<T>: Base4<T> {
override func foo<T: Protocol1>(arg: T) {} // expected-error {{method does not override any method from its superclass}}
}
// Base class not generic w/ method generic, derived class not generic w/ method
// generic but different requirement.
class Base5 {
func foo<T>(arg: T) {}
}
class Derived5: Base5 {
override func foo<T: Protocol1>(arg: T) {} // expected-error {{method does not override any method from its superclass}}
}
// Base class not generic w/ method generic, derived class not generic w/ method
// generic but removed requirement.
class Base6 {
func foo<T: Protocol2>(arg: T) {}
}
class Derived6: Base6 {
override func foo<T>(arg: T) {} // Ok?
}
// Base class not generic w/ method generic, derived class generic w/ method
// generic but different requirement.
class Base7 {
func foo<T: Protocol2>(arg: T) {}
}
class Derived7<T>: Base7 {
override func foo<T: Protocol1>(arg: T) {} // expected-error {{method does not override any method from its superclass}}
}
// Override with orthogonal requirement on contextual generic parameter.
class Base8<T> {
func foo1() where T: Protocol1 {}
func foo2() where T: Protocol1 {}
}
class Derived8<T>: Base8<T> {
override func foo1() where T: Protocol2 {} // expected-error {{method does not override any method from its superclass}}
override func foo2() {} // OK
}
// Subclass with new conformance requirement on inherited generic parameter.
class Base9<T> {
func foo() where T: Protocol1 {}
}
class Derived9<T: Protocol2, U>: Base9<T> {
// Because the generic signature of foo() is the same either way,
// it may seem confusing that placing an additional constraint on the
// generic parameter declaration directly has a different effect on
// overridability in contrast to placing the constraint on foo().
// The former (unlike the latter) is accepted because the constraint
// in question only affects the ability to initialize an instance of the
// subclass — not the visibility of the override itself relative to an
// existing instance.
override func foo() where T: Protocol1 {} // OK
}
// Override with less strict requirement via contextual where clauses.
class Base10<T> {
func foo() where T == Int {}
}
class Derived10<T>: Base10<T> {
override func foo() where T: FixedWidthInteger {} // OK
}
// Override with equivalent constraint on a different, non-inherited generic
// parameter.
class Base11<T> {
func foo() where T: Protocol1 {}
}
class Derived11<T, U>: Base11<T> {
override func foo() where U: Protocol1 {} // expected-error {{method does not override any method from its superclass}}
}
// Generic superclass / non-generic subclass.
class Base12<T> {
// The fact that the return type matches the substitution
// for T must hold across overrides.
func foo() -> T where T: FixedWidthInteger { fatalError() } // expected-note {{potential overridden instance method 'foo()' here}}
}
class Derived12_1: Base12<Int> {
override func foo() -> Int { return .zero } // OK
}
class Derived12_2: Base12<Bool> {
override func foo() -> Int { return .zero } // expected-error {{method does not override any method from its superclass}}
}
// Misc //
protocol P_Key {}
protocol P_Container {
associatedtype Key: P_Key
}
class Base13<Key: P_Key> {
func foo(forKey key: Key) throws {}
}
class Derived13<C: P_Container> : Base13<C.Key> {
typealias Key = C.Key
override func foo(forKey key: Key) throws {} // Okay, no generic signature mismatch
}
// https://github.com/apple/swift/issues/52598
class Base1_52598 {
func a<T>(_ val: T) -> String { return "not equatable" }
func a<T: Equatable>(_ val: T) -> String { return "equatable" }
}
class Derived1_52598: Base1_52598 {
override func a<T>(_ val: T) -> String { return super.a(val) } // okay
override func a<T: Equatable>(_ val: T) -> String { return super.a(val) } // okay
}
protocol P_52598 {
associatedtype Bar
}
struct S_52598: P_52598 {
typealias Bar = Int
}
class Base2_52598 {
init<F: P_52598>(_ arg: F) where F.Bar == Int {}
}
class Derived2_52598: Base2_52598 {
init(_ arg1: Int) { super.init(S_52598()) } // okay, doesn't crash
}
// https://github.com/apple/swift/issues/54147
public protocol P_54147 {}
public protocol Q_54147: P_54147 {
associatedtype A
}
public class Base_54147<F, A> {}
public class Derived_54147<F, A>
: Base_54147<Base_54147<F, A>, A>,
Q_54147 {}
public extension Base_54147 where F: Q_54147 {
static func foo(_: F.A) {}
}
extension Derived_54147 where F: P_54147 {
public static func foo(_: A) {}
}
// Make sure we don't crash on generic requirement mismatch
protocol P3 {}
protocol P4 {
associatedtype T
}
class Base {
func method<T: P3>(_: T) {}
func method<T: P4>(_: T) where T.T : P3 {}
}
class Derived: Base {
override func method<T: P3>(_: T) {}
}
|
acc6e43a874eb90d3c90e16b5f6b98ad
| 33.644444 | 212 | 0.670702 | false | false | false | false |
beallej/krlx-app
|
refs/heads/master
|
KRLX/KRLX/ShowHeader.swift
|
mit
|
1
|
//
// ShowHeader.swift
// KRLX
//
// This class define each show's properties (including title, DJ, start, end time and date of show)
// Created by Josie Bealle, Phuong Dinh, Maraki Ketema, Naomi Yamamoto on 5/20/15.
// Copyright (c) 2015 KRLXpert. All rights reserved.
//
import Foundation
class ShowHeader {
var title : String
var start : String
var end : String
var DJ : String
var date: String
init (titleString: String, startString: String, endString: String, DJString: String, dateString:String){
self.title = titleString
self.start = startString
self.end = endString
self.DJ = DJString
self.date = dateString // initialize to nil
if dateString != "" {
self.date = self.formatDate(dateString)
}
}
func getTitle() -> String{
return self.title
}
func getDJ() -> String{
return self.DJ
}
func getStartTime() -> String{
return self.start
}
func getEndTime() -> String{
return self.end
}
func getDate() -> String{
return self.date
}
//Returns date as "Mon, Dec 21",for example
func formatDate(dateString : String) -> String{
//converts string to nsdate
var dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"
dateFormatter.timeZone = NSTimeZone(abbreviation: "America/Chicago")
let showDate = dateFormatter.dateFromString(dateString)
//converts nsdate to preferred format, then back to a string
var prettyDateFormatter = NSDateFormatter()
//DayOfWeek-MonthAsString-DayNumber
prettyDateFormatter.dateFormat = "EEEE-LLLL-dd"
prettyDateFormatter.timeZone = NSTimeZone(abbreviation: "America/Chicago")
let prettyDateString = prettyDateFormatter.stringFromDate(showDate!)
var dateStringArray = prettyDateString.componentsSeparatedByString("-")
let day = dateStringArray[0]
let month = dateStringArray[1]
//Shorten December-> Dec, Monday -> Mon, for example
dateStringArray[0] = day.substringWithRange(Range<String.Index>(start: day.startIndex, end: advance(day.startIndex, 3)))
dateStringArray[1] = month.substringWithRange(Range<String.Index>(start: month.startIndex, end: advance(month.startIndex, 3)))
// Day of week , Month Day
let finalDateString = dateStringArray[0]+", "+dateStringArray[1]+" "+dateStringArray[2]
return finalDateString
}
}
|
8433d94c748db2c73b4e2ab5336069e1
| 31.047619 | 134 | 0.61627 | false | true | false | false |
sessionm/ios-smp-example
|
refs/heads/master
|
Referrals/ReferralDetailViewController.swift
|
mit
|
1
|
//
// ReferralDetailViewController.swift
// SMPExample
//
// Copyright © 2018 SessionM. All rights reserved.
//
import SessionMReferralsKit
import UIKit
class ReferralDetailViewController: UIViewController, UITextViewDelegate, UITextFieldDelegate {
@IBOutlet private var idTop: NSLayoutConstraint!
@IBOutlet private var idLabel: UILabel!
@IBOutlet private var referralID: UILabel!
@IBOutlet private var statusLabel: UILabel!
@IBOutlet private var status: UILabel!
@IBOutlet private var pendingTimeLabel: UILabel!
@IBOutlet private var pendingTime: UILabel!
@IBOutlet private var referee: UITextField!
@IBOutlet private var email: UITextField!
@IBOutlet private var phoneNumber: UITextField!
@IBOutlet private var source: UITextField!
@IBOutlet private var origin: UITextField!
@IBOutlet private var clientData: UITextView!
@IBOutlet private var submit: UIButton!
private var baseY: CGFloat = 0.0
private var latestY: CGFloat = 0.0
var isAddingReferral = false
var referral: SMReferral?
@IBAction private func submit(_ sender: UIButton) {
guard let emailText = email.text, emailText.count > 0 else {
let emailMissing = UIAlertController(title: "Email Missing", message: "Email is required", preferredStyle: .alert)
emailMissing.addAction(UIAlertAction(title: "Dismiss", style: .default))
self.present(emailMissing, animated: true)
return
}
let referralRequest = SMReferralRequest(email: emailText, name: referee.text, phoneNumber: phoneNumber.text, origin: origin.text, source: source.text, clientData: clientData.text)
let referralsRequest = SMReferralsRequest(requests: [referralRequest], referrer: "Me")
SMReferralsManager.instance().sendReferrals(referralsRequest, completionHandler: {(referrals: [SMReferral]?, referralErrors: [SMReferralError]?, error: SMError?) in
let referralAlert = UIAlertController(title: nil, message: nil, preferredStyle: .alert)
var alertHandler: ((UIAlertAction?) -> Void)?
if let errors = referralErrors {
referralAlert.title = "Error"
if let firstError = errors.first {
referralAlert.message = "\(firstError.referral.email)\n\(firstError.error.message)"
} else {
referralAlert.message = "Error encountered when submitting referral"
}
} else {
referralAlert.title = "Success"
referralAlert.message = "Refferal sent to \(emailText)"
alertHandler = { (action: UIAlertAction?) in
self.navigationController!.popViewController(animated: true)
}
}
referralAlert.addAction(UIAlertAction(title: "Dismiss", style: .default, handler: alertHandler))
self.present(referralAlert, animated: true)
})
}
override func viewDidLoad() {
super.viewDidLoad()
clientData.delegate = self
referee.delegate = self
email.delegate = self
phoneNumber.delegate = self
source.delegate = self
origin.delegate = self
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow(_:)), name: .UIKeyboardWillShow, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide(_:)), name: .UIKeyboardWillHide, object: nil)
let tap = UITapGestureRecognizer(target: self, action: #selector(endEditing(_:)))
self.view.addGestureRecognizer(tap)
baseY = idTop.constant
}
@objc private func endEditing(_: UITapGestureRecognizer) {
self.view.endEditing(true)
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
self.updateFieldVisibility()
if !isAddingReferral, let r = referral {
referralID.text = r.referralID
status.text = SMReferral.string(from: r.status)
pendingTime.text = r.pendingTime
referee.text = r.referee
email.text = r.email
phoneNumber.text = r.phoneNumber
source.text = r.source
origin.text = r.origin
clientData.text = "\(String(describing: r.clientData))"
}
}
private func updateFieldVisibility() {
if isAddingReferral {
idTop.constant = baseY - (idLabel.frame.size.height + statusLabel.frame.size.height + pendingTimeLabel.frame.size.height)
submit.isHidden = false
idLabel.isHidden = true
referralID.isHidden = true
statusLabel.isHidden = true
status.isHidden = true
pendingTimeLabel.isHidden = true
pendingTime.isHidden = true
referee.borderStyle = .roundedRect
email.borderStyle = .roundedRect
phoneNumber.borderStyle = .roundedRect
source.borderStyle = .roundedRect
origin.borderStyle = .roundedRect
referee.isEnabled = true
email.isEnabled = true
phoneNumber.isEnabled = true
source.isEnabled = true
origin.isEnabled = true
} else {
idTop.constant = baseY
submit.isHidden = true
idLabel.isHidden = false
referralID.isHidden = false
statusLabel.isHidden = false
status.isHidden = false
pendingTimeLabel.isHidden = false
pendingTime.isHidden = false
referee.borderStyle = .none
email.borderStyle = .none
phoneNumber.borderStyle = .none
source.borderStyle = .none
origin.borderStyle = .none
referee.isEnabled = false
email.isEnabled = false
phoneNumber.isEnabled = false
source.isEnabled = false
origin.isEnabled = false
}
}
func textViewShouldBeginEditing(_ textView: UITextView) -> Bool {
latestY = textView.frame.origin.y
return isAddingReferral
}
func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool {
latestY = textField.frame.origin.y
return true
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true
}
@objc private func keyboardWillShow(_ notification: Notification) {
idTop.constant = 80.0 - latestY
}
@objc private func keyboardWillHide(_ notification: Notification) {
idTop.constant = baseY - (idLabel.frame.size.height + statusLabel.frame.size.height + pendingTimeLabel.frame.size.height)
}
}
|
928c7bd053f9634ebb2b15b2c7bb6860
| 37.754286 | 187 | 0.639487 | false | false | false | false |
klaus01/Centipede
|
refs/heads/master
|
Centipede/PassKit/CE_PKPaymentAuthorizationViewController.swift
|
mit
|
1
|
//
// CE_PKPaymentAuthorizationViewController.swift
// Centipede
//
// Created by kelei on 2016/9/15.
// Copyright (c) 2016年 kelei. All rights reserved.
//
import PassKit
extension PKPaymentAuthorizationViewController {
private struct Static { static var AssociationKey: UInt8 = 0 }
private var _delegate: PKPaymentAuthorizationViewController_Delegate? {
get { return objc_getAssociatedObject(self, &Static.AssociationKey) as? PKPaymentAuthorizationViewController_Delegate }
set { objc_setAssociatedObject(self, &Static.AssociationKey, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN) }
}
private var ce: PKPaymentAuthorizationViewController_Delegate {
if let obj = _delegate {
return obj
}
if let obj: AnyObject = self.delegate {
if obj is PKPaymentAuthorizationViewController_Delegate {
return obj as! PKPaymentAuthorizationViewController_Delegate
}
}
let obj = getDelegateInstance()
_delegate = obj
return obj
}
private func rebindingDelegate() {
let delegate = ce
self.delegate = nil
self.delegate = delegate
}
internal override func getDelegateInstance() -> PKPaymentAuthorizationViewController_Delegate {
return PKPaymentAuthorizationViewController_Delegate()
}
@discardableResult
public func ce_paymentAuthorizationViewController_didAuthorizePayment(handle: @escaping (PKPaymentAuthorizationViewController, PKPayment, @escaping (PKPaymentAuthorizationStatus) -> Void) -> Void) -> Self {
ce._paymentAuthorizationViewController_didAuthorizePayment = handle
rebindingDelegate()
return self
}
@discardableResult
public func ce_paymentAuthorizationViewControllerDidFinish(handle: @escaping (PKPaymentAuthorizationViewController) -> Void) -> Self {
ce._paymentAuthorizationViewControllerDidFinish = handle
rebindingDelegate()
return self
}
@discardableResult
public func ce_paymentAuthorizationViewController_didSelect(handle: @escaping (PKPaymentAuthorizationViewController, PKShippingMethod, @escaping (PKPaymentAuthorizationStatus, [PKPaymentSummaryItem]) -> Void) -> Void) -> Self {
ce._paymentAuthorizationViewController_didSelect = handle
rebindingDelegate()
return self
}
}
internal class PKPaymentAuthorizationViewController_Delegate: UIViewController_Delegate, PKPaymentAuthorizationViewControllerDelegate {
var _paymentAuthorizationViewController_didAuthorizePayment: ((PKPaymentAuthorizationViewController, PKPayment, @escaping (PKPaymentAuthorizationStatus) -> Void) -> Void)?
var _paymentAuthorizationViewControllerDidFinish: ((PKPaymentAuthorizationViewController) -> Void)?
var _paymentAuthorizationViewController_didSelect: ((PKPaymentAuthorizationViewController, PKShippingMethod, @escaping (PKPaymentAuthorizationStatus, [PKPaymentSummaryItem]) -> Void) -> Void)?
override func responds(to aSelector: Selector!) -> Bool {
let funcDic1: [Selector : Any?] = [
#selector(paymentAuthorizationViewController(_:didAuthorizePayment:completion:)) : _paymentAuthorizationViewController_didAuthorizePayment,
#selector(paymentAuthorizationViewControllerDidFinish(_:)) : _paymentAuthorizationViewControllerDidFinish,
#selector(paymentAuthorizationViewController(_:didSelect:completion:)) : _paymentAuthorizationViewController_didSelect,
]
if let f = funcDic1[aSelector] {
return f != nil
}
return super.responds(to: aSelector)
}
@objc func paymentAuthorizationViewController(_ controller: PKPaymentAuthorizationViewController, didAuthorizePayment payment: PKPayment, completion: @escaping (PKPaymentAuthorizationStatus) -> Void) {
_paymentAuthorizationViewController_didAuthorizePayment!(controller, payment, completion)
}
@objc func paymentAuthorizationViewControllerDidFinish(_ controller: PKPaymentAuthorizationViewController) {
_paymentAuthorizationViewControllerDidFinish!(controller)
}
@objc func paymentAuthorizationViewController(_ controller: PKPaymentAuthorizationViewController, didSelect shippingMethod: PKShippingMethod, completion: @escaping (PKPaymentAuthorizationStatus, [PKPaymentSummaryItem]) -> Void) {
_paymentAuthorizationViewController_didSelect!(controller, shippingMethod, completion)
}
}
|
b038013803d5f70d2e293562f6c473b8
| 47.052632 | 233 | 0.737349 | false | false | false | false |
mastahyeti/SoftU2F
|
refs/heads/master
|
SoftU2FToolTests/TestUtil.swift
|
mit
|
2
|
//
// Util.swift
// SoftU2F
//
// Created by Benjamin P Toews on 9/10/16.
//
import XCTest
@testable import SoftU2F
func tupleDigestEqual(_ a: SHA256.TupleDigest, _ b: SHA256.TupleDigest) -> Bool {
return a.0 == b.0 &&
a.1 == b.1 &&
a.2 == b.2 &&
a.3 == b.3 &&
a.4 == b.4 &&
a.5 == b.5 &&
a.6 == b.6 &&
a.7 == b.7 &&
a.8 == b.8 &&
a.9 == b.9 &&
a.10 == b.10 &&
a.11 == b.11 &&
a.12 == b.12 &&
a.13 == b.13 &&
a.14 == b.14 &&
a.15 == b.15 &&
a.16 == b.16 &&
a.17 == b.17 &&
a.18 == b.18 &&
a.19 == b.19 &&
a.20 == b.20 &&
a.21 == b.21 &&
a.22 == b.22 &&
a.23 == b.23 &&
a.24 == b.24 &&
a.25 == b.25 &&
a.26 == b.26 &&
a.27 == b.27 &&
a.28 == b.28 &&
a.29 == b.29 &&
a.30 == b.30 &&
a.31 == b.31
}
func randData(maxLen: Int = 4096) -> Data {
let dLen = Int(arc4random()) % maxLen
return randData(length: dLen)
}
func randData(length len: Int) -> Data {
var d = Data(repeating: 0x00, count: len)
d.withUnsafeMutableBytes { dPtr in
arc4random_buf(dPtr, len)
}
return d
}
extension u2fh_rc {
var name: String {
let namePtr = u2fh_strerror_name(rawValue)
return String(cString: namePtr!)
}
}
|
27432ddb9cdfb35e30de341706f0bdfa
| 21.681818 | 81 | 0.398798 | false | false | false | false |
bangslosan/ImagePickerSheetController
|
refs/heads/master
|
ImagePickerSheetController/Example/ViewController.swift
|
mit
|
1
|
//
// ViewController.swift
// Example
//
// Created by Laurin Brandner on 26/05/15.
// Copyright (c) 2015 Laurin Brandner. All rights reserved.
//
import UIKit
import Photos
import ImagePickerSheetController
class ViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
// MARK: View Lifecycle
override func viewDidLoad() {
super.viewDidLoad()
let tapRecognizer = UITapGestureRecognizer(target: self, action: "presentImagePickerSheet:")
view.addGestureRecognizer(tapRecognizer)
}
// MARK: Other Methods
func presentImagePickerSheet(gestureRecognizer: UITapGestureRecognizer) {
let authorization = PHPhotoLibrary.authorizationStatus()
if authorization == .NotDetermined {
PHPhotoLibrary.requestAuthorization() { status in
dispatch_async(dispatch_get_main_queue()) {
self.presentImagePickerSheet(gestureRecognizer)
}
}
return
}
if authorization == .Authorized {
let presentImagePickerController: UIImagePickerControllerSourceType -> () = { source in
let controller = UIImagePickerController()
controller.delegate = self
var sourceType = source
if (!UIImagePickerController.isSourceTypeAvailable(sourceType)) {
sourceType = .PhotoLibrary
println("Fallback to camera roll as a source since the simulator doesn't support taking pictures")
}
controller.sourceType = sourceType
self.presentViewController(controller, animated: true, completion: nil)
}
let controller = ImagePickerSheetController()
controller.addAction(ImageAction(title: NSLocalizedString("Take Photo Or Video", comment: "Action Title"), secondaryTitle: NSLocalizedString("Add comment", comment: "Action Title"), handler: { _ in
presentImagePickerController(.Camera)
}, secondaryHandler: { _, numberOfPhotos in
println("Comment \(numberOfPhotos) photos")
}))
controller.addAction(ImageAction(title: NSLocalizedString("Photo Library", comment: "Action Title"), secondaryTitle: { NSString.localizedStringWithFormat(NSLocalizedString("ImagePickerSheet.button1.Send %lu Photo", comment: "Action Title"), $0) as String}, handler: { _ in
presentImagePickerController(.PhotoLibrary)
}, secondaryHandler: { _, numberOfPhotos in
controller.getSelectedImagesWithCompletion() { images in
println("Send \(images) photos")
}
}))
controller.addAction(ImageAction(title: NSLocalizedString("Cancel", comment: "Action Title"), style: .Cancel, handler: { _ in
println("Cancelled")
}))
presentViewController(controller, animated: true, completion: nil)
}
else {
let alertView = UIAlertView(title: NSLocalizedString("An error occurred", comment: "An error occurred"), message: NSLocalizedString("ImagePickerSheet needs access to the camera roll", comment: "ImagePickerSheet needs access to the camera roll"), delegate: nil, cancelButtonTitle: NSLocalizedString("OK", comment: "OK"))
alertView.show()
}
}
// MARK: UIImagePickerControllerDelegate
func imagePickerControllerDidCancel(picker: UIImagePickerController) {
dismissViewControllerAnimated(true, completion: nil)
}
}
|
6c64b7a603c5f84e200c922d75afb907
| 43.77381 | 331 | 0.628556 | false | false | false | false |
avaidyam/Parrot
|
refs/heads/master
|
Hangouts/PeopleAPI.swift
|
mpl-2.0
|
1
|
import Foundation
import HangoutsCore
import ParrotServiceExtension
import class Mocha.Logger
internal enum PeopleAPI {
private static let baseURL = "https://people-pa.clients6.google.com/v2/people"
private static let groupsURL = "https://hangoutssearch-pa.clients6.google.com/v1"
private static let APIKey = "AIzaSyBokvzEPUrkgfws0OrFWkpKkVBVuhRfKpk"
internal static func suggestions(on channel: Channel, completionHandler: @escaping (PeopleAPIData.SuggestionsResponse?, Error?) -> ()) {
self._post(channel, PeopleAPI.baseURL + "/me/allPeople", [
"requestMask.includeField.paths": "person.email",
"requestMask.includeField.paths": "person.gender",
"requestMask.includeField.paths": "person.in_app_reachability",
"requestMask.includeField.paths": "person.metadata",
"requestMask.includeField.paths": "person.name",
"requestMask.includeField.paths": "person.phone",
"requestMask.includeField.paths": "person.photo",
"requestMask.includeField.paths": "person.read_only_profile_info",
"extensionSet.extensionNames": "HANGOUTS_ADDITIONAL_DATA",
"extensionSet.extensionNames": "HANGOUTS_SUGGESTED_PEOPLE",
"extensionSet.extensionNames": "HANGOUTS_PHONE_DATA",
"key": PeopleAPI.APIKey
], nil, completionHandler)
}
internal static func list(on channel: Channel, completionHandler: @escaping (PeopleAPIData.ListAllResponse?, Error?) -> ()) {
self._post(channel, PeopleAPI.baseURL + "/me/allPeople", [
"requestMask.includeField.paths": "person.email",
"requestMask.includeField.paths": "person.gender",
"requestMask.includeField.paths": "person.in_app_reachability",
"requestMask.includeField.paths": "person.metadata",
"requestMask.includeField.paths": "person.name",
"requestMask.includeField.paths": "person.phone",
"requestMask.includeField.paths": "person.photo",
"requestMask.includeField.paths": "person.read_only_profile_info",
"extensionSet.extensionNames": "HANGOUTS_PHONE_DATA",
"fieldFilter.field": "PHONE",
"key": PeopleAPI.APIKey
], nil, completionHandler)
}
internal static func lookup(on channel: Channel, ids: [String], completionHandler: @escaping (PeopleAPIData.GetByIdResponse?, Error?) -> ()) {
guard ids.count > 0 else { return }
self._post(channel, PeopleAPI.baseURL + "", [
"requestMask.includeField.paths": "person.email",
"requestMask.includeField.paths": "person.gender",
"requestMask.includeField.paths": "person.in_app_reachability",
"requestMask.includeField.paths": "person.metadata",
"requestMask.includeField.paths": "person.name",
"requestMask.includeField.paths": "person.phone",
"requestMask.includeField.paths": "person.photo",
"requestMask.includeField.paths": "person.read_only_profile_info",
"requestMask.includeField.paths": "person.organization", // extra
"requestMask.includeField.paths": "person.location", // extra
"requestMask.includeField.paths": "person.cover_photo", // extra
"extensionSet.extensionNames": "HANGOUTS_ADDITIONAL_DATA",
"extensionSet.extensionNames": "HANGOUTS_OFF_NETWORK_GAIA_GET",
"extensionSet.extensionNames": "HANGOUTS_PHONE_DATA",
"includedProfileStates": "ADMIN_BLOCKED",
"includedProfileStates": "DELETED",
"includedProfileStates": "PRIVATE_PROFILE",
"mergedPersonSourceOptions.includeAffinity": "CHAT_AUTOCOMPLETE",
"coreIdParams.useRealtimeNotificationExpandedAcls": "true",
"key": PeopleAPI.APIKey
], ids.map { "personId=" + $0 }.joined(separator: "&"), completionHandler)
}
internal static func lookup(on channel: Channel, phones: [String], completionHandler: @escaping (PeopleAPIData.LookupResponse?, Error?) -> ()) {
guard phones.count > 0 else { return }
self._post(channel, PeopleAPI.baseURL + "/lookup", [
"type": "PHONE",
"matchType": "LENIENT",
"requestMask.includeField.paths": "person.email",
"requestMask.includeField.paths": "person.gender",
"requestMask.includeField.paths": "person.in_app_reachability",
"requestMask.includeField.paths": "person.metadata",
"requestMask.includeField.paths": "person.name",
"requestMask.includeField.paths": "person.phone",
"requestMask.includeField.paths": "person.photo",
"requestMask.includeField.paths": "person.read_only_profile_info",
"extensionSet.extensionNames": "HANGOUTS_ADDITIONAL_DATA",
"extensionSet.extensionNames": "HANGOUTS_OFF_NETWORK_GAIA_LOOKUP",
"extensionSet.extensionNames": "HANGOUTS_PHONE_DATA",
"coreIdParams.useRealtimeNotificationExpandedAcls": "true",
"quotaFilterType": "PHONE",
"key": PeopleAPI.APIKey
], phones.map { "id=" + $0 }.joined(separator: "&"), completionHandler)
}
internal static func lookup(on channel: Channel, emails: [String], completionHandler: @escaping (PeopleAPIData.LookupResponse?, Error?) -> ()) {
guard emails.count > 0 else { return }
self._post(channel, PeopleAPI.baseURL + "/lookup", [
"type": "EMAIL",
"matchType": "EXACT",
"requestMask.includeField.paths": "person.email",
"requestMask.includeField.paths": "person.gender",
"requestMask.includeField.paths": "person.in_app_reachability",
"requestMask.includeField.paths": "person.metadata",
"requestMask.includeField.paths": "person.name",
"requestMask.includeField.paths": "person.phone",
"requestMask.includeField.paths": "person.photo",
"requestMask.includeField.paths": "person.read_only_profile_info",
"extensionSet.extensionNames": "HANGOUTS_ADDITIONAL_DATA",
"extensionSet.extensionNames": "HANGOUTS_OFF_NETWORK_GAIA_LOOKUP",
"extensionSet.extensionNames": "HANGOUTS_PHONE_DATA",
"coreIdParams.useRealtimeNotificationExpandedAcls": "true",
"key": PeopleAPI.APIKey
], emails.map { "id=" + $0 }.joined(separator: "&"), completionHandler)
}
internal static func autocomplete(on channel: Channel, person: String, length: UInt = 15,
completionHandler: @escaping (PeopleAPIData.AutocompleteResponse?, Error?) -> ())
{
self._post(channel, PeopleAPI.baseURL + "/autocomplete", [
"query": person,
"client": "HANGOUTS_WITH_DATA",
"pageSize": "\(length)",
"key": PeopleAPI.APIKey
], nil, completionHandler)
}
internal static func autocomplete(on channel: Channel, group: String, length: UInt = 15,
completionHandler: @escaping (PeopleAPIData.AutocompleteGroupResponse?, Error?) -> ())
{
self._post(channel, PeopleAPI.groupsURL + "/metadata:search", [
"query": group,
"pageSize": "\(length)",
"includeMetadata": "true",
"key": PeopleAPI.APIKey,
"alt": "json"
], nil, completionHandler)
}
// Note: DictionaryLiteral accepts duplicate keys and preserves order.
// Note: `prefix` is a silly hack for multiple `id`'s which are dynamic and cannot be in a literal.
private static func _post<T: Codable>(_ channel: Channel, _ api: String, _ params: DictionaryLiteral<String, String>,
_ prefix: String? = nil, _ completionHandler: @escaping (T?, Error?) -> ())
{
var merge = params.map { "\($0)=\($1)" }.joined(separator: "&")
if let prefix2 = prefix {
merge = prefix2 + "&" + merge
}
merge = merge.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)!
.replacingOccurrences(of: "+", with: "%2B") // since + is somehow allowed???
var request = URLRequest(url: URL(string: api)!)
request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
request.httpMethod = "POST"
request.httpBody = merge.data(using: .utf8)
for (k, v) in Channel.getAuthorizationHeaders(channel.cachedSAPISID,
origin: "https://hangouts.google.com",
extras: ["X-HTTP-Method-Override": "GET"]) {
request.setValue(v, forHTTPHeaderField: k)
}
channel.session.dataTask(with: request) { data, response, error in
guard let data = data, error == nil else {
completionHandler(nil, error); return
}
if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 {
completionHandler(nil, NSError(domain: NSURLErrorDomain, code: httpStatus.statusCode, userInfo: [
"status": httpStatus,
"response": data
]))
}
do {
let res = try JSONDecoder().decode(T.self, from: data)
completionHandler(res, nil)
} catch(let error) {
completionHandler(nil, error)
}
}.resume()
}
}
internal enum PeopleAPIData {
internal struct Metadata: Codable {
internal var container: String? = nil
internal var containerType: String? = nil
internal var visibility: String? = nil
internal var primary: Bool? = nil
internal var writable: Bool? = nil
}
internal struct Address: Codable {
internal var metadata: Metadata? = nil
internal var formatted: String? = nil
internal var type: String? = nil
}
internal struct Location: Codable {
internal var metadata: Metadata? = nil
internal var value: String? = nil
}
internal struct Birthday: Codable {
internal var metadata: Metadata? = nil
internal var dateMs: String? = nil
internal var dateMsAsNumber: String? = nil
}
internal struct Organization: Codable {
internal var metadata: Metadata? = nil
internal var name: String? = nil
internal var stringType: String? = nil
internal var title: String? = nil
}
internal struct Tagline: Codable {
internal var metadata: Metadata? = nil
internal var value: String? = nil
}
internal struct Membership: Codable {
internal var contactGroupId: String? = nil
internal var systemContactGroupId: String? = nil
}
internal struct ProfileUrl: Codable {
internal var url: String? = nil
}
internal struct Email: Codable {
internal var metadata: Metadata? = nil
internal var formattedType: String? = nil
internal var type: String? = nil
internal var value: String? = nil
}
internal struct Gender: Codable {
internal var metadata: Metadata? = nil
internal var formattedType: String? = nil
internal var type: String? = nil
}
internal struct Name: Codable {
internal var metadata: Metadata? = nil
internal var displayName: String? = nil
internal var displayNameLastFirst: String? = nil
internal var familyName: String? = nil
internal var givenName: String? = nil
internal var unstructuredName: String? = nil
}
internal struct Photo: Codable {
internal var metadata: Metadata? = nil
internal var isDefault: Bool? = nil
internal var isMonogram: Bool? = nil
internal var monogramBackground: String? = nil
internal var photoToken: String? = nil
internal var url: String? = nil
}
internal struct CoverPhoto: Codable {
internal var imageHeight: UInt? = nil
internal var imageWidth: UInt? = nil
internal var imageId: String? = nil
internal var imageUrl: String? = nil
}
internal struct Phone: Codable {
internal struct PhoneExtendedData: Codable {
internal struct StructuredPhone: Codable {
internal struct PhoneNumber: Codable {
internal struct I18nData: Codable {
internal var countryCode: UInt? = nil
internal var internationalNumber: String? = nil
internal var isValid: Bool = false
internal var nationalNumber: String? = nil
internal var regionCode: String? = nil
internal var validationResult: String? = nil
}
internal var e164: String? = nil
internal var i18nData: I18nData? = nil
}
internal var phoneNumber: PhoneNumber? = nil
internal var type: String? = nil
}
internal var structuredPhone: StructuredPhone? = nil
}
internal var metadata: Metadata? = nil
internal var canonicalizedForm: String? = nil
internal var extendedData: PhoneExtendedData? = nil
internal var formattedType: String? = nil
internal var type: String? = nil
internal var uri: String? = nil
internal var value: String? = nil
}
internal struct InAppReachability: Codable {
internal struct ReachabilityKey: Codable {
internal var keyType: String? = nil
internal var keyValue: String? = nil
}
internal var appType: String? = nil
internal var reachabilityKey: ReachabilityKey? = nil
internal var status: String? = nil
}
internal struct ProfileInfo: Codable {
internal struct AccountEmail: Codable {
internal var email: String? = nil
}
internal var accountEmail: AccountEmail? = nil
internal var objectType: String? = nil
}
internal struct ExtendedData: Codable {
internal struct HangoutsExtendedData: Codable {
internal var hadPastHangoutState: String? = nil
internal var invitationStatus: String? = nil
internal var isBot: Bool? = nil
internal var isDismissed: Bool? = nil
internal var isFavorite: Bool? = nil
internal var isPinned: Bool? = nil
internal var userType: String? = nil
}
internal var hangoutsExtendedData: HangoutsExtendedData? = nil
}
internal struct Person: Codable {
internal var coverPhoto: CoverPhoto? = nil
internal var email: [Email]? = nil
internal var extendedData: ExtendedData? = nil
internal var fingerprint: String? = nil
internal var gender: [Gender]? = nil
internal var inAppReachability: [InAppReachability]? = nil
internal var name: [Name]? = nil
internal var personId: String? = nil
internal var phone: [Phone]? = nil
internal var photo: [Photo]? = nil
internal var address: [Address]? = nil
internal var location: [Location]? = nil
internal var birthday: [Birthday]? = nil
internal var organization: [Organization]? = nil
internal var tagline: [Tagline]? = nil
internal var membership: [Membership]? = nil
internal var readOnlyProfileInfo: [ProfileInfo]? = nil
internal var profileUrlRepeated: [ProfileUrl]? = nil
}
internal struct Participant: Codable {
internal struct Id: Codable {
internal var profileId: String? = nil
}
internal var displayName: String? = nil
internal var email: String? = nil
internal var id: Id? = nil
internal var invitationStatus: String? = nil
internal var profilePictureUrl: String? = nil
}
internal struct ConversationResult: Codable {
internal struct ConversationAndSelfState: Codable {
internal struct ConversationMetadata: Codable {
internal struct Id: Codable {
internal var id: String? = nil
}
internal var id: Id? = nil
internal var otrStatus: String? = nil
internal var participants: [Participant]? = nil
internal var type: String? = nil
}
internal var conversationMetadata: ConversationMetadata? = nil
}
internal var conversationAndSelfState: ConversationAndSelfState? = nil
}
internal struct GetByIdResponse: Codable {
internal struct Result: Codable {
internal var person: Person? = nil
internal var personId: String? = nil
internal var status: String? = nil
}
internal var personResponse: [Result]? = nil
}
internal struct LookupResponse: Codable {
internal struct Match: Codable {
internal var lookupId: String? = nil
internal var personId: [String]? = nil
}
internal var people: [String: Person]? = nil
internal var matches: [Match]? = nil
}
internal struct ListAllResponse: Codable {
internal var nextSyncToken: String? = nil
internal var people: [Person]? = nil
internal var totalItems: UInt? = nil
internal var nextPageToken: String? = nil
}
internal struct SuggestionsResponse: Codable {
internal var people: [Person]? = nil
}
internal struct AutocompleteResponse: Codable {
internal struct Status: Codable {
internal var personalResultsNotReady: Bool? = nil
}
internal struct Suggestion: Codable {
internal var objectType: String? = nil
internal var person: Person? = nil
internal var suggestion: String? = nil
}
internal var status: Status? = nil
internal var nextPageToken: String? = nil
internal var results: [Suggestion]? = nil
}
internal struct AutocompleteGroupResponse: Codable {
internal var results: [ConversationResult]? = nil
}
// Convenience for this crazy nesting.
internal typealias PhoneNumber = Phone.PhoneExtendedData.StructuredPhone.PhoneNumber
internal typealias I18nData = Phone.PhoneExtendedData.StructuredPhone.PhoneNumber.I18nData
internal typealias HangoutsExtendedData = ExtendedData.HangoutsExtendedData
internal typealias ConversationMetadata = ConversationResult.ConversationAndSelfState.ConversationMetadata
}
internal extension PeopleAPIData.HangoutsExtendedData {
var userInterest: Bool { return (self.isFavorite ?? false || self.isPinned ?? false) }
}
|
0cb89e6754466eca32cf88aff8df4dc0
| 42.522523 | 148 | 0.606707 | false | false | false | false |
stolycizmus/WowToken
|
refs/heads/master
|
WowToken/RoundedRect.swift
|
gpl-3.0
|
1
|
//
// RoundedRect.swift
// WowToken
//
// Created by Kadasi Mate on 2015. 11. 22..
// Copyright © 2015. Tairpake Inc. All rights reserved.
//
import UIKit
@IBDesignable class RoundedRect: UIView {
@IBInspectable var fillColor: UIColor = UIColor(colorLiteralRed: 0.035, green: 0.043, blue: 0.133, alpha: 1.0)
override func draw(_ rect: CGRect) {
self.backgroundColor = UIColor.clear
fillColor.setFill()
var path = UIBezierPath()
path.move(to: CGPoint(x: 0, y: 5))
path.addLine(to: CGPoint(x: 5, y: 0))
path.addLine(to: CGPoint(x: rect.width-5, y: 0))
path.addLine(to: CGPoint(x: rect.width, y: 5))
path.addLine(to: CGPoint(x: rect.width, y: rect.height-5))
path.addLine(to: CGPoint(x: rect.width-5, y: rect.height))
path.addLine(to: CGPoint(x: 5, y: rect.height))
path.addLine(to: CGPoint(x: 0, y: rect.height-5))
path.close()
path.addClip()
path.fill()
path = UIBezierPath()
path.lineWidth = 3
UIColor.white.setStroke()
path.move(to: CGPoint(x: 0, y: 5))
path.addLine(to: CGPoint(x: 5, y: 0))
path.addLine(to: CGPoint(x: rect.width-5, y: 0))
path.addLine(to: CGPoint(x: rect.width, y: 5))
path.stroke()
path = UIBezierPath()
path.lineWidth = 3
UIColor(colorLiteralRed: 0.467, green: 0.467, blue: 0.467, alpha: 1.0).setStroke()
path.move(to: CGPoint(x: rect.width, y: 5))
path.addLine(to: CGPoint(x: rect.width, y: rect.height-5))
path.addLine(to: CGPoint(x: rect.width-5, y: rect.height))
path.addLine(to: CGPoint(x: 5, y: rect.height))
path.addLine(to: CGPoint(x: 0, y: rect.height-5))
path.addLine(to: CGPoint(x: 0, y: 5))
path.stroke()
}
}
|
583ce960fbe0837fbe3a11601471e9f5
| 33.773585 | 114 | 0.583831 | false | false | false | false |
davirdgs/ABC4
|
refs/heads/master
|
MN4/StartViewController.swift
|
gpl-3.0
|
1
|
//
// StartViewController.swift
// MN4
//
// Created by Davi Rodrigues on 20/08/15.
// Copyright (c) 2015 Pedro Rodrigues Grijó. All rights reserved.
//
import UIKit
class StartViewController: UIViewController {
let defaults = UserDefaults.standard
///Displays score
@IBOutlet weak var scoreLabel: UILabel!
///Trophy image icon
@IBOutlet weak var scoreIcon: UIImageView!
@IBOutlet weak var tutorialButton: UIButton!
@IBOutlet weak var playButton: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
//Set background image as newspaper
self.view.backgroundColor = Styles.backgroundColor
//tutorialButton.layer.borderColor = UIColor.blackColor().CGColor
tutorialButton.layer.borderWidth = 0
//playButton.layer.borderColor = UIColor.blackColor().CGColor
playButton.layer.borderWidth = 0
tutorialButton.layer.cornerRadius = tutorialButton.frame.height/4
tutorialButton.layer.masksToBounds = true
playButton.layer.cornerRadius = playButton.frame.height/4
playButton.layer.masksToBounds = true
//Set Trophy
scoreIcon.image = scoreIcon.image!.withRenderingMode(UIImageRenderingMode.alwaysTemplate)
scoreIcon.tintColor = UIColor(red: 255/255, green: 200/255, blue: 0/255, alpha: 1.0)
scoreIcon.layer.shadowOffset = CGSize(width: 1, height: 1)
scoreIcon.layer.shadowOpacity = 1
scoreIcon.layer.shadowRadius = 1
//Set font
scoreLabel.font = Styles.getFont()
playButton.titleLabel!.font = Styles.getFont()
tutorialButton.titleLabel!.font = Styles.getFont()
// Creates the dataBase
WordDataBase.setDataBase()
WordDataBaseEnglish.setDataBase()
WordDataBaseSpanish.setDataBase()
}
override func viewWillAppear(_ animated: Bool) {
let record = defaults.integer(forKey: "Record")
scoreLabel.text = String(format: "%03d", record)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
// Hide status bar from this view
override var prefersStatusBarHidden : Bool {
return true
}
@IBAction func tutorialButtonHandler(_ sender: AnyObject) {
performSegue(withIdentifier: "toTutorialViewController", sender: self)
}
@IBAction func playButtonHandler(_ sender: AnyObject) {
let level = Level()
level.setLevel()
performSegue(withIdentifier: "toGameViewController", sender: self)
}
@IBAction func returnToStart(_ sender: UIStoryboardSegue) {
}
}
|
afac279c0c92c9f81ea4abed08273177
| 29.505618 | 97 | 0.658932 | false | false | false | false |
jianweihehe/JWDouYuZB
|
refs/heads/master
|
JWDouYuZB/JWDouYuZB/Classes/Main/Controller/CustomNavigationController.swift
|
mit
|
1
|
//
// CustomNavigationController.swift
// JWDouYuZB
//
// Created by [email protected] on 2017/1/16.
// Copyright © 2017年 简伟. All rights reserved.
//
import UIKit
class CustomNavigationController: UINavigationController {
override func viewDidLoad() {
super.viewDidLoad()
//获取系统pop手势
guard let systemGes = interactivePopGestureRecognizer else { return }
//获取手势添加到的view中
guard let gesView = systemGes.view else { return }
//获取target/action
/** 利用运行时机制查看所有的属性名称
var count:UInt32 = 0
let ivars = class_copyIvarList(UIGestureRecognizer.self, &count)
for i in 0..<count {
let ivar = ivars?[Int(i)]
let name = ivar_getName(ivar)
print(String(cString: name!))
}
*/
let targets = systemGes.value(forKey: "_targets") as? [NSObject]
guard let targetsObjc = targets?.first else { return }
guard let target = targetsObjc.value(forKey: "target") else { return }
let action = Selector(("handleNavigationTransition:"))
let panGes = UIPanGestureRecognizer(target: target, action: action)
gesView.addGestureRecognizer(panGes)
}
override func pushViewController(_ viewController: UIViewController, animated: Bool) {
viewController.hidesBottomBarWhenPushed = true
super.pushViewController(viewController, animated: animated)
}
}
|
cc6d1174b1729a71b3b8733f364e1e4c
| 31.727273 | 90 | 0.648611 | false | false | false | false |
toggl/superday
|
refs/heads/develop
|
teferi/Services/Implementations/Persistency/Adapters/GoalModelAdapter.swift
|
bsd-3-clause
|
1
|
import Foundation
import CoreData
class GoalModelAdapter : CoreDataModelAdapter<Goal>
{
//MARK: Private Properties
private let dateKey = "date"
private let categoryKey = "category"
private let targetTimeKey = "targetTime"
//MARK: Initializers
override init()
{
super.init()
sortDescriptorsForList = [ NSSortDescriptor(key: dateKey, ascending: false) ]
sortDescriptorsForLast = sortDescriptorsForList
}
//MARK: Public Methods
override func getModel(fromManagedObject managedObject: NSManagedObject) -> Goal
{
let date = managedObject.value(forKey: dateKey) as! Date
let category = Category(rawValue: managedObject.value(forKey: categoryKey) as! String)!
let targetTime = managedObject.value(forKey: targetTimeKey) as! Seconds
let goal = Goal(date: date, category: category, targetTime: targetTime)
return goal
}
override func setManagedElementProperties(fromModel model: Goal, managedObject: NSManagedObject)
{
managedObject.setValue(model.targetTime, forKey: targetTimeKey)
managedObject.setValue(model.date, forKey: dateKey)
managedObject.setValue(model.category.rawValue, forKey: categoryKey)
}
}
|
ce57be599556c6dacf7b98cbf4a0e53d
| 32.947368 | 100 | 0.688372 | false | false | false | false |
colemancda/Pedido
|
refs/heads/master
|
Pedido Admin/Pedido Admin/PickerViewController.swift
|
mit
|
1
|
//
// PickerViewController.swift
// Pedido Admin
//
// Created by Alsey Coleman Miller on 12/10/14.
// Copyright (c) 2014 ColemanCDA. All rights reserved.
//
import Foundation
import UIKit
import CoreData
import CorePedido
import CorePedidoClient
/** View controller for editing to-many relationships between entities. It allows selection from a list of existing items. */
class PickerViewController: FetchedResultsViewController {
// MARK: - Properties
var relationship: (NSManagedObject, String)? {
didSet {
// create fetch request
if relationship != nil {
let (managedObject, key) = self.relationship!
let relationshipDescription = managedObject.entity.relationshipsByName[key] as? NSRelationshipDescription
assert(relationshipDescription != nil, "Relationship \(key) not found on \(managedObject.entity.name!) entity")
assert(relationshipDescription!.toMany, "Relationship \(key) on \(managedObject.entity.name!) is not to-many")
let fetchRequest = NSFetchRequest(entityName: relationshipDescription!.destinationEntity!.name!)
fetchRequest.sortDescriptors = [NSSortDescriptor(key: Store.sharedStore.resourceIDAttributeName, ascending: true)]
self.fetchRequest = fetchRequest
}
else {
self.fetchRequest = nil
}
}
}
// MARK: - Initialization
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
// MARK: - Methods
func selectManagedObject(managedObject: NSManagedObject) {
let (parentManagedObject, relationshipName) = self.relationship!
let relationshipValue = parentManagedObject.valueForKey(relationshipName) as? NSSet
var newRelationshipValue: NSSet?
if relationshipValue?.containsObject(managedObject) ?? false {
// remove...
let arrayValue = (relationshipValue!.allObjects as NSArray).mutableCopy() as NSMutableArray
arrayValue.removeObject(managedObject)
newRelationshipValue = NSSet(array: arrayValue)
}
else {
// add to set...
var arrayValue: NSMutableArray?
if relationshipValue != nil {
arrayValue = (relationshipValue!.allObjects as NSArray).mutableCopy() as? NSMutableArray
}
else {
arrayValue = NSMutableArray()
}
arrayValue!.addObject(managedObject)
newRelationshipValue = NSSet(array: arrayValue!)
}
// edit managed object
Store.sharedStore.editManagedObject(parentManagedObject, changes: [relationshipName: newRelationshipValue!], completionBlock: { (error) -> Void in
NSOperationQueue.mainQueue().addOperationWithBlock({ () -> Void in
// show error
if error != nil {
self.showErrorAlert(error!.localizedDescription, retryHandler: { () -> Void in
self.selectManagedObject(managedObject)
})
return
}
})
})
}
// MARK: - UITableViewDataSource
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
// get model object
let managedObject = self.fetchedResultsController!.objectAtIndexPath(indexPath) as NSManagedObject
let dateCached = managedObject.valueForKey(Store.sharedStore.dateCachedAttributeName!) as? NSDate
let cell = super.tableView(tableView, cellForRowAtIndexPath: indexPath)
// only set selection if managed object was cached
if dateCached != nil {
// set selection
let (parentManagedObject, relationshipName) = self.relationship!
let relationshipValue = parentManagedObject.valueForKey(relationshipName) as? NSSet
if relationshipValue?.containsObject(managedObject) ?? false {
cell.accessoryType = .Checkmark
}
else {
cell.accessoryType = .None
}
}
return cell
}
// MARK: - UITableViewDelegate
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
// remove or add to relationship...
let managedObject = self.fetchedResultsController!.objectAtIndexPath(indexPath) as NSManagedObject
self.selectManagedObject(managedObject)
tableView.deselectRowAtIndexPath(indexPath, animated: true)
}
// MARK: - NSFetchedResultsControllerDelegate
override func controller(controller: NSFetchedResultsController,
didChangeObject object: AnyObject,
atIndexPath indexPath: NSIndexPath,
forChangeType type: NSFetchedResultsChangeType,
newIndexPath: NSIndexPath) {
switch type {
case .Insert:
self.tableView.insertRowsAtIndexPaths([newIndexPath], withRowAnimation: .Automatic)
case .Update:
if let cell = self.tableView.cellForRowAtIndexPath(indexPath) {
self.configureCell(cell, atIndexPath: indexPath)
// get model object
let managedObject = self.fetchedResultsController!.objectAtIndexPath(indexPath) as NSManagedObject
let dateCached = managedObject.valueForKey(Store.sharedStore.dateCachedAttributeName!) as? NSDate
// only set selection if managed object was cached
if dateCached != nil {
// set selection
let (parentManagedObject, relationshipName) = self.relationship!
let relationshipValue = parentManagedObject.valueForKey(relationshipName) as? NSSet
if relationshipValue?.containsObject(managedObject) ?? false {
cell.accessoryType = .Checkmark
}
else {
cell.accessoryType = .None
}
}
}
case .Move:
self.tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Automatic)
self.tableView.insertRowsAtIndexPaths([newIndexPath], withRowAnimation: .Automatic)
case .Delete:
self.tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Automatic)
default:
return
}
}
}
|
9da1ab695de2a85312b9907db0e2c1b7
| 34.638889 | 154 | 0.541829 | false | false | false | false |
ducyen/ClasHStamP
|
refs/heads/master
|
samples/CalcOrtho/swift/Main/CalcModel.swift
|
gpl-3.0
|
3
|
import Foundation
import Main.Statemachine
import Main.CalcOperand
import Main.CalcView
class CalcModel : System.Object
{
public class OPER_PARAMS {
public var key: char
}
public class DIGIT_1_9_PARAMS {
public var digit: char
}
public enum TestNestedEnum {
case ONE
case TWO
case THREE
}
var _stm: Statemachine
var _intEntry: string
var _fracEntry: string
var _signEntry: char
var _operEntry: char
var _operand1: double
var _entry: string
var _operand_input: CalcOperand
var _testNestedEnumAttr: TestNestedEnum
var _testNestedEnumProb: TestNestedEnum
var _calcView: CalcView
UInt32 nOnHistory;
public init (
entry: string
) {
_stm = Value0
_intEntry = ""
_fracEntry = ""
_signEntry = ' '
_operEntry = ' '
_operand1 = 0f
_entry = entry
_operand_input = new CalcOperand(this)
_testNestedEnumAttr = TestNestedEnum.ONE
_testNestedEnumProb = TestNestedEnum.ONE
_calcView = new CalcView()
nOnHistory = ON;
}
public void insertInt( char digit) {
_intEntry = _intEntry + digit;
_calcView.Update(entry);
} // insertInt
public void insertFrac( char digit) {
_fracEntry = _fracEntry + digit;
_calcView.Update(entry);
} // insertFrac
public void negate() {
_signEntry = '-';
_calcView.Update(entry);
} // negate
public void set( char digit) {
_intEntry = digit.ToString();
_fracEntry = "";
_calcView.Update(entry);
} // set
public void clear() {
_signEntry = ' ';
set( '0' );
} // clear
public void setOper( char key) {
_operEntry = key;
_calcView.Update(entry);
} // setOper
public bool calculate() {
bool error = false;
switch (_operEntry) {
case '+': _operand1 = _operand1 + curOperand; break;
case '-': _operand1 = _operand1 - curOperand; break;
case '*': _operand1 = _operand1 * curOperand; break;
case '/':
if (curOperand == 0f) {
error = true;
} else {
_operand1 = _operand1 / curOperand;
}
break;
}
return error;
} // calculate
public void showResult() {
string result = _operand1.ToString("0.########");
int dotPos = result.IndexOf(".");
string intRslt = "0";
string fracRslt = "";
if (dotPos >= 0) {
intRslt = result.Substring(0, dotPos);
fracRslt = result.Substring(dotPos + 1);
} else {
intRslt = result.Substring(0);
}
_calcView.Update(intRslt + "." + fracRslt + _operEntry);
} // showResult
public void showError() {
_calcView.Update("Err" + _operEntry);
} // showError
public TestNestedEnumOper(x: TestNestedEnum): TestNestedEnum {
return x;
} // TestNestedEnumOper
public var stm: Statemachine {
get {
return _stm
}
set {
_stm = newValue
}
}
public var entry: string {
get {
return _entry
}
set {
_entry = newValue
}
}
public var curOperand: double {
XXX
}
public var testNestedEnumProb: TestNestedEnum {
get {
return _testNestedEnumProb
}
set {
_testNestedEnumProb = newValue
}
}
const UInt32 RESULT = 1;
const UInt32 BEGIN = 2;
const UInt32 ERROR = 4;
const UInt32 OP_ENTERED = 8;
const UInt32 OPERAND_INPUT1 = 16;
const UInt32 OPERAND_INPUT2 = 32;
const UInt32 POWER_SAVE = 64;
const UInt32 STM = UInt32.MaxValue;
const UInt32 ON = ( READY | ERROR | OP_ENTERED | OPERAND_INPUT1 | OPERAND_INPUT2 );
const UInt32 READY = ( RESULT | BEGIN );
internal enum CALC_MODEL_EVENT {
case AC
case CE
case DIGIT_0
case DIGIT_1_9
case EQUALS
case OFF
case OPER
case POINT
case PSAVE_OFF
case PSAVE_ON
}
void EndTrans( bool isFinished ){
_stm.nCurrentState = _stm.nTargetState;
_stm.bIsFinished = isFinished;
_stm.bIsExternTrans = false;
if( isFinished ){
return;
}
switch( _stm.nCurrentState ){
case ON: On_Entry(); break;
case READY: Ready_Entry(); break;
case RESULT: Result_Entry(); break;
case BEGIN: Begin_Entry(); break;
case ERROR: Error_Entry(); break;
case OP_ENTERED: OpEntered_Entry(); break;
case OPERAND_INPUT1: OperandInput1_Entry(); break;
case OPERAND_INPUT2: OperandInput2_Entry(); break;
case POWER_SAVE: PowerSave_Entry(); break;
default: break;
}
}
void BgnTrans( UInt32 sourceState, UInt32 targetState ){
_stm.nSourceState = sourceState;
_stm.nTargetState = targetState;
switch( _stm.nCurrentState ){
case ON: On_Exit(); break;
case READY: Ready_Exit(); break;
case RESULT: Result_Exit(); break;
case BEGIN: Begin_Exit(); break;
case ERROR: Error_Exit(); break;
case OP_ENTERED: OpEntered_Exit(); break;
case OPERAND_INPUT1: OperandInput1_Exit(); break;
case OPERAND_INPUT2: OperandInput2_Exit(); break;
case POWER_SAVE: PowerSave_Exit(); break;
default: break;
}
}
public bool RunToCompletion(){
bool bResult;
do{
if( Statemachine.IsComposite( _stm.nCurrentState ) && !_stm.bIsFinished ){
bResult = Start();
}else{
bResult = Done();
}
}while( bResult );
if (IsFinished() && _stm.pParentContext != null) {
_stm.pParentContext.runToCompletion();
}
return bResult;
}
public bool IsFinished() {
return _stm.bIsFinished && _stm.nCurrentState == STM;
}
public bool IsEventHandled( bool bReset ) {
_stm.bIsEventHandled &= !bReset;
return _stm.bIsEventHandled;
}
public bool Abort() {
BgnTrans( STM, STM );
EndTrans( true );
return true;
}
bool EventProc( UInt32 nEventId, Object pEventParams ){
bool bResult = false;
if (IsFinished()) {
return bResult;
}
bResult |= _operand_input.IsEventHandled( true );
switch( ( CALC_MODEL_EVENT )nEventId ){
case CALC_MODEL_EVENT.CE:{
_operand_input.Ce( );
} break;
case CALC_MODEL_EVENT.DIGIT_0:{
_operand_input.Digit0( );
} break;
case CALC_MODEL_EVENT.DIGIT_1_9:{
CalcModel.DIGIT_1_9_PARAMS e = ( CalcModel.DIGIT_1_9_PARAMS )pEventParams;
_operand_input.Digit19(e.digit );
} break;
case CALC_MODEL_EVENT.EQUALS:{
_operand_input.Equals( );
} break;
case CALC_MODEL_EVENT.OPER:{
CalcModel.OPER_PARAMS e = ( CalcModel.OPER_PARAMS )pEventParams;
_operand_input.Oper(e.key );
} break;
case CALC_MODEL_EVENT.POINT:{
_operand_input.Point( );
} break;
default: break;
}
switch( _stm.nCurrentState ){
case ON: bResult = On_EventProc( nEventId, pEventParams ); break;
case READY: bResult = Ready_EventProc( nEventId, pEventParams ); break;
case RESULT: bResult = Result_EventProc( nEventId, pEventParams ); break;
case BEGIN: bResult = Begin_EventProc( nEventId, pEventParams ); break;
case ERROR: bResult = Error_EventProc( nEventId, pEventParams ); break;
case OP_ENTERED: bResult = OpEntered_EventProc( nEventId, pEventParams ); break;
case OPERAND_INPUT1: bResult = OperandInput1_EventProc( nEventId, pEventParams ); break;
case OPERAND_INPUT2: bResult = OperandInput2_EventProc( nEventId, pEventParams ); break;
case POWER_SAVE: bResult = PowerSave_EventProc( nEventId, pEventParams ); break;
default: break;
}
return bResult;
}
void On_Entry(){
if( Statemachine.IsIn( STM, _stm.nLCAState ) || _stm.nLCAState == 0 ){
_operand_input.Start();
_operand_input.RunToCompletion();
_stm.nLCAState = 0;
}
}
bool On_EventProc(
UInt32 nEventId,
Object pEventParams
){
bool bResult = false;
switch( ( CALC_MODEL_EVENT )nEventId ){
case CALC_MODEL_EVENT.AC:{
_stm.bIsExternTrans = true;
BgnTrans( ON, ON );
_operEntry = ' ';
EndTrans( false );
bResult = true;
} break;
case CALC_MODEL_EVENT.OFF:{
BgnTrans( ON, STM );
EndTrans( true );
bResult = true;
} break;
case CALC_MODEL_EVENT.PSAVE_ON:{
BgnTrans( ON, POWER_SAVE );
EndTrans( false );
bResult = true;
} break;
default: break;
}
bResult |= _operand_input.IsEventHandled( false );
return bResult;
}
void On_Exit(){
bool isThisLCA = Statemachine.IsIn( _stm.nSourceState, ON ) && Statemachine.IsIn( _stm.nTargetState, ON );
if( !isThisLCA || _stm.bIsExternTrans ){
_stm.bIsExternTrans &= !isThisLCA;
_operand_input.Abort();
} else {
_stm.nLCAState = ON;
}
}
void Ready_Entry(){
if( Statemachine.IsIn( ON, _stm.nLCAState ) || _stm.nLCAState == 0 ){
On_Entry();
_signEntry = ' ';
nOnHistory = READY;
_stm.nLCAState = 0;
}
}
bool Ready_EventProc(
UInt32 nEventId,
Object pEventParams
){
bool bResult = false;
switch( ( CALC_MODEL_EVENT )nEventId ){
case CALC_MODEL_EVENT.DIGIT_0:{
BgnTrans( READY, OPERAND_INPUT1 );
EndTrans( false );
bResult = true;
} break;
case CALC_MODEL_EVENT.DIGIT_1_9:{
CalcModel.DIGIT_1_9_PARAMS e = ( CalcModel.DIGIT_1_9_PARAMS )pEventParams;
BgnTrans( READY, OPERAND_INPUT1 );
set(e.digit);
EndTrans( false );
bResult = true;
} break;
case CALC_MODEL_EVENT.POINT:{
BgnTrans( READY, OPERAND_INPUT1 );
EndTrans( false );
bResult = true;
} break;
default: break;
}
return bResult ? bResult : On_EventProc( nEventId, pEventParams );
}
void Ready_Exit(){
bool isThisLCA = Statemachine.IsIn( _stm.nSourceState, READY ) && Statemachine.IsIn( _stm.nTargetState, READY );
if( !isThisLCA || _stm.bIsExternTrans ){
_stm.bIsExternTrans &= !isThisLCA;
On_Exit();
} else {
_stm.nLCAState = READY;
}
}
void Result_Entry(){
if( Statemachine.IsIn( READY, _stm.nLCAState ) || _stm.nLCAState == 0 ){
Ready_Entry();
_stm.nLCAState = 0;
}
}
bool Result_EventProc(
UInt32 nEventId,
Object pEventParams
){
bool bResult = false;
return bResult ? bResult : Ready_EventProc( nEventId, pEventParams );
}
void Result_Exit(){
bool isThisLCA = Statemachine.IsIn( _stm.nSourceState, RESULT ) && Statemachine.IsIn( _stm.nTargetState, RESULT );
if( !isThisLCA || _stm.bIsExternTrans ){
_stm.bIsExternTrans &= !isThisLCA;
Ready_Exit();
} else {
_stm.nLCAState = RESULT;
}
}
void Begin_Entry(){
if( Statemachine.IsIn( READY, _stm.nLCAState ) || _stm.nLCAState == 0 ){
Ready_Entry();
clear();
_stm.nLCAState = 0;
}
}
bool Begin_EventProc(
UInt32 nEventId,
Object pEventParams
){
bool bResult = false;
switch( ( CALC_MODEL_EVENT )nEventId ){
case CALC_MODEL_EVENT.OPER:{
CalcModel.OPER_PARAMS e = ( CalcModel.OPER_PARAMS )pEventParams;
if (e.key == '-') {
BgnTrans( BEGIN, OPERAND_INPUT1 );
EndTrans( false );
bResult = true;
}
} break;
default: break;
}
return bResult ? bResult : Ready_EventProc( nEventId, pEventParams );
}
void Begin_Exit(){
bool isThisLCA = Statemachine.IsIn( _stm.nSourceState, BEGIN ) && Statemachine.IsIn( _stm.nTargetState, BEGIN );
if( !isThisLCA || _stm.bIsExternTrans ){
_stm.bIsExternTrans &= !isThisLCA;
Ready_Exit();
} else {
_stm.nLCAState = BEGIN;
}
}
void Error_Entry(){
if( Statemachine.IsIn( ON, _stm.nLCAState ) || _stm.nLCAState == 0 ){
On_Entry();
showError();
nOnHistory = ERROR;
_stm.nLCAState = 0;
}
}
bool Error_EventProc(
UInt32 nEventId,
Object pEventParams
){
bool bResult = false;
return bResult ? bResult : On_EventProc( nEventId, pEventParams );
}
void Error_Exit(){
bool isThisLCA = Statemachine.IsIn( _stm.nSourceState, ERROR ) && Statemachine.IsIn( _stm.nTargetState, ERROR );
if( !isThisLCA || _stm.bIsExternTrans ){
_stm.bIsExternTrans &= !isThisLCA;
On_Exit();
} else {
_stm.nLCAState = ERROR;
}
}
void OpEntered_Entry(){
if( Statemachine.IsIn( ON, _stm.nLCAState ) || _stm.nLCAState == 0 ){
On_Entry();
_signEntry = ' ';
nOnHistory = OP_ENTERED;
_stm.nLCAState = 0;
}
}
bool OpEntered_EventProc(
UInt32 nEventId,
Object pEventParams
){
bool bResult = false;
switch( ( CALC_MODEL_EVENT )nEventId ){
case CALC_MODEL_EVENT.DIGIT_0:{
BgnTrans( OP_ENTERED, OPERAND_INPUT2 );
EndTrans( false );
bResult = true;
} break;
case CALC_MODEL_EVENT.DIGIT_1_9:{
CalcModel.DIGIT_1_9_PARAMS e = ( CalcModel.DIGIT_1_9_PARAMS )pEventParams;
BgnTrans( OP_ENTERED, OPERAND_INPUT2 );
set(e.digit);
EndTrans( false );
bResult = true;
} break;
case CALC_MODEL_EVENT.OPER:{
CalcModel.OPER_PARAMS e = ( CalcModel.OPER_PARAMS )pEventParams;
if (e.key == '-') {
BgnTrans( OP_ENTERED, OPERAND_INPUT2 );
EndTrans( false );
bResult = true;
}
} break;
case CALC_MODEL_EVENT.POINT:{
BgnTrans( OP_ENTERED, OPERAND_INPUT2 );
EndTrans( false );
bResult = true;
} break;
default: break;
}
return bResult ? bResult : On_EventProc( nEventId, pEventParams );
}
void OpEntered_Exit(){
bool isThisLCA = Statemachine.IsIn( _stm.nSourceState, OP_ENTERED ) && Statemachine.IsIn( _stm.nTargetState, OP_ENTERED );
if( !isThisLCA || _stm.bIsExternTrans ){
_stm.bIsExternTrans &= !isThisLCA;
On_Exit();
} else {
_stm.nLCAState = OP_ENTERED;
}
}
void OperandInput1_Entry(){
if( Statemachine.IsIn( ON, _stm.nLCAState ) || _stm.nLCAState == 0 ){
On_Entry();
nOnHistory = OPERAND_INPUT1;
_stm.nLCAState = 0;
}
}
bool OperandInput1_EventProc(
UInt32 nEventId,
Object pEventParams
){
bool bResult = false;
switch( ( CALC_MODEL_EVENT )nEventId ){
case CALC_MODEL_EVENT.CE:{
BgnTrans( OPERAND_INPUT1, BEGIN );
EndTrans( false );
bResult = true;
} break;
case CALC_MODEL_EVENT.OPER:{
CalcModel.OPER_PARAMS e = ( CalcModel.OPER_PARAMS )pEventParams;
BgnTrans( OPERAND_INPUT1, OP_ENTERED );
_operand1 = curOperand;
setOper( e.key );
EndTrans( false );
bResult = true;
} break;
default: break;
}
return bResult ? bResult : On_EventProc( nEventId, pEventParams );
}
void OperandInput1_Exit(){
bool isThisLCA = Statemachine.IsIn( _stm.nSourceState, OPERAND_INPUT1 ) && Statemachine.IsIn( _stm.nTargetState, OPERAND_INPUT1 );
if( !isThisLCA || _stm.bIsExternTrans ){
_stm.bIsExternTrans &= !isThisLCA;
On_Exit();
} else {
_stm.nLCAState = OPERAND_INPUT1;
}
}
void OperandInput2_Entry(){
if( Statemachine.IsIn( ON, _stm.nLCAState ) || _stm.nLCAState == 0 ){
On_Entry();
nOnHistory = OPERAND_INPUT2;
_stm.nLCAState = 0;
}
}
bool OperandInput2_EventProc(
UInt32 nEventId,
Object pEventParams
){
bool bResult = false;
switch( ( CALC_MODEL_EVENT )nEventId ){
case CALC_MODEL_EVENT.CE:{
BgnTrans( OPERAND_INPUT2, OP_ENTERED );
clear();
EndTrans( false );
bResult = true;
} break;
case CALC_MODEL_EVENT.EQUALS:{
bool error = calculate();
if (error) {
BgnTrans( OPERAND_INPUT2, ERROR );
EndTrans( false );
bResult = true;
} else {
BgnTrans( OPERAND_INPUT2, RESULT );
_operEntry = ' ';
showResult();
EndTrans( false );
bResult = true;
}
} break;
case CALC_MODEL_EVENT.OPER:{
CalcModel.OPER_PARAMS e = ( CalcModel.OPER_PARAMS )pEventParams;
bool error = calculate();
setOper( e.key );
if (error) {
BgnTrans( OPERAND_INPUT2, ERROR );
EndTrans( false );
bResult = true;
} else {
BgnTrans( OPERAND_INPUT2, OP_ENTERED );
showResult();
EndTrans( false );
bResult = true;
}
} break;
default: break;
}
return bResult ? bResult : On_EventProc( nEventId, pEventParams );
}
void OperandInput2_Exit(){
bool isThisLCA = Statemachine.IsIn( _stm.nSourceState, OPERAND_INPUT2 ) && Statemachine.IsIn( _stm.nTargetState, OPERAND_INPUT2 );
if( !isThisLCA || _stm.bIsExternTrans ){
_stm.bIsExternTrans &= !isThisLCA;
On_Exit();
} else {
_stm.nLCAState = OPERAND_INPUT2;
}
}
void PowerSave_Entry(){
if( Statemachine.IsIn( STM, _stm.nLCAState ) || _stm.nLCAState == 0 ){
_stm.nLCAState = 0;
}
}
bool PowerSave_EventProc(
UInt32 nEventId,
Object pEventParams
){
bool bResult = false;
switch( ( CALC_MODEL_EVENT )nEventId ){
case CALC_MODEL_EVENT.PSAVE_OFF:{
BgnTrans( POWER_SAVE, nOnHistory );
EndTrans( false );
bResult = true;
} break;
default: break;
}
return bResult;
}
void PowerSave_Exit(){
bool isThisLCA = Statemachine.IsIn( _stm.nSourceState, POWER_SAVE ) && Statemachine.IsIn( _stm.nTargetState, POWER_SAVE );
if( !isThisLCA || _stm.bIsExternTrans ){
_stm.bIsExternTrans &= !isThisLCA;
} else {
_stm.nLCAState = POWER_SAVE;
}
}
public bool Start(
){
bool bResult = false;
_stm.bIsFinished = false;
switch( _stm.nCurrentState ){
case STM:{
BgnTrans( STM, ON );
_calcView.DrawFrame();
EndTrans( false );
bResult = true;
} break;
case ON:{
BgnTrans( ON, READY );
EndTrans( false );
bResult = true;
} break;
case READY:{
BgnTrans( READY, BEGIN );
EndTrans( false );
bResult = true;
} break;
default: break;
}
return bResult;
}
public void Ac(
) {
Object pEventParams = null;
_stm.bIsEventHandled = EventProc( ( UInt32 )CALC_MODEL_EVENT.AC, pEventParams );
_stm.bIsEventHandled |= RunToCompletion();
}
public void Ce(
) {
Object pEventParams = null;
_stm.bIsEventHandled = EventProc( ( UInt32 )CALC_MODEL_EVENT.CE, pEventParams );
_stm.bIsEventHandled |= RunToCompletion();
}
public void Digit0(
) {
Object pEventParams = null;
_stm.bIsEventHandled = EventProc( ( UInt32 )CALC_MODEL_EVENT.DIGIT_0, pEventParams );
_stm.bIsEventHandled |= RunToCompletion();
}
public void Digit19(
char digit
) {
Object pEventParams = null;
CalcModel.DIGIT_1_9_PARAMS eventParams = new CalcModel.DIGIT_1_9_PARAMS();
pEventParams = ( Object )eventParams;
eventParams.digit = digit;
_stm.bIsEventHandled = EventProc( ( UInt32 )CALC_MODEL_EVENT.DIGIT_1_9, pEventParams );
_stm.bIsEventHandled |= RunToCompletion();
}
public void Equals(
) {
Object pEventParams = null;
_stm.bIsEventHandled = EventProc( ( UInt32 )CALC_MODEL_EVENT.EQUALS, pEventParams );
_stm.bIsEventHandled |= RunToCompletion();
}
public void Off(
) {
Object pEventParams = null;
_stm.bIsEventHandled = EventProc( ( UInt32 )CALC_MODEL_EVENT.OFF, pEventParams );
_stm.bIsEventHandled |= RunToCompletion();
}
public void Oper(
char key
) {
Object pEventParams = null;
CalcModel.OPER_PARAMS eventParams = new CalcModel.OPER_PARAMS();
pEventParams = ( Object )eventParams;
eventParams.key = key;
_stm.bIsEventHandled = EventProc( ( UInt32 )CALC_MODEL_EVENT.OPER, pEventParams );
_stm.bIsEventHandled |= RunToCompletion();
}
public void Point(
) {
Object pEventParams = null;
_stm.bIsEventHandled = EventProc( ( UInt32 )CALC_MODEL_EVENT.POINT, pEventParams );
_stm.bIsEventHandled |= RunToCompletion();
}
public void PsaveOff(
) {
Object pEventParams = null;
_stm.bIsEventHandled = EventProc( ( UInt32 )CALC_MODEL_EVENT.PSAVE_OFF, pEventParams );
_stm.bIsEventHandled |= RunToCompletion();
}
public void PsaveOn(
) {
Object pEventParams = null;
_stm.bIsEventHandled = EventProc( ( UInt32 )CALC_MODEL_EVENT.PSAVE_ON, pEventParams );
_stm.bIsEventHandled |= RunToCompletion();
}
public bool Done(
){
bool bResult = false;
return bResult;
}
}
}
|
22e113263b62030771551efebad62eb7
| 31.816384 | 138 | 0.531764 | false | false | false | false |
jwamin/Xnpm
|
refs/heads/master
|
Xnpm/ConsoleViewController.swift
|
mit
|
1
|
//
// ConsoleViewController.swift
// Xnpm
//
// Created by Joss Manger on 6/29/17.
// Copyright © 2017 Joss Manger. All rights reserved.
//
import Cocoa
class ConsoleViewController: NSViewController,NSWindowDelegate {
@IBOutlet weak var touchBarButton: NSButton!
@IBOutlet var textView: NSTextView!
var parentController:ViewController?
@IBOutlet weak var indicator: NSProgressIndicator!
override func viewDidLoad() {
NotificationCenter.default.addObserver(self, selector: #selector(handleText), name: NSNotification.Name(rawValue: "gotOut"), object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(handleEnd), name: NSNotification.Name(rawValue: "gotEnd"), object: nil)
// if #available(OSX 10.12.2, *) {
// touchBarButton.image = NSImage(named: NSImageNameTouchBarRecordStopTemplate)
// indicator.startAnimation(self)
// }
}
override func viewDidAppear() {
self.view.window?.delegate = self;
if #available(OSX 10.12.2, *) {
self.view.window?.unbind(#keyPath(touchBar)) // unbind first
self.view.window?.bind(#keyPath(touchBar), to: self, withKeyPath: #keyPath(touchBar), options: nil)
}
}
override func awakeFromNib() {
//print("hello world")
textView.font = NSFont(name: "Andale Mono", size: 11.0)
}
func handleText(notification:NSNotification){
//print(notification.object ?? "none")
let dict = notification.object as! NSDictionary
let str = dict.object(forKey: "str") as! String
let notificationID = dict.object(forKey: "sender") as! String
if let identifier = parentController?.package.packageTitle{
if(identifier==notificationID){
updateTextView(str: str)
}
}
}
func handleEnd(notification:NSNotification){
//print(notification.object ?? "none")
updateTextView(str: notification.object as! String)
}
func updateTextView(str:String){
// Smart Scrolling
let scroll = (NSMaxY(textView.visibleRect) == NSMaxY(textView.bounds));
// Append string to textview
textView.textStorage?.append(NSAttributedString(string: str))
//Set Font
textView.textStorage?.font = NSFont(name: "Andale Mono", size: 11.0)
if (scroll){
textView.scrollRangeToVisible(NSMakeRange((textView.string?.count)!, 0));
}// Scroll to end of the textview contents
}
func windowShouldClose(_ sender: Any) -> Bool {
self.parentController?.executeScript(sender: self)
return false;
}
func removeObservers(){
NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: "gotOut"), object: nil)
NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: "gotEnd"), object: nil)
}
override var representedObject: Any? {
didSet {
// Update the view, if already loaded.
}
}
override func viewDidDisappear() {
removeObservers()
}
deinit {
if #available(OSX 10.12.2, *) {
self.view.window?.unbind(#keyPath(touchBar))
}
}
}
|
4f069dd95e2d7af5a854039635899dce
| 29.882883 | 145 | 0.612894 | false | false | false | false |
alexcurylo/chatalyzer
|
refs/heads/master
|
Chatalyzer/Chatalyzer/source/ViewController.swift
|
mit
|
1
|
//
// ViewController.swift
// Chatalyzer
//
// Created by alex on 2016-04-28.
// Copyright © 2016 Trollwerks Inc. All rights reserved.
//
import UIKit
/// Takes string input from user and displays its parsed contents.
class ViewController: UIViewController, UITextFieldDelegate {
// MARK: - Properties
@IBOutlet weak var chatView: UITextField!
@IBOutlet weak var resultView: UITextView!
@IBOutlet weak var stackBottom: NSLayoutConstraint!
// MARK: - View lifecycle
override func viewDidLoad() {
super.viewDidLoad()
chatView.addTarget(self, action: #selector(onChatChange), forControlEvents: .EditingChanged)
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(keyboardWillChange), name:UIKeyboardWillChangeFrameNotification, object:nil)
}
// MARK: - Text input handling
func onChatChange(sender: AnyObject?) {
if let legalJSON = chatView.text?.chatalysis() {
// Make it more readable for display
let legalHTML = legalJSON.stringByReplacingOccurrencesOfString("\\/", withString: "/")
resultView.text = legalHTML.stringByDecodingHTMLEntities
} else {
resultView.text = nil
}
}
func textFieldShouldReturn(textField: UITextField) -> Bool {
view.endEditing(true)
return true
}
func keyboardWillChange(notification: NSNotification) {
let userInfo = notification.userInfo!
let animationDuration: NSTimeInterval = (userInfo[UIKeyboardAnimationDurationUserInfoKey] as! NSNumber).doubleValue
let keyboardScreenBeginFrame = (userInfo[UIKeyboardFrameBeginUserInfoKey] as! NSValue).CGRectValue()
let keyboardScreenEndFrame = (userInfo[UIKeyboardFrameEndUserInfoKey] as! NSValue).CGRectValue()
let keyboardViewBeginFrame = view.convertRect(keyboardScreenBeginFrame, fromView: view.window)
let keyboardViewEndFrame = view.convertRect(keyboardScreenEndFrame, fromView: view.window)
let originDelta = keyboardViewEndFrame.origin.y - keyboardViewBeginFrame.origin.y
stackBottom.constant -= originDelta
view.setNeedsUpdateConstraints()
UIView.animateWithDuration(animationDuration, delay:0, options:.BeginFromCurrentState, animations: {
self.view.layoutIfNeeded()
}, completion: nil)
}
}
|
754430e43271aa938cd6b0530f6b726b
| 36.169231 | 159 | 0.701159 | false | false | false | false |
DevAspirant/SwiftPro
|
refs/heads/master
|
PrimeCount.swift
|
gpl-2.0
|
1
|
/*------/ prime count /------*/
var number = 2
var isPrime = true
for(var i=2;i<=number;i++){
if number % i == 0{
isPrime=false;
}
}
print("is it Prime: " , isPrime);
|
01f521d3fe47740b29aae5e208e300a8
| 19.666667 | 33 | 0.5 | false | false | false | false |
Zglove/DouYu
|
refs/heads/master
|
DYTV/DYTV/Classes/Tools/Common.swift
|
mit
|
1
|
//
// Common.swift
// DYTV
//
// Created by people on 2016/10/28.
// Copyright © 2016年 people2000. All rights reserved.
//
import UIKit
let kStatusBarH : CGFloat = 20
let kNavigationBarH : CGFloat = 44
let kTabBarH : CGFloat = 44
let kScreenW : CGFloat = UIScreen.main.bounds.width
let kScreenH : CGFloat = UIScreen.main.bounds.height
|
20e8bd176ff7ce5c690c0772c0bde14b
| 20.375 | 54 | 0.716374 | false | false | false | false |
scottkawai/sendgrid-swift
|
refs/heads/master
|
Tests/SendGridTests/API/V3/Mail/Send/EmailTests.swift
|
mit
|
1
|
@testable import SendGrid
import XCTest
class EmailTests: XCTestCase, EncodingTester {
typealias EncodableObject = Email.Parameters
let goodFrom = Address(email: "[email protected]")
func generatePersonalizations(_ amount: Int) -> [Personalization] {
Array(0..<amount).map { (i) -> Personalization in
let recipient = Address(email: "test\(i)@example.none")
return Personalization(to: [recipient])
}
}
func generateBaseEmail(_ subject: String? = "Hello World") -> Email {
let personalization = self.generatePersonalizations(1)
return Email(
personalizations: personalization,
from: self.goodFrom,
content: [Content.plainText(body: "plain")],
subject: subject
)
}
func testOnlyApiKeys() {
do {
let auth = try Authentication.credential(username: "foo", password: "bar")
let session = Session(auth: auth)
let goodContent = Content.emailBody(plain: "plain", html: "html")
let email = Email(personalizations: self.generatePersonalizations(1), from: self.goodFrom, content: goodContent, subject: "Test")
try session.send(request: email)
XCTFail("Expected an error to be thrown when using basic auth with the mail send API, but nothing was thrown.")
} catch let SendGrid.Exception.Session.unsupportedAuthetication(desc) {
XCTAssertEqual(desc, "credential")
} catch {
XCTFailUnknownError(error)
}
}
func testNoImpersonation() {
do {
let auth = Authentication.apiKey("foobar")
let session = Session(auth: auth, onBehalfOf: "baz")
let goodContent = Content.emailBody(plain: "plain", html: "html")
let email = Email(personalizations: self.generatePersonalizations(1), from: self.goodFrom, content: goodContent, subject: "Test")
try session.send(request: email)
XCTFail("Expected an error to be thrown when impersonating a subuser with the mail send API, but nothing was thrown.")
} catch SendGrid.Exception.Session.impersonationNotAllowed {
XCTAssertTrue(true)
} catch {
XCTFailUnknownError(error)
}
}
func testEncoding() {
let goodContent = Content.emailBody(plain: "plain", html: "html")
let min = Email(personalizations: self.generatePersonalizations(1), from: self.goodFrom, content: goodContent)
let minExpectations: [String: Any] = [
"personalizations": [
[
"to": [
[
"email": "[email protected]"
]
]
]
],
"from": [
"email": "[email protected]"
],
"content": [
[
"type": "text/plain",
"value": "plain"
],
[
"type": "text/html",
"value": "html"
]
]
]
XCTAssertEncodedObject(min.parameters!, equals: minExpectations)
let max = Email(
personalizations: self.generatePersonalizations(1),
from: self.goodFrom,
content: goodContent,
subject: "Root Subject"
)
max.parameters?.replyTo = "[email protected]"
let data = Data(AttachmentTests.redDotBytes)
max.parameters?.attachments = [Attachment(filename: "red.png", content: data)]
max.parameters?.templateID = "1334949C-CE58-4A21-A633-47638EFA358A"
max.parameters?.sections = [
":male": "Mr. :name",
":female": "Ms. :name",
":neutral": ":name",
":event1": "New User Event on :event_date",
":event2": "Veteran User Appreciation on :event_date"
]
max.parameters?.headers = [
"Foo": "Bar"
]
max.parameters?.categories = ["Foo", "Bar"]
max.parameters?.customArguments = [
"foo": "bar"
]
max.parameters?.sendAt = Date(timeIntervalSince1970: 1505705165)
max.parameters?.batchID = "foobar"
max.parameters?.asm = ASM(groupID: 1234)
max.parameters?.ipPoolName = "Marketing"
max.parameters?.mailSettings.sandboxMode = SandboxMode()
max.parameters?.trackingSettings.clickTracking = ClickTracking(section: .off)
let maxExpectations: [String: Any] = [
"personalizations": [
[
"to": [
[
"email": "[email protected]"
]
]
]
],
"from": [
"email": "[email protected]"
],
"content": [
[
"type": "text/plain",
"value": "plain"
],
[
"type": "text/html",
"value": "html"
]
],
"subject": "Root Subject",
"reply_to": [
"email": "[email protected]"
],
"attachments": [
[
"content": AttachmentTests.dotBase64,
"filename": "red.png",
"disposition": "attachment"
]
],
"template_id": "1334949C-CE58-4A21-A633-47638EFA358A",
"sections": [
":male": "Mr. :name",
":female": "Ms. :name",
":neutral": ":name",
":event1": "New User Event on :event_date",
":event2": "Veteran User Appreciation on :event_date"
],
"headers": [
"Foo": "Bar"
],
"categories": ["Foo", "Bar"],
"custom_args": [
"foo": "bar"
],
"send_at": 1505705165,
"batch_id": "foobar",
"asm": [
"group_id": 1234
],
"ip_pool_name": "Marketing",
"mail_settings": [
"sandbox_mode": [
"enable": true
]
],
"tracking_settings": [
"click_tracking": [
"enable": false
]
]
]
XCTAssertEncodedObject(max.parameters!, equals: maxExpectations)
}
func testInitialization() {
let personalization = self.generatePersonalizations(Constants.PersonalizationLimit)
let goodContent = Content.emailBody(plain: "plain", html: "html")
let good = Email(personalizations: personalization, from: self.goodFrom, content: goodContent)
XCTAssertEqual(good.parameters!.personalizations.count, Constants.PersonalizationLimit)
XCTAssertEqual(good.parameters!.personalizations[0].to[0].email, "[email protected]")
XCTAssertEqual(good.parameters!.from.email, "[email protected]")
XCTAssertEqual(good.parameters!.content?.count, 2)
XCTAssertEqual(good.parameters!.content?[0].value, "plain")
XCTAssertEqual(good.parameters!.content?[1].value, "html")
XCTAssertNil(good.parameters!.subject)
}
func testPersonalizationValidation() {
let goodContent = Content.emailBody(plain: "plain", html: "html")
do {
let empty = Email(personalizations: [], from: self.goodFrom, content: goodContent, subject: "Hello World")
try empty.validate()
XCTFail("Expected error to be thrown when initializing Email with an empty personalization array, but nothing was thrown.")
} catch SendGrid.Exception.Mail.invalidNumberOfPersonalizations {
XCTAssertTrue(true)
} catch {
XCTFailUnknownError(error)
}
do {
let over = self.generatePersonalizations(Constants.PersonalizationLimit + 1)
let tooMany = Email(personalizations: over, from: self.goodFrom, content: goodContent, subject: "Hello World")
try tooMany.validate()
XCTFail("Expected error to be thrown when providing more than \(Constants.PersonalizationLimit) personalizations, but nothing was thrown.")
} catch SendGrid.Exception.Mail.invalidNumberOfPersonalizations {
XCTAssertTrue(true)
} catch {
XCTFailUnknownError(error)
}
do {
// Over 1000 recipients should throw an error.
let personalizations = Array(0...334).map(
{ (i) -> Personalization in
let to = Address(email: "to\(i)@example.none")
let cc = Address(email: "cc\(i)@example.none")
let bcc = Address(email: "bcc\(i)@example.none")
return Personalization(to: [to], cc: [cc], bcc: [bcc], subject: nil, headers: nil, substitutions: nil, customArguments: nil)
}
)
let bad = Email(personalizations: personalizations, from: self.goodFrom, content: [Content.plainText(body: "uh oh")])
try bad.validate()
XCTFail("Expected an error to be thrown when an email contains more than \(Constants.RecipientLimit) total recipients, but nothing was thrown")
} catch SendGrid.Exception.Mail.tooManyRecipients {
XCTAssertTrue(true)
} catch {
XCTFailUnknownError(error)
}
do {
// Under 1000 recipients should have no errors.
let personalizations = Array(0...3).map(
{ (i) -> Personalization in
let to = Address(email: "to\(i)@example.none")
let cc = Address(email: "cc\(i)@example.none")
let bcc = Address(email: "bcc\(i)@example.none")
return Personalization(to: [to], cc: [cc], bcc: [bcc], subject: nil, headers: nil, substitutions: nil, customArguments: nil)
}
)
let good = Email(personalizations: personalizations, from: self.goodFrom, content: [Content.plainText(body: "uh oh")], subject: "Hello World")
try good.validate()
XCTAssertTrue(true)
} catch {
XCTFailUnknownError(error)
}
do {
let personalizations: [Personalization] = [
Personalization(recipients: "[email protected]"),
Personalization(to: [Address(email: "[email protected]")], cc: nil, bcc: [Address(email: "[email protected]")], subject: "Hello", headers: nil, substitutions: nil, customArguments: nil)
]
let bad = Email(personalizations: personalizations, from: self.goodFrom, content: [Content.plainText(body: "uh oh")])
try bad.validate()
XCTFail("Expected an error to be thrown when an email is listed more than once in the personalizations array, but nothing was thrown.")
} catch let SendGrid.Exception.Mail.duplicateRecipient(duplicate) {
XCTAssertEqual(duplicate, "[email protected]")
} catch {
XCTFailUnknownError(error)
}
do {
let personalizations: [Personalization] = [
Personalization(recipients: "[email protected]"),
Personalization(to: [Address(email: "[email protected]")], cc: [Address(email: "[email protected]")], bcc: nil, subject: "Hello", headers: nil, substitutions: nil, customArguments: nil)
]
let bad = Email(personalizations: personalizations, from: self.goodFrom, content: [Content.plainText(body: "uh oh")])
try bad.validate()
XCTFail("Expected an error to be thrown when an email is listed more than once in the personalizations array, but nothing was thrown.")
} catch let SendGrid.Exception.Mail.duplicateRecipient(duplicate) {
XCTAssertEqual(duplicate, "[email protected]")
} catch {
XCTFailUnknownError(error)
}
do {
let personalizations: [Personalization] = [
Personalization(recipients: "[email protected]"),
Personalization(recipients: "[email protected]")
]
let bad = Email(personalizations: personalizations, from: self.goodFrom, content: [Content.plainText(body: "uh oh")])
try bad.validate()
XCTFail("Expected an error to be thrown when an email is listed more than once in the personalizations array, but nothing was thrown.")
} catch let SendGrid.Exception.Mail.duplicateRecipient(duplicate) {
XCTAssertEqual(duplicate, "[email protected]")
} catch {
XCTFailUnknownError(error)
}
do {
let personalizations: [Personalization] = [Personalization(recipients: "[email protected]")]
let fromTest = Email(personalizations: personalizations, from: Address(email: "from"), content: [Content.plainText(body: "uh oh")], subject: "Hello World")
try fromTest.validate()
XCTFail("Expected error to be thrown when an email has a malformed From address, but nothing was thrown.")
} catch SendGrid.Exception.Mail.malformedEmailAddress(_) {
XCTAssertTrue(true)
} catch {
XCTFailUnknownError(error)
}
do {
let personalizations: [Personalization] = [Personalization(recipients: "[email protected]")]
let replyToTest = Email(personalizations: personalizations, from: self.goodFrom, content: [Content.plainText(body: "uh oh")], subject: "Hello World")
replyToTest.parameters?.replyTo = "reply"
try replyToTest.validate()
XCTFail("Expected error to be thrown when an email has a malformed Reply To address, but nothing was thrown.")
} catch SendGrid.Exception.Mail.malformedEmailAddress(_) {
XCTAssertTrue(true)
} catch {
XCTFailUnknownError(error)
}
}
func testContentValidation() {
let personalization = self.generatePersonalizations(Constants.PersonalizationLimit)
let plain = Content.plainText(body: "plain")
let html = Content.html(body: "html")
let csv = Content(contentType: .csv, value: "foo,bar")
let amp = Content(contentType: .amp, value: "AMP")
let goodContent = [plain, html]
do {
let empty = Email(personalizations: personalization, from: self.goodFrom, content: [], subject: "Hello World")
try empty.validate()
XCTFail("Expected error to be thrown when initializing Email with an empty content array, but nothing was thrown.")
} catch SendGrid.Exception.Mail.missingContent {
XCTAssertTrue(true)
} catch {
XCTFailUnknownError(error)
}
let badContent1 = [csv] + goodContent
do {
let badOrder = Email(personalizations: personalization, from: self.goodFrom, content: badContent1, subject: "Hello World")
try badOrder.validate()
XCTFail("Expected error to be thrown when providing an out of order content array, but nothing was thrown.")
} catch SendGrid.Exception.Mail.invalidContentOrder {
XCTAssertTrue(true)
} catch {
XCTFailUnknownError(error)
}
let badContent2 = [plain, csv, html]
do {
let badOrder2 = Email(personalizations: personalization, from: self.goodFrom, content: badContent2, subject: "Hello World")
try badOrder2.validate()
XCTFail("Expected error to be thrown when providing an out of order content array, but nothing was thrown.")
} catch SendGrid.Exception.Mail.invalidContentOrder {
XCTAssertTrue(true)
} catch {
XCTFailUnknownError(error)
}
let badContent3 = [html, plain, csv]
do {
let badOrder3 = Email(personalizations: personalization, from: self.goodFrom, content: badContent3, subject: "Hello World")
try badOrder3.validate()
XCTFail("Expected error to be thrown when providing an out of order content array, but nothing was thrown.")
} catch SendGrid.Exception.Mail.invalidContentOrder {
XCTAssertTrue(true)
} catch {
XCTFailUnknownError(error)
}
do {
let goodOrder = Email(personalizations: personalization, from: self.goodFrom, content: [plain, html, csv], subject: "Hello World")
try goodOrder.validate()
XCTAssertTrue(true)
} catch {
XCTFailUnknownError(error)
}
do {
let goodOrderAMP1 = Email(personalizations: personalization, from: self.goodFrom, content: [plain, html, amp], subject: "Hello World")
try goodOrderAMP1.validate()
XCTAssertTrue(true)
} catch {
XCTFailUnknownError(error)
}
do {
let goodOrderAMP2 = Email(personalizations: personalization, from: self.goodFrom, content: [plain, amp, html], subject: "Hello World")
try goodOrderAMP2.validate()
XCTAssertTrue(true)
} catch {
XCTFailUnknownError(error)
}
do {
let badOrderAMP = Email(personalizations: personalization, from: self.goodFrom, content: [amp, plain, html], subject: "Hello World")
try badOrderAMP.validate()
XCTFail("Expected error to be thrown when providing an out of order content array, but nothing was thrown.")
} catch SendGrid.Exception.Mail.invalidContentOrder {
XCTAssertTrue(true)
} catch {
XCTFailUnknownError(error)
}
/// No content with no template ID should throw an error.
do {
let personalization = Personalization(recipients: "[email protected]")
let noContentEmail = Email(personalizations: [personalization], from: self.goodFrom, content: [], subject: "Hello world")
noContentEmail.parameters?.content = nil
try noContentEmail.validate()
} catch SendGrid.Exception.Mail.missingContent {
XCTAssertTrue(true)
} catch {
XCTFailUnknownError(error)
}
/// Empty array content with no template ID should throw an error.
do {
let personalization = Personalization(recipients: "[email protected]")
let emptyContentEmail = Email(personalizations: [personalization], from: self.goodFrom, content: [], subject: "Hello world")
try emptyContentEmail.validate()
} catch SendGrid.Exception.Mail.missingContent {
XCTAssertTrue(true)
} catch {
XCTFailUnknownError(error)
}
/// No content with a template ID throws no error.
do {
let personalization = Personalization(recipients: "[email protected]")
let emptyTemplatedEmail = Email(personalizations: [personalization], from: self.goodFrom, templateID: "ABCDEFG", subject: "Hello world")
XCTAssertNoThrow(try emptyTemplatedEmail.validate())
}
/// Empty array content with a template ID throws no error.
do {
let personalization = Personalization(recipients: "[email protected]")
let emptyTemplatedEmail = Email(personalizations: [personalization], from: self.goodFrom, templateID: "ABCDEFG", subject: "Hello world")
emptyTemplatedEmail.parameters?.content = []
XCTAssertNoThrow(try emptyTemplatedEmail.validate())
}
/// Content with a template ID throws no error.
do {
let personalization = Personalization(recipients: "[email protected]")
let templatedEmail = Email(personalizations: [personalization], from: self.goodFrom, templateID: "ABCDEFG", subject: "Hello world")
templatedEmail.parameters?.content = Content.emailBody(plain: "foobar", html: "<p>foobar</p>")
XCTAssertNoThrow(try templatedEmail.validate())
}
}
func testSubjectValidation() {
do {
let missing = self.generateBaseEmail(nil)
try missing.validate()
XCTFail("Expected an error to be thrown when a subject is missing, but nothing was thrown.")
} catch SendGrid.Exception.Mail.missingSubject {
XCTAssertTrue(true)
} catch {
XCTFailUnknownError(error)
}
do {
let missing = self.generateBaseEmail("")
try missing.validate()
XCTFail("Expected an error to be thrown when a subject is an empty, but nothing was thrown.")
} catch SendGrid.Exception.Mail.missingSubject {
XCTAssertTrue(true)
} catch {
XCTFailUnknownError(error)
}
do {
let personalizations = [
Personalization(to: [Address(email: "[email protected]")], cc: nil, bcc: nil, subject: "Subject 1", headers: nil, substitutions: nil, customArguments: nil),
Personalization(recipients: "[email protected]")
]
let missing = Email(personalizations: personalizations, from: Address(email: "[email protected]"), content: Content.emailBody(plain: "plain", html: "html"))
try missing.validate()
XCTFail("Expected an error to be thrown when a subject is not set as global, and not present in a personalization, but nothing was thrown.")
} catch SendGrid.Exception.Mail.missingSubject {
XCTAssertTrue(true)
} catch {
XCTFailUnknownError(error)
}
do {
let personalizations = [
Personalization(to: [Address(email: "[email protected]")], cc: nil, bcc: nil, subject: "", headers: nil, substitutions: nil, customArguments: nil)
]
let missing = Email(personalizations: personalizations, from: Address(email: "[email protected]"), content: Content.emailBody(plain: "plain", html: "html"))
try missing.validate()
XCTFail("Expected an error to be thrown when a subject is not set as global, and an empty string in a personalization, but nothing was thrown.")
} catch SendGrid.Exception.Mail.missingSubject {
XCTAssertTrue(true)
} catch {
XCTFailUnknownError(error)
}
do {
// No error should be thrown when each personalization has a subject line.
let personalizations = [
Personalization(to: [Address(email: "[email protected]")], cc: nil, bcc: nil, subject: "Subject 1", headers: nil, substitutions: nil, customArguments: nil),
Personalization(to: [Address(email: "[email protected]")], cc: nil, bcc: nil, subject: "Subject 2", headers: nil, substitutions: nil, customArguments: nil)
]
let valid = Email(personalizations: personalizations, from: Address(email: "[email protected]"), content: Content.emailBody(plain: "plain", html: "html"))
try valid.validate()
XCTAssertTrue(true)
} catch {
XCTFailUnknownError(error)
}
do {
// No error should be thrown if all subject properties are `nil` and a template ID is specified.
let personalizations = [
Personalization(recipients: "[email protected]"),
Personalization(recipients: "[email protected]")
]
let valid = Email(personalizations: personalizations, from: Address(email: "[email protected]"), content: Content.emailBody(plain: "plain", html: "html"))
valid.parameters?.templateID = "696DC347-E82F-44EB-8CB1-59320BA1F136"
try valid.validate()
XCTAssertTrue(true)
} catch {
XCTFailUnknownError(error)
}
}
func testHeaderValidation() {
do {
let good = self.generateBaseEmail()
good.parameters!.headers = [
"X-Custom-Header": "Foo",
"X-UID": "12345"
]
try good.validate()
XCTAssertTrue(true)
} catch {
XCTFail("Unexpected error: \(error)")
}
do {
let bad = self.generateBaseEmail()
bad.parameters!.headers = [
"X-Custom-Header": "Foo",
"subject": "12345"
]
try bad.validate()
XCTFail("Expected error when using a reserved header, but no error was thrown")
} catch let SendGrid.Exception.Mail.headerNotAllowed(header) {
XCTAssertEqual(header, "subject")
} catch {
XCTFailUnknownError(error)
}
do {
let bad = self.generateBaseEmail()
bad.parameters!.headers = [
"X-Custom Header": "Foo"
]
try bad.validate()
XCTFail("Expected error when using a header with a space, but no error was thrown")
} catch let SendGrid.Exception.Mail.malformedHeader(header) {
XCTAssertEqual(header, "X-Custom Header")
} catch {
XCTFailUnknownError(error)
}
}
func testCategoryValidation() {
do {
let good = self.generateBaseEmail()
good.parameters?.categories = ["Category1", "Category2", "Category3", "Category4", "Category5", "Category6", "Category7", "Category8", "Category9", "Category10"]
try good.validate()
XCTAssertTrue(true)
} catch {
XCTFailUnknownError(error)
}
do {
let good = self.generateBaseEmail()
good.parameters?.categories = ["Category1", "Category2", "Category3", "Category4", "Category5", "Category6", "Category7", "Category8", "Category9", "category3"]
try good.validate()
XCTFail("Expected error when there are duplicate categories, but nothing was thrown.")
} catch let SendGrid.Exception.Mail.duplicateCategory(dupe) {
XCTAssertEqual(dupe, "category3")
} catch {
XCTFailUnknownError(error)
}
do {
let bad = self.generateBaseEmail()
bad.parameters?.categories = ["Category1", "Category2", "Category3", "Category4", "Category5", "Category6", "Category7", "Category8", "Category9", "Category10", "Category11"]
try bad.validate()
XCTFail("Expected error when there are too many categories, but nothing was thrown.")
} catch SendGrid.Exception.Mail.tooManyCategories {
XCTAssertTrue(true)
} catch {
XCTFailUnknownError(error)
}
let characters = Array(0..<200).map { "\($0)" }
let longCategory = characters.joined(separator: "")
do {
let bad = self.generateBaseEmail()
bad.parameters?.categories = [longCategory]
try bad.validate()
XCTFail("Expected error when a category name is too long, but nothing was thrown.")
} catch SendGrid.Exception.Mail.categoryTooLong(_) {
XCTAssertTrue(true)
} catch {
XCTFailUnknownError(error)
}
}
func testCustomArgs() {
let email = self.generateBaseEmail()
email.parameters?.customArguments = ["foo": "bar"]
XCTAssertEqual(email.parameters!.customArguments!["foo"], "bar")
let new = Personalization(recipients: "[email protected]")
new.customArguments = ["foo": "bar"]
let over = Email(personalizations: [new], from: self.goodFrom, content: [Content.plainText(body: "plain")], subject: "Custom Args")
var args = [String: String]()
for i in 0..<300 {
args["custom_arg_\(i)"] = "custom value \(i)"
}
over.parameters?.customArguments = args
do {
try over.validate()
XCTFail("Expected an error when the custom arguments exceed \(Constants.CustomArguments.MaximumBytes) bytes, but nothing was thrown.")
} catch SendGrid.Exception.Mail.tooManyCustomArguments(_, _) {
XCTAssertTrue(true)
} catch {
XCTFailUnknownError(error)
}
}
func testSendAt() {
let test = self.generateBaseEmail()
let goodDate = Date(timeIntervalSinceNow: 4 * 60 * 60)
test.parameters?.sendAt = goodDate
do {
try test.validate()
XCTAssertEqual(test.parameters?.sendAt?.timeIntervalSince1970, goodDate.timeIntervalSince1970)
} catch SendGrid.Exception.Mail.invalidScheduleDate {
XCTAssertTrue(true)
} catch {
XCTFailUnknownError(error)
}
let failTest = self.generateBaseEmail()
let badDate = Date(timeIntervalSinceNow: 80 * 60 * 60)
failTest.parameters?.sendAt = badDate
do {
try failTest.validate()
XCTFail("Expected a failure when scheduling a date further than 72 hours out, but nothing was thrown.")
} catch SendGrid.Exception.Mail.invalidScheduleDate {
XCTAssertTrue(true)
} catch {
XCTFailUnknownError(error)
}
}
}
|
6505fa6b3c6aeed6445817db5c5022e6
| 43.863363 | 195 | 0.576492 | false | true | false | false |
Tanglo/OpalStability
|
refs/heads/master
|
OpalStability/AppDelegate.swift
|
mit
|
1
|
//
// AppDelegate.swift
// OpalStability
//
// Created by Lee Walsh on 30/11/2015.
// Copyright © 2015 Lee David Walsh. All rights reserved.
//
import Cocoa
import LabBot
@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {
func applicationDidFinishLaunching(aNotification: NSNotification) {
// Insert code here to initialize your application
}
func applicationWillTerminate(aNotification: NSNotification) {
// Insert code here to tear down your application
}
func applicationShouldOpenUntitledFile(sender: NSApplication) -> Bool {
return false
}
@IBAction func importData(sender: AnyObject){
let openPanel = NSOpenPanel()
openPanel.canChooseDirectories = false
openPanel.canChooseFiles = true
openPanel.allowedFileTypes = ["csv","CSV"]
let result = openPanel.runModal()
if result == NSModalResponseOK {
do{
var newOpalData = try LBDataMatrix(csvURL: openPanel.URL!, titles: true)
var metadata: [String]
(metadata, newOpalData) = self.importDataMatrix(newOpalData)
do{
let newDoc = try NSDocumentController.sharedDocumentController().openUntitledDocumentAndDisplay(false) as! LDWOpalDocument
newDoc.opalData = LDWOpalData(data: newOpalData, metadataArray: metadata)
newDoc.makeWindowControllers()
newDoc.showWindows()
} catch {
NSDocumentController.sharedDocumentController().presentError((error as NSError))
}
} catch {
let errorAlert = NSAlert(error: error as NSError)
errorAlert.runModal()
}
}
}
func importDataMatrix(dataMatrix: LBDataMatrix) -> ([String], LBDataMatrix){
let numVariables = dataMatrix.numberOfVariables()
let numObservations = dataMatrix.numberOfObservations() - 1 //the last row of the .csv data from the opal file is blank
let metadataIndex = dataMatrix.indexOfVariable("Metadata")
var metadata = [String]()
let importedDataMatrix = LBDataMatrix(numberOfObservations: numObservations)
if metadataIndex != nil{
metadata = dataMatrix.variableAtIndex(metadataIndex!) as! [String]
}
for i in 0..<numVariables{
if dataMatrix.nameOfVariableAtIndex(i) != "Metadata"{
let variableName = dataMatrix.nameOfVariableAtIndex(i)!
importedDataMatrix.appendVariable(variableName, values: dataMatrix.variableAtIndex(i)!)
if (importedDataMatrix.variableWithName(variableName)![0] as! String).containsString("."){
importedDataMatrix.changeStringVariableToDouble(variableName)
} else {
importedDataMatrix.changeStringVariableToInt(variableName)
}
}
}
return (metadata, importedDataMatrix)
}
}
|
3562b8d0d79624cdff4c855b60462072
| 38.217949 | 143 | 0.632887 | false | false | false | false |
nifti/CinchKit
|
refs/heads/master
|
CinchKit/Serializers/ErrorResponseSerializer.swift
|
mit
|
1
|
//
// ErrorResponseSerializer.swift
// CinchKit
//
// Created by Ryan Fitzgerald on 2/19/15.
// Copyright (c) 2015 cinch. All rights reserved.
//
import Foundation
import SwiftyJSON
class ErrorResponseSerializer : JSONObjectSerializer {
func jsonToObject(json: SwiftyJSON.JSON) -> NSError? {
let statusCode = json["statusCode"].intValue
var userInfo = [String : String]()
if let err = json["error"].string {
userInfo[NSLocalizedDescriptionKey] = err
}
if let message = json["message"].string {
userInfo[NSLocalizedFailureReasonErrorKey] = message
}
return NSError(domain: CinchKitErrorDomain, code: statusCode, userInfo: userInfo)
}
}
|
8e9b15a65702e8517b5acc244dca1982
| 24.533333 | 89 | 0.63268 | false | false | false | false |
SandcastleApps/partyup
|
refs/heads/master
|
PartyUP/NSDateComponentsFormatter+Postfix.swift
|
mit
|
1
|
//
// NSDateComponentsFormatter+Postfix.swift
// PartyUP
//
// Created by Fritz Vander Heide on 2016-03-25.
// Copyright © 2016 Sandcastle Application Development. All rights reserved.
//
import Foundation
extension NSDateComponentsFormatter {
func stringFromDate(startDate: NSDate,
toDate endDate: NSDate,
classicThreshold classic: NSTimeInterval?,
postfix: Bool = false,
substituteZero zero: String? = nil) -> String? {
var capped = false
var interval = endDate.timeIntervalSinceDate(startDate)
if let classic = classic where interval > classic {
interval = classic
capped = true
if unitsStyle != .Abbreviated {
return NSLocalizedString("Classic", comment: "Stale time display")
}
}
var formatted = stringFromTimeInterval(interval) ?? "?"
formatted = formatted.characters.split(",").prefixUpTo(self.maximumUnitCount).map { String($0) }.joinWithSeparator(",")
if capped {
formatted += "+"
}
if let zero = zero where formatted.hasPrefix("0") {
formatted = zero
} else if postfix {
formatted += NSLocalizedString(" ago", comment:"Samples more than a minute old")
}
return formatted
}
}
|
5c90f2b877ad007bde5f85e8e02c1bcd
| 34.634146 | 121 | 0.560959 | false | false | false | false |
joostholslag/BNRiOS
|
refs/heads/master
|
iOSProgramming6ed/16 - Archiving/Solutions/Homepwner/Homepwner/Item.swift
|
gpl-3.0
|
2
|
//
// Copyright © 2015 Big Nerd Ranch
//
import Foundation
class Item: NSObject, NSCoding {
var name: String
var valueInDollars: Int
var serialNumber: String?
let dateCreated: Date
let itemKey: String
init(name: String, serialNumber: String?, valueInDollars: Int) {
self.name = name
self.serialNumber = serialNumber
self.valueInDollars = valueInDollars
self.dateCreated = Date()
self.itemKey = UUID().uuidString
}
convenience init(random: Bool = false) {
if random {
let adjectives = ["Fluffy", "Rusty", "Shiny"]
let nouns = ["Bear", "Spork", "Mac"]
var idx = arc4random_uniform(UInt32(adjectives.count))
let randomAdjective = adjectives[Int(idx)]
idx = arc4random_uniform(UInt32(nouns.count))
let randomNoun = nouns[Int(idx)]
let randomName = "\(randomAdjective) \(randomNoun)"
let randomValue = Int(arc4random_uniform(100))
let randomSerialNumber =
UUID().uuidString.components(separatedBy: "-").first!
self.init(name: randomName,
serialNumber: randomSerialNumber,
valueInDollars: randomValue)
} else {
self.init(name: "", serialNumber: nil, valueInDollars: 0)
}
}
required init(coder aDecoder: NSCoder) {
name = aDecoder.decodeObject(forKey: "name") as! String
dateCreated = aDecoder.decodeObject(forKey: "dateCreated") as! Date
itemKey = aDecoder.decodeObject(forKey: "itemKey") as! String
serialNumber = aDecoder.decodeObject(forKey: "serialNumber") as! String?
valueInDollars = aDecoder.decodeInteger(forKey: "valueInDollars")
super.init()
}
func encode(with aCoder: NSCoder) {
aCoder.encode(name, forKey: "name")
aCoder.encode(dateCreated, forKey: "dateCreated")
aCoder.encode(itemKey, forKey: "itemKey")
aCoder.encode(serialNumber, forKey: "serialNumber")
aCoder.encode(valueInDollars, forKey: "valueInDollars")
}
}
|
550acee3f64a4cf852527ddeaa11edc9
| 32.014925 | 80 | 0.594033 | false | false | false | false |
xmartlabs/Bender
|
refs/heads/master
|
Example/Example/Luminance.swift
|
mit
|
1
|
//
// LuminanceLayer.swift
// Bender
//
// Created by Mathias Claassen on 4/25/17.
// Copyright © 2017 Xmartlabs. All rights reserved.
//
import MetalPerformanceShaders
import MetalPerformanceShadersProxy
import MetalBender
/// Receives two input images. The first is used to take the luminance and the second is used to take the color for the output image. Used for color preservation
class Luminance: NetworkLayer {
var enabled: Bool
// Custom kernels
let pipelineLuminance: MTLComputePipelineState
init(enabled: Bool, id: String? = nil) {
self.enabled = enabled
pipelineLuminance = MetalShaderManager.shared.getFunction(name: "luminance_transfer")
super.init(id: id)
}
override func validate() {
let incoming = getIncoming()
precondition(incoming.count == 2, "Luminance layer must have two inputs")
precondition(incoming[1].outputSize == incoming[0].outputSize, "Luminance layer must have two inputs with same size")
}
override func initialize(network: Network, device: MTLDevice, temporaryImage: Bool = true) {
super.initialize(network: network, device: device, temporaryImage: temporaryImage)
let incoming = getIncoming()
outputSize = incoming[0].outputSize
createOutputs(size: outputSize, temporary: temporaryImage)
}
override func execute(commandBuffer: MTLCommandBuffer, executionIndex index: Int = 0) {
let incoming = getIncoming()
let input1 = incoming[0].getOutput(index: index)
let input2 = incoming[1].getOutput(index: index)
let output = getOrCreateOutput(commandBuffer: commandBuffer, index: index)
if !enabled {
rewireIdentity(at: index, image: input1)
return
}
let encoder = commandBuffer.makeComputeCommandEncoder()!
encoder.label = "Luminance encoder"
encoder.setComputePipelineState(pipelineLuminance)
encoder.setTexture(input1.texture, index: 0)
encoder.setTexture(input2.texture, index: 1)
encoder.setTexture(output.texture, index: 2)
let threadsPerGroups = MTLSizeMake(32, 8, 1)
let threadGroups = MTLSizeMake(output.texture.width / threadsPerGroups.width,
output.texture.height / threadsPerGroups.height, 1)
encoder.dispatchThreadgroups(threadGroups, threadsPerThreadgroup: threadsPerGroups)
encoder.endEncoding()
input1.setRead()
input2.setRead()
}
}
|
44fb8529952493133995e7f09451a4e2
| 38.375 | 161 | 0.686905 | false | false | false | false |
ello/ello-ios
|
refs/heads/master
|
Specs/Controllers/Notifications/NotificationsGeneratorSpec.swift
|
mit
|
1
|
////
/// NotificationsGeneratorSpec.swift
//
@testable import Ello
import Quick
import Nimble
class NotificationsGeneratorSpec: QuickSpec {
class MockNotificationsDestination: StreamDestination {
var placeholderItems: [StreamCellItem] = []
var announcementItems: [StreamCellItem] = []
var notificationItems: [StreamCellItem] = []
var otherPlaceholderLoaded = false
var responseConfig: ResponseConfig?
var isPagingEnabled: Bool = false
func setPlaceholders(items: [StreamCellItem]) {
placeholderItems = items
}
func replacePlaceholder(
type: StreamCellType.PlaceholderType,
items: [StreamCellItem],
completion: @escaping Block
) {
switch type {
case .announcements:
announcementItems = items
case .notifications:
notificationItems = items
default:
otherPlaceholderLoaded = true
}
}
func setPrimary(jsonable: Model) {
}
func primaryModelNotFound() {
}
func setPagingConfig(responseConfig: ResponseConfig) {
self.responseConfig = responseConfig
}
}
override func spec() {
describe("NotificationsGenerator") {
var destination: MockNotificationsDestination!
var currentUser: User!
var streamKind: StreamKind!
var subject: NotificationsGenerator!
beforeEach {
destination = MockNotificationsDestination()
currentUser = User.stub(["id": "42"])
streamKind = .notifications(category: nil)
subject = NotificationsGenerator(
currentUser: currentUser,
streamKind: streamKind,
destination: destination
)
}
describe("load()") {
it("sets 2 placeholders") {
subject.load()
expect(destination.placeholderItems.count) == 2
}
it("replaces only Announcements and Notifications") {
subject.load()
expect(destination.announcementItems.count) > 0
expect(destination.notificationItems.count) > 0
expect(destination.otherPlaceholderLoaded) == false
}
it("sets the config response") {
subject.load()
expect(destination.responseConfig).toNot(beNil())
}
}
describe("reloadAnnouncements()") {
it("does not trigger when identical announcements are found") {
ElloProvider.moya = ElloProvider.DefaultProvider()
subject.load()
let prevItems = destination.announcementItems
subject.reloadAnnouncements()
expect(destination.announcementItems) == prevItems
}
}
}
}
}
|
3dd7cf798e099477510980b1b4858956
| 30.636364 | 79 | 0.54023 | false | true | false | false |
CUNY-Hunter-CSCI-Capstone-Summer2014/XMPP-Chat
|
refs/heads/master
|
DampKeg/OS X/Source Code/RosterListViewItem.swift
|
apache-2.0
|
1
|
//
// RosterListItem.swift
// DampKeg
//
// Created by Omar Stefan Evans on 7/23/14.
// Copyright (c) 2014 DampKeg. All rights reserved.
//
import Foundation
import Rambler
class RosterListViewItem : NSObject {
let isGroup: Bool
let groupName: String?
let rosterItem: RosterItem?
var presence: Presence?
var items: NSArray?
init(rosterItem: RosterItem) {
self.rosterItem = rosterItem
self.isGroup = false
super.init()
}
init(groupName: String) {
self.groupName = groupName
self.isGroup = true
super.init()
}
var name: String {
get {
if isGroup {
return groupName!;
} else {
return rosterItem!.name ? rosterItem!.name : rosterItem!.jid.description
}
}
}
var jid: String {
return isGroup ? "" : rosterItem!.jid.description
}
var children:NSArray? {
get {
return isGroup ? items : nil
}
set {
if isGroup {
items = newValue
}
}
}
var textColor:NSColor {
get{
if isGroup {
return NSColor.controlTextColor()
} else {
if presence? {
switch presence!.state {
case .Available:
return NSColor.controlTextColor();
case .Unavailable:
return NSColor.disabledControlTextColor()
case .WantsToChat:
return NSColor.controlTextColor();
case .DoNotDisturb:
return NSColor(calibratedRed: 0.240, green:0.393, blue:0.641, alpha:1.000)
case .Away:
return NSColor(calibratedRed:0.858, green:0.175, blue:0.159, alpha:1.000)
case .ExtendedAway:
return NSColor(calibratedRed:0.525, green:0.138, blue:0.153, alpha:1.000)
}
}
return NSColor.controlTextColor();
}
}
}
}
|
1e8644687ba60ddea7f40c7fc58ed092
| 21.943182 | 94 | 0.528975 | false | false | false | false |
odigeoteam/TableViewKit
|
refs/heads/develop
|
Examples/SampleApp/SampleApp/CustomItem.swift
|
mit
|
1
|
import Foundation
import UIKit
import TableViewKit
public class CustomDrawer: CellDrawer {
public static var type = CellType.class(UITableViewCell.self)
public static func draw(_ cell: UITableViewCell, with item: CustomItem) {
cell.accessoryType = item.accessoryType
cell.accessoryView = item.accessoryView
cell.textLabel?.text = item.title
}
}
public class CustomItem: Selectable, TableItem {
public static var drawer = AnyCellDrawer(CustomDrawer.self)
public var title: String?
public var onSelection: (Selectable) -> Void = { _ in }
public var cellStyle: UITableViewCell.CellStyle = .default
public var accessoryType: UITableViewCell.AccessoryType = .none
public var accessoryView: UIView?
public var cellHeight: CGFloat? = UITableView.automaticDimension
public init() { }
public convenience init(title: String) {
self.init()
self.title = title
}
public func didSelect() {
onSelection(self)
}
}
|
cb2956aad099223b442dbd511a133288
| 25.736842 | 77 | 0.698819 | false | false | false | false |
BenziAhamed/Nevergrid
|
refs/heads/master
|
NeverGrid/Source/PriorityQueue.swift
|
isc
|
1
|
//
// PriorityQueue.swift
// MrGreen
//
// Created by Benzi on 03/09/14.
// Copyright (c) 2014 Benzi Ahamed. All rights reserved.
//
import Foundation
struct PriorityQueueNode<T> {
var item:T
var priority:Int
}
class PriorityQueue<T> {
var q = [PriorityQueueNode<T>]()
var count:Int {
return q.count
}
func put(item:T, priority:Int) {
let node = PriorityQueueNode(item: item, priority: priority)
if q.count == 0 {
q.append(node)
} else {
var insertIndex = 0
while insertIndex < count && q[insertIndex].priority <= priority {
insertIndex++
}
if insertIndex < q.count {
q.insert(node, atIndex: insertIndex)
} else {
q.append(node)
}
}
}
func get() -> T? {
if q.count == 0 {
return nil
}
else {
return q.removeAtIndex(0).item
}
}
}
|
b0b59f4ca31c23b68eea4a689d3b1ede
| 19.66 | 78 | 0.487403 | false | false | false | false |
wwdc14/SkyNet
|
refs/heads/master
|
SkyNet/Classes/Settings/NetworkSettingTableViewController.swift
|
mit
|
1
|
//
// NetworkSettingTableViewController.swift
// Pods
//
// Created by FD on 21/08/2017.
//
//
import UIKit
struct NetworkSettingModel {
let title:String
let isOn: Bool
let type: HTTPModelShortType
}
struct NetworkSettingViewModel {
let model:[NetworkSettingModel]
let sectionTitle: String
}
class NetworkSettingTableViewController: UITableViewController {
var dataSource:[NetworkSettingViewModel]? = nil
override func viewDidLoad() {
super.viewDidLoad()
navigationItem.title = "networkSetting"
tableView.register(NetworkSettingTableViewCell.self, forCellReuseIdentifier: "cell")
let netViewModel = NetworkSettingViewModel(model: loadData(), sectionTitle: "NetworkFilterType")
dataSource = []
dataSource?.append(netViewModel)
tableView.reloadData()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
return dataSource?.count ?? 0
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
let viewModel = dataSource?[section]
return viewModel?.model.count ?? 0
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell: NetworkSettingTableViewCell = tableView.dequeueReusableCell(withIdentifier: "cell") as! NetworkSettingTableViewCell
func switchChange() {
NetworkSettings.saveFilterType(index: indexPath.row)
}
if let dataSource = dataSource {
let viewModel = dataSource[indexPath.section]
let model = viewModel.model[indexPath.row]
cell.switchControl.isOn = model.isOn
cell.textLabel?.text = model.type.rawValue
cell.handler = switchChange
}
return cell
}
override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
if let dataSource = dataSource {
return dataSource[section].sectionTitle
}else{
return ""
}
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
}
//MARK: - load method
func loadData() -> [NetworkSettingModel] {
let filter = NetworkSettings.getFilterTypes()
let xml = NetworkSettingModel(title: "xml", isOn: filter[HTTPModelShortType.allValues.index(of: .XML)!], type:.XML)
let json = NetworkSettingModel(title: "json", isOn: filter[HTTPModelShortType.allValues.index(of: .JSON)!], type: .JSON)
let html = NetworkSettingModel(title: "html", isOn: filter[HTTPModelShortType.allValues.index(of: .HTML)!], type: .HTML)
let image = NetworkSettingModel(title: "image", isOn: filter[HTTPModelShortType.allValues.index(of: .IMAGE)!], type: .IMAGE)
let other = NetworkSettingModel(title: "other", isOn: filter[HTTPModelShortType.allValues.index(of: .OTHER)!], type: .OTHER)
return [json,xml,html,image,other]
}
}
|
592c0f9fa3daf1716175590023dbc43c
| 35.119565 | 134 | 0.668974 | false | false | false | false |
pman215/ONH305
|
refs/heads/master
|
Sources/ONH305SvrLib/ServerUtil.swift
|
apache-2.0
|
1
|
import Foundation
import PerfectLib
import PerfectLogger
struct ServerUtil {
let name = "0.0.0.0"
let port: UInt16 = 8080
let root = "./v2"
let templates = "./v2/templates"
let dataPath = "./v2/data"
let httpLogFile = "./v2/log/ONH305SvrHTTP.log"
let logFile = "./v2/log/ONH305Svr.log"
let templateExtension = ".mustache"
let dataExtension = ".json"
func root(path: String) -> String {
guard let url = URL(string: path) else {
return ""
}
var pathComponents = url.pathComponents
if !pathComponents.isEmpty { pathComponents.removeFirst() }
pathComponents.popLast()
pathComponents.insert("", at: 0)
return pathComponents.joined(separator: "/")
}
func templatePath(path: String) -> String {
guard let url = URL(string: path) else {
return ""
}
let templateFolder = folder(url: url, name: "templates")
let templateName = url.lastPathComponent + templateExtension
return templateFolder + "/" + templateName
}
func data(path: String) -> [String : Any] {
guard let url = URL(string: path) else {
return [String : Any]()
}
let templateFolder = folder(url: url, name: "data")
let dataFilenames = filenames(in: templateFolder)
let dataFiles = dataFilenames.map {
File("\(templateFolder)/\($0)")
}
let dataContent: [String] = dataFiles.map {
do {
let content = try $0.readString()
return content
} catch {
LogFile.error("Unable to read content of file \($0.path)")
return ""
}
}
var values = [String : Any]()
dataContent.forEach {
do {
guard let decodedValues = try $0.jsonDecode() as? [String : Any] else {
return
}
decodedValues.forEach {
values[$0.key] = $0.value
}
} catch {
LogFile.error("Unable to decode file as JSON: \($0)")
return
}
}
return values
}
}
private extension ServerUtil {
func folder(url: URL, name: String) -> String {
var pathComponents = url.pathComponents
let lastPathComponent = url.lastPathComponent
if !pathComponents.isEmpty { pathComponents.removeFirst() }
pathComponents.popLast()
pathComponents.append(name)
pathComponents.append(lastPathComponent)
pathComponents.insert(".", at: 0)
return pathComponents.joined(separator: "/")
}
func filenames(in folder: String) -> [String] {
guard File(folder).isDir else {
LogFile.warning("Path \(folder) is not a folder")
return [String]()
}
let dir = Dir(folder)
var files = [String]()
do {
try dir.forEachEntry { (entry) in
files.append(entry)
}
} catch {
LogFile.error("Unable to retrieve folder \(folder) files")
}
LogFile.debug("Folder \(folder) contains files \(files)")
return files
}
func filenames(in folder: String, ext: String, prefix: String) -> [String] {
let allFiles = filenames(in: folder)
let allFilesPrefix = allFiles.filter {
$0.hasPrefix(prefix) && $0.hasSuffix(ext)
}
return allFilesPrefix
}
}
|
940a369f7bd1f5ac36e58cb1fc2c141d
| 24.271186 | 81 | 0.649229 | false | false | false | false |
mlpqaz/V2ex
|
refs/heads/master
|
ZZV2ex/ZZV2ex/Common/V2Response.swift
|
apache-2.0
|
1
|
//
// V2Response.swift
// ZZV2ex
//
// Created by ios on 2017/5/3.
// Copyright © 2017年 张璋. All rights reserved.
//
import UIKit
class V2Response: NSObject {
var success: Bool = false
var message: String = "No message"
init(success:Bool,message:String?) {
super.init()
self.success = success
if let message = message{
self.message = message
}
}
init(success:Bool) {
super.init()
self.success = success
}
}
class V2ValueResponse<T>: V2Response {
var value:T?
override init(success: Bool) {
super.init(success: success)
}
override init(success: Bool,message:String?) {
super.init(success: success)
if let message = message {
self.message = message
}
}
convenience init(value:T,success:Bool){
self.init(success: success)
self.value = value
}
convenience init(value:T,success:Bool,message:String?) {
self.init(value:value,success:success)
if let message = message{
self.message = message
}
}
}
|
a7aea57ac156a421233f1a0a6954e3b4
| 22.058824 | 64 | 0.552721 | false | false | false | false |
AlexeyGolovenkov/DevHelper
|
refs/heads/master
|
DevHelper/Ext/Extensions/DHTextRange.swift
|
mit
|
1
|
//
// DHTextRange.swift
// DevHelper
//
// Created by Alexey Golovenkov on 12.03.17.
// Copyright © 2017 Alexey Golovenkov. All rights reserved.
//
import Cocoa
struct DHTextPosition: Equatable {
var line = 0
var column = 0
public static func ==(lhs: DHTextPosition, rhs: DHTextPosition) -> Bool {
return lhs.column == rhs.column && lhs.line == rhs.line
}
}
class DHTextRange: NSObject {
var start = DHTextPosition(line: 0, column: 0)
var end = DHTextPosition(line: 0, column: 0)
convenience init(start: DHTextPosition, end: DHTextPosition) {
self.init()
self.start = start
self.end = end
}
func isCursorPosition() -> Bool {
return self.start == self.end
}
}
|
a8f52c02ac2b89ef1242e66c5352d295
| 20.969697 | 74 | 0.652414 | false | false | false | false |
con-beo-vang/Spendy
|
refs/heads/master
|
Spendy/Helpers/Helper.swift
|
mit
|
1
|
//
// Helper.swift
// Spendy
//
// Created by Dave Vo on 9/16/15.
// Copyright (c) 2015 Cheetah. All rights reserved.
//
import UIKit
var logoColor = UIColor.redColor()
class Helper: NSObject {
static let sharedInstance = Helper()
func customizeBarButton(viewController: UIViewController, button: UIButton, imageName: String, isLeft: Bool) {
let avatar = UIImageView(frame: CGRect(x: 0, y: 0, width: 22, height: 22))
avatar.image = UIImage(named: imageName)
button.setImage(avatar.image, forState: .Normal)
button.frame = CGRectMake(0, 0, 22, 22)
let item: UIBarButtonItem = UIBarButtonItem()
item.customView = button
if isLeft {
viewController.navigationItem.leftBarButtonItem = item
} else {
viewController.navigationItem.rightBarButtonItem = item
}
}
func getCellAtGesture(gestureRecognizer: UIGestureRecognizer, tableView: UITableView) -> UITableViewCell? {
let location = gestureRecognizer.locationInView(tableView)
let indexPath = tableView.indexPathForRowAtPoint(location)
if let indexPath = indexPath {
return tableView.cellForRowAtIndexPath(indexPath)!
} else {
return nil
}
}
func showActionSheet(viewController: UIViewController, imagePicker: UIImagePickerController) {
let optionMenu = UIAlertController(title: nil, message: nil, preferredStyle: .ActionSheet)
let takePhotoAction = UIAlertAction(title: "Take a Photo", style: .Default, handler: {
(alert: UIAlertAction!) -> Void in
print("Take a Photo", terminator: "\n")
imagePicker.allowsEditing = false
imagePicker.sourceType = UIImagePickerControllerSourceType.Camera
imagePicker.cameraCaptureMode = UIImagePickerControllerCameraCaptureMode.Photo
imagePicker.modalPresentationStyle = .FullScreen
viewController.presentViewController(imagePicker, animated: true, completion: nil)
})
let photoLibraryAction = UIAlertAction(title: "Photo from Library", style: .Default, handler: {
(alert: UIAlertAction!) -> Void in
print("Photo from Library", terminator: "\n")
imagePicker.allowsEditing = true
imagePicker.sourceType = .PhotoLibrary
viewController.presentViewController(imagePicker, animated: true, completion: nil)
})
let cancelAction = UIAlertAction(title: "Cancel", style: .Cancel, handler: {
(alert: UIAlertAction!) -> Void in
print("Cancelled", terminator: "\n")
})
optionMenu.addAction(takePhotoAction)
optionMenu.addAction(photoLibraryAction)
optionMenu.addAction(cancelAction)
viewController.presentViewController(optionMenu, animated: true, completion: nil)
}
func setPopupShadowAndColor(popupView: UIView, label: UILabel) {
// Set shadow
popupView.layer.shadowPath = UIBezierPath(roundedRect: popupView.layer.bounds, cornerRadius: 5).CGPath
popupView.layer.shadowColor = Color.strongColor.CGColor
popupView.layer.shadowOffset = CGSizeMake(5, 5)
popupView.layer.shadowRadius = 5
popupView.layer.shadowOpacity = 0.5
// Set header color
label.backgroundColor = Color.popupHeaderColor
label.textColor = UIColor.whiteColor()
}
// MARK: Category
func createIcon(imageName: String) -> UIImage {
let markerView = UIView(frame:CGRectMake(0, 0, 50, 50))
//Add icon
let icon = UIImageView(frame: CGRectMake(7, 7, 36, 36))
icon.image = UIImage(named: imageName)
markerView.addSubview(icon)
return imageFromView(markerView)
}
func imageFromView(aView:UIView) -> UIImage {
if(UIScreen.mainScreen().respondsToSelector("scale")) {
UIGraphicsBeginImageContextWithOptions(aView.frame.size, false, UIScreen.mainScreen().scale)
}
else {
UIGraphicsBeginImageContext(aView.frame.size)
}
aView.layer.renderInContext(UIGraphicsGetCurrentContext()!)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image
}
func setIconLayer(iconView: UIImageView) {
iconView.layer.cornerRadius = iconView.frame.height / 2
iconView.layer.masksToBounds = true
// TODO: remove this line after category has type
iconView.layer.backgroundColor = Color.strongColor.CGColor
}
}
enum ViewMode: Int {
case Weekly = 0,
Monthly,
Yearly,
Custom
}
|
ba3009209f6887d4c2e8688ddaf84186
| 32.189394 | 112 | 0.709427 | false | false | false | false |
Pyroh/Fluor
|
refs/heads/main
|
Fluor/Views/PoppingLinkButton.swift
|
mit
|
1
|
//
// PoppingLinkButton.swift
//
// Fluor
//
// MIT License
//
// Copyright (c) 2020 Pierre Tacchi
//
// 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 Cocoa
@IBDesignable
class PoppingLinkButton: NSButton {
@IBInspectable var growsOnHover: Bool = true
@IBInspectable var growFactor: CGFloat = 1.15
override func layout() {
super.layout()
self.centerLayerAnchor()
}
override func updateTrackingAreas() {
super.updateTrackingAreas()
self.trackingAreas.forEach(self.removeTrackingArea(_:))
let trackingArea = NSTrackingArea(rect: self.bounds, options: [.activeAlways, .mouseEnteredAndExited], owner: self, userInfo: nil)
self.addTrackingArea(trackingArea)
}
override func resetCursorRects() {
super.resetCursorRects()
self.addCursorRect(self.bounds, cursor: .pointingHand)
}
// Thanks to Kite Compositor (kiteapp.co)
override func mouseEntered(with event: NSEvent) {
guard self.growsOnHover, let layer = self.layer else { return }
let transformScaleAnimation = CASpringAnimation()
transformScaleAnimation.fillMode = CAMediaTimingFillMode.forwards
transformScaleAnimation.duration = 0.99321
transformScaleAnimation.isRemovedOnCompletion = false
transformScaleAnimation.keyPath = "transform.scale"
transformScaleAnimation.toValue = self.growFactor
transformScaleAnimation.stiffness = 200
transformScaleAnimation.damping = 10
transformScaleAnimation.mass = 0.7
transformScaleAnimation.initialVelocity = 4
layer.add(transformScaleAnimation, forKey: "growAnimation")
}
// Thanks to Kite Compositor (kiteapp.co)
override func mouseExited(with event: NSEvent) {
guard self.growsOnHover, let layer = self.layer else { return }
let transformScaleAnimation1 = CASpringAnimation()
transformScaleAnimation1.duration = 0.99321
transformScaleAnimation1.fillMode = CAMediaTimingFillMode.forwards
transformScaleAnimation1.isRemovedOnCompletion = false
transformScaleAnimation1.keyPath = "transform.scale"
transformScaleAnimation1.toValue = 1
transformScaleAnimation1.stiffness = 200
transformScaleAnimation1.damping = 10
transformScaleAnimation1.mass = 0.7
transformScaleAnimation1.initialVelocity = 4
layer.add(transformScaleAnimation1, forKey: "shrinkAnimation")
}
}
|
b86a93093ebcf977f1cd6600c0d331b4
| 38.217391 | 138 | 0.707871 | false | false | false | false |
hilen/TSWeChat
|
refs/heads/master
|
TSWeChat/Classes/CoreModule/Http/TSResponseSerializer.swift
|
mit
|
1
|
//
// TSResponseSerializer.swift
// TSWeChat
//
// Created by Hilen on 3/2/16.
// Copyright © 2016 Hilen. All rights reserved.
//
import Alamofire
import SwiftyJSON
private let kKeyMessage = "message"
private let kKeyData = "data"
private let kKeyCode = "code"
// MARK: - SwiftyJSON 和 Alamofire 的自定义解析器
//文件上传的解析,图片和音频
extension Alamofire.DataRequest {
@discardableResult
// static func responseFileUploadSwiftyJSON(completionHandler: (Alamofire.Result) -> Void) -> Self {
// return response(responseSerializer: DataRequest.fileUploadSwiftyJSONResponseSerializer(), completionHandler)
//// return response(responseSerializer: <#T##T#>, completionHandler: <#T##(DataResponse<T.SerializedObject>) -> Void#>)
// }
static func fileUploadSwiftyJSONResponseSerializer() -> DataResponseSerializer<Any> {
return DataResponseSerializer { request, response, data, error in
guard error == nil else {
log.error("error:\(String(describing: error))")
let failureReason = "网络不给力,请稍候再试 :)"
let userInfo = [NSLocalizedFailureReasonErrorKey: failureReason]
let error = NSError(domain: "", code: 1002, userInfo: userInfo)
return .failure(error)
}
guard let validData = data, validData.count > 0 else {
let failureReason = "数据错误,请稍候再试 :)"
let userInfo = [NSLocalizedFailureReasonErrorKey: failureReason]
let error = NSError(domain: "", code: 1003, userInfo: userInfo)
return .failure(error)
}
//JSON 解析错误
if let json = try? JSON(data: validData) {
if let jsonError = json.error {
return Result.failure(jsonError)
}
//服务器返回 code 错误处理, 假设是 1993
let code = json[kKeyCode].intValue
if code == 1993 {
let userInfo = [NSLocalizedFailureReasonErrorKey: json["message"].stringValue]
let error = NSError(domain: "", code: 1004, userInfo: userInfo)
return Result.failure(error)
}
return Result.success(json)
} else {
let userInfo = [NSLocalizedFailureReasonErrorKey: "JSON parse error"]
let error = NSError(domain: "", code: 1005, userInfo: userInfo)
return Result.failure(error)
}
}
}
}
|
f72609ab213d657e40af65ccfcc285cb
| 39.046875 | 127 | 0.577448 | false | false | false | false |
azu/command-line-tool-by-swift
|
refs/heads/master
|
git-current-branch.swift
|
mit
|
1
|
#!/usr/bin/env xcrun swift -i -sdk /Applications/Xcode6-Beta.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.10.sdk
// -sdk $(xcrun --show-sdk-path --sdk macosx)
import Cocoa
var task = NSTask();
task.launchPath = "/bin/sh"
task.arguments = ["-c", "git symbolic-ref --short HEAD"]
let stdout = NSPipe()
task.standardOutput = stdout;
task.launch()
task.waitUntilExit()
var fileHandle = stdout.fileHandleForReading
var result = NSString(
data: fileHandle.readDataToEndOfFile(),
encoding:NSUTF8StringEncoding
)
print(result)
|
f26f951e2ecc75150da65f8f238ea3ff
| 26.95 | 140 | 0.744186 | false | false | false | false |
googlemaps/maps-sdk-for-ios-samples
|
refs/heads/main
|
GoogleMaps-Swift/GoogleMapsSwiftDemos/Swift/Samples/TrafficMapViewController.swift
|
apache-2.0
|
1
|
// Copyright 2020 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 GoogleMaps
import UIKit
class TrafficMapViewController: UIViewController {
private var mapView: GMSMapView = {
let camera = GMSCameraPosition(latitude: -33.868, longitude: 151.2086, zoom: 12)
let mapView = GMSMapView(frame: .zero, camera: camera)
mapView.isTrafficEnabled = true
return mapView
}()
override func loadView() {
view = mapView
}
}
|
6bf76887e24814587d27c17945c9e53d
| 32 | 91 | 0.734343 | false | false | false | false |
exponent/exponent
|
refs/heads/master
|
packages/expo-dev-menu/ios/DevMenuUtils.swift
|
bsd-3-clause
|
2
|
// Copyright 2015-present 650 Industries. All rights reserved.
import Foundation
class DevMenuUtils {
/**
Swizzles implementations of given selectors.
*/
static func swizzle(selector selectorA: Selector, withSelector selectorB: Selector, forClass: AnyClass) {
if let methodA = class_getInstanceMethod(forClass, selectorA),
let methodB = class_getInstanceMethod(forClass, selectorB) {
let impA = method_getImplementation(methodA)
let argsTypeA = method_getTypeEncoding(methodA)
let impB = method_getImplementation(methodB)
let argsTypeB = method_getTypeEncoding(methodB)
if class_addMethod(forClass, selectorA, impB, argsTypeB) {
class_replaceMethod(forClass, selectorB, impA, argsTypeA)
} else {
method_exchangeImplementations(methodA, methodB)
}
}
}
/**
Strips `RCT` prefix from given string.
*/
static func stripRCT(_ str: String) -> String {
return str.starts(with: "RCT") ? String(str.dropFirst(3)) : str
}
static func resourcesBundle() -> Bundle? {
let frameworkBundle = Bundle(for: DevMenuUtils.self)
guard let resourcesBundleUrl = frameworkBundle.url(forResource: "EXDevMenu", withExtension: "bundle") else {
return nil
}
return Bundle(url: resourcesBundleUrl)
}
}
|
2b4b63087f08ddc8fdab8260f65deea2
| 30.829268 | 112 | 0.700383 | false | false | false | false |
apple/swift-numerics
|
refs/heads/main
|
Sources/RealModule/ElementaryFunctions.swift
|
apache-2.0
|
1
|
//===--- ElementaryFunctions.swift ----------------------------*- swift -*-===//
//
// This source file is part of the Swift Numerics open source project
//
// Copyright (c) 2019 Apple Inc. and the Swift Numerics project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
//
//===----------------------------------------------------------------------===//
/// A type that has elementary functions available.
///
/// An ["elementary function"][elfn] is a function built up from powers, roots,
/// exponentials, logarithms, trigonometric functions (sin, cos, tan) and
/// their inverses, and the hyperbolic functions (sinh, cosh, tanh) and their
/// inverses.
///
/// Conformance to this protocol means that all of these building blocks are
/// available as static functions on the type.
///
/// ```swift
/// let x: Float = 1
/// let y = Float.sin(x) // 0.84147096
/// ```
///
/// There are three broad families of functions defined by
/// `ElementaryFunctions`:
/// - Exponential, trigonometric, and hyperbolic functions:
/// `exp`, `expMinusOne`, `cos`, `sin`, `tan`, `cosh`, `sinh`, and `tanh`.
/// - Logarithmic, inverse trigonometric, and inverse hyperbolic functions:
/// `log`, `log(onePlus:)`, `acos`, `asin`, `atan`, `acosh`, `asinh`, and
/// `atanh`.
/// - Power and root functions:
/// `pow`, `sqrt`, and `root`.
///
/// `ElementaryFunctions` conformance implies `AdditiveArithmetic`, so addition
/// and subtraction and the `.zero` property are also available.
///
/// There are two other protocols that you are more likely to want to use
/// directly:
///
/// `RealFunctions` refines `ElementaryFunctions` and includes
/// additional functions specific to real number types.
///
/// `Real` conforms to `RealFunctions` and `FloatingPoint`, and is the
/// protocol that you will want to use most often for generic code.
///
/// See Also:
///
/// - `RealFunctions`
/// - `Real`
///
/// [elfn]: http://en.wikipedia.org/wiki/Elementary_function
public protocol ElementaryFunctions: AdditiveArithmetic {
/// The [exponential function][wiki] e^x whose base `e` is the base of the
/// natural logarithm.
///
/// See also `expMinusOne()`, as well as `exp2()` and `exp10()`
/// defined for types conforming to `RealFunctions`.
///
/// [wiki]: https://en.wikipedia.org/wiki/Exponential_function
static func exp(_ x: Self) -> Self
/// exp(x) - 1, computed in such a way as to maintain accuracy for small x.
///
/// When `x` is close to zero, the expression `.exp(x) - 1` suffers from
/// catastrophic cancellation and the result will not have full accuracy.
/// The `.expMinusOne(x)` function gives you a means to address this problem.
///
/// As an example, consider the expression `(x + 1)*exp(x) - 1`. When `x`
/// is smaller than `.ulpOfOne`, this expression evaluates to `0.0`, when it
/// should actually round to `2*x`. We can get a full-accuracy result by
/// using the following instead:
/// ```
/// let t = .expMinusOne(x)
/// return x*(t+1) + t // x*exp(x) + (exp(x)-1) = (x+1)*exp(x) - 1
/// ```
/// This re-written expression delivers an accurate result for all values
/// of `x`, not just for small values.
///
/// See also `exp()`, as well as `exp2()` and `exp10()` defined for types
/// conforming to `RealFunctions`.
static func expMinusOne(_ x: Self) -> Self
/// The [hyperbolic cosine][wiki] of `x`.
/// ```
/// e^x + e^-x
/// cosh(x) = ------------
/// 2
/// ```
///
/// See also `sinh()`, `tanh()` and `acosh()`.
///
/// [wiki]: https://en.wikipedia.org/wiki/Hyperbolic_function
static func cosh(_ x: Self) -> Self
/// The [hyperbolic sine][wiki] of `x`.
/// ```
/// e^x - e^-x
/// sinh(x) = ------------
/// 2
/// ```
///
/// See also `cosh()`, `tanh()` and `asinh()`.
///
/// [wiki]: https://en.wikipedia.org/wiki/Hyperbolic_function
static func sinh(_ x: Self) -> Self
/// The [hyperbolic tangent][wiki] of `x`.
/// ```
/// sinh(x)
/// tanh(x) = ---------
/// cosh(x)
/// ```
///
/// See also `cosh()`, `sinh()` and `atanh()`.
///
/// [wiki]: https://en.wikipedia.org/wiki/Hyperbolic_function
static func tanh(_ x: Self) -> Self
/// The [cosine][wiki] of `x`.
///
/// For real types, `x` may be interpreted as an angle measured in radians.
///
/// See also `sin()`, `tan()` and `acos()`.
///
/// [wiki]: https://en.wikipedia.org/wiki/Cosine
static func cos(_ x: Self) -> Self
/// The [sine][wiki] of `x`.
///
/// For real types, `x` may be interpreted as an angle measured in radians.
///
/// See also `cos()`, `tan()` and `asin()`.
///
/// [wiki]: https://en.wikipedia.org/wiki/Sine
static func sin(_ x: Self) -> Self
/// The [tangent][wiki] of `x`.
///
/// For real types, `x` may be interpreted as an angle measured in radians.
///
/// See also `cos()`, `sin()` and `atan()`, as well as `atan2(y:x:)` for
/// types that conform to `RealFunctions`.
///
/// [wiki]: https://en.wikipedia.org/wiki/Tangent
static func tan(_ x: Self) -> Self
/// The [natural logarithm][wiki] of `x`.
///
/// See also `log(onePlus:)`, as well as `log2()` and `log10()` for types
/// that conform to `RealFunctions`.
///
/// [wiki]: https://en.wikipedia.org/wiki/Logarithm
static func log(_ x: Self) -> Self
/// log(1 + x), computed in such a way as to maintain accuracy for small x.
///
/// See also `log()`, as well as `log2()` and `log10()` for types
/// that conform to `RealFunctions`.
static func log(onePlus x: Self) -> Self
/// The [inverse hyperbolic cosine][wiki] of `x`.
/// ```
/// cosh(acosh(x)) ≅ x
/// ```
/// See also `asinh()`, `atanh()` and `cosh()`.
///
/// [wiki]: https://en.wikipedia.org/wiki/Inverse_hyperbolic_function
static func acosh(_ x: Self) -> Self
/// The [inverse hyperbolic sine][wiki] of `x`.
/// ```
/// sinh(asinh(x)) ≅ x
/// ```
/// See also `acosh()`, `atanh()` and `sinh()`.
///
/// [wiki]: https://en.wikipedia.org/wiki/Inverse_hyperbolic_function
static func asinh(_ x: Self) -> Self
/// The [inverse hyperbolic tangent][wiki] of `x`.
/// ```
/// tanh(atanh(x)) ≅ x
/// ```
/// See also `acosh()`, `asinh()` and `tanh()`.
///
/// [wiki]: https://en.wikipedia.org/wiki/Inverse_hyperbolic_function
static func atanh(_ x: Self) -> Self
/// The [arccosine][wiki] (inverse cosine) of `x`.
///
/// For real types, the result may be interpreted as an angle measured in
/// radians.
/// ```
/// cos(acos(x)) ≅ x
/// ```
/// See also `asin()`, `atan()` and `cos()`.
///
/// [wiki]: https://en.wikipedia.org/wiki/Inverse_trigonometric_functions
static func acos(_ x: Self) -> Self
/// The [arcsine][wiki] (inverse sine) of `x`.
///
/// For real types, the result may be interpreted as an angle measured in
/// radians.
/// ```
/// sin(asin(x)) ≅ x
/// ```
/// See also `acos()`, `atan()` and `sin()`.
///
/// [wiki]: https://en.wikipedia.org/wiki/Inverse_trigonometric_functions
static func asin(_ x: Self) -> Self
/// The [arctangent][wiki] (inverse tangent) of `x`.
///
/// For real types, the result may be interpreted as an angle measured in
/// radians.
/// ```
/// tan(atan(x)) ≅ x
/// ```
/// See also `acos()`, `asin()` and `tan()`, as well as `atan2(y:x:)` for
/// types that conform to `RealArithmetic`.
///
/// [wiki]: https://en.wikipedia.org/wiki/Inverse_trigonometric_functions
static func atan(_ x: Self) -> Self
/// exp(y * log(x)) computed with additional internal precision.
///
/// The edge-cases of this function are defined based on the behavior of the
/// expression `exp(y log x)`, matching IEEE 754's `powr` operation.
/// In particular, this means that if `x` and `y` are both zero, `pow(x,y)`
/// is `nan` for real types and `infinity` for complex types, rather than 1.
///
/// There is also a `pow(_:Self,_:Int)` overload, whose behavior is defined
/// in terms of repeated multiplication, and hence returns 1 for this case.
///
/// See also `sqrt()` and `root()`.
static func pow(_ x: Self, _ y: Self) -> Self
/// `x` raised to the nth power.
///
/// The edge-cases of this function are defined in terms of repeated
/// multiplication or division, rather than exp(n log x). In particular,
/// `Float.pow(0, 0)` is 1.
///
/// See also `sqrt()` and `root()`.
static func pow(_ x: Self, _ n: Int) -> Self
/// The [square root][wiki] of `x`.
///
/// See also `pow()` and `root()`.
///
/// [wiki]: https://en.wikipedia.org/wiki/Square_root
static func sqrt(_ x: Self) -> Self
/// The nth root of `x`.
///
/// See also `pow()` and `sqrt()`.
static func root(_ x: Self, _ n: Int) -> Self
}
|
58ded39cfc10410b4db049916579575f
| 33.198473 | 80 | 0.581585 | false | false | false | false |
ledwards/ios-yelp
|
refs/heads/master
|
Yelp/BusinessCell.swift
|
mit
|
1
|
//
// BusinessCell.swift
// Yelp
//
// Created by Lee Edwards on 2/6/16.
// Copyright © 2016 Timothy Lee. All rights reserved.
//
import UIKit
class BusinessCell: UITableViewCell {
@IBOutlet weak var thumbImageView: UIImageView!
@IBOutlet weak var ratingLabel: UIImageView!
@IBOutlet weak var reviewsCountLabel: UILabel!
@IBOutlet weak var addressLabel: UILabel!
@IBOutlet weak var nameLabel: UILabel!
@IBOutlet weak var categoriesLabel: UILabel!
@IBOutlet weak var distanceLabel: UILabel!
var business: Business! {
didSet {
nameLabel.text = business.name
thumbImageView.setImageWithURL(business.imageURL!)
ratingLabel.setImageWithURL(business.ratingImageURL!)
reviewsCountLabel.text = "\(business.reviewCount!) Reviews"
addressLabel.text = business.address
categoriesLabel.text = business.categories
distanceLabel.text = business.distance
}
}
override func awakeFromNib() {
super.awakeFromNib()
thumbImageView.layer.cornerRadius = 5
thumbImageView.clipsToBounds = true
nameLabel.preferredMaxLayoutWidth = nameLabel.frame.size.width
}
override func layoutSubviews() {
super.layoutSubviews()
nameLabel.preferredMaxLayoutWidth = nameLabel.frame.size.width
}
}
|
a6c73aaffdcc68296ac7a8e420d0e2dc
| 28.93617 | 71 | 0.662402 | false | false | false | false |
teaxus/TSAppEninge
|
refs/heads/master
|
Source/Basic/Controller/TSImagePicker/TSGeneralHook.swift
|
mit
|
1
|
//
// TSGeneralHook.swift
// StandardProject
//
// Created by teaxus on 15/12/31.
// Copyright © 2015年 teaxus. All rights reserved.
//
import UIKit
public class TSGeneralHook: UIView {
public override init(frame: CGRect) {
super.init(frame: frame)
}
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
public override func draw(_ rect: CGRect) {
self.backgroundColor = UIColor.clear
self.layer.cornerRadius = self.frame.size.width / 2.0
self.layer.masksToBounds = true
let width = self.frame.size.width
let height = self.frame.size.height
//// Color Declarations
let color2 = UIColor(red: 1.000, green: 1.000, blue: 1.000, alpha: 1.000)
let color4 = UIColor(red: 0.000, green: 0.478, blue: 1.000, alpha: 1.000)
//// C_2 Drawing
let c_2Path = UIBezierPath(ovalIn: CGRect(x: 0, y: 0, width: width, height: height))
color2.setFill()
c_2Path.fill()
//// C_1 Drawing
let c_1Path = UIBezierPath(ovalIn: CGRect(x: 3.0/31.0*width, y: 3.0/31.0*height, width: 25.0/31.0*width, height: 25.0/31.0*height))
color4.setFill()
c_1Path.fill()
//// Bezier Drawing
let bezierPath = UIBezierPath()
UIColor.blue.setFill()
bezierPath.fill()
//// Hold Drawing
let holdPath = UIBezierPath()
holdPath.move(to: CGPoint(x:8.5/31.0*width,y:15.77/31.0*height))
holdPath.addLine(to: CGPoint(x:13.79/31.0*width,y:21.5/31.0*height))
holdPath.addLine(to: CGPoint(x:23.5/31.0*width,y:12.5/31.0*height))
holdPath.lineCapStyle = .round
UIColor.white.setStroke()
holdPath.lineWidth = 3
holdPath.stroke()
}
}
|
325b78a36e148d213b05ce777cc42bb8
| 30.084746 | 139 | 0.589422 | false | false | false | false |
RemyDCF/tpg-offline
|
refs/heads/master
|
tpg offline/Departures/Callout.swift
|
mit
|
1
|
import Mapbox
class CustomCalloutView: UIView, MGLCalloutView {
var representedObject: MGLAnnotation
// Allow the callout to remain open during panning.
let dismissesAutomatically: Bool = false
let isAnchoredToAnnotation: Bool = true
// https://github.com/mapbox/mapbox-gl-native/issues/9228
override var center: CGPoint {
set {
var newCenter = newValue
newCenter.y -= bounds.midY
super.center = newCenter
}
get {
return super.center
}
}
lazy var leftAccessoryView = UIView() /* unused */
lazy var rightAccessoryView = UIView() /* unused */
weak var delegate: MGLCalloutViewDelegate?
let tipHeight: CGFloat = 10.0
let tipWidth: CGFloat = 20.0
let mainBody: UIStackView
let titleLabel: UILabel
let subTitleLabel: UILabel
private lazy var backgroundView: UIView = {
let view = UIView()
view.backgroundColor = App.cellBackgroundColor
view.layer.cornerRadius = 4.0
return view
}()
required init(representedObject: MGLAnnotation) {
self.representedObject = representedObject
self.titleLabel = UILabel(frame: CGRect(x: 0, y: 0, width: 50, height: 8))
self.titleLabel.text = representedObject.title ?? ""
self.titleLabel.numberOfLines = 0
self.titleLabel.textColor = App.textColor
self.subTitleLabel = UILabel(frame: CGRect(x: 0, y: 0, width: 50, height: 8))
self.subTitleLabel.text = representedObject.subtitle ?? ""
self.subTitleLabel.font = UIFont.systemFont(ofSize: UIFont.smallSystemFontSize)
self.subTitleLabel.numberOfLines = 0
self.subTitleLabel.textColor = App.textColor
self.mainBody = UIStackView()
self.mainBody.alignment = .fill
self.mainBody.distribution = .fill
self.mainBody.axis = .vertical
self.mainBody.translatesAutoresizingMaskIntoConstraints = false
self.mainBody.widthAnchor.constraint(equalToConstant: 150).isActive = true
self.mainBody.addArrangedSubview(self.titleLabel)
self.mainBody.addArrangedSubview(self.subTitleLabel)
self.mainBody.layoutMargins = UIEdgeInsets(top: 8, left: 8, bottom: 8, right: 8)
self.mainBody.isLayoutMarginsRelativeArrangement = true
super.init(frame: .zero)
backgroundColor = .clear
mainBody.backgroundColor = .darkGray
mainBody.tintColor = .white
mainBody.layer.cornerRadius = 4.0
pinBackground(backgroundView, to: mainBody)
addSubview(mainBody)
}
required init?(coder decoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
private func pinBackground(_ view: UIView, to stackView: UIStackView) {
view.translatesAutoresizingMaskIntoConstraints = false
stackView.insertSubview(view, at: 0)
view.pin(to: stackView)
}
// MARK: - MGLCalloutView API
func presentCallout(from rect: CGRect,
in view: UIView,
constrainedTo constrainedRect: CGRect,
animated: Bool) {
view.addSubview(self)
// Prepare title label.
//mainBody.setTitle(representedObject.title!, for: .normal)
// Prepare our frame, adding extra space at the bottom for the tip.
let size = mainBody.systemLayoutSizeFitting(UIView.layoutFittingCompressedSize)
let frameWidth: CGFloat = size.width
let frameHeight: CGFloat = size.height + tipHeight
let frameOriginX = rect.origin.x + (rect.size.width/2.0) - (frameWidth/2.0)
let frameOriginY = rect.origin.y - frameHeight
frame = CGRect(x: frameOriginX,
y: frameOriginY,
width: frameWidth,
height: frameHeight)
mainBody.backgroundColor = .white
if animated {
alpha = 0
UIView.animate(withDuration: 0.2) { [weak self] in
self?.alpha = 1
}
}
}
func dismissCallout(animated: Bool) {
if superview != nil {
if animated {
UIView.animate(withDuration: 0.2, animations: { [weak self] in
self?.alpha = 0
}, completion: { [weak self] _ in
self?.removeFromSuperview()
})
} else {
removeFromSuperview()
}
}
}
// MARK: - Callout interaction handlers
func isCalloutTappable() -> Bool {
if let delegate = delegate {
if delegate.responds(to:
#selector(MGLCalloutViewDelegate.calloutViewShouldHighlight)) {
return delegate.calloutViewShouldHighlight!(self)
}
}
return false
}
@objc func calloutTapped() {
if isCalloutTappable(),
delegate!.responds(to: #selector(MGLCalloutViewDelegate.calloutViewTapped)) {
delegate!.calloutViewTapped!(self)
}
}
// MARK: - Custom view styling
override func draw(_ rect: CGRect) {
// Draw the pointed tip at the bottom.
let fillColor: UIColor = App.cellBackgroundColor
let tipLeft = rect.origin.x + (rect.size.width / 2.0) - (tipWidth / 2.0)
let tipBottom = CGPoint(x: rect.origin.x + (rect.size.width / 2.0),
y: rect.origin.y + rect.size.height)
let heightWithoutTip = rect.size.height - tipHeight - 1
let currentContext = UIGraphicsGetCurrentContext()!
let tipPath = CGMutablePath()
tipPath.move(to: CGPoint(x: tipLeft, y: heightWithoutTip))
tipPath.addLine(to: CGPoint(x: tipBottom.x, y: tipBottom.y))
tipPath.addLine(to: CGPoint(x: tipLeft + tipWidth, y: heightWithoutTip))
tipPath.closeSubpath()
fillColor.setFill()
currentContext.addPath(tipPath)
currentContext.fillPath()
}
}
public extension UIView {
func pin(to view: UIView) {
NSLayoutConstraint.activate([
leadingAnchor.constraint(equalTo: view.leadingAnchor),
trailingAnchor.constraint(equalTo: view.trailingAnchor),
topAnchor.constraint(equalTo: view.topAnchor),
bottomAnchor.constraint(equalTo: view.bottomAnchor)
])
}
}
|
494e95c1ac575ccf5c257e583e6ee65c
| 30.61413 | 84 | 0.678013 | false | false | false | false |
aredotna/case
|
refs/heads/master
|
ios/Add to Are.na/ShareViewController.swift
|
mit
|
1
|
//
// ShareViewController.swift
// Add to Are.na
//
// Created by Charles Broskoski on 1/30/18.
// Copyright © 2018 When It Changed, Inc. All rights reserved.
//
import UIKit
import Social
import MobileCoreServices
import Apollo
import AWSCore
import AWSS3
extension NSItemProvider {
var isURL: Bool {
return hasItemConformingToTypeIdentifier(kUTTypeURL as String)
}
var isText: Bool {
return hasItemConformingToTypeIdentifier(kUTTypeText as String)
}
var isImage: Bool {
return hasItemConformingToTypeIdentifier(kUTTypeImage as String)
}
}
func getDocumentsDirectory() -> URL {
let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
return paths[0]
}
class ShareViewController: SLComposeServiceViewController {
// For fetching data via Apollo
private var apollo: ApolloClient?
private var authToken = String()
private var appToken = String()
// Label for placeholder when text field is empty
var placeholderLabel : UILabel!
// Arrays that hold fetched channels
private var recentConnections = [Channel]()
private var userChannels = [Channel]()
// Values to hold the block that will be created
private var selectedChannel: Channel!
private var urlString: String?
private var textString: String?
private var sourceURL: String?
private var imageString: String?
private var customTitle = String()
// Values for uploading images to S3
private var groupID = String()
private var AWSBucket = String()
private var AWSPoolId = String()
private var AWSTransferKey = String()
override func viewDidLoad() {
super.viewDidLoad()
setConfig()
setupUI()
getShareContext()
if #available(iOS 13.0, *) {
// Always adopt a light interface style.
overrideUserInterfaceStyle = .light
}
}
override func presentationAnimationDidFinish() {
getDefaults()
setupApollo()
fetchRecentConnections()
}
override func isContentValid() -> Bool {
if ((selectedChannel != nil) && (selectedChannel.id != nil)) {
return true
}
return false
}
override func didSelectPost() {
var mutation = CreateBlockMutationMutation(channel_ids: [GraphQLID(describing: selectedChannel.id!)], title: self.customTitle, description: self.contentText, source_url: urlString)
// Content is text
if ((urlString) == nil && (self.contentText) != nil && (self.imageString) == nil) {
mutation = CreateBlockMutationMutation(channel_ids: [GraphQLID(describing: selectedChannel.id!)], title: self.customTitle, content: self.contentText, description: "")
}
// If content is not an image
if ((self.imageString) == nil) {
apollo?.perform(mutation: mutation) { (result, error) in
self.extensionContext!.completeRequest(returningItems: [], completionHandler: nil)
}
// If content is an image, then upload the image and create a block
} else {
let bucket = self.AWSBucket
let url = URL(string: self.imageString!)!
let data = try? Data(contentsOf: url)
let uuid = NSUUID().uuidString.lowercased()
let key = "\(uuid)/\(url.lastPathComponent)"
let credentialProvider = AWSCognitoCredentialsProvider(regionType: .USEast1, identityPoolId: self.AWSPoolId)
let configuration = AWSServiceConfiguration(region: .USEast1, credentialsProvider: credentialProvider)
configuration?.sharedContainerIdentifier = self.groupID
AWSServiceManager.default().defaultServiceConfiguration = configuration
AWSS3TransferUtility.register(with: configuration!, forKey: self.AWSTransferKey)
let transferUtility = AWSS3TransferUtility.s3TransferUtility(forKey: self.AWSTransferKey)
let expression = AWSS3TransferUtilityUploadExpression()
expression.setValue("public-read", forRequestHeader: "x-amz-acl")
var completionHandler: AWSS3TransferUtilityUploadCompletionHandlerBlock?
completionHandler = { (task, error) -> Void in
DispatchQueue.main.async(execute: {
let url = URL(string: "https://s3.amazonaws.com/")?.appendingPathComponent(bucket)
let publicURL = url?.appendingPathComponent(key).absoluteString
// Create image in Are.na
mutation.source_url = publicURL
self.apollo?.perform(mutation: mutation) { (result, error) in }
// Remove reference to transferUtility
AWSS3TransferUtility.remove(forKey: self.AWSTransferKey)
self.extensionContext!.completeRequest(returningItems: [], completionHandler: nil)
})
}
transferUtility.uploadData(
data!,
bucket: bucket,
key: key,
contentType: "image/png",
expression: expression,
completionHandler: completionHandler).continueWith { (task) -> AnyObject! in
if let error = task.error {
print("Error: \(error.localizedDescription)")
self.showAlert(message: "Error uploading file \(error.localizedDescription)", title: "Error")
self.extensionContext!.completeRequest(returningItems: [], completionHandler: nil)
}
return nil;
}
}
}
override func configurationItems() -> [Any]! {
if let channel = SLComposeSheetConfigurationItem() {
channel.title = "Channel"
channel.value = selectedChannel?.title
channel.valuePending = selectedChannel?.title == nil
channel.tapHandler = {
let vc = ShareSelectViewController()
vc.recentConnections = self.recentConnections
vc.userChannels = self.userChannels
vc.delegate = self
self.pushConfigurationViewController(vc)
}
let customTitle = SLComposeSheetConfigurationItem()
customTitle?.title = "Title"
customTitle?.value = self.customTitle
customTitle?.tapHandler = {
let vc = ShareTitleViewController()
vc.currentValue = self.customTitle
vc.delegate = self
self.pushConfigurationViewController(vc)
}
return [customTitle, channel]
}
return nil
}
// Handle empty textView by showing the placeholder
override func textViewDidChange(_ textView: UITextView) {
super.textViewDidChange(textView)
placeholderLabel.isHidden = !textView.text.isEmpty
}
// Set values needed for S3 transfer
private func setConfig() -> Any {
guard let path = Bundle.main.path(forResource: "Info", ofType: "plist"),
let dict = NSDictionary(contentsOfFile: path) else {
return false
}
self.groupID = dict.value(forKey: "Group ID") as! String
self.AWSBucket = dict.value(forKey: "AWS Bucket") as! String
self.AWSPoolId = dict.value(forKey: "AWS Cognito Pool ID") as! String
self.AWSTransferKey = dict.value(forKey: "AWS Transfer Key") as! String
return true
}
// "CSS"
private func setupUI() {
let imageView = UIImageView(image: UIImage(named: "logo.png"))
imageView.contentMode = .scaleAspectFit
navigationItem.titleView = imageView
navigationController?.navigationBar.topItem?.titleView = imageView
navigationController?.navigationBar.tintColor = UIColor.black
navigationController?.navigationBar.backgroundColor = UIColor.white
navigationController?.view.backgroundColor = UIColor.white
navigationController?.navigationBar.topItem?.rightBarButtonItem?.title = "Connect"
placeholderLabel = UILabel()
placeholderLabel.text = "Description"
placeholderLabel.font = UIFont.italicSystemFont(ofSize: (textView.font?.pointSize)!)
placeholderLabel.sizeToFit()
textView.addSubview(placeholderLabel)
placeholderLabel.frame.origin = CGPoint(x: 5, y: (textView.font?.pointSize)! / 2)
placeholderLabel.textColor = UIColor.lightGray
placeholderLabel.isHidden = !textView.text.isEmpty
}
// Get tokens used for Apollo
private func getDefaults() {
let userDefaults = UserDefaults(suiteName: self.groupID)
if let authToken = userDefaults?.string(forKey: "authToken") {
self.authToken = authToken
}
if let appToken = userDefaults?.string(forKey: "appToken") {
self.appToken = appToken
}
}
// Set headers on Apollo client
private func setupApollo() {
let configuration = URLSessionConfiguration.default
configuration.httpAdditionalHeaders = [
"X-APP-TOKEN": self.appToken,
"X-AUTH-TOKEN": self.authToken
]
let url = URL(string: "https://api.are.na/graphql")!
let transport = HTTPNetworkTransport(url: url, configuration: configuration)
self.apollo = ApolloClient(networkTransport: transport)
}
// Fetch both recent connections and all channels for the user
private func fetchRecentConnections() {
self.apollo?.fetch(query: RecentConnectionsQuery()) { (result, error) in
if let error = error {
self.showAlert(message: "Please log in through the Are.na app and try again.", title: "Access Denied")
NSLog("Error fetching connections: \(error.localizedDescription)")
}
let recentConnections = result?.data?.me?.recentConnections
recentConnections?.forEach {
let channel = Channel()
channel.id = $0?.id
channel.title = $0?.title
channel.visibility = $0?.visibility
self.recentConnections.append(channel)
}
let allChannels = result?.data?.me?.contents
allChannels?.forEach {
let channel = Channel()
channel.id = $0?.id
channel.title = $0?.title
channel.visibility = $0?.visibility
self.userChannels.append(channel)
}
self.selectedChannel = self.recentConnections.first
self.reloadConfigurationItems()
self.validateContent()
}
}
// Figure out what kind of content we are dealing with
private func getShareContext() {
let extensionItem = extensionContext?.inputItems[0] as! NSExtensionItem
let contentTypeURL = kUTTypeURL as String
let contentTypeText = kUTTypeText as String
let contentTypeImage = kUTTypeImage as String
for attachment in extensionItem.attachments as! [NSItemProvider] {
if attachment.isImage {
attachment.loadItem(forTypeIdentifier: contentTypeImage, options: nil, completionHandler: { (results, error) in
if let image = results as? URL {
self.imageString = image.absoluteString
self.customTitle = image.lastPathComponent
} else if let image = results as? UIImage {
if let data = UIImagePNGRepresentation(image) {
let filename = getDocumentsDirectory().appendingPathComponent("screenshot.png")
try? data.write(to: filename)
self.imageString = filename.absoluteString
self.customTitle = filename.lastPathComponent
}
}
})
}
if attachment.isURL {
// if the attachment is a url, clear the default text field.
self.customTitle = self.contentText
self.textView.text = ""
placeholderLabel.isHidden = false
attachment.loadItem(forTypeIdentifier: contentTypeURL, options: nil, completionHandler: { (results, error) in
let url = results as! URL?
self.urlString = url!.absoluteString
})
}
if attachment.isText {
attachment.loadItem(forTypeIdentifier: contentTypeText, options: nil, completionHandler: { (results, error) in
let text = results as! String
self.textString = text
_ = self.isContentValid()
})
}
}
}
// Show an alert on the event of an error
private func showAlert(message: String, title: String) {
let alert = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(title: "Ok", style: .default))
self.present(alert, animated: true, completion: nil)
}
}
extension ShareViewController: ShareSelectViewControllerDelegate {
func selected(channel: Channel) {
selectedChannel = channel
reloadConfigurationItems()
popConfigurationViewController()
}
}
extension ShareViewController: ShareTitleViewControllerDelegate {
func titleFinshedEditing(newValue: String) {
self.customTitle = newValue
reloadConfigurationItems()
popConfigurationViewController()
}
}
|
d61d43f2bcf87b1da39722e16c8faa11
| 39.944606 | 188 | 0.604671 | false | true | false | false |
grandiere/box
|
refs/heads/master
|
box/View/Handler/VHandler.swift
|
mit
|
1
|
import UIKit
class VHandler:VView
{
private weak var controller:CHandler!
private(set) weak var viewField:VHandlerField!
private(set) weak var labelWarning:UILabel!
private weak var layoutFieldLeft:NSLayoutConstraint!
private weak var layoutButtonLeft:NSLayoutConstraint!
private let kTitleHeight:CGFloat = 120
private let kTitleMarginHorizontal:CGFloat = 10
private let kFieldHeight:CGFloat = 50
private let kFieldWidth:CGFloat = 160
private let kWarningHeight:CGFloat = 90
private let kButtonWidth:CGFloat = 100
private let kButtonHeight:CGFloat = 34
override init(controller:CController)
{
let attributesTitle:[String:AnyObject] = [
NSFontAttributeName:UIFont.bold(size:19),
NSForegroundColorAttributeName:UIColor.white]
let attributesSubtitle:[String:AnyObject] = [
NSFontAttributeName:UIFont.regular(size:16),
NSForegroundColorAttributeName:UIColor(white:1, alpha:0.7)]
let stringTitle:NSAttributedString = NSAttributedString(
string:NSLocalizedString("VHandler_labelTitle", comment:""),
attributes:attributesTitle)
let stringSubtitle:NSAttributedString = NSAttributedString(
string:NSLocalizedString("VHandler_labelSubtitle", comment:""),
attributes:attributesSubtitle)
let mutableString:NSMutableAttributedString = NSMutableAttributedString()
mutableString.append(stringTitle)
mutableString.append(stringSubtitle)
super.init(controller:controller)
self.controller = controller as? CHandler
let viewField:VHandlerField = VHandlerField(
controller:self.controller)
self.viewField = viewField
let labelTitle:UILabel = UILabel()
labelTitle.isUserInteractionEnabled = false
labelTitle.translatesAutoresizingMaskIntoConstraints = false
labelTitle.textAlignment = NSTextAlignment.center
labelTitle.backgroundColor = UIColor.clear
labelTitle.numberOfLines = 0
labelTitle.attributedText = mutableString
let labelWarning:UILabel = UILabel()
labelWarning.isHidden = true
labelWarning.isUserInteractionEnabled = false
labelWarning.translatesAutoresizingMaskIntoConstraints = false
labelWarning.backgroundColor = UIColor.clear
labelWarning.textAlignment = NSTextAlignment.center
labelWarning.font = UIFont.regular(size:15)
labelWarning.textColor = UIColor(white:1, alpha:0.6)
labelWarning.text = NSLocalizedString("VHandler_labelWarning", comment:"")
self.labelWarning = labelWarning
let buttonDone:UIButton = UIButton()
buttonDone.translatesAutoresizingMaskIntoConstraints = false
buttonDone.clipsToBounds = true
buttonDone.backgroundColor = UIColor.gridBlue
buttonDone.setTitleColor(
UIColor.white,
for:UIControlState.normal)
buttonDone.setTitleColor(
UIColor(white:1, alpha:0.2),
for:UIControlState.highlighted)
buttonDone.setTitle(
NSLocalizedString("VHandler_buttonDone", comment:""),
for:UIControlState.normal)
buttonDone.titleLabel!.font = UIFont.bold(size:14)
buttonDone.layer.cornerRadius = kButtonHeight / 2.0
buttonDone.addTarget(
self,
action:#selector(actionDone(sender:)),
for:UIControlEvents.touchUpInside)
addSubview(labelTitle)
addSubview(labelWarning)
addSubview(viewField)
addSubview(buttonDone)
NSLayoutConstraint.topToTop(
view:labelTitle,
toView:self)
NSLayoutConstraint.height(
view:labelTitle,
constant:kTitleHeight)
NSLayoutConstraint.equalsHorizontal(
view:labelTitle,
toView:self)
NSLayoutConstraint.topToBottom(
view:viewField,
toView:labelTitle)
NSLayoutConstraint.height(
view:viewField,
constant:kFieldHeight)
NSLayoutConstraint.width(
view:viewField,
constant:kFieldWidth)
layoutFieldLeft = NSLayoutConstraint.leftToLeft(
view:viewField,
toView:self)
NSLayoutConstraint.topToBottom(
view:labelWarning,
toView:viewField)
NSLayoutConstraint.height(
view:labelWarning,
constant:kWarningHeight)
NSLayoutConstraint.equalsHorizontal(
view:labelWarning,
toView:self)
NSLayoutConstraint.topToBottom(
view:buttonDone,
toView:labelWarning)
NSLayoutConstraint.height(
view:buttonDone,
constant:kButtonHeight)
NSLayoutConstraint.width(
view:buttonDone,
constant:kButtonWidth)
layoutButtonLeft = NSLayoutConstraint.leftToLeft(
view:buttonDone,
toView:self)
}
required init?(coder:NSCoder)
{
return nil
}
override func layoutSubviews()
{
let width:CGFloat = bounds.maxX
let remainField:CGFloat = width - kFieldWidth
let fieldLeft:CGFloat = remainField / 2.0
layoutFieldLeft.constant = fieldLeft
let remainButton:CGFloat = width - kButtonWidth
let buttonLeft:CGFloat = remainButton / 2.0
layoutButtonLeft.constant = buttonLeft
super.layoutSubviews()
}
//MARK: actions
func actionDone(sender button:UIButton)
{
UIApplication.shared.keyWindow!.endEditing(true)
controller.back()
}
}
|
c3963c5b88e47d76f893f50b4cd05f82
| 34.785276 | 82 | 0.647694 | false | false | false | false |
DarrenKong/firefox-ios
|
refs/heads/master
|
Client/Helpers/UserActivityHandler.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 Foundation
import Shared
import Storage
import CoreSpotlight
import MobileCoreServices
import WebKit
private let browsingActivityType: String = "org.mozilla.ios.firefox.browsing"
private let searchableIndex = CSSearchableIndex(name: "firefox")
class UserActivityHandler {
private var tabObservers: TabObservers!
init() {
self.tabObservers = registerFor(
.didLoseFocus,
.didGainFocus,
.didLoadPageMetadata,
// .didLoadFavicon, // only useful when we fix Bug 1390200.
.didClose,
queue: .main)
}
deinit {
unregister(tabObservers)
}
class func clearSearchIndex(completionHandler: ((Error?) -> Void)? = nil) {
searchableIndex.deleteAllSearchableItems(completionHandler: completionHandler)
}
}
extension UserActivityHandler: TabEventHandler {
func tabDidGainFocus(_ tab: Tab) {
tab.userActivity?.becomeCurrent()
}
func tabDidLoseFocus(_ tab: Tab) {
tab.userActivity?.resignCurrent()
}
func tab(_ tab: Tab, didLoadPageMetadata metadata: PageMetadata) {
guard let url = tab.canonicalURL else {
tabDidLoseFocus(tab)
tab.userActivity = nil
return
}
tab.userActivity?.invalidate()
let userActivity = NSUserActivity(activityType: browsingActivityType)
let attributeSet = CSSearchableItemAttributeSet(itemContentType: kUTTypeHTML as String)
userActivity.title = metadata.title
userActivity.webpageURL = url
userActivity.keywords = metadata.keywords
userActivity.isEligibleForSearch = false
userActivity.isEligibleForHandoff = true
attributeSet.contentURL = url
attributeSet.title = metadata.title
attributeSet.contentDescription = metadata.description
userActivity.contentAttributeSet = attributeSet
tab.userActivity = userActivity
userActivity.becomeCurrent()
}
func tab(_ tab: Tab, didLoadFavicon favicon: Favicon?, with data: Data?) {
guard let url = tab.canonicalURL,
let userActivity = tab.userActivity,
let attributeSet = userActivity.contentAttributeSet,
!tab.isPrivate else {
return
}
attributeSet.thumbnailData = data
let searchableItem = CSSearchableItem(uniqueIdentifier: url.absoluteString, domainIdentifier: "webpages", attributeSet: attributeSet)
searchableIndex.indexSearchableItems([searchableItem])
userActivity.needsSave = true
}
func tabDidClose(_ tab: Tab) {
guard let userActivity = tab.userActivity else {
return
}
tab.userActivity = nil
userActivity.invalidate()
}
}
|
e99d8f5e52919ab2c40e6929b8da8b4a
| 30.816327 | 141 | 0.642399 | false | false | false | false |
salesforce-ux/design-system-ios
|
refs/heads/master
|
Demo-Swift/slds-sample-app/demo/views/AccountHeaderView.swift
|
bsd-3-clause
|
1
|
// Copyright (c) 2015-present, salesforce.com, inc. All rights reserved
// Licensed under BSD 3-Clause - see LICENSE.txt or git.io/sfdc-license
import UIKit
class AccountHeaderView: UIView {
var headerIcon = UIImageView()
var headerTitle = UILabel()
//––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––
override func draw(_ rect: CGRect) {
let aPath = UIBezierPath()
aPath.move(to: CGPoint(x:0, y:self.frame.height))
aPath.addLine(to: CGPoint(x:self.frame.width, y:self.frame.height))
aPath.close()
aPath.lineWidth = 1.0
UIColor.sldsBorderColor(.colorBorderSeparatorAlt2).set()
aPath.stroke()
}
//––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––
override init (frame : CGRect) {
super.init(frame : frame)
self.makeLayout()
}
//––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––
convenience init () {
self.init(frame:CGRect.zero)
}
//––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––
required init(coder aDecoder: NSCoder) {
fatalError("This class does not support NSCoding")
}
//––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––
func makeLayout() {
self.backgroundColor = UIColor.sldsBackgroundColor(.colorBackground)
headerIcon = UIImageView(image: UIImage.sldsStandardIcon(.account,
withSize: SLDSSquareIconMedium))
self.addSubview(headerIcon)
self.constrainChild(headerIcon,
xAlignment: .left,
yAlignment: .top,
xOffset: 10,
yOffset: 10)
headerTitle = UILabel()
headerTitle.font = UIFont.sldsFont(.regular, with: .large)
headerTitle.textColor = UIColor.sldsTextColor(.colorTextDefault)
self.addSubview(headerTitle)
headerTitle.constrainRightOf(headerIcon,
yAlignment: .top,
xOffset: 15)
}
}
|
b0fc12b1bb984ee7b10d29c8dca3fb90
| 32.457143 | 97 | 0.442784 | false | false | false | false |
cotkjaer/Silverback
|
refs/heads/master
|
Silverback/UITextView.swift
|
mit
|
1
|
//
// UITextView.swift
// Silverback
//
// Created by Christian Otkjær on 10/01/16.
// Copyright © 2016 Christian Otkjær. All rights reserved.
//
import UIKit
//MARK: - Auto update
extension UITextView
{
public var preferredHeightForCurrentWidth : CGFloat { return heightThatFits(width: bounds.width) }
public func heightThatFits(width fixedWidth: CGFloat) -> CGFloat
{
let boundingSize = CGSize(width: fixedWidth, height: CGFloat.max)
let bestFit = sizeThatFits(boundingSize)
return bestFit.height
// let fixedWidth = textView.frame.size.width
// textView.sizeThatFits(CGSize(width: fixedWidth, height: CGFloat.max))
// let newSize = textView.sizeThatFits(CGSize(width: fixedWidth, height: CGFloat.max))
// var newFrame = textView.frame
// newFrame.size = CGSize(width: max(newSize.width, fixedWidth), height: newSize.height)
// textView.frame = newFrame;
}
}
|
d173d8d91b285ea3a8fc8f0f1e3f13b0
| 31.1875 | 103 | 0.637864 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.