repo_name
stringlengths 7
91
| path
stringlengths 8
658
| copies
stringclasses 125
values | size
stringlengths 3
6
| content
stringlengths 118
674k
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 6.09
99.2
| line_max
int64 17
995
| alpha_frac
float64 0.3
0.9
| ratio
float64 2
9.18
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
a2/Gulliver | Gulliver Tests/Source/MultiStringSpec.swift | 1 | 1752 | import Gulliver
import Nimble
import Quick
class MultiStringSpec: QuickSpec {
override func spec() {
describe("multiValueRepresentation") {
it("should equal value") {
let string = "Hello, world!"
let multiString = MultiString(string)
expect(multiString.value) == string
}
}
describe("init(multiValueRepresentation:)") {
it("should set value to the input") {
let string = "Hello, world!"
let multiString = MultiString(multiValueRepresentation: string)
expect(multiString).notTo(beNil())
expect(multiString!.value) == string
}
it("should fail for non-string inputs") {
let date = NSDate()
let multiString = MultiString(multiValueRepresentation: date)
expect(multiString).to(beNil())
}
}
describe("==") {
it("should return true if values are equal") {
let stringA = "Hello, world!"
let stringB = "Hello, world!"
expect(stringA) == stringB
let multiStringA = MultiString(stringA)
let multiStringB = MultiString(stringB)
expect(multiStringA) == multiStringB
}
it("should return false if values are different") {
let stringA = "Hello, world!"
let stringB = stringA + "?"
expect(stringA) != stringB
let multiStringA = MultiString(stringA)
let multiStringB = MultiString(stringB)
expect(multiStringA) != multiStringB
}
}
}
}
| mit | 84a05184324b9a6bd93df153b0a3be32 | 32.692308 | 79 | 0.519977 | 4.963173 | false | false | false | false |
shnuzxw/PhotoBrowser | PhotoBrowser/DisplayVC+Host.swift | 13 | 4490 | //
// DisplayVC+Host.swift
// PhotoBrowser
//
// Created by 冯成林 on 15/8/14.
// Copyright (c) 2015年 冯成林. All rights reserved.
//
import UIKit
extension DisplayVC{
var hostHDImageUrls: [String] {
return [
"http://ios-android.cn/PB/HD/1.jpg",
"http://ios-android.cn/PB/HD/2.jpg",
"http://ios-android.cn/PB/HD/3.jpg",
"http://ios-android.cn/PB/HD/4.jpg",
"http://ios-android.cn/PB/HD/5.jpg",
"http://ios-android.cn/PB/HD/6.jpg",
"http://ios-android.cn/PB/HD/7.jpg",
"http://ios-android.cn/PB/HD/8.jpg",
"http://ios-android.cn/PB/HD/9.jpg",
]
}
var titleHostCH: [String] {
return [
"漫山遍野的牦牛正在吃草",
"起伏的山峦",
"月亮湾",
"框架作者:成都.冯成林",
"凌晨",
"大草原",
"三朵金花",
"水鬼",
"若尔盖花湖",
]
}
var titleHostEN: [String] {
return [
"The yak grazing all over the mountains and plains",
"Rolling hills",
"Moon Bay",
"Frame Author: Chengdu Charlin Feng",
"Early in the morning",
"Prairie",
"Three golden flowers",
"Kelpy",
"Ruoergai Lake",
]
}
var descHostCH: [String] {
return [
"作为世界三大高寒动物之一,牦牛肉被誉为牛肉之冠",
"有一种win xp的壁纸的感觉,这里是没有树木的,因为海拔的原因",
"红原月亮湾风景区位于红原县城3公里处的安曲牧场;距离若尔盖县城142公里。",
"",
"这个是凌晨的照片,天空中的是明月",
"这里是一望无际的大草原,非常辽阔",
"三朵金花啊",
"黑夜水鬼,正迎面扑来",
"花湖位于若尔盖和甘肃郎木寺之间的213国道旁,热尔大坝上有3个相邻的海子,最小的叫错尔干,最大的叫错热哈,花湖是居中的一个。若尔盖花湖四周数百亩水草地就是高原湿地生物多样性自然保护区",
]
}
var descHostEN: [String] {
return [
"As one of the world's three largest alpine animals, yak meat is known as the crown of beef",
"There is a feeling of XP win's wallpaper, there is no trees, because of the reasons above sea level",
"Red Moon Bay scenic area is located in the county 3 kilometers in an Qu pasture; 142 kilometers from the Ruoergai county.",
"",
"This is the morning of the photo, the sky is the moon",
"Here is a very vast prairie stretch as far as eye can see,",
"Three golden flowers.",
"The night is coming home,",
"Lake is located in the Zoige and Gansu Langmusi between 213 national highway, gers dam has three adjacent Haizi, minimum call wrong Durkheim, largest called wrong hot ha, Kusum is in the middle of a. Ruoergai lake water is around hundreds of acres of grassland biodiversity of the plateau wetland biological nature reserve",
]
}
/** 网络相册相册 */
func showHost(index: Int){
let pbVC = PhotoBrowser()
/** 设置相册展示样式 */
pbVC.showType = showType
/** 设置相册类型 */
pbVC.photoType = PhotoBrowser.PhotoType.Host
//强制关闭显示一切信息
pbVC.hideMsgForZoomAndDismissWithSingleTap = true
var models: [PhotoBrowser.PhotoModel] = []
let titles = langType == LangType.Chinese ? titleHostCH : titleHostEN
let descs = langType == LangType.Chinese ? descHostCH : descHostEN
//模型数据数组
for (var i=0; i<9; i++){
let model = PhotoBrowser.PhotoModel(hostHDImgURL: hostHDImageUrls[i], hostThumbnailImg: (displayView.subviews[i] as! UIImageView).image, titleStr: titles[i], descStr: descs[i], sourceView: displayView.subviews[i] as! UIView)
models.append(model)
}
/** 设置数据 */
pbVC.photoModels = models
pbVC.show(inVC: self,index: index)
}
} | mit | 7d90b28304e3f932305b45c5308c93e2 | 28.823077 | 337 | 0.535604 | 3.281964 | false | false | false | false |
shridharmalimca/iOSDev | iOS/Components/FirebasePushMessaging/FCMNotificationService/NotificationService.swift | 2 | 5449 | //
// NotificationService.swift
// FCMNotificationService
//
// Created by Shridhar Mali on 1/12/17.
// Copyright © 2017 Shridhar Mali. All rights reserved.
//
import UserNotifications
class NotificationService: UNNotificationServiceExtension {
var contentHandler: ((UNNotificationContent) -> Void)?
var content: UNMutableNotificationContent?
override func didReceive(_ request: UNNotificationRequest, withContentHandler contentHandler: @escaping (UNNotificationContent) -> Void) {
self.contentHandler = contentHandler
content = (request.content.mutableCopy() as? UNMutableNotificationContent)
content?.title = "Notification Title Here"
content?.subtitle = "Notification Sub Title Here"
content?.body = "Notification Body Text Here"
content?.badge = 1
content?.categoryIdentifier = "myNotificationCategory"
/*print("UserInfo \(request.content.userInfo)")
if let bestAttemptContent = bestAttemptContent {
// Modify the notification content here...
bestAttemptContent.title = "\(bestAttemptContent.title) [modified]"
print("bestAttemptContent")
contentHandler(bestAttemptContent)
}
func schedule(imageUrl: String) {
let content = UNMutableNotificationContent()
content.title = "Notification Title Here"
content.subtitle = "Notification Sub Title Here"
content.body = "Notification Body Text Here"
content.badge = 1
content.categoryIdentifier = "myNotificationCategory"
let fileURL = URL(string: imageUrl)!
print(fileURL)
let session = URLSession.shared
let task = session.dataTask(with: fileURL) { (data: Data?, response: URLResponse?, error: Error?) in
let fileManager = FileManager.default
let path = NSSearchPathForDirectoriesInDomains(.documentDirectory, FileManager.SearchPathDomainMask.userDomainMask, true)
let documentPath = path.first
let filePath = documentPath?.appending("/image.png")
let baseURL = URL(fileURLWithPath: filePath!)
if let imageData = data {
// let image = UIImage(data: imageData)
fileManager.createFile(atPath: filePath!, contents: imageData, attributes: nil)
}
// let url = URL(string: baseURL)
print(baseURL)
if let attachement = try? UNNotificationAttachment(identifier: "image", url: baseURL, options:nil) {
content.attachments = [attachement]
let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 5, repeats: false)
let requestIdentifier = "myNotificationCategory"
let request = UNNotificationRequest(identifier: requestIdentifier, content: content, trigger: trigger)
UNUserNotificationCenter.current().add(request, withCompletionHandler: { error in
// handle error
})
} else {
print("Attchement found nil")
}
}
task.resume()
}
*/
// Get the custom data from the notification payload
//if let notificationData = request.content.userInfo["data"] as? [String: String] {
// Grab the attachment
if let fileUrl = URL(string: request.content.userInfo["image"] as! String) {
// Download the attachment
URLSession.shared.downloadTask(with: fileUrl) { (location, response, error) in
if let location = location {
// Move temporary file to remove .tmp extension
let tmpDirectory = NSTemporaryDirectory()
let tmpFile = "file://".appending(tmpDirectory).appending(fileUrl.lastPathComponent)
let tmpUrl = URL(string: tmpFile)!
try! FileManager.default.moveItem(at: location, to: tmpUrl)
// Add the attachment to the notification content
if let attachment = try? UNNotificationAttachment(identifier: "image", url: tmpUrl) {
self.content?.attachments = [attachment]
let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 5, repeats: false)
let requestIdentifier = "myNotificationCategory"
let request = UNNotificationRequest(identifier: requestIdentifier, content: self.content!, trigger: trigger)
UNUserNotificationCenter.current().add(request, withCompletionHandler: { error in
// handle error
})
}
}
// Serve the notification content
self.contentHandler!(self.content!)
}.resume()
}
//}
}
override func serviceExtensionTimeWillExpire() {
// Called just before the extension will be terminated by the system.
// Use this as an opportunity to deliver your "best attempt" at modified content, otherwise the original push payload will be used.
if let contentHandler = contentHandler, let content = content {
contentHandler(content)
}
}
}
| apache-2.0 | 0ca59d491d4f79681162816e9d126431 | 44.024793 | 142 | 0.602606 | 5.960613 | false | false | false | false |
FromF/OlympusCameraKit | HDRRecCameraSwift/RecCameraSwift/LiveView.swift | 1 | 6742 | //
// LiveView.swift
// RecCameraSwift
//
// Created by haruhito on 2015/04/12.
// Copyright (c) 2015年 FromF. All rights reserved.
//
import UIKit
class LiveView: UIViewController , OLYCameraLiveViewDelegate , OLYCameraRecordingSupportsDelegate {
@IBOutlet weak var liveViewImage: UIImageView!
@IBOutlet weak var recviewImage: UIImageView!
@IBOutlet weak var infomation: UILabel!
//AppDelegate instance
var appDelegate:AppDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
var imagecache:ImageCacheObject = ImageCacheObject()
var liveViewImageCount = 0
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
//Notification Regist
NSNotificationCenter.defaultCenter().addObserver(self, selector: "NotificationApplicationBackground:", name: UIApplicationDidEnterBackgroundNotification , object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: "NotificationCameraKitDisconnect:", name: appDelegate.NotificationCameraKitDisconnect as String, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: "NotificationRechabilityDisconnect:", name: appDelegate.NotificationNetworkDisconnected as String, object: nil)
var camera = AppDelegate.sharedCamera
camera.liveViewDelegate = self
camera.recordingSupportsDelegate = self
camera.connect(OLYCameraConnectionTypeWiFi, error: nil)
if (camera.connected) {
camera.changeRunMode(OLYCameraRunModeRecording, error: nil)
let propertyDictionary = [
"TAKEMODE":"<TAKEMODE/A>",
"TAKE_DRIVE":"<TAKE_DRIVE/DRIVE_NORMAL>",
"APERTURE":"<APERTURE/8.0>",
"RAW":"<RAW/ON>",
"RECVIEW":"<RECVIEW/OFF>",
]
camera.setCameraPropertyValues(propertyDictionary, error: nil)
let inquire = camera.inquireHardwareInformation(nil) as NSDictionary
let modelname = inquire.objectForKey(OLYCameraHardwareInformationCameraModelNameKey) as? String
let version = inquire.objectForKey(OLYCameraHardwareInformationCameraFirmwareVersionKey) as? String
infomation.text = modelname! + " Ver." + version!
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func viewWillDisappear(animated: Bool) {
super.viewWillDisappear(animated)
var camera = AppDelegate.sharedCamera
camera.disconnectWithPowerOff(false, error: nil)
}
// MARK: - Button Action
@IBAction func shutterButtonAction(sender: AnyObject) {
var camera:OLYCamera = AppDelegate.sharedCamera
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), {
let semaphore:dispatch_semaphore_t = dispatch_semaphore_create(0)
//HDR Shooting sequence call
camera.lockAutoExposure(nil)
camera.lockAutoFocus( { info -> Void in
dispatch_semaphore_signal(semaphore)
println("Comp")
}, errorHandler: { error -> Void in
dispatch_semaphore_signal(semaphore)
println("Error")
})
dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER)
for var i = 0 ; i < 3 ; i++ {
switch i {
case 0:
camera.setCameraPropertyValue("EXPREV", value: "<EXPREV/+2.0>", error: nil)
case 1:
camera.setCameraPropertyValue("EXPREV", value: "<EXPREV/+0.0>", error: nil)
case 2:
camera.setCameraPropertyValue("EXPREV", value: "<EXPREV/-2.0>", error: nil)
default:
camera.setCameraPropertyValue("EXPREV", value: "<EXPREV/+0.0>", error: nil)
}
camera.takePicture(nil, progressHandler: nil, completionHandler:{info -> Void in
dispatch_semaphore_signal(semaphore)
println("Comp")
}, errorHandler: {error -> Void in
dispatch_semaphore_signal(semaphore)
println("Error")
})
dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER)
while camera.mediaBusy {
println("media busy...")
NSThread.sleepForTimeInterval(0.5)
}
}
camera.setCameraPropertyValue("EXPREV", value: "<EXPREV/0.0>", error: nil)
camera.unlockAutoFocus(nil)
camera.unlockAutoExposure(nil)
})
}
// MARK: - 露出補正
@IBAction func exprevSlider(sender: AnyObject) {
let slider = sender as! UISlider
let index = Int(slider.value + 0.5)
slider.value = Float(index)
var value = NSString(format: "%+0.1f" , slider.value)
if (slider.value == 0) {
value = NSString(format: "%0.1f" , slider.value)
}
var camera = AppDelegate.sharedCamera
camera.setCameraPropertyValue("EXPREV", value: "<EXPREV/" + (value as String) + ">", error: nil)
}
// MARK: - LiveView Update
func camera(camera: OLYCamera!, didUpdateLiveView data: NSData!, metadata: [NSObject : AnyObject]!) {
var image : UIImage = OLYCameraConvertDataToImage(data,metadata)
self.liveViewImage.image = image
liveViewImageCount++
imagecache.setUncahcedImage("\(liveViewImageCount)", image: image)
var lastimage = imagecache.getUncachedImage("\(liveViewImageCount - 30)")
if (lastimage != nil) {
recviewImage.image = lastimage
}
}
// MARK: - Recview
func camera(camera: OLYCamera!, didReceiveCapturedImagePreview data: NSData!, metadata: [NSObject : AnyObject]!) {
var image : UIImage = OLYCameraConvertDataToImage(data,metadata)
recviewImage.image = image
}
// MARK: - Notification
func NotificationApplicationBackground(notification : NSNotification?) {
self.dismissViewControllerAnimated(true, completion: nil)
}
func NotificationCameraKitDisconnect(notification : NSNotification?) {
self.dismissViewControllerAnimated(true, completion: nil)
}
func NotificationRechabilityDisconnect(notification : NSNotification?) {
self.dismissViewControllerAnimated(true, completion: nil)
}
}
| mit | d8307bc4e4f61121fc3fbb65247ab1ee | 41.878981 | 184 | 0.623143 | 4.832735 | false | false | false | false |
HJliu1123/LearningNotes-LHJ | April/tabbar/tabbar/tabbarViewController.swift | 1 | 2800 | //
// tabbarViewController.swift
// tabbar
//
// Created by liuhj on 16/4/25.
// Copyright © 2016年 liuhj. All rights reserved.
//
import UIKit
class tabbarViewController: UITabBarController, UITabBarControllerDelegate, HJTabBarDelegate {
var lastSelectVC : UIViewController?
var firstVC : firstViewController?
var secondVC : sceondViewController?
var thirdVC : thirdViewController?
var fouthVC : fouthViewController?
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = UIColor.whiteColor()
self.delegate = self
// self.tabBar.hidden = true
self.addCustomTabBar()
self.addAllChildVCs()
}
func tabBarController(tabBarController: UITabBarController, didSelectViewController viewController: UIViewController) {
let vc = viewController.childViewControllers.first
if (vc?.isKindOfClass(firstViewController.classForCoder()) != nil) {
if self.lastSelectVC == vc {
firstVC!.refresh(true)
} else {
firstVC!.refresh(false)
}
}
lastSelectVC = vc
}
func addCustomTabBar() {
let customTabBar = HJTabBar()
customTabBar.tabBarDelegate = self
//tabbar是只读的属性,不能直接赋值
self.setValue(customTabBar, forKey: "tabBar")
}
func addAllChildVCs() {
firstVC = firstViewController()
self.addChildViewController(firstVC!, title: "第一个", imageName: "", selectImageName: "")
lastSelectVC = firstVC
secondVC = sceondViewController()
self.addChildViewController(secondVC!, title: "第二个", imageName: "", selectImageName: "")
thirdVC = thirdViewController()
self.addChildViewController(thirdVC!, title: "第三个", imageName: "", selectImageName: "")
fouthVC = fouthViewController()
self.addChildViewController(fouthVC!, title: "第四个", imageName: "", selectImageName: "")
}
func addChildViewController(childController : UIViewController, title : String, imageName : String, selectImageName : String) {
childController.title = title
childController.view.backgroundColor = UIColor.lightGrayColor()
childController.tabBarItem.title = title
let navi = UINavigationController(rootViewController: childController)
self.addChildViewController(navi)
}
func clickButton(tabBar: HJTabBar) {
}
}
| apache-2.0 | d529b9e7b12865aa61ced04cc6ba9489 | 24.672897 | 131 | 0.594467 | 5.629098 | false | false | false | false |
kstaring/swift | test/stdlib/NewStringAppending.swift | 15 | 4067 | // RUN: %target-run-stdlib-swift | %FileCheck %s
// REQUIRES: executable_test
//
// Parts of this test depend on memory allocator specifics. The test
// should be rewritten soon so it doesn't expose legacy components
// like OpaqueString anyway, so we can just disable the failing
// configuration
//
// Memory allocator specifics also vary across platforms.
// REQUIRES: CPU=x86_64, OS=macosx
import Foundation
import Swift
func hexAddrVal<T>(_ x: T) -> String {
return "@0x" + String(UInt64(unsafeBitCast(x, to: Int.self)), radix: 16)
}
func hexAddr(_ x: AnyObject?) -> String {
if let owner = x {
if let y = owner as? _StringBuffer._Storage.Storage {
return ".native\(hexAddrVal(y))"
}
if let y = owner as? NSString {
return ".cocoa\(hexAddrVal(y))"
}
else {
return "?Uknown?\(hexAddrVal(owner))"
}
}
return "nil"
}
func repr(_ x: NSString) -> String {
return "\(NSStringFromClass(object_getClass(x)))\(hexAddr(x)) = \"\(x)\""
}
func repr(_ x: _StringCore) -> String {
if x.hasContiguousStorage {
if let b = x.nativeBuffer {
var offset = x.elementWidth == 2
? b.start - UnsafeMutableRawPointer(x.startUTF16)
: b.start - UnsafeMutableRawPointer(x.startASCII)
return "Contiguous(owner: "
+ "\(hexAddr(x._owner))[\(offset)...\(x.count + offset)]"
+ ", capacity = \(b.capacity))"
}
return "Contiguous(owner: \(hexAddr(x._owner)), count: \(x.count))"
}
else if let b2 = x.cocoaBuffer {
return "Opaque(buffer: \(hexAddr(b2))[0...\(x.count)])"
}
return "?????"
}
func repr(_ x: String) -> String {
return "String(\(repr(x._core))) = \"\(x)\""
}
// ===------- Appending -------===
// CHECK: --- Appending ---
print("--- Appending ---")
var s = "⓪" // start non-empty
// To make this test independent of the memory allocator implementation,
// explicitly request initial capacity.
s.reserveCapacity(8)
// CHECK-NEXT: String(Contiguous(owner: .native@[[buffer0:[x0-9a-f]+]][0...2], capacity = 8)) = "⓪1"
s += "1"
print("\(repr(s))")
// CHECK-NEXT: String(Contiguous(owner: .native@[[buffer1:[x0-9a-f]+]][0...8], capacity = 8)) = "⓪1234567"
s += "234567"
print("\(repr(s))")
// -- expect a reallocation here
// CHECK-NEXT: String(Contiguous(owner: .native@[[buffer2:[x0-9a-f]+]][0...9], capacity = 16)) = "⓪12345678"
// CHECK-NOT: .native@[[buffer1]]
s += "8"
print("\(repr(s))")
// CHECK-NEXT: String(Contiguous(owner: .native@[[buffer2]][0...16], capacity = 16)) = "⓪123456789012345"
s += "9012345"
print("\(repr(s))")
// -- expect a reallocation here
// Appending more than the next level of capacity only takes as much
// as required. I'm not sure whether this is a great idea, but the
// point is to prevent huge amounts of fragmentation when a long
// string is appended to a short one. The question, of course, is
// whether more appends are coming, in which case we should give it
// more capacity. It might be better to always grow to a multiple of
// the current capacity when the capacity is exceeded.
// CHECK-NEXT: String(Contiguous(owner: .native@[[buffer3:[x0-9a-f]+]][0...48], capacity = 48))
// CHECK-NOT: .native@[[buffer2]]
s += s + s
print("\(repr(s))")
// -- expect a reallocation here
// CHECK-NEXT: String(Contiguous(owner: .native@[[buffer4:[x0-9a-f]+]][0...49], capacity = 96))
// CHECK-NOT: .native@[[buffer3]]
s += "C"
print("\(repr(s))")
/// An additional reference to the same buffer doesn't, by itself,
/// impede the use of available capacity
var s1 = s
// CHECK-NEXT: String(Contiguous(owner: .native@[[buffer4]][0...50], capacity = 96))
s += "F"
print("\(repr(s))")
// CHECK-NEXT: String(Contiguous(owner: .native@[[buffer4]][0...49], capacity = 96))
print("\(repr(s1))")
/// The use of later buffer capacity by another string forces
/// reallocation
// CHECK-NEXT: String{{.*}} = {{.*}}X"
// CHECK-NOT: .native@[[buffer4]]
s1 += "X"
print("\(repr(s1))")
/// Appending to an empty string re-uses the RHS
// CHECK-NEXT: .native@[[buffer4]]
var s2 = String()
s2 += s
print("\(repr(s2))")
| apache-2.0 | d5c9842a462e3f2612663681a77d92a8 | 28.613139 | 108 | 0.634212 | 3.298374 | false | false | false | false |
osjup/EasyAPNS | Sources/EasyAPNS/Utils/Base64Encoding.swift | 1 | 2405 | //
// Base64Encoding.swift
// EasyAPNSPackageDescription
//
// Created by damian.malarczyk on 15.08.2017.
//
import Core
import Crypto
import Foundation
struct Base64URLEncoding: Encoding {
private let base64URLTranscoder: Base64URLTranscoding
init() {
self.init(base64URLTranscoder: Base64URLTranscoder())
}
init(base64URLTranscoder: Base64URLTranscoding) {
self.base64URLTranscoder = base64URLTranscoder
}
func encode(_ bytes: Bytes) throws -> String {
guard let base64URL = base64URLTranscoder.base64URLEncode( bytes.base64Encoded.makeString()) else {
throw JWTError.encoding
}
return base64URL
}
func decode(_ base64URLEncoded: String) throws -> Bytes {
guard
let base64Encoded = base64URLTranscoder.base64Encode(base64URLEncoded),
let data = Data(base64Encoded: base64Encoded) else {
throw JWTError.decoding
}
return data.makeBytes()
}
}
protocol Base64URLTranscoding {
func base64Encode(_: String) -> String?
func base64URLEncode(_: String) -> String?
}
struct Base64URLTranscoder: Base64URLTranscoding {
func base64Encode(_ string: String) -> String? {
var converted = string.utf8CString.map { char -> CChar in
switch char {
case 45: // '-'
return 43 // '+'
case 95: // '_'
return 47 // '/'
default:
return char
}
}
guard let unpadded = String(utf8String: &converted) else {
return nil
}
let characterCount = unpadded.utf8CString.count - 1 // ignore last /0
let paddingRemainder = (characterCount % 4)
let paddingCount = paddingRemainder > 0 ? 4 - paddingRemainder : 0
let padding = Array(repeating: "=", count: paddingCount).joined()
return unpadded + padding
}
func base64URLEncode(_ string: String) -> String? {
var converted = string.utf8CString.compactMap { char -> CChar? in
switch char {
case 43: // '+'
return 45 // '-'
case 47: // '/'
return 95 // '_'
case 61: // '='
return nil
default:
return char
}
}
return String(utf8String: &converted)
}
}
| apache-2.0 | c52acdbf07a146d513aad79935b081bd | 27.630952 | 107 | 0.576299 | 4.47026 | false | false | false | false |
FraDeliro/ISaMaterialLogIn | Example/Pods/Material/Sources/iOS/TextField.swift | 1 | 19968 | /*
* Copyright (C) 2015 - 2016, Daniel Dahan and CosmicMind, Inc. <http://cosmicmind.com>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* * Neither the name of CosmicMind nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
import UIKit
@objc(TextFieldDelegate)
public protocol TextFieldDelegate: UITextFieldDelegate {
/**
A delegation method that is executed when the textField changed.
- Parameter textField: A UITextField.
- Parameter didChange text: An optional String.
*/
@objc
optional func textField(textField: UITextField, didChange text: String?)
/**
A delegation method that is executed when the textField will clear.
- Parameter textField: A UITextField.
- Parameter willClear text: An optional String.
*/
@objc
optional func textField(textField: UITextField, willClear text: String?)
/**
A delegation method that is executed when the textField is cleared.
- Parameter textField: A UITextField.
- Parameter didClear text: An optional String.
*/
@objc
optional func textField(textField: UITextField, didClear text: String?)
}
open class TextField: UITextField {
/// Will layout the view.
open var willLayout: Bool {
return 0 < width && 0 < height && nil != superview
}
/// Default size when using AutoLayout.
open override var intrinsicContentSize: CGSize {
return CGSize(width: width, height: 32)
}
/// A Boolean that indicates if the placeholder label is animated.
@IBInspectable
open var isPlaceholderAnimated = true
/// A Boolean that indicates if the TextField is in an animating state.
open internal(set) var isAnimating = false
/// A boolean indicating whether the text is empty.
open var isEmpty: Bool {
return true == text?.isEmpty
}
open override var leftView: UIView? {
didSet {
prepareLeftView()
layoutSubviews()
}
}
/// The leftView width value.
open var leftViewWidth: CGFloat {
guard nil != leftView else {
return 0
}
return leftViewOffset + height
}
/// The leftView width value.
open var leftViewOffset: CGFloat = 16
/// Placeholder normal text
@IBInspectable
open var leftViewNormalColor = Color.darkText.others {
didSet {
updateLeftViewColor()
}
}
/// Placeholder active text
@IBInspectable
open var leftViewActiveColor = Color.blue.base {
didSet {
updateLeftViewColor()
}
}
/// Divider normal height.
@IBInspectable
open var dividerNormalHeight: CGFloat = 1 {
didSet {
guard !isEditing else {
return
}
dividerThickness = dividerNormalHeight
}
}
/// Divider active height.
@IBInspectable
open var dividerActiveHeight: CGFloat = 2 {
didSet {
guard isEditing else {
return
}
dividerThickness = dividerActiveHeight
}
}
/// Divider normal color.
@IBInspectable
open var dividerNormalColor = Color.darkText.dividers {
didSet {
guard !isEditing else {
return
}
dividerColor = dividerNormalColor
}
}
/// Divider active color.
@IBInspectable
open var dividerActiveColor = Color.blue.base {
didSet {
guard isEditing else {
return
}
dividerColor = dividerActiveColor
}
}
/// The placeholderLabel font value.
@IBInspectable
open override var font: UIFont? {
didSet {
placeholderLabel.font = font
}
}
/// The placeholderLabel text value.
@IBInspectable
open override var placeholder: String? {
get {
return placeholderLabel.text
}
set(value) {
placeholderLabel.text = value
layoutSubviews()
}
}
/// The placeholder UILabel.
@IBInspectable
open let placeholderLabel = UILabel()
/// Placeholder normal text
@IBInspectable
open var placeholderNormalColor = Color.darkText.others {
didSet {
updatePlaceholderLabelColor()
}
}
/// Placeholder active text
@IBInspectable
open var placeholderActiveColor = Color.blue.base {
didSet {
updatePlaceholderLabelColor()
}
}
/// This property adds a padding to placeholder y position animation
@IBInspectable
open var placeholderVerticalOffset: CGFloat = 0
/// The detailLabel UILabel that is displayed.
@IBInspectable
open let detailLabel = UILabel()
/// The detailLabel text value.
@IBInspectable
open var detail: String? {
get {
return detailLabel.text
}
set(value) {
detailLabel.text = value
layoutSubviews()
}
}
/// Detail text
@IBInspectable
open var detailColor = Color.darkText.others {
didSet {
updateDetailLabelColor()
}
}
/// Vertical distance for the detailLabel from the divider.
@IBInspectable
open var detailVerticalOffset: CGFloat = 8 {
didSet {
layoutDetailLabel()
}
}
/// Handles the textAlignment of the placeholderLabel.
open override var textAlignment: NSTextAlignment {
get {
return super.textAlignment
}
set(value) {
super.textAlignment = value
placeholderLabel.textAlignment = value
detailLabel.textAlignment = value
}
}
/// A reference to the clearIconButton.
open fileprivate(set) var clearIconButton: IconButton?
/// Enables the clearIconButton.
@IBInspectable
open var isClearIconButtonEnabled: Bool {
get {
return nil != clearIconButton
}
set(value) {
guard value else {
clearIconButton?.removeTarget(self, action: #selector(handleClearIconButton), for: .touchUpInside)
clearIconButton = nil
return
}
guard nil == clearIconButton else {
return
}
clearIconButton = IconButton(image: Icon.cm.clear, tintColor: placeholderNormalColor)
clearIconButton!.contentEdgeInsetsPreset = .none
clearIconButton!.pulseAnimation = .none
clearButtonMode = .never
rightViewMode = .whileEditing
rightView = clearIconButton
isClearIconButtonAutoHandled = isClearIconButtonAutoHandled ? true : false
layoutSubviews()
}
}
/// Enables the automatic handling of the clearIconButton.
@IBInspectable
open var isClearIconButtonAutoHandled = true {
didSet {
clearIconButton?.removeTarget(self, action: #selector(handleClearIconButton), for: .touchUpInside)
guard isClearIconButtonAutoHandled else {
return
}
clearIconButton?.addTarget(self, action: #selector(handleClearIconButton), for: .touchUpInside)
}
}
/// A reference to the visibilityIconButton.
open fileprivate(set) var visibilityIconButton: IconButton?
/// Enables the visibilityIconButton.
@IBInspectable
open var isVisibilityIconButtonEnabled: Bool {
get {
return nil != visibilityIconButton
}
set(value) {
guard value else {
visibilityIconButton?.removeTarget(self, action: #selector(handleVisibilityIconButton), for: .touchUpInside)
visibilityIconButton = nil
return
}
guard nil == visibilityIconButton else {
return
}
visibilityIconButton = IconButton(image: Icon.visibility, tintColor: placeholderNormalColor.withAlphaComponent(isSecureTextEntry ? 0.38 : 0.54))
visibilityIconButton!.contentEdgeInsetsPreset = .none
visibilityIconButton!.pulseAnimation = .none
isSecureTextEntry = true
clearButtonMode = .never
rightViewMode = .whileEditing
rightView = visibilityIconButton
isVisibilityIconButtonAutoHandled = isVisibilityIconButtonAutoHandled ? true : false
layoutSubviews()
}
}
/// Enables the automatic handling of the visibilityIconButton.
@IBInspectable
open var isVisibilityIconButtonAutoHandled: Bool = true {
didSet {
visibilityIconButton?.removeTarget(self, action: #selector(handleVisibilityIconButton), for: .touchUpInside)
guard isVisibilityIconButtonAutoHandled else {
return
}
visibilityIconButton?.addTarget(self, action: #selector(handleVisibilityIconButton), for: .touchUpInside)
}
}
/**
An initializer that initializes the object with a NSCoder object.
- Parameter aDecoder: A NSCoder instance.
*/
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
prepare()
}
/**
An initializer that initializes the object with a CGRect object.
If AutoLayout is used, it is better to initilize the instance
using the init() initializer.
- Parameter frame: A CGRect instance.
*/
public override init(frame: CGRect) {
super.init(frame: frame)
prepare()
}
/// A convenience initializer.
public convenience init() {
self.init(frame: .zero)
}
open override func layoutSubviews() {
super.layoutSubviews()
guard willLayout && !isAnimating else {
return
}
layoutShape()
reload()
}
/**
Prepares the view instance when intialized. When subclassing,
it is recommended to override the prepare method
to initialize property values and other setup operations.
The super.prepare method should always be called immediately
when subclassing.
*/
open func prepare() {
clipsToBounds = false
borderStyle = .none
backgroundColor = nil
contentScaleFactor = Screen.scale
prepareDivider()
preparePlaceholderLabel()
prepareDetailLabel()
prepareTargetHandlers()
prepareTextAlignment()
}
/// Ensures that the components are sized correctly.
open func reload() {
layoutPlaceholderLabel()
layoutDetailLabel()
layoutButton(button: clearIconButton)
layoutButton(button: visibilityIconButton)
layoutDivider()
layoutLeftView()
}
}
extension TextField {
/// Prepares the divider.
fileprivate func prepareDivider() {
dividerColor = dividerNormalColor
}
/// Prepares the placeholderLabel.
fileprivate func preparePlaceholderLabel() {
font = RobotoFont.regular(with: 16)
placeholderNormalColor = Color.darkText.others
addSubview(placeholderLabel)
}
/// Prepares the detailLabel.
fileprivate func prepareDetailLabel() {
detailLabel.font = RobotoFont.regular(with: 12)
detailLabel.numberOfLines = 0
detailColor = Color.darkText.others
addSubview(detailLabel)
}
/// Prepares the leftView.
fileprivate func prepareLeftView() {
leftView?.contentMode = .left
updateLeftViewColor()
}
/// Prepares the target handlers.
fileprivate func prepareTargetHandlers() {
addTarget(self, action: #selector(handleEditingDidBegin), for: .editingDidBegin)
addTarget(self, action: #selector(handleEditingChanged), for: .editingChanged)
addTarget(self, action: #selector(handleEditingDidEnd), for: .editingDidEnd)
}
/// Prepares the textAlignment.
fileprivate func prepareTextAlignment() {
textAlignment = .rightToLeft == Application.userInterfaceLayoutDirection ? .right : .left
}
}
extension TextField {
/// Updates the leftView tint color.
fileprivate func updateLeftViewColor() {
leftView?.tintColor = isEditing ? leftViewActiveColor : leftViewNormalColor
}
/// Updates the placeholderLabel text color.
fileprivate func updatePlaceholderLabelColor() {
tintColor = placeholderActiveColor
placeholderLabel.textColor = isEditing ? placeholderActiveColor : placeholderNormalColor
}
/// Updates the detailLabel text color.
fileprivate func updateDetailLabelColor() {
detailLabel.textColor = detailColor
}
}
extension TextField {
/// Layout the placeholderLabel.
fileprivate func layoutPlaceholderLabel() {
let w = leftViewWidth
let h = 0 == height ? intrinsicContentSize.height : height
guard isEditing || !isEmpty || !isPlaceholderAnimated else {
placeholderLabel.frame = CGRect(x: w, y: 0, width: width - w, height: h)
return
}
placeholderLabel.transform = CGAffineTransform.identity
placeholderLabel.frame = CGRect(x: w, y: 0, width: width - w, height: h)
placeholderLabel.transform = CGAffineTransform(scaleX: 0.75, y: 0.75)
switch textAlignment {
case .left, .natural:
placeholderLabel.x = w
case .right:
placeholderLabel.x = width - placeholderLabel.width
default:break
}
placeholderLabel.y = -placeholderLabel.height + placeholderVerticalOffset
}
/// Layout the detailLabel.
fileprivate func layoutDetailLabel() {
let c = dividerContentEdgeInsets
detailLabel.sizeToFit()
detailLabel.x = c.left
detailLabel.y = height + detailVerticalOffset
detailLabel.width = width - c.left - c.right
}
/// Layout the a button.
fileprivate func layoutButton(button: UIButton?) {
guard 0 < width && 0 < height else {
return
}
button?.frame = CGRect(x: width - height, y: 0, width: height, height: height)
}
/// Layout the divider.
fileprivate func layoutDivider() {
divider.reload()
}
/// Layout the leftView.
fileprivate func layoutLeftView() {
guard let v = leftView else {
return
}
let w = leftViewWidth
v.frame = CGRect(x: 0, y: 0, width: w, height: height)
dividerContentEdgeInsets.left = w
}
}
extension TextField {
/// Handles the text editing did begin state.
@objc
fileprivate func handleEditingDidBegin() {
leftViewEditingBeginAnimation()
placeholderEditingDidBeginAnimation()
dividerEditingDidBeginAnimation()
}
// Live updates the textField text.
@objc
fileprivate func handleEditingChanged(textField: UITextField) {
(delegate as? TextFieldDelegate)?.textField?(textField: self, didChange: textField.text)
}
/// Handles the text editing did end state.
@objc
fileprivate func handleEditingDidEnd() {
leftViewEditingEndAnimation()
placeholderEditingDidEndAnimation()
dividerEditingDidEndAnimation()
}
/// Handles the clearIconButton TouchUpInside event.
@objc
fileprivate func handleClearIconButton() {
guard nil == delegate?.textFieldShouldClear || true == delegate?.textFieldShouldClear?(self) else {
return
}
let t = text
(delegate as? TextFieldDelegate)?.textField?(textField: self, willClear: t)
text = nil
(delegate as? TextFieldDelegate)?.textField?(textField: self, didClear: t)
}
/// Handles the visibilityIconButton TouchUpInside event.
@objc
fileprivate func handleVisibilityIconButton() {
isSecureTextEntry = !isSecureTextEntry
if !isSecureTextEntry {
super.font = nil
font = placeholderLabel.font
}
visibilityIconButton?.tintColor = visibilityIconButton?.tintColor.withAlphaComponent(isSecureTextEntry ? 0.38 : 0.54)
}
}
extension TextField {
/// The animation for leftView when editing begins.
fileprivate func leftViewEditingBeginAnimation() {
updateLeftViewColor()
}
/// The animation for leftView when editing ends.
fileprivate func leftViewEditingEndAnimation() {
updateLeftViewColor()
}
/// The animation for the divider when editing begins.
fileprivate func dividerEditingDidBeginAnimation() {
dividerThickness = dividerActiveHeight
dividerColor = dividerActiveColor
}
/// The animation for the divider when editing ends.
fileprivate func dividerEditingDidEndAnimation() {
dividerThickness = dividerNormalHeight
dividerColor = dividerNormalColor
}
/// The animation for the placeholder when editing begins.
fileprivate func placeholderEditingDidBeginAnimation() {
updatePlaceholderLabelColor()
guard isPlaceholderAnimated else {
return
}
guard isEmpty && !isAnimating else {
return
}
isAnimating = true
UIView.animate(withDuration: 0.15, animations: { [weak self] in
guard let s = self else {
return
}
s.placeholderLabel.transform = CGAffineTransform(scaleX: 0.75, y: 0.75)
switch s.textAlignment {
case .left, .natural:
s.placeholderLabel.x = s.leftViewWidth
case .right:
s.placeholderLabel.x = s.width - s.placeholderLabel.width
default:break
}
s.placeholderLabel.y = -s.placeholderLabel.height + s.placeholderVerticalOffset
}) { [weak self] _ in
self?.isAnimating = false
}
}
/// The animation for the placeholder when editing ends.
fileprivate func placeholderEditingDidEndAnimation() {
updatePlaceholderLabelColor()
guard isPlaceholderAnimated else {
return
}
guard isEmpty && !isAnimating else {
return
}
isAnimating = true
UIView.animate(withDuration: 0.15, animations: { [weak self] in
guard let s = self else {
return
}
s.placeholderLabel.transform = CGAffineTransform.identity
s.placeholderLabel.x = s.leftViewWidth
s.placeholderLabel.y = 0
}) { [weak self] _ in
self?.isAnimating = false
}
}
}
| mit | e9468bbad1bc788cfb42945241d3193c | 28.758569 | 156 | 0.63757 | 5.204066 | false | false | false | false |
dhf/SwiftForms | SwiftForms/cells/base/FormBaseCell.swift | 1 | 2964 | //
// FormBaseCell.swift
// SwiftForms
//
// Created by Miguel Angel Ortuno on 20/08/14.
// Copyright (c) 2014 Miguel Angel Ortuño. All rights reserved.
//
import UIKit
public class FormBaseCell: UITableViewCell {
/// MARK: Properties
var rowDescriptor: FormRowDescriptor! {
didSet {
self.update()
}
}
public weak var formViewController: FormViewController!
private var customConstraints: [NSLayoutConstraint] = []
/// MARK: Public interface
public func configure() {
/// override
}
public func update() {
/// override
}
public func defaultVisualConstraints() -> [String] {
/// override
return []
}
public func constraintsViews() -> [String : UIView] {
/// override
return [:]
}
public func firstResponderElement() -> UIResponder? {
/// override
return nil
}
public func inputAccesoryView() -> UIToolbar {
let actionBar = UIToolbar()
actionBar.translucent = true
actionBar.sizeToFit()
actionBar.barStyle = .Default
let doneButton = UIBarButtonItem(title: NSLocalizedString("Done", comment: ""), style: .Done, target: self, action: "handleDoneAction:")
let flexible = UIBarButtonItem(barButtonSystemItem: .FlexibleSpace, target: nil, action: nil)
actionBar.items = [flexible, doneButton]
return actionBar
}
internal func handleDoneAction(_: UIBarButtonItem) {
firstResponderElement()?.resignFirstResponder()
}
public class func formRowCellHeight() -> CGFloat {
return 44.0
}
public class func formRowCanBecomeFirstResponder() -> Bool {
return false
}
public class func formViewController(formViewController: FormViewController, didSelectRow: FormBaseCell) {
}
/// MARK: Constraints
public override func updateConstraints() {
NSLayoutConstraint.deactivateConstraints(customConstraints)
customConstraints.removeAll()
let visualConstraints = rowDescriptor.configuration.visualConstraintsClosure.map { $0(self) } ?? defaultVisualConstraints()
let views = constraintsViews()
customConstraints = visualConstraints.flatMap { visualConstraint in
NSLayoutConstraint.constraintsWithVisualFormat(visualConstraint, options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: views)
}
NSLayoutConstraint.activateConstraints(customConstraints)
super.updateConstraints()
}
/// MARK: Init
public required override init(style: UITableViewCellStyle, reuseIdentifier: String!) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
}
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
}
| mit | d66df76aa2ea8c63b2142a5141c5f33b | 27.219048 | 149 | 0.635505 | 5.601134 | false | false | false | false |
mitchellporter/Speedometer | Speedometer/Controllers/CurrentSpeedViewController.swift | 1 | 2471 | import QuartzCore
import UIKit
class CurrentSpeedViewController: UIViewController {
var backgroundLayer: CAGradientLayer!
var speedometerView: SpeedometerView!
var currentSpeedLabel: UILabel!
override func viewDidLoad() {
self.backgroundLayer = CAGradientLayer()
self.setupBackgroundLayer()
self.view.layer.addSublayer(self.backgroundLayer)
let radius = 100.0
self.speedometerView = SpeedometerView(frame: self.speedometerFrame(radius), radius: radius, maxSpeed: 200.0)
self.view.addSubview(self.speedometerView)
self.currentSpeedLabel = UILabel(frame: self.view.frame)
self.currentSpeedLabel.center = self.speedometerView.center
self.currentSpeedLabel.textColor = UIColor.whiteColor()
self.currentSpeedLabel.font = UIFont(name: "Avenir", size: 36.0)
self.currentSpeedLabel.textAlignment = NSTextAlignment.Center
self.view.addSubview(self.currentSpeedLabel)
self.setSpeed(0.0)
self.startTimer()
}
func speedometerFrame(radius: Double) -> CGRect {
var speedometerFrame = CGRectMake(CGFloat(0.0), CGFloat(0.0), CGFloat(2 * radius + 25.0), CGFloat(2 * radius + 25.0))
speedometerFrame.origin.x = CGRectGetMidX(self.view.bounds) - CGRectGetMidX(speedometerFrame)
speedometerFrame.origin.y = CGRectGetMidY(self.view.bounds) - CGRectGetMidY(speedometerFrame)
return speedometerFrame
}
override func viewWillLayoutSubviews() {
self.setupBackgroundLayer()
}
func setupBackgroundLayer() {
let startColor = UIColor(red: 27.0/255.0, green: 214.0/255.0, blue: 253.0/255.0, alpha: 1.0);
let endColor = UIColor(red: 29.0/255.0, green: 98.0/255.0, blue: 240.0/255.0, alpha: 1.0);
self.backgroundLayer.locations = [0.0, 0.5]
self.backgroundLayer.colors = [startColor.CGColor, endColor.CGColor]
self.backgroundLayer.frame = self.view.bounds
}
func startTimer() {
NSTimer.scheduledTimerWithTimeInterval(1.0, target: self, selector: "updateSpeed", userInfo: nil, repeats: true)
}
func updateSpeed() {
let randomSpeed = 200.0 * Double(arc4random()) / 0xFFFFFFFF
self.setSpeed(randomSpeed)
}
func setSpeed(speed: Double) {
self.speedometerView.setSpeed(speed)
self.currentSpeedLabel.text = "\(Int(speed)) kmph"
}
}
| gpl-2.0 | d97f5bb20211b72580252afbcd4d02c1 | 38.222222 | 125 | 0.668555 | 4.159933 | false | false | false | false |
longitachi/ZLPhotoBrowser | Sources/General/ZLAddPhotoCell.swift | 1 | 2343 | //
// ZLAddPhotoCell.swift
// ZLPhotoBrowser
//
// Created by ruby109 on 2020/11/3.
//
// Copyright (c) 2020 Long Zhang <[email protected]>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import UIKit
import Foundation
class ZLAddPhotoCell: UICollectionViewCell {
private lazy var imageView: UIImageView = {
let view = UIImageView(image: .zl.getImage("zl_addPhoto"))
view.contentMode = .scaleAspectFit
view.clipsToBounds = true
return view
}()
override init(frame: CGRect) {
super.init(frame: frame)
setupUI()
}
deinit {
zl_debugPrint("ZLAddPhotoCell deinit")
}
@available(*, unavailable)
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func layoutSubviews() {
super.layoutSubviews()
imageView.frame = CGRect(x: 0, y: 0, width: bounds.width / 3, height: bounds.width / 3)
imageView.center = CGPoint(x: bounds.midX, y: bounds.midY)
}
func setupUI() {
layer.masksToBounds = true
layer.cornerRadius = ZLPhotoConfiguration.default().cellCornerRadio
backgroundColor = .zl.cameraCellBgColor
contentView.addSubview(imageView)
}
}
| mit | 0a6733c4b201d6e2c41cc64000737637 | 33.455882 | 95 | 0.682458 | 4.420755 | false | false | false | false |
abreis/swift-gissumo | scripts/parsers/archive/binAndWeighPositiveDecisions.swift | 1 | 4591 | /* This script takes a list of 'decisionCellCoverageEffects' data files.
* It then averages all post-coefficient decisions, binning by a specified
* bin width, and outputs the resulting calculations
*/
import Foundation
guard CommandLine.arguments.count == 3 else {
print("usage: \(CommandLine.arguments[0]) [list of data files] [binning width in seconds]")
exit(EXIT_FAILURE)
}
guard let binningWidth = UInt(CommandLine.arguments[2])
else {
print("ERROR: Invalid binning width.")
exit(EXIT_FAILURE)
}
var statFiles: String
do {
let statFilesURL = NSURL.fileURL(withPath: CommandLine.arguments[1])
_ = try statFilesURL.checkResourceIsReachable()
statFiles = try String(contentsOf: statFilesURL, encoding: String.Encoding.utf8)
} catch {
print(error)
exit(EXIT_FAILURE)
}
struct DecisionEntry {
var time: Double
var id: UInt
var dNew: Int
var dBoost: Int
var dSat: Int
var dScore: Double
var kappa: Double
var lambda: Double
var mu: Double
}
// Process statistics files
var decisionData: [DecisionEntry] = []
let statFileArray = statFiles.components(separatedBy: .newlines).filter({!$0.isEmpty})
guard statFileArray.count > 0 else {
print("Error: No statistics files provided.")
exit(EXIT_FAILURE)
}
for statFile in statFileArray {
// 1. Open and read the statFile into a string
var statFileData: String
do {
let statFileURL = NSURL.fileURL(withPath: statFile)
_ = try statFileURL.checkResourceIsReachable()
statFileData = try String(contentsOf: statFileURL, encoding: String.Encoding.utf8)
} catch {
print(error)
exit(EXIT_FAILURE)
}
// 2. Break the stat file into lines
var statFileLines: [String] = statFileData.components(separatedBy: .newlines).filter({!$0.isEmpty})
// 3. Drop the first line (header)
statFileLines.removeFirst()
// 4. Run through the statFile lines
for statFileLine in statFileLines {
// Split each line by tabs
let statFileLineColumns = statFileLine.components(separatedBy: "\t").filter({!$0.isEmpty})
guard let intime = Double(statFileLineColumns[0]),
let inid = UInt(statFileLineColumns[1]),
let indNew = Int(statFileLineColumns[2]),
let indBoost = Int(statFileLineColumns[3]),
let indSat = Int(statFileLineColumns[4]),
let indScore = Double(statFileLineColumns[5]),
let inkappa = Double(statFileLineColumns[6]),
let inlambda = Double(statFileLineColumns[7]),
let inmu = Double(statFileLineColumns[8])
else {
print("ERROR: Can't interpret input files.")
exit(EXIT_FAILURE)
}
var newDecision = DecisionEntry(time: intime, id: inid, dNew: indNew, dBoost: indBoost, dSat: indSat, dScore: indScore, kappa: inkappa, lambda: inlambda, mu: inmu)
// Push the decision into our array
decisionData.append(newDecision)
}
}
// Sort the array
decisionData.sort { $0.time < $1.time }
// Determine bins
let firstBin = UInt( decisionData.first!.time.subtracting(decisionData.first!.time.truncatingRemainder(dividingBy: Double(binningWidth)) ) )
let lastBin = UInt( decisionData.last!.time.subtracting(decisionData.last!.time.truncatingRemainder(dividingBy: Double(binningWidth)) ) )
var bins: [UInt] = []
var binIterator = firstBin
while(binIterator <= lastBin) {
bins.append(binIterator)
binIterator += binningWidth
}
struct SubDecisionEntry {
var dNew: Double = 0
var dBoost: Double = 0
var dSat: Double = 0
var dScore: Double = 0.0
}
var outputDictionary : [UInt:SubDecisionEntry] = [:]
var countStart = 0
binLoop: for bin in bins {
var decisions: UInt = 0
var accumulatedDecision = SubDecisionEntry()
// Decision array is sorted, so we brute iterate
decisionLoop: for index in countStart..<Int(decisionData.count) {
let decision = decisionData[index]
if(decision.time < Double(bin+binningWidth)) {
if(decision.dScore > 0) {
accumulatedDecision.dNew += Double(decision.dNew) * decision.kappa
accumulatedDecision.dBoost += Double(decision.dBoost) * decision.lambda
accumulatedDecision.dSat += Double(decision.dSat) * decision.mu
accumulatedDecision.dScore += decision.dScore
decisions += 1
}
} else {
break decisionLoop
}
countStart = index
}
accumulatedDecision.dNew /= Double(decisions)
accumulatedDecision.dBoost /= Double(decisions)
accumulatedDecision.dSat /= Double(decisions)
accumulatedDecision.dScore /= Double(decisions)
outputDictionary[bin] = accumulatedDecision
}
print("bin", "dNew", "dBoost", "dSat", "dScore", separator: "\t")
for (key, value) in outputDictionary.sorted(by: {$0.key < $1.key}) {
print(key, value.dNew, value.dBoost, value.dSat, value.dScore, separator: "\t")
}
| mit | 0cd72e65141e617a74fcf2f1008e6bd2 | 29.203947 | 165 | 0.732302 | 3.300503 | false | false | false | false |
normand1/TDDWeatherApp | TDDWeatherApp/TemperatureConverter.swift | 1 | 1442 | //
// TemperatureConverter.swift
// PigLatin
//
// Created by David Norman on 6/24/15.
// Copyright (c) 2015 Monsoon. All rights reserved.
//
import Foundation
class TemperatureConverter {
class func convertCtoF(_ celsius : Double)->Double {
let result = celsius * 1.8 + 32
return result
}
class func convertFtoC(_ fahrenheit : Double)-> Double? {
let result = ((fahrenheit - 32 ) * 5) / 9
return result
}
class func convertKtoC(_ kelvin : Double)->Double {
return kelvin - 273.15
}
class func convertCtoK(_ celsius : Double)->Double {
return celsius + 273.15
}
class func convertFtoK(_ fahrenheit : Double)->Double {
let result = (fahrenheit + 459.67) * (5 / 9)
return result
}
class func convertKtoF(_ kelvin : Double)->Double {
let result = (kelvin * (9/5)) - 459.67
return result
}
class func correctTempForCurrentMeasurementUnit(_ kelvin: Double, measurementUnit : MeasurementUnit)->Double? {
switch measurementUnit {
case MeasurementUnit.celsius:
var cTemp = self.convertKtoC(kelvin)
return cTemp
case MeasurementUnit.fahrenheit:
var fTemp = self.convertKtoF(kelvin)
return fTemp
case MeasurementUnit.kelvin:
return kelvin
}
}
}
| mit | f3b3d20ad7432ab00110c2da49a7a178 | 24.75 | 115 | 0.580444 | 4.369697 | false | false | false | false |
dropbox/SwiftyDropbox | Source/SwiftyDropbox/Shared/Handwritten/OAuth/AuthSession.swift | 1 | 4568 | ///
/// Copyright (c) 2020 Dropbox, Inc. All rights reserved.
///
import Foundation
import CommonCrypto
// MARK: Public
/// Struct contains the information of a requested scopes.
public struct ScopeRequest {
/// Type of the requested scopes.
public enum ScopeType: String {
case team
case user
}
/// An array of scopes to be granted.
let scopes: [String]
/// Boolean indicating whether to keep all previously granted scopes.
let includeGrantedScopes: Bool
/// Type of the scopes to be granted.
let scopeType: ScopeType
/// String representation of the scopes, used in URL query. Nil if the array is empty.
var scopeString: String? {
guard !scopes.isEmpty else { return nil }
return scopes.joined(separator: " ")
}
/// Designated Initializer.
///
/// - Parameters:
/// - scopeType: Type of the requested scopes.
/// - scopes: A list of scope returned by Dropbox server. Each scope correspond to a group of API endpoints.
/// To call one API endpoint you have to obtains the scope first otherwise you will get HTTP 401.
/// - includeGrantedScopes: If false, Dropbox will give you the scopes in scopes array.
/// Otherwise Dropbox server will return a token with all scopes user previously granted your app
/// together with the new scopes.
public init(scopeType: ScopeType, scopes: [String], includeGrantedScopes: Bool) {
self.scopeType = scopeType
self.scopes = scopes
self.includeGrantedScopes = includeGrantedScopes
}
}
// MARK: Internal
/// Object that contains all the necessary data of an OAuth 2 Authorization Code Flow with PKCE.s
struct OAuthPKCESession {
// The scope request for this auth session.
let scopeRequest: ScopeRequest?
// PKCE data generated for this auth session.
let pkceData: PkceData
// A string of colon-delimited options/state - used primarily to indicate if the token type to be returned.
let state: String
// Token access type, hardcoded to "offline" to indicate short-lived access token + refresh token.
let tokenAccessType = "offline"
// Type of the auth response, hardcoded to "code" to indicate code flow.
let responseType = "code"
init(scopeRequest: ScopeRequest?) {
self.pkceData = PkceData()
self.scopeRequest = scopeRequest
self.state = Self.createState(with: pkceData, scopeRequest: scopeRequest, tokenAccessType: tokenAccessType)
}
private static func createState(
with pkceData: PkceData, scopeRequest: ScopeRequest?, tokenAccessType: String
) -> String {
var state = ["oauth2code", pkceData.codeChallenge, pkceData.codeChallengeMethod, tokenAccessType]
if let scopeRequest = scopeRequest {
if let scopeString = scopeRequest.scopeString {
state.append(scopeString)
}
if scopeRequest.includeGrantedScopes {
state.append(scopeRequest.scopeType.rawValue)
}
}
return state.joined(separator: ":")
}
}
/// PKCE data for OAuth 2 Authorization Code Flow.
struct PkceData {
// A random string generated for each code flow.
let codeVerifier = Self.randomStringOfLength(128)
// A string derived from codeVerifier by using BASE64URL-ENCODE(SHA256(ASCII(code_verifier))).
let codeChallenge: String
// The hash method used to generate codeChallenge.
let codeChallengeMethod = "S256"
init() {
self.codeChallenge = Self.codeChallengeFromCodeVerifier(codeVerifier)
}
private static func randomStringOfLength(_ length: Int) -> String {
let alphanumerics = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
return String((0..<length).map { _ in alphanumerics.randomElement()! })
}
private static func codeChallengeFromCodeVerifier(_ codeVerifier: String) -> String {
guard let data = codeVerifier.data(using: .ascii) else { fatalError("Failed to create code challenge.") }
var digest = [UInt8](repeating: 0, count:Int(CC_SHA256_DIGEST_LENGTH))
_ = data.withUnsafeBytes {
CC_SHA256($0.baseAddress, UInt32(data.count), &digest)
}
/// Replace these characters to make the string safe to use in a URL.
return Data(digest).base64EncodedString()
.replacingOccurrences(of: "/", with: "_")
.replacingOccurrences(of: "+", with: "-")
.replacingOccurrences(of: "=", with: "")
}
}
| mit | a78c93af7967ce39521ed90ae4b1acde | 39.070175 | 116 | 0.672067 | 4.527255 | false | false | false | false |
PureSwift/BluetoothLinux | Sources/BluetoothLinux/RFCOMM/RFCOMMDevice.swift | 1 | 924 | //
// RFCOMMDevice.swift
//
//
// Created by Alsey Coleman Miller on 27/10/21.
//
import Bluetooth
import SystemPackage
/// RFCOMM Device Information
@frozen
public struct RFCOMMDevice: Equatable, Hashable {
public let id: HostController.ID
public var flags: BitMaskOptionSet<RFCOMMFlag>
public var state: RFCOMMState
public var source: BluetoothAddress
public var destination: BluetoothAddress
public var channel: UInt8
}
extension RFCOMMDevice: Identifiable { }
internal extension RFCOMMDevice {
@usableFromInline
init(_ cValue: CInterop.RFCOMMDeviceInformation) {
self.id = .init(rawValue: cValue.id)
self.flags = .init(rawValue: cValue.flags)
self.state = .init(rawValue: cValue.state) ?? .unknown
self.source = cValue.source
self.destination = cValue.source
self.channel = cValue.channel
}
}
| mit | 5888a0f3da61851847a75f783ca48903 | 21.536585 | 62 | 0.676407 | 4.088496 | false | false | false | false |
futomtom/DynoOrder | Dyno/DynoOrder/putOrderVC.swift | 1 | 11381 | //
// ExampleViewController.swift
// Segmentio
//
// Created by Dmitriy Demchenko
// Copyright © 2016 Yalantis Mobile. All rights reserved.
//
import UIKit
import Segmentio
import SideMenu
import RealmSwift
class putOrderVC: UIViewController {
var segmentioStyle = SegmentioStyle.imageBeforeLabel
@IBOutlet weak var collectionView: UICollectionView!
@IBOutlet fileprivate weak var segmentViewHeightConstraint: NSLayoutConstraint!
@IBOutlet fileprivate weak var segmentioView: Segmentio!
@IBOutlet fileprivate weak var containerView: UIView!
// @IBOutlet fileprivate weak var scrollView: UIScrollView!
fileprivate lazy var viewControllers: [UIViewController] = []
var realm: Realm!
var products: Results<Product>!
var order: Order!
var beginOrder = false
// MARK: - Init
class func create() -> putOrderVC {
let board = UIStoryboard(name: "Main", bundle: nil)
return board.instantiateViewController(withIdentifier: String(describing: self)) as! putOrderVC
}
// MARK: - Lifecycle
override func viewDidLoad() {
super.viewDidLoad()
realm = try! Realm(configuration: RealmConfig.Main.configuration)
switch segmentioStyle {
case .onlyLabel, .imageBeforeLabel, .imageAfterLabel:
segmentViewHeightConstraint.constant = 50
case .onlyImage:
segmentViewHeightConstraint.constant = 100
default:
break
}
(collectionView.collectionViewLayout as! UICollectionViewFlowLayout).sectionHeadersPinToVisibleBounds = true
LoadData()
setupSideMenu()
}
func LoadData() {
products = Product.all(realm: realm)
print(products.count)
}
@IBAction func orderSwitch_ValueChange(_ sender: UISwitch) {
if sender.isOn {
BeginOrder()
} else {
let alertController = UIAlertController(title: NSLocalizedString("Clean Order", comment: ""), message: NSLocalizedString("Clean Order", comment: ""), preferredStyle: UIAlertControllerStyle.alert)
let cancelAction = UIAlertAction(title: NSLocalizedString("Clean Order", comment: ""), style: .cancel) { _ in
sender.isOn = true
}
alertController.addAction(cancelAction)
let OKAction = UIAlertAction(title: NSLocalizedString("Clean Order", comment: ""), style: .default) { _ in
self.CleanOrder()
}
alertController.addAction(OKAction)
self.present(alertController, animated: true, completion: nil)
}
}
func BeginOrder() {
order = Order()
order.name = "hi"
beginOrder = true
}
func CleanOrder() {
beginOrder = false
}
fileprivate func setupSideMenu() {
// Define the menus
SideMenuManager.menuLeftNavigationController = storyboard!.instantiateViewController(withIdentifier: "LeftMenuNavigationController") as? UISideMenuNavigationController
SideMenuManager.menuRightNavigationController = storyboard!.instantiateViewController(withIdentifier: "RightMenuNavigationController") as? UISideMenuNavigationController
// Enable gestures. The left and/or right menus must be set up above for these to work.
// Note that these continue to work on the Navigation Controller independent of the View Controller it displays!
SideMenuManager.menuAddPanGestureToPresent(toView: self.navigationController!.navigationBar)
SideMenuManager.menuAddScreenEdgePanGesturesToPresent(toView: self.navigationController!.view)
}
func collectionView(_ collectionView: UICollectionView,
viewForSupplementaryElementOfKind kind: String,
at indexPath: IndexPath) -> UICollectionReusableView {
switch kind {
case UICollectionElementKindSectionHeader:
let headerView: CollectionHeadView = collectionView.dequeueReusableSupplementaryView(ofKind: kind,
withReuseIdentifier: "headview",
for: indexPath) as! CollectionHeadView
return headerView
default:
fatalError("Unexpected element kind")
}
}
@IBAction func OpenMainMenu(_ sender: Any) { present(SideMenuManager.menuLeftNavigationController!, animated: true, completion: nil)
}
@IBAction func OpenSideMenu(_ sender: Any) {
present(SideMenuManager.menuRightNavigationController!, animated: true, completion: nil)
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
setupSegmentioView()
setupBadgeCountForIndex(1)
}
@IBAction func StepperValueChange(_ sender: UIStepper) {
guard beginOrder else {
sender.value = 0
return
}
/*
let items = realm.
.query(order.class)
.contains("PurchaseItem.product.pid", products[sender.tag].pid)
.findAll()
if items == nil {
} else {
items.
}
*/
let indexPath = IndexPath(item: sender.tag, section: 0)
// if order.itemList.contains(PurchaseItem)
let cell = collectionView.cellForItem(at: indexPath) as! ItemCell
cell.number.text = "\(Int(sender.value))"
}
}
extension putOrderVC: UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return products.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell: ItemCell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! ItemCell
cell.setData(item: products[indexPath.row], index: indexPath.row)
return cell
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
print(products[indexPath.row].name)
let cell = collectionView.cellForItem(at: indexPath)
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let width = (UIScreen.main.bounds.width - 10 * 5) / 3
return CGSize(width: width, height: width)
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
return UIEdgeInsetsMake(0, 10, 0, 10)
}
}
extension putOrderVC {
fileprivate func setupSegmentioView() {
segmentioView.setup(
content: segmentioContent(),
style: segmentioStyle,
options: segmentioOptions()
)
segmentioView.selectedSegmentioIndex = selectedSegmentioIndex()
segmentioView.valueDidChange = { [weak self] _, segmentIndex in
print (segmentIndex)
}
}
fileprivate func setupBadgeCountForIndex(_ index: Int) {
segmentioView.addBadge(at: index, count: 10, color: ColorPalette.coral)
}
fileprivate func segmentioContent() -> [SegmentioItem] {
return [
SegmentioItem(title: "菜", image: UIImage(named: "tornado")),
SegmentioItem(title: "湯", image: UIImage(named: "earthquakes")),
SegmentioItem(title: "素", image: UIImage(named: "heat")),
SegmentioItem(title: "點心", image: UIImage(named: "eruption")),
SegmentioItem(title: "飲料", image: UIImage(named: "floods")),
SegmentioItem(title: "飯", image: UIImage(named: "wildfires"))
]
}
fileprivate func segmentioOptions() -> SegmentioOptions {
var imageContentMode = UIViewContentMode.center
switch segmentioStyle {
case .imageBeforeLabel, .imageAfterLabel:
imageContentMode = .scaleAspectFit
default:
break
}
return SegmentioOptions(
backgroundColor: ColorPalette.white,
maxVisibleItems: 3,
scrollEnabled: true,
indicatorOptions: segmentioIndicatorOptions(),
horizontalSeparatorOptions: segmentioHorizontalSeparatorOptions(),
verticalSeparatorOptions: segmentioVerticalSeparatorOptions(),
imageContentMode: imageContentMode,
labelTextAlignment: .center,
segmentStates: segmentioStates()
)
}
fileprivate func segmentioStates() -> SegmentioStates {
let font = UIFont(name: "Avenir-Book", size: 13)!
return SegmentioStates(
defaultState: segmentioState(
backgroundColor: .clear,
titleFont: font,
titleTextColor: ColorPalette.grayChateau
),
selectedState: segmentioState(
backgroundColor: .clear,
titleFont: font,
titleTextColor: ColorPalette.black
),
highlightedState: segmentioState(
backgroundColor: ColorPalette.whiteSmoke,
titleFont: font,
titleTextColor: ColorPalette.grayChateau
)
)
}
fileprivate func segmentioState(backgroundColor: UIColor, titleFont: UIFont, titleTextColor: UIColor) -> SegmentioState {
return SegmentioState(backgroundColor: backgroundColor, titleFont: titleFont, titleTextColor: titleTextColor)
}
fileprivate func segmentioIndicatorOptions() -> SegmentioIndicatorOptions {
return SegmentioIndicatorOptions(type: .bottom, ratio: 1, height: 5, color: ColorPalette.coral)
}
fileprivate func segmentioHorizontalSeparatorOptions() -> SegmentioHorizontalSeparatorOptions {
return SegmentioHorizontalSeparatorOptions(type: .topAndBottom, height: 1, color: ColorPalette.whiteSmoke)
}
fileprivate func segmentioVerticalSeparatorOptions() -> SegmentioVerticalSeparatorOptions {
return SegmentioVerticalSeparatorOptions(ratio: 1, color: ColorPalette.whiteSmoke)
}
fileprivate func selectedSegmentioIndex() -> Int {
return 0
}
}
| mit | 6ca257d5705ca67cf6f3c5eb0e79af76 | 33.858896 | 207 | 0.606829 | 5.906445 | false | false | false | false |
futomtom/DynoOrder | Segmentio/Source/Segmentio.swift | 2 | 23281 | //
// Segmentio.swift
// Segmentio
//
// Created by Dmitriy Demchenko
// Copyright © 2016 Yalantis Mobile. All rights reserved.
//
import UIKit
import QuartzCore
public typealias SegmentioSelectionCallback = ((_ segmentio: Segmentio, _ selectedSegmentioIndex: Int) -> Void)
private let animationDuration: CFTimeInterval = 0.3
open class Segmentio: UIView {
internal struct Points {
var startPoint: CGPoint
var endPoint: CGPoint
}
internal struct Context {
var isFirstCell: Bool
var isLastCell: Bool
var isLastOrPrelastVisibleCell: Bool
var isFirstOrSecondVisibleCell: Bool
var isFirstIndex: Bool
}
internal struct ItemInSuperview {
var collectionViewWidth: CGFloat
var cellFrameInSuperview: CGRect
var shapeLayerWidth: CGFloat
var startX: CGFloat
var endX: CGFloat
}
open var valueDidChange: SegmentioSelectionCallback?
open var selectedSegmentioIndex = -1 {
didSet {
if selectedSegmentioIndex != oldValue {
reloadSegmentio()
valueDidChange?(self, selectedSegmentioIndex)
}
}
}
fileprivate var segmentioCollectionView: UICollectionView?
fileprivate var segmentioItems = [SegmentioItem]()
fileprivate var segmentioOptions = SegmentioOptions()
fileprivate var segmentioStyle = SegmentioStyle.imageOverLabel
fileprivate var isPerformingScrollAnimation = false
fileprivate var topSeparatorView: UIView?
fileprivate var bottomSeparatorView: UIView?
fileprivate var indicatorLayer: CAShapeLayer?
fileprivate var selectedLayer: CAShapeLayer?
fileprivate var cachedOrientation: UIInterfaceOrientation? = UIApplication.shared.statusBarOrientation {
didSet {
if cachedOrientation != oldValue {
reloadSegmentio()
}
}
}
// MARK: - Lifecycle
deinit {
NotificationCenter.default.removeObserver(self)
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
commonInit()
}
override public init(frame: CGRect) {
super.init(frame: frame)
commonInit()
}
fileprivate func commonInit() {
setupSegmentedCollectionView()
NotificationCenter.default.addObserver(
self,
selector: #selector(Segmentio.handleOrientationNotification),
name: NSNotification.Name.UIDeviceOrientationDidChange,
object: nil
)
}
fileprivate func setupSegmentedCollectionView() {
let layout = UICollectionViewFlowLayout()
layout.sectionInset = UIEdgeInsets.zero
layout.scrollDirection = .horizontal
layout.minimumInteritemSpacing = 0
layout.minimumLineSpacing = 0
let collectionView = UICollectionView(
frame: frameForSegmentCollectionView(),
collectionViewLayout: layout
)
collectionView.dataSource = self
collectionView.delegate = self
collectionView.isPagingEnabled = false
collectionView.showsHorizontalScrollIndicator = false
collectionView.showsVerticalScrollIndicator = false
collectionView.bounces = true
collectionView.isScrollEnabled = segmentioOptions.scrollEnabled
collectionView.backgroundColor = .clear
segmentioCollectionView = collectionView
if let segmentioCollectionView = segmentioCollectionView {
addSubview(segmentioCollectionView, options: .overlay)
}
}
fileprivate func frameForSegmentCollectionView() -> CGRect {
var separatorsHeight: CGFloat = 0
var collectionViewFrameMinY: CGFloat = 0
if let horizontalSeparatorOptions = segmentioOptions.horizontalSeparatorOptions {
let separatorHeight = horizontalSeparatorOptions.height
switch horizontalSeparatorOptions.type {
case .top:
collectionViewFrameMinY = separatorHeight
separatorsHeight = separatorHeight
case .bottom:
separatorsHeight = separatorHeight
case .topAndBottom:
collectionViewFrameMinY = separatorHeight
separatorsHeight = separatorHeight * 2
}
}
return CGRect(
x: 0,
y: collectionViewFrameMinY,
width: bounds.width,
height: bounds.height - separatorsHeight
)
}
// MARK: - Handle orientation notification
@objc fileprivate func handleOrientationNotification() {
cachedOrientation = UIApplication.shared.statusBarOrientation
}
// MARK: - Setups:
// MARK: Main setup
open func setup(content: [SegmentioItem], style: SegmentioStyle, options: SegmentioOptions?) {
segmentioItems = content
segmentioStyle = style
selectedLayer?.removeFromSuperlayer()
indicatorLayer?.removeFromSuperlayer()
if let options = options {
segmentioOptions = options
segmentioCollectionView?.isScrollEnabled = segmentioOptions.scrollEnabled
backgroundColor = options.backgroundColor
}
if segmentioOptions.states.selectedState.backgroundColor != .clear {
selectedLayer = CAShapeLayer()
if let selectedLayer = selectedLayer, let sublayer = segmentioCollectionView?.layer {
setupShapeLayer(
shapeLayer: selectedLayer,
backgroundColor: segmentioOptions.states.selectedState.backgroundColor,
height: bounds.height,
sublayer: sublayer
)
}
}
if let indicatorOptions = segmentioOptions.indicatorOptions {
indicatorLayer = CAShapeLayer()
if let indicatorLayer = indicatorLayer {
setupShapeLayer(
shapeLayer: indicatorLayer,
backgroundColor: indicatorOptions.color,
height: indicatorOptions.height,
sublayer: layer
)
}
}
setupHorizontalSeparatorIfPossible()
setupCellWithStyle(segmentioStyle)
segmentioCollectionView?.reloadData()
}
open override func didMoveToSuperview() {
super.didMoveToSuperview()
setupHorizontalSeparatorIfPossible()
}
open func addBadge(at index: Int, count: Int, color: UIColor = .red) {
segmentioItems[index].addBadge(count, color: color)
segmentioCollectionView?.reloadData()
}
open func removeBadge(at index: Int) {
segmentioItems[index].removeBadge()
segmentioCollectionView?.reloadData()
}
// MARK: Collection view setup
fileprivate func setupCellWithStyle(_ style: SegmentioStyle) {
var cellClass: SegmentioCell.Type {
switch style {
case .onlyLabel:
return SegmentioCellWithLabel.self
case .onlyImage:
return SegmentioCellWithImage.self
case .imageOverLabel:
return SegmentioCellWithImageOverLabel.self
case .imageUnderLabel:
return SegmentioCellWithImageUnderLabel.self
case .imageBeforeLabel:
return SegmentioCellWithImageBeforeLabel.self
case .imageAfterLabel:
return SegmentioCellWithImageAfterLabel.self
}
}
segmentioCollectionView?.register(
cellClass,
forCellWithReuseIdentifier: segmentioStyle.rawValue
)
segmentioCollectionView?.layoutIfNeeded()
}
// MARK: Horizontal separators setup
fileprivate func setupHorizontalSeparatorIfPossible() {
if superview != nil && segmentioOptions.horizontalSeparatorOptions != nil {
setupHorizontalSeparator()
}
}
fileprivate func setupHorizontalSeparator() {
topSeparatorView?.removeFromSuperview()
bottomSeparatorView?.removeFromSuperview()
guard let horizontalSeparatorOptions = segmentioOptions.horizontalSeparatorOptions else {
return
}
let height = horizontalSeparatorOptions.height
let type = horizontalSeparatorOptions.type
if type == .top || type == .topAndBottom {
topSeparatorView = UIView(frame: CGRect.zero)
setupConstraintsForSeparatorView(
separatorView: topSeparatorView,
originY: 0
)
}
if type == .bottom || type == .topAndBottom {
bottomSeparatorView = UIView(frame: CGRect.zero)
setupConstraintsForSeparatorView(
separatorView: bottomSeparatorView,
originY: frame.maxY - height
)
}
}
fileprivate func setupConstraintsForSeparatorView(separatorView: UIView?, originY: CGFloat) {
guard let horizontalSeparatorOptions = segmentioOptions.horizontalSeparatorOptions, let separatorView = separatorView else {
return
}
separatorView.translatesAutoresizingMaskIntoConstraints = false
separatorView.backgroundColor = horizontalSeparatorOptions.color
addSubview(separatorView)
let topConstraint = NSLayoutConstraint(
item: separatorView,
attribute: .top,
relatedBy: .equal,
toItem: superview,
attribute: .top,
multiplier: 1,
constant: originY
)
topConstraint.isActive = true
let leadingConstraint = NSLayoutConstraint(
item: separatorView,
attribute: .leading,
relatedBy: .equal,
toItem: self,
attribute: .leading,
multiplier: 1,
constant: 0
)
leadingConstraint.isActive = true
let trailingConstraint = NSLayoutConstraint(
item: separatorView,
attribute: .trailing,
relatedBy: .equal,
toItem: self,
attribute: .trailing,
multiplier: 1,
constant: 0
)
trailingConstraint.isActive = true
let heightConstraint = NSLayoutConstraint(
item: separatorView,
attribute: .height,
relatedBy: .equal,
toItem: nil,
attribute: .notAnAttribute,
multiplier: 1,
constant: horizontalSeparatorOptions.height
)
heightConstraint.isActive = true
}
// MARK: CAShapeLayers setup
fileprivate func setupShapeLayer(shapeLayer: CAShapeLayer, backgroundColor: UIColor, height: CGFloat, sublayer: CALayer) {
shapeLayer.fillColor = backgroundColor.cgColor
shapeLayer.strokeColor = backgroundColor.cgColor
shapeLayer.lineWidth = height
layer.insertSublayer(shapeLayer, below: sublayer)
}
// MARK: - Actions:
// MARK: Reload segmentio
fileprivate func reloadSegmentio() {
segmentioCollectionView?.reloadData()
scrollToItemAtContext()
moveShapeLayerAtContext()
}
// MARK: Move shape layer to item
fileprivate func moveShapeLayerAtContext() {
if let indicatorLayer = indicatorLayer, let options = segmentioOptions.indicatorOptions {
let item = itemInSuperview(ratio: options.ratio)
let context = contextForItem(item)
let points = Points(
context: context,
item: item,
pointY: indicatorPointY()
)
moveShapeLayer(
indicatorLayer,
startPoint: points.startPoint,
endPoint: points.endPoint,
animated: true
)
}
if let selectedLayer = selectedLayer {
let item = itemInSuperview()
let context = contextForItem(item)
let points = Points(
context: context,
item: item,
pointY: bounds.midY
)
moveShapeLayer(
selectedLayer,
startPoint: points.startPoint,
endPoint: points.endPoint,
animated: true
)
}
}
// MARK: Scroll to item
fileprivate func scrollToItemAtContext() {
guard let numberOfSections = segmentioCollectionView?.numberOfSections else {
return
}
let item = itemInSuperview()
let context = contextForItem(item)
if context.isLastOrPrelastVisibleCell == true {
let newIndex = selectedSegmentioIndex + (context.isLastCell ? 0 : 1)
let newIndexPath = IndexPath(item: newIndex, section: numberOfSections - 1)
segmentioCollectionView?.scrollToItem(
at: newIndexPath,
at: UICollectionViewScrollPosition(),
animated: true
)
}
if context.isFirstOrSecondVisibleCell == true {
let newIndex = selectedSegmentioIndex - (context.isFirstIndex ? 1 : 0)
let newIndexPath = IndexPath(item: newIndex, section: numberOfSections - 1)
segmentioCollectionView?.scrollToItem(
at: newIndexPath,
at: UICollectionViewScrollPosition(),
animated: true
)
}
}
// MARK: Move shape layer
fileprivate func moveShapeLayer(_ shapeLayer: CAShapeLayer, startPoint: CGPoint, endPoint: CGPoint, animated: Bool = false) {
var endPointWithVerticalSeparator = endPoint
let isLastItem = selectedSegmentioIndex + 1 == segmentioItems.count
endPointWithVerticalSeparator.x = endPoint.x - (isLastItem ? 0 : 1)
let shapeLayerPath = UIBezierPath()
shapeLayerPath.move(to: startPoint)
shapeLayerPath.addLine(to: endPointWithVerticalSeparator)
if animated == true {
isPerformingScrollAnimation = true
isUserInteractionEnabled = false
CATransaction.begin()
let animation = CABasicAnimation(keyPath: "path")
animation.fromValue = shapeLayer.path
animation.toValue = shapeLayerPath.cgPath
animation.duration = animationDuration
CATransaction.setCompletionBlock() {
self.isPerformingScrollAnimation = false
self.isUserInteractionEnabled = true
}
shapeLayer.add(animation, forKey: "path")
CATransaction.commit()
}
shapeLayer.path = shapeLayerPath.cgPath
}
// MARK: - Context for item
fileprivate func contextForItem(_ item: ItemInSuperview) -> Context {
let cellFrame = item.cellFrameInSuperview
let cellWidth = cellFrame.width
let lastCellMinX = floor(item.collectionViewWidth - cellWidth)
let minX = floor(cellFrame.minX)
let maxX = floor(cellFrame.maxX)
let isLastVisibleCell = maxX >= item.collectionViewWidth
let isLastVisibleCellButOne = minX < lastCellMinX && maxX > lastCellMinX
let isFirstVisibleCell = minX <= 0
let isNextAfterFirstVisibleCell = minX < cellWidth && maxX > cellWidth
return Context(
isFirstCell: selectedSegmentioIndex == 0,
isLastCell: selectedSegmentioIndex == segmentioItems.count - 1,
isLastOrPrelastVisibleCell: isLastVisibleCell || isLastVisibleCellButOne,
isFirstOrSecondVisibleCell: isFirstVisibleCell || isNextAfterFirstVisibleCell,
isFirstIndex: selectedSegmentioIndex > 0
)
}
// MARK: - Item in superview
fileprivate func itemInSuperview(ratio: CGFloat = 1) -> ItemInSuperview {
var collectionViewWidth: CGFloat = 0
var cellWidth: CGFloat = 0
var cellRect = CGRect.zero
var shapeLayerWidth: CGFloat = 0
if let collectionView = segmentioCollectionView {
collectionViewWidth = collectionView.frame.width
let maxVisibleItems = segmentioOptions.maxVisibleItems > segmentioItems.count ? CGFloat(segmentioItems.count) : CGFloat(segmentioOptions.maxVisibleItems)
cellWidth = floor(collectionViewWidth / maxVisibleItems)
cellRect = CGRect(
x: floor(CGFloat(selectedSegmentioIndex) * cellWidth - collectionView.contentOffset.x),
y: 0,
width: floor(collectionViewWidth / maxVisibleItems),
height: collectionView.frame.height
)
shapeLayerWidth = floor(cellWidth * ratio)
}
return ItemInSuperview(
collectionViewWidth: collectionViewWidth,
cellFrameInSuperview: cellRect,
shapeLayerWidth: shapeLayerWidth,
startX: floor(cellRect.midX - (shapeLayerWidth / 2)),
endX: floor(cellRect.midX + (shapeLayerWidth / 2))
)
}
// MARK: - Indicator point Y
fileprivate func indicatorPointY() -> CGFloat {
var indicatorPointY: CGFloat = 0
guard let indicatorOptions = segmentioOptions.indicatorOptions else {
return indicatorPointY
}
switch indicatorOptions.type {
case .top:
indicatorPointY = (indicatorOptions.height / 2)
case .bottom:
indicatorPointY = frame.height - (indicatorOptions.height / 2)
}
guard let horizontalSeparatorOptions = segmentioOptions.horizontalSeparatorOptions else {
return indicatorPointY
}
let separatorHeight = horizontalSeparatorOptions.height
let isIndicatorTop = indicatorOptions.type == .top
switch horizontalSeparatorOptions.type {
case .top:
indicatorPointY = isIndicatorTop ? indicatorPointY + separatorHeight : indicatorPointY
case .bottom:
indicatorPointY = isIndicatorTop ? indicatorPointY : indicatorPointY - separatorHeight
case .topAndBottom:
indicatorPointY = isIndicatorTop ? indicatorPointY + separatorHeight : indicatorPointY - separatorHeight
}
return indicatorPointY
}
}
// MARK: - UICollectionViewDataSource
extension Segmentio: UICollectionViewDataSource {
public func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return segmentioItems.count
}
public func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(
withReuseIdentifier: segmentioStyle.rawValue,
for: indexPath) as! SegmentioCell
cell.configure(
content: segmentioItems[indexPath.row],
style: segmentioStyle,
options: segmentioOptions,
isLastCell: indexPath.row == segmentioItems.count - 1
)
cell.configure(selected: (indexPath.row == selectedSegmentioIndex))
return cell
}
}
// MARK: - UICollectionViewDelegate
extension Segmentio: UICollectionViewDelegate {
public func collectionView(_ collectionView: UICollectionView, shouldSelectItemAt indexPath: IndexPath) -> Bool {
return true
}
public func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
selectedSegmentioIndex = indexPath.row
}
}
// MARK: - UICollectionViewDelegateFlowLayout
extension Segmentio: UICollectionViewDelegateFlowLayout {
public func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let maxVisibleItems = segmentioOptions.maxVisibleItems > segmentioItems.count ? CGFloat(segmentioItems.count) : CGFloat(segmentioOptions.maxVisibleItems)
return CGSize( width: floor(collectionView.frame.width / maxVisibleItems), height: collectionView.frame.height)
}
}
// MARK: - UIScrollViewDelegate
extension Segmentio: UIScrollViewDelegate {
public func scrollViewDidScroll(_ scrollView: UIScrollView) {
if isPerformingScrollAnimation {
return
}
if let options = segmentioOptions.indicatorOptions, let indicatorLayer = indicatorLayer {
let item = itemInSuperview(ratio: options.ratio)
moveShapeLayer(
indicatorLayer,
startPoint: CGPoint(x: item.startX, y: indicatorPointY()),
endPoint: CGPoint(x: item.endX, y: indicatorPointY()),
animated: false
)
}
if let selectedLayer = selectedLayer {
let item = itemInSuperview()
moveShapeLayer(
selectedLayer,
startPoint: CGPoint(x: item.startX, y: bounds.midY),
endPoint: CGPoint(x: item.endX, y: bounds.midY),
animated: false
)
}
}
}
extension Segmentio.Points {
init(context: Segmentio.Context, item: Segmentio.ItemInSuperview, pointY: CGFloat) {
let cellWidth = item.cellFrameInSuperview.width
var startX = item.startX
var endX = item.endX
if context.isFirstCell == false && context.isLastCell == false {
if context.isLastOrPrelastVisibleCell == true {
let updatedStartX = item.collectionViewWidth - (cellWidth * 2) + ((cellWidth - item.shapeLayerWidth) / 2)
startX = updatedStartX
let updatedEndX = updatedStartX + item.shapeLayerWidth
endX = updatedEndX
}
if context.isFirstOrSecondVisibleCell == true {
let updatedEndX = (cellWidth * 2) - ((cellWidth - item.shapeLayerWidth) / 2)
endX = updatedEndX
let updatedStartX = updatedEndX - item.shapeLayerWidth
startX = updatedStartX
}
}
if context.isFirstCell == true {
startX = (cellWidth - item.shapeLayerWidth) / 2
endX = startX + item.shapeLayerWidth
}
if context.isLastCell == true {
startX = item.collectionViewWidth - cellWidth + (cellWidth - item.shapeLayerWidth) / 2
endX = startX + item.shapeLayerWidth
}
startPoint = CGPoint(x: startX, y: pointY)
endPoint = CGPoint(x: endX, y: pointY)
}
}
| mit | b3a26707fa9fe652287de3eefb89d47e | 33.902549 | 167 | 0.61177 | 5.923664 | false | false | false | false |
wireapp/wire-ios | Wire-iOS/Sources/UserInterface/Conversation/InputBar/URLs+zip.swift | 1 | 1108 | // Wire
// Copyright (C) 2020 Wire Swiss GmbH
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
import Foundation
import ZipArchive
extension Array where Element == URL {
func zipFiles(filename: String = "archive.zip") -> URL? {
let archiveURL = URL(fileURLWithPath: NSTemporaryDirectory() + filename)
let paths = map {$0.path}
let zipSucceded = SSZipArchive.createZipFile(atPath: archiveURL.path, withFilesAtPaths: paths)
return zipSucceded ? archiveURL : nil
}
}
| gpl-3.0 | 95ab96f2b53e0120425b0ab17089dbc3 | 34.741935 | 102 | 0.723827 | 4.294574 | false | false | false | false |
svdo/ipatool | IpaTool/ITMain.swift | 1 | 1091 | //
// ITMain.swift
// IpaTool
//
// Created by Stefan on 01/10/14.
// Copyright (c) 2014 Stefan van den Oord. All rights reserved.
//
import Foundation
class ITMain
{
class func version() -> String {
return "1.0"
}
let commandFactory : ITCommandFactory = ITCommandFactory()
func run(_ args:[String]) -> String
{
let command = commandForArguments(args)
var output:String
if let c = command {
output = c.execute(args)
}
else {
output = "Invocation error. Please refer to documentation."
}
return output
}
func commandForArguments(_ args:[String]) -> ITCommand?
{
var commandName = ""
switch (args.count) {
case 0: commandName = "usage"
case 1: commandName = "info"
default: commandName = args[1]
}
var command = commandFactory.commandWithName(commandName)
if command == nil {
command = commandFactory.commandWithName("usage")
}
return command
}
}
| mit | 4f19f050df0a364e8f1be58064bf7381 | 22.212766 | 71 | 0.55912 | 4.329365 | false | false | false | false |
dboyliao/NumSwift | NumSwift/dev/type_query.swift | 2 | 509 | #!/usr/bin/env xcrun swift
class MyClass<T> {
typealias Element = T
let int:Int
init(num:Int){
self.int = num
}
func say(){
switch (self.int, Element.self) {
case (1, is Double.Type):
print("Double!")
case (2, is Float.Type):
print("Float!")
default:
print("Something else")
}
}
}
let d = MyClass<Double>(num: 1)
let f = MyClass<Float>(num: 2)
let i = MyClass<Int>(num: 2)
d.say()
f.say()
i.say() | mit | 06de5b73a924d17c0a7b045fb08479bb | 16.586207 | 41 | 0.508841 | 3.305195 | false | false | false | false |
michaelradtke/NSData-ByteView | NSData+ByteViewTests/Data+ByteViewTests.swift | 1 | 8073 | //
// Data+ByteViewTests.swift
//
// Copyright (c) 2015 Michael Radtke
//
// 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 XCTest
@testable import NSData_ByteView
class Data_ByteViewTests: XCTestCase {
let byteArray: ByteArray = [0, 1, (Byte.max - 1), Byte.max]
let singleWordArray: SingleWordArray = [1, (SingleWord.max - 1)]
let doubleWordArray: DoubleWordArray = [1, (DoubleWord.max - 1), 0x34dc296e]
let longArray: LongArray = [1, (Long.max - 1), 0x8712dc4fa30d7af9]
// MARK: -
func testHexString() {
let testHash = "€@&Ai∆".data(using: String.Encoding.utf8)! // Has a hex value of e282ac40264169e28886
XCTAssertEqual(testHash.hexString, "e282ac40264169e28886")
}
// MARK: - Test that Data can be created from different values
// MARK: Byte
func testByteCreateable_Sequence_Array() {
let data = Data(byteSequence: byteArray)
XCTAssertEqual(data.hexString, "0001feff")
}
func testByteCreateable_Sequence_Range() {
let data = Data(byteSequence: 251..<255)
XCTAssertEqual(data.hexString, "fbfcfdfe")
}
func testByteCreateable_Variadic() {
let data = Data(bytes: 0, 1, 254, 255)
XCTAssertEqual(data.hexString, "0001feff")
}
// MARK: Word
func testWordAsBigEndianCreateable() {
let data = Data(singleWordSequence: singleWordArray)
XCTAssertEqual(data.hexString, "0001fffe")
}
func testWordAsLittleEndianCreateable() {
let data = Data(singleWordSequence: singleWordArray, byteOrder: .littleEndian)
XCTAssertEqual(data.hexString, "0100feff")
}
// MARK: DoubleWord
func testDoubleWordAsBigEndianCreateable() {
let data = Data(doubleWordSequence: doubleWordArray)
XCTAssertEqual(data.hexString, "00000001fffffffe34dc296e")
}
func testDoubleWordAsLittleEndianCreateable() {
let data = Data(doubleWordSequence: doubleWordArray, byteOrder: .littleEndian)
XCTAssertEqual(data.hexString, "01000000feffffff6e29dc34")
}
// MARK: Long
func testLongAsBigEndianCreateable() {
let data = Data(longSequence: longArray)
XCTAssertEqual(data.hexString, "0000000000000001fffffffffffffffe8712dc4fa30d7af9")
}
func testLongAsLitteEndianCreateable() {
let data = Data(longSequence: longArray, byteOrder: .littleEndian)
XCTAssertEqual(data.hexString, "0100000000000000fefffffffffffffff97a0da34fdc1287")
}
// MARK: Bool
func testBoolCreateable_SmallSized() {
let data = Data(booleans: true, false, true, true, false)
XCTAssertEqual(data.hexString, "8d")
}
func testBoolCreateable_MediumSized() {
let data = Data(booleans: true, false, true, true, true, false, false, false, true, true, true, true)
XCTAssertEqual(data.hexString, "0b1d0f")
}
func testBoolCreateable_HighSized() {
var booleanArray = BooleanArray()
for _ in 1...257 {
booleanArray.append(randomBoolean)
}
let data = Data(booleanSequence: booleanArray)
XCTAssertEqual(data.count, 35)
}
func testBoolCreateable_VeryHighSized() {
var booleanArray = BooleanArray()
for _ in 1...65537 {
booleanArray.append(randomBoolean)
}
let data = Data(booleanSequence: booleanArray)
XCTAssertEqual(data.count, 8197)
}
// MARK: HexString
func testHexStringCreateable() {
let data = try! Data(hexString: "e8A43f00Ff")
XCTAssertEqual(data.hexString, "e8a43f00ff")
}
func DISABLEtestHexStringCreationCanFail_ToShort() {
do {
try Data(hexString: "")
XCTAssertTrue(false)
} catch {
XCTAssertTrue(true)
}
}
func DISABLEtestHexStringCreationCanFail_NoEvenLength() {
do {
try Data(hexString: "123")
XCTAssertTrue(false)
} catch {
XCTAssertTrue(true)
}
}
func DISABLEtestHexStringCreationCanFail_InsufficientCharacter() {
do {
try Data(hexString: "fg")
XCTAssertTrue(false)
} catch {
XCTAssertTrue(true)
}
}
// MARK: - Test that values can be retored from Data
func testByteRestoreable() {
let data = Data(byteSequence: byteArray)
XCTAssertEqual(data.byteArray, byteArray)
}
func testWordAsBigEndianRestoreable() {
let data = Data(singleWordSequence: singleWordArray)
let restored = try! data.singleWordSequence()
XCTAssertEqual(Array.init(restored), singleWordArray)
}
func testWordAsLittleEndianRestoreable() {
let data = Data(singleWordSequence: singleWordArray, byteOrder: .littleEndian)
let restored = try! data.singleWordSequence(byteOrder: .littleEndian)
XCTAssertEqual(Array.init(restored), singleWordArray)
}
func testDoubleWordAsBigEndianRestoreable() {
let data = Data(doubleWordSequence: doubleWordArray)
let restored = try! data.doubleWordSequence()
XCTAssertEqual(Array.init(restored), doubleWordArray)
}
func testDoubleWordAsLittleEndianRestoreable() {
let data = Data(doubleWordSequence: doubleWordArray, byteOrder: .littleEndian)
let restored = try! data.doubleWordSequence(byteOrder: .littleEndian)
XCTAssertEqual(Array.init(restored), doubleWordArray)
}
func testLongAsBigEndianRestoreable() {
let data = Data(longSequence: longArray)
let restored = try! data.longSequence()
XCTAssertEqual(Array.init(restored), longArray)
}
func testLongAsLitteEndianRestoreable() {
let data = Data(longSequence: longArray, byteOrder: .littleEndian)
let restored = try! data.longSequence(byteOrder: .littleEndian)
XCTAssertEqual(Array.init(restored), longArray)
}
func testBoolRestoreable_SmallSized() {
let boolArray: BooleanArray = [true, false, true, true, false]
let data = Data(booleanSequence: boolArray)
let restored = Array.init(data.booleanSequence())
XCTAssertEqual(restored.count, 5)
XCTAssertEqual(restored, boolArray)
}
func testBoolRestoreable_MediumSized() {
let boolArray: BooleanArray = [true, false, true, true, true, false, false, false, true, true, true, true]
let data = Data(booleanSequence: boolArray)
let restored = Array.init(data.booleanSequence())
XCTAssertEqual(restored.count, 12)
XCTAssertEqual(restored, boolArray)
}
func testBoolRestoreable_HighSized() {
var booleanArray = BooleanArray()
for _ in 1...1029 {
booleanArray.append(randomBoolean)
}
let data = Data(booleanSequence: booleanArray)
let restored = Array.init(data.booleanSequence())
XCTAssertEqual(restored.count, 1029)
XCTAssertEqual(restored, booleanArray)
}
func testBoolRestoreable_VeryHighSized() {
var booleanArray = BooleanArray()
for _ in 1...66321 {
booleanArray.append(randomBoolean)
}
let data = Data(booleanSequence: booleanArray)
let restored = Array.init(data.booleanSequence())
XCTAssertEqual(restored.count, 66321)
XCTAssertEqual(restored, booleanArray)
}
// MARK: HexString
func testHexStringRestoreable() {
let data = try! Data(hexString: "0001feff")
XCTAssertEqual(data.byteArray, byteArray)
}
}
extension Data_ByteViewTests {
var randomBoolean: Bool {
let randomValue = Int(arc4random_uniform(UInt32(2)))
return randomValue == 0 ? false : true
}
}
| mit | ce07ad1722f486c0d427903e10882133 | 26.728522 | 108 | 0.728839 | 3.543698 | false | true | false | false |
KingAce023/DreamChasers | Navigate/TableViewController.swift | 1 | 4658 | //
// TableViewController.swift
// SearchBar
//
// Created by Shinkangsan on 12/20/16.
// Copyright © 2016 Sheldon. All rights reserved.
//
import UIKit
let WIDTHSIZE = UIScreen.main.bounds.width * 0.85
enum selectedScope:Int {
case name = 0
case year = 1
case price = 2
}
class TableViewController: UITableViewController, UISearchBarDelegate{
let initialDataAry:[Model] = Model.generateModelArray()
var dataAry:[Model] = Model.generateModelArray()
override func viewDidLoad() {
super.viewDidLoad()
self.searchBarSetup()
}
func searchBarSetup() {
let searchBar = UISearchBar(frame: CGRect(x:CGFloat(0),y:CGFloat(0),width: CGFloat(WIDTHSIZE),height:CGFloat(70)))
searchBar.showsScopeBar = true
searchBar.scopeButtonTitles = ["Name","Year","Price"]
searchBar.selectedScopeButtonIndex = 0
searchBar.delegate = self
self.tableView.tableHeaderView = searchBar
//self.navigationItem.titleView = searchBar
}
// MARK: - search bar delegate
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
if searchText.isEmpty {
dataAry = initialDataAry
self.tableView.reloadData()
}else {
filterTableView(ind: searchBar.selectedScopeButtonIndex, text: searchText)
}
}
func filterTableView(ind:Int,text:String) {
switch ind {
case selectedScope.name.rawValue:
//fix of not searching when backspacing
dataAry = initialDataAry.filter({ (mod) -> Bool in
return mod.imageName.lowercased().contains(text.lowercased())
})
self.tableView.reloadData()
case selectedScope.year.rawValue:
//fix of not searching when backspacing
dataAry = initialDataAry.filter({ (mod) -> Bool in
return mod.imageYear.lowercased().contains(text.lowercased())
})
self.tableView.reloadData()
case selectedScope.price.rawValue:
//fix of not searching when backspacing
dataAry = initialDataAry.filter({ (mod) -> Bool in
return mod.imagePrice.lowercased().contains(text.lowercased())
})
self.tableView.reloadData()
default:
print("no type")
}
}
// MARK: - Table view data source
//---------USED TO OVERWRITE WIDTH SIZE OF THE LEFT TABLEVIEW----------
/* reference: https://stackoverflow.com/questions/42976006/ios-how-to-set-width-of-tableview-in-tableviewcontroller
*/
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(true)
self.tableView.frame = CGRect(x: CGFloat(0), y: CGFloat(0), width: CGFloat(WIDTHSIZE), height: CGFloat(UIScreen.main.bounds.height))
}
//---------------------------------------------------------------------
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(true)
self.tableView.frame = CGRect(x: CGFloat(0), y: CGFloat(0), width: CGFloat(WIDTHSIZE), height: CGFloat(UIScreen.main.bounds.height))
}
override func numberOfSections(in tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return dataAry.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell1", for: indexPath) as! TableViewCell1
let model = dataAry[indexPath.row]
cell.nameLbl.text = model.imageName
cell.imgView.image = UIImage(named: model.imageName)
cell.priceLbl.text = model.imagePrice
cell.yearLbl.text = model.imageYear
return cell
}
//add delegate method for pushing to new detail controller
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let vc = self.storyboard?.instantiateViewController(withIdentifier: "DetailViewController") as! DetailViewController
vc.dataModel = dataAry[indexPath.row]
self.navigationController?.pushViewController(vc, animated: true)
}
}
| mit | 7b3e4ba416d3cdb67fb6e822d81cf3ea | 32.992701 | 140 | 0.616491 | 4.991426 | false | false | false | false |
Lionas/Emoji-Extractor | EmojiExtractor/emoji.swift | 1 | 2159 | //
// emoji.swift
// EmojiExtractor
//
// Created by 瀬戸 直喜 on 2017/08/24.
// Copyright © 2017年 Lionas. All rights reserved.
//
import Foundation
func readEmojiDataFile(emojiDataPath: String) -> String {
var text = ""
do {
text = try String(contentsOf: URL(string: emojiDataPath)!, encoding: String.Encoding.utf8)
} catch {
print("Read Emoji data file error!")
}
return text
}
func extractEmoji(text: String) -> String {
// 改行で分割
let arr = text.components(separatedBy: "\n")
var emojiCodePattern = "["
for row in arr {
// 1文字以上ある場合
if row.utf8.count != 0 {
// 先頭がコメントの場合
if row.substring(to: row.index(after: row.startIndex)) == "#" {
if row.range(of: "Total elements:") != nil {
// 初回の絵文字一覧(Emoji)を読み込んだら終了
// Emoji_Presentation, Emoji_Modifier_Base, Extended_Pictographicは無視
break
}
else {
// 無視して次の行へ
continue
}
}
// 「;」で分割する
let code = row.components(separatedBy: ";")
// 絵文字でないデータの除去
let tmp = code[0].components(separatedBy: "..")
if tmp[0] < "00A9" {
// x00A9以下は通常の記号・数字なので絵文字としてカウントしない
continue
}
// 先頭に「\x{」を追加、「..」を「}\x{」に置換、末尾に「}」を追加、不要なスペースの削除
let unicodeRow = "\\\\x{" +
code[0]
.replacingOccurrences(of: "..", with: "}-\\\\x{")
.trimmingCharacters(in: .whitespacesAndNewlines) +
"}"
emojiCodePattern += unicodeRow
}
}
emojiCodePattern += "]"
return emojiCodePattern
}
| apache-2.0 | 23ccd770404b0953497fa436e4857ef5 | 25.422535 | 98 | 0.471215 | 3.836401 | false | false | false | false |
nissivm/AppleWatchKeyboard | AppleWatchKeyboard WatchKit Extension/ChatRoom.swift | 1 | 4990 | //
// ChatRoom.swift
// AppleWatchKeyboard
//
// Created by Nissi Vieira Miranda on 9/26/15.
// Copyright © 2015 Nissi Vieira Miranda. All rights reserved.
//
import WatchKit
import Foundation
import UIKit
class ChatRoom: WKInterfaceController
{
@IBOutlet var chatTable: WKInterfaceTable!
@IBOutlet var notice: WKInterfaceLabel!
let defaults = NSUserDefaults.standardUserDefaults()
var tableData = [NSMutableDictionary]()
var counter = 0
var userName = "Mark"
var friendName = ""
override func awakeWithContext(context: AnyObject?)
{
super.awakeWithContext(context)
friendName = context as! String
}
override func willActivate()
{
if defaults.objectForKey("textMessage") != nil
{
let textMessage = defaults.objectForKey("textMessage") as! String
let dic = NSMutableDictionary()
dic.setObject(getCurrentDate(), forKey: "date")
dic.setObject(textMessage, forKey: "textMessage")
if (counter % 2) == 0
{
dic.setObject(userName, forKey: "name")
}
else
{
dic.setObject(friendName, forKey: "name")
}
tableData.append(dic)
counter++
defaults.removeObjectForKey("textMessage")
defaults.synchronize()
}
else if defaults.objectForKey("imageMessage") != nil
{
let imageMessage = defaults.objectForKey("imageMessage") as! String
let dic = NSMutableDictionary()
dic.setObject(getCurrentDate(), forKey: "date")
dic.setObject(imageMessage, forKey: "imageMessage")
if (counter % 2) == 0
{
dic.setObject(userName, forKey: "name")
}
else
{
dic.setObject(friendName, forKey: "name")
}
tableData.append(dic)
counter++
defaults.removeObjectForKey("imageMessage")
defaults.synchronize()
}
if tableData.count > 0
{
notice.setHidden(true)
chatTable.setHidden(false)
populateTable()
}
super.willActivate()
}
override func didDeactivate()
{
// This method is called when watch view controller is no longer visible
super.didDeactivate()
}
func getCurrentDate() -> String
{
let todayDate = NSDate()
let dateFormatter = NSDateFormatter()
dateFormatter.timeStyle = .ShortStyle
return dateFormatter.stringFromDate(todayDate)
}
//-------------------------------------------------------------------------//
// MARK: IBAction
//-------------------------------------------------------------------------//
@IBAction func smileyButtonTapped()
{
presentControllerWithName("SmileysTable", context: nil)
}
@IBAction func textButtonTapped()
{
presentControllerWithName("CharactersKeyboard", context: nil)
}
//-------------------------------------------------------------------------//
// MARK: Table
//-------------------------------------------------------------------------//
func populateTable()
{
chatTable.setNumberOfRows(tableData.count, withRowType: "MessageCell")
for (index, message) in tableData.enumerate()
{
let row = chatTable.rowControllerAtIndex(index) as! MessageCell
let name = message.objectForKey("name") as! String
let path = NSBundle.mainBundle().pathForResource(name, ofType: "png")
let image = UIImage(contentsOfFile: path!)
row.avatar.setImage(image)
let date = message.objectForKey("date") as! String
row.date.setText(date)
if message.objectForKey("textMessage") != nil
{
let msg = message.objectForKey("textMessage") as! String
row.imageMessageBubble.setHidden(true)
row.textMessageBubble.setHidden(false)
row.textMessage.setText(msg)
}
else
{
let imgName = message.objectForKey("imageMessage") as! String
let bundlePath = NSBundle.mainBundle().pathForResource(imgName, ofType: "png")
let image = UIImage(contentsOfFile: bundlePath!)
row.textMessageBubble.setHidden(true)
row.imageMessageBubble.setHidden(false)
row.smiley.setImage(image)
}
}
chatTable.scrollToRowAtIndex(tableData.count - 1)
}
}
| mit | 4b3079728ee04101b651a746d584df9f | 29.796296 | 94 | 0.50892 | 5.84192 | false | false | false | false |
getwagit/Baya | Baya/layouts/BayaGravityLayout.swift | 1 | 3967 | //
// Copyright (c) 2016-2017 wag it GmbH.
// License: MIT
//
import Foundation
import UIKit
/**
Simple layout that positions one child according to its gravity.
It also assumes layout mode .matchParent for gravitating axis.
*/
public struct BayaGravityLayout: BayaLayout {
public var bayaMargins: UIEdgeInsets = UIEdgeInsets.zero
public var frame: CGRect
public let bayaModes: BayaLayoutOptions.Modes
private var element: BayaLayoutable
private var measure: CGSize?
private let horizontalGravity: BayaLayoutOptions.Gravity.Horizontal?
private let verticalGravity: BayaLayoutOptions.Gravity.Vertical?
init(
element: BayaLayoutable,
horizontalGravity: BayaLayoutOptions.Gravity.Horizontal?,
verticalGravity: BayaLayoutOptions.Gravity.Vertical?) {
self.element = element
self.horizontalGravity = horizontalGravity
self.verticalGravity = verticalGravity
self.frame = CGRect()
self.bayaModes = BayaLayoutOptions.Modes(
width: horizontalGravity != nil ? .matchParent : element.bayaModes.width,
height: verticalGravity != nil ? .matchParent : element.bayaModes.height)
}
public mutating func layoutWith(frame: CGRect) {
self.frame = frame
let size = calculateSizeForLayout(forChild: &element, cachedSize: measure, ownSize: frame.size)
var point = CGPoint()
switch horizontalGravity {
case .none: fallthrough
case .some(.left): point.x = frame.minX + element.bayaMargins.left
case .some(.centerX): point.x = frame.midX - (size.width * 0.5)
case .some(.right): point.x = frame.maxX - size.width - element.bayaMargins.right
}
switch verticalGravity {
case .none: fallthrough
case .some(.top): point.y = frame.minY + element.bayaMargins.top
case .some(.centerY): point.y = frame.midY - (size.height * 0.5)
case .some(.bottom): point.y = frame.maxY - size.height - element.bayaMargins.bottom
}
element.layoutWith(frame: CGRect(
origin: point,
size: size))
}
public mutating func sizeThatFits(_ size: CGSize) -> CGSize {
measure = element.sizeThatFitsWithMargins(size)
return measure!.addMargins(ofElement: element)
}
}
public extension BayaLayoutable {
/// Positions the element on the horizontal axis.
/// - parameter horizontalGravity: Specifies where the element should be positioned horizontally.
/// - returns: A `BayaGravityLayout`.
func layoutGravitating(to horizontalGravity: BayaLayoutOptions.Gravity.Horizontal) -> BayaGravityLayout {
return BayaGravityLayout(
element: self,
horizontalGravity: horizontalGravity,
verticalGravity: nil)
}
/// Positions the element on the vertical axis.
/// - parameter verticalGravity: Specifies where the element should be positioned vertically.
/// - returns: A `BayaGravityLayout`.
func layoutGravitating(to verticalGravity: BayaLayoutOptions.Gravity.Vertical) -> BayaGravityLayout {
return BayaGravityLayout(
element: self,
horizontalGravity: nil,
verticalGravity: verticalGravity)
}
/// Positions the element on both the horizontal and vertical axis.
/// - parameter horizontalGravity: Specifies where the element should be positioned horizontally.
/// - parameter verticalGravity: Specifies where the element should be positioned vertically.
/// - returns: A `BayaGravityLayout`.
func layoutGravitating(
horizontally horizontalGravity: BayaLayoutOptions.Gravity.Horizontal,
vertically verticalGravity: BayaLayoutOptions.Gravity.Vertical)
-> BayaGravityLayout {
return BayaGravityLayout(
element: self,
horizontalGravity: horizontalGravity,
verticalGravity: verticalGravity)
}
}
| mit | 998beee67a376e0d110fd7a01f372447 | 39.070707 | 109 | 0.684396 | 4.528539 | false | false | false | false |
maxim-pervushin/Time-Logger | HyperTimeLogger/HyperTimeLoggerUISnapshots/HyperTimeLoggerUISnapshots.swift | 2 | 1768 | //
// HyperTimeLoggerUISnapshots.swift
// HyperTimeLoggerUISnapshots
//
// Created by Maxim Pervushin on 29/03/16.
// Copyright © 2016 Maxim Pervushin. All rights reserved.
//
import XCTest
class HyperTimeLoggerUISnapshots: XCTestCase {
override func setUp() {
super.setUp()
continueAfterFailure = false
let app = XCUIApplication()
setupSnapshot(app)
app.launch()
}
override func tearDown() {
super.tearDown()
}
func testMakeSnapshots() {
let app = XCUIApplication()
waitFor(app.buttons["Settings"], seconds: 1)
app.buttons["Settings"].tap()
// Settings Screen
snapshot("04_Settings")
// Generate Test Data
app.tables.elementBoundByIndex(0).cells.elementBoundByIndex(0).tapWithNumberOfTaps(7, numberOfTouches: 2)
app.buttons["Done"].tap()
// Reports List Screen
snapshot("01_Reports")
app.buttons["AddReportButton"].tap()
// Add Report Screen
app.textFields["TextField"].tapWithNumberOfTaps(7, numberOfTouches: 2)//typeText("Sleep")
app.collectionViews["Categories"].cells.elementBoundByIndex(0).tap()
snapshot("02_AddReport")
app.buttons["Save"].tap()
// Reports List Screen
app.buttons["Statistics"].tap()
// Statistics Screen
snapshot("03_Statistics")
}
func waitFor(element:XCUIElement, seconds waitSeconds:Double) {
let exists = NSPredicate(format: "exists == 1")
expectationForPredicate(exists, evaluatedWithObject: element, handler: nil)
waitForExpectationsWithTimeout(waitSeconds, handler: nil)
}
}
| mit | 2d72602eca8c18b15bf62e343a4bac64 | 27.047619 | 113 | 0.614035 | 4.827869 | false | true | false | false |
ianyh/Amethyst | Amethyst/Model/MouseState.swift | 1 | 5004 | //
// MouseState.swift
// Amethyst
//
// Created by Ian Ynda-Hummel on 3/21/19.
// Copyright © 2019 Ian Ynda-Hummel. All rights reserved.
//
import Foundation
import Silica
/**
These are the possible actions that the mouse might be taking (that we care about).
We use this enum to convey some information about the window that the mouse might be interacting with.
*/
enum MouseState<Window: WindowType> {
typealias Screen = Window.Screen
case pointing
case clicking
case dragging
case moving(window: Window)
case resizing(screen: Screen, ratio: CGFloat)
case doneDragging(atTime: Date)
}
/// MouseStateKeeper will need a few things to do its job effectively
protocol MouseStateKeeperDelegate: class {
associatedtype Window: WindowType
func recommendMainPaneRatio(_ ratio: CGFloat)
func swapDraggedWindowWithDropzone(_ draggedWindow: Window)
}
/**
Maintains state information about the mouse for the purposes of mouse-based window operations.
MouseStateKeeper exists because we need a single shared mouse state between all applications being observed. This class captures the state and coordinates any Amethyst reflow actions that are required in response to mouse events.
Note that some actions may be initiated here and some actions may be completed here; we don't know whether the mouse event stream or the accessibility event stream will fire first.
This class by itself can only understand clicking, dragging, and "pointing" (no mouse buttons down). The SIApplication observers are able to augment that understanding of state by "upgrading" a drag action to a "window move" or a "window resize" event since those observers will have proper context.
*/
class MouseStateKeeper<Delegate: MouseStateKeeperDelegate> {
let dragRaceThresholdSeconds = 0.15 // prevent race conditions during drag ops
var state: MouseState<Delegate.Window>
private(set) weak var delegate: Delegate?
private(set) var lastClick: Date?
private var monitor: Any?
init(delegate: Delegate) {
self.delegate = delegate
state = .pointing
let mouseEventsToWatch: NSEvent.EventTypeMask = [.leftMouseDown, .leftMouseUp, .leftMouseDragged]
monitor = NSEvent.addGlobalMonitorForEvents(matching: mouseEventsToWatch, handler: self.handleMouseEvent)
}
deinit {
guard let oldMonitor = monitor else { return }
NSEvent.removeMonitor(oldMonitor)
}
// Update our understanding of the current state unless an observer has already
// done it for us. mouseUp events take precedence over anything an observer had
// found -- you can't be dragging or resizing with a mouse button up, even if
// you're using the "3 finger drag" accessibility option, where no physical button
// is being pressed.
func handleMouseEvent(anEvent: NSEvent) {
switch anEvent.type {
case .leftMouseDown:
self.state = .clicking
case .leftMouseDragged:
switch self.state {
case .moving, .resizing:
break // ignore - we have what we need
case .pointing, .clicking, .dragging, .doneDragging:
self.state = .dragging
}
case .leftMouseUp:
switch self.state {
case .dragging:
// assume window move event will come shortly after
self.state = .doneDragging(atTime: Date())
case let .moving(draggedWindow):
self.state = .pointing // flip state first to prevent race condition
self.swapDraggedWindowWithDropzone(draggedWindow)
case let .resizing(_, ratio):
self.state = .pointing
self.resizeFrameToDraggedWindowBorder(ratio)
case .doneDragging:
self.state = .doneDragging(atTime: Date()) // reset the clock I guess
case .clicking:
lastClick = Date()
self.state = .pointing
case .pointing:
self.state = .pointing
}
default: ()
}
}
// React to a reflow event. Typically this means that any window we were dragging
// is no longer valid and should be de-correlated from the mouse
func handleReflowEvent() {
switch self.state {
case .doneDragging:
self.state = .pointing // remove associated timestamp
case .moving:
self.state = .dragging // remove associated window
default: ()
}
}
// Execute an action that was initiated by the observer and completed by the state keeper
func resizeFrameToDraggedWindowBorder(_ ratio: CGFloat) {
delegate?.recommendMainPaneRatio(ratio)
}
// Execute an action that was initiated by the observer and completed by the state keeper
func swapDraggedWindowWithDropzone(_ draggedWindow: Delegate.Window) {
delegate?.swapDraggedWindowWithDropzone(draggedWindow)
}
}
| mit | d117d52360f2166e1f88bd0f5efe1d4e | 39.024 | 299 | 0.678193 | 4.710923 | false | false | false | false |
RemyDCF/tpg-offline | tpg offline/Departures/Cells/BusRouteTableViewCell.swift | 1 | 7127 | //
// ThermometerTableViewCell.swift
// tpgoffline
//
// Created by Rémy Da Costa Faro on 11/06/2017.
// Copyright © 2018 Rémy Da Costa Faro DA COSTA FARO. All rights reserved.
//
import UIKit
class BusRouteTableViewCell: UITableViewCell {
@IBOutlet weak var titleLabel: UILabel!
@IBOutlet weak var busTrackView: UIImageView!
@IBOutlet weak var remainingTimeLabel: UILabel!
@IBOutlet weak var busImageView: UIImageView!
var busRoute: BusRoute?
var stop: Stop?
func configure(with busRoute: BusRoute, color: UIColor, selected: Bool = false) {
self.backgroundColor = App.darkMode ?
App.cellBackgroundColor : (selected ? color : .white)
self.busRoute = busRoute
var color = busRoute.arrivalTime != "" ? color : .gray
if !App.darkMode {
color = selected ? color.contrast : color
}
titleLabel.textColor = color
titleLabel.text = App.stops.filter({
$0.code == busRoute.stop.code
})[safe: 0]?.name ?? Text.unknow
remainingTimeLabel.textColor = color
if busRoute.arrivalTime == "00" {
remainingTimeLabel.isHidden = true
busImageView.image = #imageLiteral(resourceName: "bus").maskWith(color: color)
busImageView.isHidden = false
} else {
remainingTimeLabel.text = busRoute.arrivalTime == "" ?"" :
"\(busRoute.reliability == .theoretical ? "~" : "")\(busRoute.arrivalTime)'"
remainingTimeLabel.isHidden = false
busImageView.image = nil
busImageView.isHidden = true
}
/*var rectanglePath: UIBezierPath
if busRoute.first {
rectanglePath = UIBezierPath(rect: CGRect(x: self.bounds.height / 2 - 4.5,
y: self.bounds.height / 2,
width: 9,
height: self.bounds.height))
} else if busRoute.last {
rectanglePath = UIBezierPath(rect: CGRect(x: self.bounds.height / 2 - 4.5,
y: 0,
width: 9,
height: self.bounds.height / 2))
} else {
rectanglePath = UIBezierPath(rect: CGRect(x: self.bounds.height / 2 - 4.5,
y: 0,
width: 9,
height: self.bounds.height))
}
let ovalPath = UIBezierPath(ovalIn: CGRect(x: self.bounds.height / 4,
y: self.bounds.height / 4,
width: self.bounds.height / 2,
height: self.bounds.height / 2))
color.setFill()
rectanglePath.fill()
ovalPath.fill()
self.busTrackView.layer.sublayers?.removeAll()
var shapeLayer = CAShapeLayer()
shapeLayer.path = rectanglePath.cgPath
shapeLayer.strokeColor = color.cgColor
shapeLayer.fillColor = color.cgColor
shapeLayer.backgroundColor = App.cellBackgroundColor.cgColor
shapeLayer.lineWidth = 3
self.busTrackView.layer.addSublayer(shapeLayer)
shapeLayer = CAShapeLayer()
shapeLayer.path = ovalPath.cgPath
shapeLayer.strokeColor = color.cgColor
shapeLayer.fillColor = color.cgColor
shapeLayer.backgroundColor = App.cellBackgroundColor.cgColor
shapeLayer.lineWidth = 3
self.busTrackView.layer.addSublayer(shapeLayer)*/
if busRoute.first {
self.busTrackView.image = #imageLiteral(resourceName: "firstStep").maskWith(color: color)
} else if busRoute.last {
self.busTrackView.image = #imageLiteral(resourceName: "endStep").maskWith(color: color)
} else {
self.busTrackView.image = #imageLiteral(resourceName: "middleStep").maskWith(color: color)
}
self.selectedBackgroundView = UIView()
self.selectedBackgroundView?.backgroundColor = color.withAlphaComponent(0.1)
self.accessoryType = .disclosureIndicator
}
func configure(with stopId: Int, color: UIColor, first: Bool, last: Bool) {
self.backgroundColor = App.cellBackgroundColor
guard let stop = App.stops.filter({ $0.appId == stopId })[safe: 0] else {
print("Warning: \(stopId) was not found")
titleLabel.text = "Unknow stop: \(stopId)"
return
}
self.stop = stop
var color = color
if color.contrast == .black {
color = color.darken(by: 0.1)
}
titleLabel.textColor = color
titleLabel.text = stop.name
remainingTimeLabel.text = ""
//var rectanglePath: UIBezierPath
if first {
self.busTrackView.image = #imageLiteral(resourceName: "firstStep").maskWith(color: color)
} else if last {
self.busTrackView.image = #imageLiteral(resourceName: "endStep").maskWith(color: color)
} else {
self.busTrackView.image = #imageLiteral(resourceName: "middleStep").maskWith(color: color)
}
/*if first {
rectanglePath = UIBezierPath(rect: CGRect(x: self.bounds.height / 2 - 4.5,
y: self.bounds.height / 2,
width: 9,
height: self.bounds.height))
} else if last {
rectanglePath = UIBezierPath(rect: CGRect(x: self.bounds.height / 2 - 4.5,
y: 0,
width: 9,
height: self.bounds.height / 2))
} else {
rectanglePath = UIBezierPath(rect: CGRect(x: self.bounds.height / 2 - 4.5,
y: 0,
width: 9,
height: self.bounds.height))
}
let ovalPath = UIBezierPath(ovalIn: CGRect(x: self.bounds.height / 4,
y: self.bounds.height / 4,
width: self.bounds.height / 2,
height: self.bounds.height / 2))
color.setFill()
rectanglePath.fill()
ovalPath.fill()
self.busTrackView.layer.sublayers?.removeAll()
var shapeLayer = CAShapeLayer()
shapeLayer.path = rectanglePath.cgPath
shapeLayer.strokeColor = color.cgColor
shapeLayer.fillColor = color.cgColor
shapeLayer.backgroundColor = App.cellBackgroundColor.cgColor
shapeLayer.lineWidth = 3
self.busTrackView.layer.addSublayer(shapeLayer)
shapeLayer = CAShapeLayer()
shapeLayer.path = ovalPath.cgPath
shapeLayer.strokeColor = color.cgColor
shapeLayer.fillColor = color.cgColor
shapeLayer.backgroundColor = App.cellBackgroundColor.cgColor
shapeLayer.lineWidth = 3
self.busTrackView.layer.addSublayer(shapeLayer)
self.busTrackView.backgroundColor = self.backgroundColor*/
self.selectedBackgroundView = UIView()
self.selectedBackgroundView?.backgroundColor = color.withAlphaComponent(0.1)
self.accessoryType = .disclosureIndicator
}
}
| mit | ab7b41ad2afcdf47f159e3b4e3d85089 | 35.911917 | 96 | 0.58352 | 4.842964 | false | false | false | false |
gaoleegin/SwiftLianxi | SDECollectionViewAlbumTransition-PinchPopTransition/Example/SDEGalleriesViewController.swift | 1 | 9821 | //
// SDEGalleriesViewController.swift
// Albums
//
// Created by seedante on 15/7/6.
// Copyright © 2015年 seedante. All rights reserved.
//
import UIKit
import Foundation
import Photos
private let reuseIdentifier = "Cell"
private let headerReuseIdentifier = "Header"
class SDEGalleriesViewController: UICollectionViewController, PHPhotoLibraryChangeObserver {
var dataSource = [[PHAssetCollection]]()
var headerDataSource = [String]()
let fetchOptions = PHFetchOptions()
var localAlbumsDataSource = [PHAssetCollection]()
var filteredLocalAlbumsDataSource = [PHAssetCollection]()
let localSubTypes = [PHAssetCollectionSubtype](arrayLiteral:
.SmartAlbumUserLibrary,
.SmartAlbumVideos,
.SmartAlbumSlomoVideos,
.SmartAlbumTimelapses,
.SmartAlbumPanoramas,
.SmartAlbumGeneric,
.SmartAlbumBursts
)
var specialAlbumsDataSource = [PHAssetCollection]()
var filteredSpecialAlbumsDataSource = [PHAssetCollection]()
let specialSubTypes = [PHAssetCollectionSubtype](arrayLiteral:
.SmartAlbumFavorites,
.SmartAlbumAllHidden
)
var syncedAlbumsDataSource = [PHAssetCollection]()
var filterdSyncedAlbumsDataSource = [PHAssetCollection]()
let syncedSubTypes = [PHAssetCollectionSubtype](arrayLiteral:
.AlbumSyncedEvent,
.AlbumSyncedAlbum,
.AlbumImported
)
//MARK: View Life Circle
override func awakeFromNib() {
fetchOptions.predicate = NSPredicate(format: "estimatedAssetCount > 0", argumentArray: nil)
for subType in localSubTypes{
let fetchResult = PHAssetCollection.fetchAssetCollectionsWithType(.SmartAlbum, subtype: subType, options: nil)
fetchResult.enumerateObjectsUsingBlock({
(item, index, stop) in
self.localAlbumsDataSource.append(item as! PHAssetCollection)
})
}
for subType in specialSubTypes{
let fetchResult = PHAssetCollection.fetchAssetCollectionsWithType(.SmartAlbum, subtype: subType, options: nil)
fetchResult.enumerateObjectsUsingBlock({
(item, index, stop) in
self.specialAlbumsDataSource.append(item as! PHAssetCollection)
})
}
for subType in syncedSubTypes{
let fetchResult = PHAssetCollection.fetchAssetCollectionsWithType(.Album, subtype: subType, options: nil)
fetchResult.enumerateObjectsUsingBlock({
(item, index, stop) in
self.syncedAlbumsDataSource.append(item as! PHAssetCollection)
})
}
fetchData()
}
override func viewDidLoad() {
super.viewDidLoad()
PHPhotoLibrary.sharedPhotoLibrary().registerChangeObserver(self)
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
self.tabBarController?.navigationItem.title = "Galleries"
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
deinit{
PHPhotoLibrary.sharedPhotoLibrary().unregisterChangeObserver(self)
}
func fetchData(){
if headerDataSource.count > 0{
headerDataSource.removeAll()
}
if dataSource.count > 0{
dataSource.removeAll()
}
filteredLocalAlbumsDataSource = localAlbumsDataSource.filter({PHAsset.fetchAssetsInAssetCollection($0, options: nil).count > 0})
filteredSpecialAlbumsDataSource = specialAlbumsDataSource.filter({PHAsset.fetchAssetsInAssetCollection($0, options: nil).count > 0})
filterdSyncedAlbumsDataSource = syncedAlbumsDataSource.filter({$0.estimatedAssetCount > 0})
if filteredLocalAlbumsDataSource.count > 0{
headerDataSource.append("Albums")
dataSource.append(filteredLocalAlbumsDataSource)
}
if filteredSpecialAlbumsDataSource.count > 0{
headerDataSource.append("SpecialAlbums")
dataSource.append(filteredSpecialAlbumsDataSource)
}
if filterdSyncedAlbumsDataSource.count > 0{
headerDataSource.append("SyncedAlbums")
dataSource.append(filterdSyncedAlbumsDataSource)
}
}
// MARK: UICollectionViewDataSource
override func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
return dataSource.count
}
override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
let sectionInfo = dataSource[section]
return sectionInfo.count
}
override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath)
// Configure the cell
if let imageView = cell.viewWithTag(-10) as? UIImageView{
imageView.layer.borderColor = UIColor.whiteColor().CGColor
imageView.layer.borderWidth = 10.0
let assetCollectionArray = dataSource[indexPath.section]
let assetCollection = assetCollectionArray[indexPath.row]
if let titleLabel = cell.viewWithTag(-20) as? UILabel{
let titleText = NSAttributedString(string: assetCollection.localizedTitle!)
let count = PHAsset.fetchAssetsInAssetCollection(assetCollection, options: nil).count
let countText = NSAttributedString(string: " \(count)", attributes: [NSForegroundColorAttributeName: UIColor.grayColor(), NSFontAttributeName: UIFont(name: "Helvetica Neue", size: 15.0)!])
let cellTitle = NSMutableAttributedString(attributedString: titleText)
cellTitle.appendAttributedString(countText)
titleLabel.attributedText = cellTitle
}
PHFetchResult.fetchPosterImageForAssetCollection(assetCollection, imageView: imageView, targetSize: CGSizeMake(170, 170))
}
return cell
}
override func collectionView(collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, atIndexPath indexPath: NSIndexPath) -> UICollectionReusableView {
let headerView = collectionView.dequeueReusableSupplementaryViewOfKind(UICollectionElementKindSectionHeader, withReuseIdentifier: headerReuseIdentifier, forIndexPath: indexPath)
if let titleLabel = headerView.viewWithTag(-10) as? UILabel{
titleLabel.text = headerDataSource[indexPath.section]
}
return headerView
}
//MARK: PHPhotoLibraryChangeObserver
func photoLibraryDidChange(changeInstance: PHChange) {
let localAlbumsCopy = localAlbumsDataSource
for assetCollection in localAlbumsCopy{
if let changeDetail = changeInstance.changeDetailsForObject(assetCollection){
let index = localAlbumsDataSource.indexOf(assetCollection)
let newAssetCollection = changeDetail.objectAfterChanges as! PHAssetCollection
localAlbumsDataSource[index!] = newAssetCollection
}
}
let specialAlbumsCopy = specialAlbumsDataSource
for assetCollection in specialAlbumsCopy{
if let changeDetail = changeInstance.changeDetailsForObject(assetCollection){
let index = specialAlbumsDataSource.indexOf(assetCollection)
let newAssetCollection = changeDetail.objectAfterChanges as! PHAssetCollection
specialAlbumsDataSource[index!] = newAssetCollection
}
}
let syncedAlbumsCopy = syncedAlbumsDataSource
for assetCollection in syncedAlbumsCopy{
if let changeDetail = changeInstance.changeDetailsForObject(assetCollection){
let index = syncedAlbumsDataSource.indexOf(assetCollection)
let newAssetCollection = changeDetail.objectAfterChanges as! PHAssetCollection
syncedAlbumsDataSource[index!] = newAssetCollection
}
}
fetchData()
}
//MARK: UICollectionView Delegate
override func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
self.selectedIndexPath = indexPath
let layoutAttributes = self.collectionView!.layoutAttributesForItemAtIndexPath(indexPath)
let circleView = UIView(frame: CGRectMake(0, 0, 30.0, 30.0))
circleView.layer.cornerRadius = 15.0
circleView.backgroundColor = UIColor.blueColor()
self.collectionView?.addSubview(circleView)
circleView.center = layoutAttributes!.center
UIView.animateKeyframesWithDuration(0.3, delay: 0, options: UIViewKeyframeAnimationOptions.AllowUserInteraction, animations: {
circleView.transform = CGAffineTransformMakeScale(2, 2)
circleView.alpha = 0
}, completion: {
finish in
circleView.removeFromSuperview()
if let albumVC = self.storyboard?.instantiateViewControllerWithIdentifier("AlbumVC") as? SDEAlbumViewController{
let assetCollection = self.dataSource[indexPath.section][indexPath.row]
albumVC.assetCollection = assetCollection
self.navigationController?.pushViewController(albumVC, animated: true)
}
})
}
}
| apache-2.0 | 81fcd95fcf6c939676d4a384b37f4784 | 40.079498 | 204 | 0.677531 | 6.071738 | false | false | false | false |
jwfriese/FrequentFlyer | FrequentFlyer/Visuals/TitledTextField/TitledTextField.swift | 1 | 1928 | import UIKit
class TitledTextField: UIView {
private var contentView: UIView!
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
let viewPackage = Bundle.main.loadNibNamed("TitledTextField", owner: self, options: nil)
guard let loadedView = viewPackage?.first as? UIView else {
print("Failed to load nib with name 'TitledTextField'")
return
}
contentView = loadedView
addSubview(contentView)
contentView.bounds = bounds
autoresizesSubviews = true
autoresizingMask = [UIViewAutoresizing.flexibleHeight, UIViewAutoresizing.flexibleWidth]
backgroundColor = UIColor.clear
contentView.backgroundColor = UIColor.clear
}
public var textField: UITextField? { get { return internalTextField?.textField } }
override func layoutSubviews() {
super.layoutSubviews()
contentView.frame = CGRect(x: 0, y: 0, width: frame.size.width, height: frame.size.height)
}
private weak var cachedTitleLabel: UILabel?
weak var titleLabel: UILabel? {
get {
if cachedTitleLabel != nil { return cachedTitleLabel }
let label = contentView.subviews.filter { subview in
return subview.isKind(of: TitledTextFieldTitleLabel.self)
}.first as? UILabel
cachedTitleLabel = label
return cachedTitleLabel
}
}
private weak var cachedTextField: UnderlineTextField?
private weak var internalTextField: UnderlineTextField? {
get {
if cachedTextField != nil { return cachedTextField }
let textField = contentView.subviews.filter { subview in
return subview.isKind(of: UnderlineTextField.self)
}.first as? UnderlineTextField
cachedTextField = textField
return cachedTextField
}
}
}
| apache-2.0 | d241fbf66193ecf20a6997f8564c368f | 32.824561 | 98 | 0.645747 | 5.325967 | false | false | false | false |
kean/Nuke | Tests/NukeTests/ResumableDataTests.swift | 1 | 6276 | // The MIT License (MIT)
//
// Copyright (c) 2015-2022 Alexander Grebenyuk (github.com/kean).
import XCTest
@testable import Nuke
// Test ResumableData directly to make sure it makes the right decisions based
// on HTTP flows.
class ResumableDataTests: XCTestCase {
func testResumingRequest() {
let response = _makeResponse(headers: [
"Accept-Ranges": "bytes",
"Content-Length": "2000",
"ETag": "1234"
])
let data = ResumableData(response: response, data: _data)!
var request = URLRequest(url: Test.url)
data.resume(request: &request)
// Check that we've set both required "range" filed
XCTAssertEqual(request.allHTTPHeaderFields?["Range"], "bytes=1000-")
XCTAssertEqual(request.allHTTPHeaderFields?["If-Range"], "1234")
}
func testCheckingResumedResponse() {
XCTAssertTrue(ResumableData.isResumedResponse(_makeResponse(statusCode: 206)))
// Need to load new data
XCTAssertFalse(ResumableData.isResumedResponse(_makeResponse(statusCode: 200)))
XCTAssertFalse(ResumableData.isResumedResponse(_makeResponse(statusCode: 404)))
}
// MARK: - Creation (Positive)
func testCreateWithETag() {
// Given
let response = _makeResponse(headers: [
"Accept-Ranges": "bytes",
"Content-Length": "2000",
"ETag": "1234"
])
let data = ResumableData(response: response, data: _data)
// Then
XCTAssertNotNil(data)
XCTAssertEqual(data?.data.count, 1000)
XCTAssertEqual(data?.validator, "1234")
}
func testCreateWithETagSpelledIncorrectly() {
// Given
let response = _makeResponse(headers: [
"Accept-Ranges": "bytes",
"Content-Length": "2000",
"Etag": "1234"
])
let data = ResumableData(response: response, data: _data)
// Then
XCTAssertNotNil(data)
XCTAssertEqual(data?.data.count, 1000)
XCTAssertEqual(data?.validator, "1234")
}
func testCreateWithLastModified() {
// Given
let response = _makeResponse(headers: [
"Accept-Ranges": "bytes",
"Content-Length": "2000",
"Last-Modified": "Wed, 21 Oct 2015 07:28:00 GMT"
])
let data = ResumableData(response: response, data: _data)
// Then
XCTAssertNotNil(data)
XCTAssertEqual(data?.data.count, 1000)
XCTAssertEqual(data?.validator, "Wed, 21 Oct 2015 07:28:00 GMT")
}
func testCreateWithBothValidators() {
// Given
let response = _makeResponse(headers: [
"Accept-Ranges": "bytes",
"ETag": "1234",
"Content-Length": "2000",
"Last-Modified": "Wed, 21 Oct 2015 07:28:00 GMT"
])
let data = ResumableData(response: response, data: _data)
// Then
XCTAssertNotNil(data)
XCTAssertEqual(data?.data.count, 1000)
XCTAssertEqual(data?.validator, "1234")
}
// We should store resumable data not just for statuc code "200 OK", but also
// for "206 Partial Content" in case the resumed download fails.
func testCreateWithStatusCodePartialContent() {
// Given
let response = _makeResponse(statusCode: 206, headers: [
"Accept-Ranges": "bytes",
"Content-Length": "2000",
"ETag": "1234"
])
let data = ResumableData(response: response, data: _data)
// Then
XCTAssertNotNil(data)
XCTAssertEqual(data?.data.count, 1000)
XCTAssertEqual(data?.validator, "1234")
}
// MARK: - Creation (Negative)
func testCreateWithEmptyData() {
// Given
let response = _makeResponse(headers: [
"Accept-Ranges": "bytes",
"Content-Length": "2000",
"ETag": "1234"
])
let data = ResumableData(response: response, data: Data())
// Then
XCTAssertNil(data)
}
func testCreateWithNotHTTPResponse() {
// Given
let response = URLResponse(url: Test.url, mimeType: "jpeg", expectedContentLength: 10000, textEncodingName: nil)
let data = ResumableData(response: response, data: _data)
// Then
XCTAssertNil(data)
}
func testCreateWithInvalidStatusCode() {
// Given
let response = _makeResponse(statusCode: 304, headers: [
"Accept-Ranges": "bytes",
"Content-Length": "2000",
"ETag": "1234"
])
let data = ResumableData(response: response, data: _data)
// Then
XCTAssertNil(data)
}
func testCreateWithMissingValidator() {
// Given
let response = _makeResponse(headers: [
"Accept-Ranges": "bytes",
"Content-Length": "2000"
])
let data = ResumableData(response: response, data: _data)
// Then
XCTAssertNil(data)
}
func testCreateWithMissingAcceptRanges() {
// Given
let response = _makeResponse(headers: [
"ETag": "1234",
"Content-Length": "2000"
])
let data = ResumableData(response: response, data: _data)
// Then
XCTAssertNil(data)
}
func testCreateWithAcceptRangesNone() {
// Given
let response = _makeResponse(headers: [
"Accept-Ranges": "none",
"Content-Length": "2000",
"ETag": "1234"
])
let data = ResumableData(response: response, data: _data)
// Then
XCTAssertNil(data)
}
func testCreateWhenFullDataIsLoaded() {
// Given
let response = _makeResponse(headers: [
"Accept-Ranges": "none",
"Content-Length": "1000",
"ETag": "1234"
])
let data = ResumableData(response: response, data: _data)
// Then
XCTAssertNil(data)
}
}
private let _data = Data(count: 1000)
private func _makeResponse(statusCode: Int = 200, headers: [String: String]? = nil) -> HTTPURLResponse {
return HTTPURLResponse(url: Test.url, statusCode: statusCode, httpVersion: "HTTP/1.2", headerFields: headers)!
}
| mit | 061b100dad70cf12e8313b558facd817 | 29.318841 | 120 | 0.579669 | 4.473272 | false | true | false | false |
chrisamanse/Changes | Sources/Changes/Changes.swift | 1 | 7125 | //
// Diff.swift
// Diff
//
// Created by Chris Amanse on 09/19/2016.
//
//
public extension Collection where Iterator.Element: Equatable, IndexDistance == Int {
/// Get the changes of the receiver based on another collection.
///
/// - parameter oldCollection: The old collection.
/// - parameter reduced: If set to `true`, insertion and deletion pairs will be combined into a `.Move` type. Default value is `true`.
///
/// - returns: An array of changes.
public func changes(since oldCollection: Self, reduced: Bool = true) -> [Change<Iterator.Element>] {
return Changes.changes(old: oldCollection, new: self, reduced: reduced)
}
}
public extension String {
/// Get the changes of the receiver based on another String.
///
/// - parameter oldString: The old string.
/// - parameter reduced: If set to `true`, insertion and deletion pairs will be combined into a `.Move` type. Default value is `true`.
///
/// - returns: An array of changes.
public func changes(since oldString: String, reduced: Bool = true) -> [Change<Character>] {
return self.characters.changes(since: oldString.characters, reduced: reduced)
}
}
fileprivate func changes<T: Collection>(old: T, new: T, reduced: Bool = true) -> [Change<T.Iterator.Element>] where T.Iterator.Element: Equatable, T.IndexDistance == Int {
// Wagner-Fischer Algorithm
// Max sizes
let oldCount = old.count
let newCount = new.count
// If both collections are empty, return empty changes
if oldCount == 0 && newCount == 0 {
return []
}
// Empty matrix (2D array which consists of steps required taken to and from indices of each)
// +1 on both rows and columns to include to/from empty collection steps
var changesTable: [[[Change<T.Generator.Element>]]] = Array(
repeating: Array(repeating: [], count: newCount + 1),
count: oldCount + 1
)
// Changes for each index of old collection when new collection is empty
for (index, element) in old.enumerated() {
if index == 0 {
changesTable[1][0] = [.Deletion(element: element, destination: index)]
} else {
changesTable[index + 1][0] = changesTable[index][0] + [.Deletion(element: element, destination: index)]
}
}
// Changes for each index of new collection when old collection is empty
for (index, element) in new.enumerated() {
if index == 0 {
changesTable[0][1] = [.Insertion(element: element, destination: index)]
} else {
changesTable[0][index + 1] = changesTable[0][index] + [.Insertion(element: element, destination: index)]
}
}
// If either old collection or new collection is empty, return the row/column which simply consists of insertions/deletions
if oldCount == 0 || newCount == 0 {
return changesTable[oldCount][newCount]
}
// Iterate through the matrix
for (newCollectionIndex, newCollectionElement) in new.enumerated() {
let column = newCollectionIndex + 1
for (oldCollectionIndex, oldCollectionElement) in old.enumerated() {
let row = oldCollectionIndex + 1
if oldCollectionElement == newCollectionElement {
// If same element, no changes, thus copy previous changes
changesTable[row][column] = changesTable[row - 1][column - 1]
} else {
let previousRowChanges = changesTable[row - 1][column] // If least # of steps, current step is Deletion
let previousColumnChanges = changesTable[row][column - 1] // Current step is Insertion
let previousRowAndColumnChanges = changesTable[row - 1][column - 1] // Current step is Substitution
let minimumCount = min(previousRowChanges.count,
previousColumnChanges.count,
previousRowAndColumnChanges.count)
let currentChanges: [Change<T.Iterator.Element>]
switch minimumCount {
case previousRowChanges.count:
currentChanges = previousRowChanges + [.Deletion(element: oldCollectionElement, destination: oldCollectionIndex)]
case previousColumnChanges.count:
currentChanges = previousColumnChanges + [.Insertion(element: newCollectionElement, destination: newCollectionIndex)]
default:
currentChanges = previousRowAndColumnChanges + [.Substitution(element: newCollectionElement, destination: newCollectionIndex)]
}
// Save current changes to table
changesTable[row][column] = currentChanges
}
}
}
// Reduce if reduced flag is true
let changes = changesTable[oldCount][newCount]
if reduced {
return reduce(changes: changes)
} else {
return changes
}
}
fileprivate func reduce<T: Equatable>(changes: [Change<T>]) -> [Change<T>] {
return changes.reduce([Change<T>]()) { (result, change) -> [Change<T>] in
var reducedChanges = result
let currentChange: Change<T>
switch change {
case .Insertion(element: let element, destination: let insertionDestination):
// Find deletion pair in reduced changes
var deletionDestination: Int = 0
if let deletionIndex = reducedChanges.index(where: {
if case .Deletion(element: element, destination: let destination) = $0 {
// Found pair
deletionDestination = destination
return true
} else {
return false
}
}) {
reducedChanges.remove(at: deletionIndex)
currentChange = .Move(element: element, origin: deletionDestination, destination: insertionDestination)
} else {
currentChange = change
}
case .Deletion(element: let element, destination: let deletionDestination):
// Find insertion pair in reduced changes
var insertionDestination: Int = 0
if let insertionIndex = reducedChanges.index(where: {
if case .Insertion(element: element, destination: let destination) = $0 {
// Found pair
insertionDestination = destination
return true
} else {
return false
}
}) {
reducedChanges.remove(at: insertionIndex)
currentChange = .Move(element: element, origin: deletionDestination, destination: insertionDestination)
} else {
currentChange = change
}
default:
currentChange = change
}
return reducedChanges + [currentChange]
}
}
| mit | 976f96e454c49517368ad8f7e8a20454 | 40.911765 | 171 | 0.59214 | 5.063966 | false | false | false | false |
tokyovigilante/CesiumKit | CesiumKit/Platform/Array.swift | 1 | 3004 | //
// Array.swift
// Cent
//
// Created by Ankur Patel on 6/28/14.
// Copyright (c) 2014 Encore Dev Labs LLC. All rights reserved.
//
import Foundation
public func deleteDuplicates<S:RangeReplaceableCollection>(_ seq:S)-> S where S.Iterator.Element: Equatable {
let s = seq.reduce(S()){
ac, x in ac.contains(x) ? ac : ac + [x]
}
return s
}
extension Array {
var sizeInBytes: Int {
return count == 0 ? 0 : count * MemoryLayout.stride(ofValue: self[0])
}
/**
* Finds an item in a sorted array.
*
* @exports binarySearch
*
* @param {Array} array The sorted array to search.
* @param {Object} itemToFind The item to find in the array.
* @param {binarySearch~Comparator} comparator The function to use to compare the item to
* elements in the array.
* @returns {Number} The index of <code>itemToFind</code> in the array, if it exists. If <code>itemToFind</code>
* does not exist, the return value is a negative number which is the bitwise complement (~)
* of the index before which the itemToFind should be inserted in order to maintain the
* sorted order of the array.
*
* @example
* // Create a comparator function to search through an array of numbers.
* var comparator = function(a, b) {
* return a - b;
* };
* var numbers = [0, 2, 4, 6, 8];
* var index = Cesium.binarySearch(numbers, 6, comparator); // 3
*/
func binarySearch (_ itemToFind: Element, comparator: BinarySearchComparator) -> Int {
var low = 0
var high = self.count - 1
var i: Int
var comparison: Int
while low <= high {
i = Int(trunc(Double(low + high) / 2.0))
comparison = comparator(self[i], itemToFind)
if comparison < 0 {
low = i + 1
continue
}
if comparison > 0 {
high = i - 1
continue
}
return i;
}
return ~(high + 1)
}
/**
* A function used to compare two items while performing a binary search.
* @callback binarySearch~Comparator
*
* @param {Object} a An item in the array.
* @param {Object} b The item being searched for.
* @returns {Number} Returns a negative value if <code>a</code> is less than <code>b</code>,
* a positive value if <code>a</code> is greater than <code>b</code>, or
* 0 if <code>a</code> is equal to <code>b</code>.
*
* @example
* function compareNumbers(a, b) {
* return a - b;
* }
*/
typealias BinarySearchComparator = (_ a: Element, _ b: Element) -> Int
}
extension Array where Element: Equatable {
// Remove first collection element that is equal to the given `object`:
mutating func removeObject(object: Element) {
if let index = index(of: object) {
remove(at: index)
}
}
}
| apache-2.0 | 0122ee3376ba9443d1f2c0232e6307f9 | 29.969072 | 116 | 0.574234 | 3.989376 | false | false | false | false |
ivanbruel/SwipeIt | Pods/MarkdownKit/MarkdownKit/Classes/Elements/MarkdownLink.swift | 1 | 2590 | //
// MarkdownLink.swift
// Pods
//
// Created by Ivan Bruel on 18/07/16.
//
//
import UIKit
public class MarkdownLink: MarkdownLinkElement {
private static let regex = "\\[[^\\[]*?\\]\\([^\\)]*\\)"
public var font: UIFont?
public var color: UIColor?
public var regex: String {
return MarkdownLink.regex
}
public func regularExpression() throws -> NSRegularExpression {
return try NSRegularExpression(pattern: regex, options: .DotMatchesLineSeparators)
}
public init(font: UIFont? = nil, color: UIColor? = UIColor.blueColor()) {
self.font = font
self.color = color
}
public func formatText(attributedString: NSMutableAttributedString, range: NSRange,
link: String) {
guard let encodedLink = link.stringByAddingPercentEncodingWithAllowedCharacters(.URLHostAllowedCharacterSet())
else {
return
}
guard let url = NSURL(string: link) ?? NSURL(string: encodedLink) else { return }
attributedString.addAttribute(NSLinkAttributeName, value: url, range: range)
}
public func match(match: NSTextCheckingResult, attributedString: NSMutableAttributedString) {
let nsString = attributedString.string as NSString
let linkStartInResult = nsString
.rangeOfString("(", options: .BackwardsSearch, range: match.range).location
let linkRange =
NSRange(location: linkStartInResult,
length: match.range.length + match.range.location - linkStartInResult - 1)
let linkURLString = nsString
.substringWithRange(NSRange(location: linkRange.location + 1, length: linkRange.length - 1))
// deleting trailing markdown
// needs to be called before formattingBlock to support modification of length
attributedString.deleteCharactersInRange(NSRange(location: linkRange.location - 1,
length: linkRange.length + 2))
// deleting leading markdown
// needs to be called before formattingBlock to provide a stable range
attributedString.deleteCharactersInRange(NSRange(location: match.range.location, length: 1))
let formatRange = NSRange(location: match.range.location,
length: linkStartInResult - match.range.location - 2)
formatText(attributedString, range: formatRange, link: linkURLString)
addAttributes(attributedString, range: formatRange, link: linkURLString)
}
public func addAttributes(attributedString: NSMutableAttributedString, range: NSRange,
link: String) {
attributedString.addAttributes(attributes, range: range)
}
}
| mit | aaf2e5579bcd6639df4f307978f5a9e7 | 35.478873 | 114 | 0.700772 | 4.952199 | false | false | false | false |
suncry/MLHybrid | Source/Content/Model/Hybrid_headerModel.swift | 1 | 1119 | //
// Hybrid_headerModel.swift
// Hybrid_Medlinker
//
// Created by caiyang on 16/5/13.
// Copyright © 2016年 caiyang. All rights reserved.
//
import UIKit
class Hybrid_headerModel: NSObject {
var title: Hybrid_titleModel = Hybrid_titleModel()
var left: [Hybrid_naviButtonModel] = []
var right: [Hybrid_naviButtonModel] = []
class func convert(_ dic: [String: AnyObject]) -> Hybrid_headerModel {
let headerModel = Hybrid_headerModel()
headerModel.title = Hybrid_titleModel.convert(dic["title"] as? [String : AnyObject] ?? [:])
var leftArray: [Hybrid_naviButtonModel] = []
for buttonInfo in (dic["left"] as? [[String : AnyObject]] ?? []) {
leftArray.append(Hybrid_naviButtonModel.convert(buttonInfo))
}
headerModel.left = leftArray
var rightArray: [Hybrid_naviButtonModel] = []
for buttonInfo in (dic["right"] as? [[String : AnyObject]] ?? []) {
rightArray.append(Hybrid_naviButtonModel.convert(buttonInfo))
}
headerModel.right = rightArray
return headerModel
}
}
| mit | 22d1873062b4dea87a20ca0be8cfaade | 31.823529 | 99 | 0.629032 | 3.929577 | false | false | false | false |
vincent-cheny/DailyRecord | DailyRecord/DatePickerDialog.swift | 1 | 10895 | import Foundation
import UIKit
import QuartzCore
class DatePickerDialog: UIView {
typealias DatePickerCallback = (date: NSDate) -> Void
/* Consts */
private let kDatePickerDialogDefaultButtonHeight: CGFloat = 50
private let kDatePickerDialogDefaultButtonSpacerHeight: CGFloat = 1
private let kDatePickerDialogCornerRadius: CGFloat = 7
private let kDatePickerDialogDoneButtonTag: Int = 1
/* Views */
private var dialogView: UIView!
private var titleLabel: UILabel!
private var datePicker: UIDatePicker!
private var cancelButton: UIButton!
private var doneButton: UIButton!
/* Vars */
private var defaultDate: NSDate?
private var datePickerMode: UIDatePickerMode?
private var callback: DatePickerCallback?
/* Overrides */
init() {
super.init(frame: CGRectMake(0, 0, UIScreen.mainScreen().bounds.size.width, UIScreen.mainScreen().bounds.size.height))
setupView()
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func setupView() {
self.dialogView = createContainerView()
self.dialogView!.layer.shouldRasterize = true
self.dialogView!.layer.rasterizationScale = UIScreen.mainScreen().scale
self.layer.shouldRasterize = true
self.layer.rasterizationScale = UIScreen.mainScreen().scale
self.dialogView!.layer.opacity = 0.5
self.dialogView!.layer.transform = CATransform3DMakeScale(1.3, 1.3, 1)
self.backgroundColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0)
self.addSubview(self.dialogView!)
}
/* Handle device orientation changes */
func deviceOrientationDidChange(notification: NSNotification) {
close() // For now just close it
}
/* Create the dialog view, and animate opening the dialog */
func show(title: String, doneButtonTitle: String = "Done", cancelButtonTitle: String = "Cancel", defaultDate: NSDate = NSDate(), datePickerMode: UIDatePickerMode = .DateAndTime, callback: DatePickerCallback) {
self.titleLabel.text = title
self.doneButton.setTitle(doneButtonTitle, forState: .Normal)
self.cancelButton.setTitle(cancelButtonTitle, forState: .Normal)
self.datePickerMode = datePickerMode
self.callback = callback
self.defaultDate = defaultDate
self.datePicker.datePickerMode = self.datePickerMode ?? .Date
self.datePicker.date = self.defaultDate ?? NSDate()
self.datePicker.locale = NSLocale(localeIdentifier: "zh_CN")
/* */
UIApplication.sharedApplication().windows.first!.addSubview(self)
UIApplication.sharedApplication().windows.first!.endEditing(true)
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(DatePickerDialog.deviceOrientationDidChange(_:)), name: UIDeviceOrientationDidChangeNotification, object: nil)
/* Anim */
UIView.animateWithDuration(
0.2,
delay: 0,
options: UIViewAnimationOptions.CurveEaseInOut,
animations: { () -> Void in
self.backgroundColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.4)
self.dialogView!.layer.opacity = 1
self.dialogView!.layer.transform = CATransform3DMakeScale(1, 1, 1)
},
completion: nil
)
}
/* Dialog close animation then cleaning and removing the view from the parent */
private func close() {
NSNotificationCenter.defaultCenter().removeObserver(self)
let currentTransform = self.dialogView.layer.transform
let startRotation = (self.valueForKeyPath("layer.transform.rotation.z") as? NSNumber) as? Double ?? 0.0
let rotation = CATransform3DMakeRotation((CGFloat)(-startRotation + M_PI * 270 / 180), 0, 0, 0)
self.dialogView.layer.transform = CATransform3DConcat(rotation, CATransform3DMakeScale(1, 1, 1))
self.dialogView.layer.opacity = 1
UIView.animateWithDuration(
0.2,
delay: 0,
options: UIViewAnimationOptions.TransitionNone,
animations: { () -> Void in
self.backgroundColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0)
self.dialogView.layer.transform = CATransform3DConcat(currentTransform, CATransform3DMakeScale(0.6, 0.6, 1))
self.dialogView.layer.opacity = 0
}) { (finished: Bool) -> Void in
for v in self.subviews {
v.removeFromSuperview()
}
self.removeFromSuperview()
}
}
/* Creates the container view here: create the dialog, then add the custom content and buttons */
private func createContainerView() -> UIView {
let screenSize = countScreenSize()
let dialogSize = CGSizeMake(
300,
230
+ kDatePickerDialogDefaultButtonHeight
+ kDatePickerDialogDefaultButtonSpacerHeight)
// For the black background
self.frame = CGRectMake(0, 0, screenSize.width, screenSize.height)
// This is the dialog's container; we attach the custom content and the buttons to this one
let dialogContainer = UIView(frame: CGRectMake((screenSize.width - dialogSize.width) / 2, (screenSize.height - dialogSize.height) / 2, dialogSize.width, dialogSize.height))
// First, we style the dialog to match the iOS8 UIAlertView >>>
let gradient: CAGradientLayer = CAGradientLayer(layer: self.layer)
gradient.frame = dialogContainer.bounds
gradient.colors = [UIColor(red: 218/255, green: 218/255, blue: 218/255, alpha: 1).CGColor,
UIColor(red: 233/255, green: 233/255, blue: 233/255, alpha: 1).CGColor,
UIColor(red: 218/255, green: 218/255, blue: 218/255, alpha: 1).CGColor]
let cornerRadius = kDatePickerDialogCornerRadius
gradient.cornerRadius = cornerRadius
dialogContainer.layer.insertSublayer(gradient, atIndex: 0)
dialogContainer.layer.cornerRadius = cornerRadius
dialogContainer.layer.borderColor = UIColor(red: 198/255, green: 198/255, blue: 198/255, alpha: 1).CGColor
dialogContainer.layer.borderWidth = 1
dialogContainer.layer.shadowRadius = cornerRadius + 5
dialogContainer.layer.shadowOpacity = 0.1
dialogContainer.layer.shadowOffset = CGSizeMake(0 - (cornerRadius + 5) / 2, 0 - (cornerRadius + 5) / 2)
dialogContainer.layer.shadowColor = UIColor.blackColor().CGColor
dialogContainer.layer.shadowPath = UIBezierPath(roundedRect: dialogContainer.bounds, cornerRadius: dialogContainer.layer.cornerRadius).CGPath
// There is a line above the button
let lineView = UIView(frame: CGRectMake(0, dialogContainer.bounds.size.height - kDatePickerDialogDefaultButtonHeight - kDatePickerDialogDefaultButtonSpacerHeight, dialogContainer.bounds.size.width, kDatePickerDialogDefaultButtonSpacerHeight))
lineView.backgroundColor = UIColor(red: 198/255, green: 198/255, blue: 198/255, alpha: 1)
dialogContainer.addSubview(lineView)
// ˆˆˆ
//Title
self.titleLabel = UILabel(frame: CGRectMake(10, 10, 280, 30))
self.titleLabel.textAlignment = NSTextAlignment.Center
self.titleLabel.font = UIFont.boldSystemFontOfSize(17)
dialogContainer.addSubview(self.titleLabel)
self.datePicker = UIDatePicker(frame: CGRectMake(0, 30, 0, 0))
self.datePicker.autoresizingMask = UIViewAutoresizing.FlexibleRightMargin
self.datePicker.frame.size.width = 300
dialogContainer.addSubview(self.datePicker)
// Add the buttons
addButtonsToView(dialogContainer)
return dialogContainer
}
/* Add buttons to container */
private func addButtonsToView(container: UIView) {
let buttonWidth = container.bounds.size.width / 2
self.cancelButton = UIButton(type: UIButtonType.Custom) as UIButton
self.cancelButton.frame = CGRectMake(
0,
container.bounds.size.height - kDatePickerDialogDefaultButtonHeight,
buttonWidth,
kDatePickerDialogDefaultButtonHeight
)
self.cancelButton.setTitleColor(UIColor(red: 0, green: 0.5, blue: 1, alpha: 1), forState: UIControlState.Normal)
self.cancelButton.setTitleColor(UIColor(red: 0.2, green: 0.2, blue: 0.2, alpha: 0.5), forState: UIControlState.Highlighted)
self.cancelButton.titleLabel!.font = UIFont.boldSystemFontOfSize(14)
self.cancelButton.layer.cornerRadius = kDatePickerDialogCornerRadius
self.cancelButton.addTarget(self, action: #selector(DatePickerDialog.buttonTapped(_:)), forControlEvents: UIControlEvents.TouchUpInside)
container.addSubview(self.cancelButton)
self.doneButton = UIButton(type: UIButtonType.Custom) as UIButton
self.doneButton.frame = CGRectMake(
buttonWidth,
container.bounds.size.height - kDatePickerDialogDefaultButtonHeight,
buttonWidth,
kDatePickerDialogDefaultButtonHeight
)
self.doneButton.tag = kDatePickerDialogDoneButtonTag
self.doneButton.setTitleColor(UIColor(red: 0, green: 0.5, blue: 1, alpha: 1), forState: UIControlState.Normal)
self.doneButton.setTitleColor(UIColor(red: 0.2, green: 0.2, blue: 0.2, alpha: 0.5), forState: UIControlState.Highlighted)
self.doneButton.titleLabel!.font = UIFont.boldSystemFontOfSize(14)
self.doneButton.layer.cornerRadius = kDatePickerDialogCornerRadius
self.doneButton.addTarget(self, action: #selector(DatePickerDialog.buttonTapped(_:)), forControlEvents: UIControlEvents.TouchUpInside)
container.addSubview(self.doneButton)
}
func buttonTapped(sender: UIButton!) {
if sender.tag == kDatePickerDialogDoneButtonTag {
self.callback?(date: self.datePicker.date)
}
close()
}
/* Helper function: count and return the screen's size */
func countScreenSize() -> CGSize {
let screenWidth = UIScreen.mainScreen().applicationFrame.size.width
let screenHeight = UIScreen.mainScreen().bounds.size.height
return CGSizeMake(screenWidth, screenHeight)
}
}
| gpl-2.0 | 474e340c5fd3ffec8b075330162c4d1e | 45.356522 | 250 | 0.646805 | 5.323558 | false | false | false | false |
CoderAlexChan/AlexCocoa | Extension/UIScrollView+extension.swift | 1 | 6056 | //
// UIScrollView+extension.swift
// Main
//
// Created by 陈文强 on 2017/5/10.
// Copyright © 2017年 陈文强. All rights reserved.
//
import UIKit
import WebKit
// 防止scrollView手势覆盖侧滑手势
public extension UIScrollView {
public typealias CaptureHandle = (UIImage?) -> Void
public func snapShot(_ completionHandler: @escaping CaptureHandle) {
// Put a fake Cover of View
let snapShotView = self.snapshotView(afterScreenUpdates: false)
snapShotView?.frame = CGRect(x: self.frame.origin.x, y: self.frame.origin.y, width: (snapShotView?.frame.size.width)!, height: (snapShotView?.frame.size.height)!)
self.superview?.addSubview(snapShotView!)
// Backup all properties of scrollview if needed
let bakFrame = self.frame
let bakOffset = self.contentOffset
let bakSuperView = self.superview
let bakIndex = self.superview?.subviews.index(of: self)
// Scroll To Bottom show all cached view
if self.frame.size.height < self.contentSize.height {
self.contentOffset = CGPoint(x: 0, y: self.contentSize.height - self.frame.size.height)
}
self.swRenderImageView({ [weak self] (capturedImage) -> Void in
// Recover View
let strongSelf = self!
strongSelf.removeFromSuperview()
strongSelf.frame = bakFrame
strongSelf.contentOffset = bakOffset
bakSuperView?.insertSubview(strongSelf, at: bakIndex!)
snapShotView?.removeFromSuperview()
completionHandler(capturedImage)
})
}
fileprivate func swRenderImageView(_ completionHandler: @escaping (_ capturedImage: UIImage?) -> Void) {
// Rebuild scrollView superView and their hold relationship
let swTempRenderView = UIView(frame: CGRect(x: 0, y: 0, width: self.contentSize.width, height: self.contentSize.height))
self.removeFromSuperview()
swTempRenderView.addSubview(self)
self.contentOffset = CGPoint.zero
self.frame = swTempRenderView.bounds
// Swizzling setFrame
let method: Method = class_getInstanceMethod(object_getClass(self), #selector(setter: UIView.frame))
let swizzledMethod: Method = class_getInstanceMethod(object_getClass(self), Selector(("swSetFrame:")))
method_exchangeImplementations(method, swizzledMethod)
// Sometimes ScrollView will Capture nothing without defer;
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + Double(Int64(0.3 * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC)) { () -> Void in
let bounds = self.bounds
UIGraphicsBeginImageContextWithOptions(bounds.size, false, UIScreen.main.scale)
if self.containWKWebView {
self.drawHierarchy(in: bounds, afterScreenUpdates: true)
} else {
self.layer.render(in: UIGraphicsGetCurrentContext()!)
}
let capturedImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
method_exchangeImplementations(swizzledMethod, method)
completionHandler(capturedImage)
}
}
// Simulate People Action, all the `fixed` element will be repeate
// SwContentCapture will capture all content without simulate people action, more perfect.
public func swContentScrollCapture (_ completionHandler: @escaping (_ capturedImage: UIImage?) -> Void) {
// Put a fake Cover of View
let snapShotView = self.snapshotView(afterScreenUpdates: true)
snapShotView?.frame = CGRect(x: self.frame.origin.x, y: self.frame.origin.y, width: (snapShotView?.frame.size.width)!, height: (snapShotView?.frame.size.height)!)
self.superview?.addSubview(snapShotView!)
// Backup
let bakOffset = self.contentOffset
// Divide
let page = floorf(Float(self.contentSize.height / self.bounds.height))
UIGraphicsBeginImageContextWithOptions(self.contentSize, false, UIScreen.main.scale)
self.swContentScrollPageDraw(0, maxIndex: Int(page), drawCallback: { [weak self] () -> Void in
let strongSelf = self
let capturedImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
// Recover
strongSelf?.setContentOffset(bakOffset, animated: false)
snapShotView?.removeFromSuperview()
completionHandler(capturedImage)
})
}
fileprivate func swContentScrollPageDraw (_ index: Int, maxIndex: Int, drawCallback: @escaping () -> Void) {
self.setContentOffset(CGPoint(x: 0, y: CGFloat(index) * self.frame.size.height), animated: false)
let splitFrame = CGRect(x: 0, y: CGFloat(index) * self.frame.size.height, width: bounds.size.width, height: bounds.size.height)
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + Double(Int64(0.3 * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC)) { () -> Void in
self.drawHierarchy(in: splitFrame, afterScreenUpdates: true)
if index < maxIndex {
self.swContentScrollPageDraw(index + 1, maxIndex: maxIndex, drawCallback: drawCallback)
}else{
drawCallback()
}
}
}
}
public extension UIWebView {
public func swContentCapture (_ completionHandler: @escaping (_ capturedImage: UIImage?) -> Void) {
self.scrollView.snapShot(completionHandler)
}
public func swContentScrollCapture (_ completionHandler: @escaping (_ capturedImage: UIImage?) -> Void) {
self.scrollView.swContentScrollCapture(completionHandler)
}
}
| mit | 3bdbd426c5bc0ebcaf60164f5604c80a | 39.682432 | 170 | 0.62963 | 4.976033 | false | false | false | false |
hirohisa/RxSwift | RxSwift/RxSwift/Observables/Implementations/ObserveOn.swift | 11 | 3372 | //
// ObserveOn.swift
// RxSwift
//
// Created by Krunoslav Zaher on 7/25/15.
// Copyright (c) 2015 Krunoslav Zaher. All rights reserved.
//
import Foundation
class ObserveOn<E> : Producer<E> {
let scheduler: ImmediateScheduler
let source: Observable<E>
init(source: Observable<E>, scheduler: ImmediateScheduler) {
self.scheduler = scheduler
self.source = source
#if TRACE_RESOURCES
OSAtomicIncrement32(&resourceCount)
#endif
}
override func run<O : ObserverType where O.Element == E>(observer: O, cancel: Disposable, setSink: (Disposable) -> Void) -> Disposable {
let sink = ObserveOnSink(scheduler: scheduler, observer: observer, cancel: cancel)
setSink(sink)
return source.subscribeSafe(sink)
}
#if TRACE_RESOURCES
deinit {
OSAtomicDecrement32(&resourceCount)
}
#endif
}
enum ObserveOnState : Int32 {
// pump is not running
case Stopped = 0
// pump is running
case Running = 1
}
class ObserveOnSink<O: ObserverType> : ObserverBase<O.Element> {
var cancel: Disposable
let scheduler: ImmediateScheduler
var observer: O?
var state = ObserveOnState.Stopped
var queue = Queue<Event<Element>>(capacity: 10)
let scheduleDisposable = SerialDisposable()
init(scheduler: ImmediateScheduler, observer: O, cancel: Disposable) {
self.cancel = cancel
self.scheduler = scheduler
self.observer = observer
}
override func onCore(event: Event<Element>) {
let shouldStart = lock.calculateLocked { () -> Bool in
self.queue.enqueue(event)
switch self.state {
case .Stopped:
self.state = .Running
return true
case .Running:
return false
}
}
if shouldStart {
scheduleDisposable.disposable = scheduleRecursively(self.scheduler, (), self.run)
}
}
func run(state: Void, recurse: Void -> Void) {
let (nextEvent, observer) = self.lock.calculateLocked { () -> (Event<Element>?, O?) in
if self.queue.count > 0 {
return (self.queue.dequeue(), self.observer)
}
else {
self.state = .Stopped
return (nil, self.observer)
}
}
if let nextEvent = nextEvent {
trySend(observer, nextEvent)
if nextEvent.isStopEvent {
self.dispose()
}
}
else {
return
}
let shouldContinue = self.lock.calculateLocked { () -> Bool in
if self.queue.count > 0 {
return true
}
else {
self.state = .Stopped
return false
}
}
if shouldContinue {
recurse()
}
}
override func dispose() {
super.dispose()
let toDispose = lock.calculateLocked { () -> Disposable in
let originalCancel = self.cancel
self.cancel = NopDisposable.instance
self.scheduleDisposable.dispose()
self.observer = nil
return originalCancel
}
toDispose.dispose()
}
} | mit | 8cb11a26481945babd5d6957a461708c | 25.351563 | 140 | 0.548636 | 4.901163 | false | false | false | false |
meika-tea-room/SDC-DIOS | Studio Inventory/Controller/ProfileTableViewController.swift | 1 | 3149 | //
// ProfileTableViewController.swift
// Studio Inventory
//
// Created by William PHETSINORATH on 19/04/2017.
// Copyright © 2017 ETNA. All rights reserved.
//
import UIKit
class ProfileTableViewController: UITableViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 0
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return 0
}
/*
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "reuseIdentifier", for: indexPath)
// Configure the cell...
return cell
}
*/
/*
// Override to support conditional editing of the table view.
override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
// Return false if you do not want the specified item to be editable.
return true
}
*/
/*
// Override to support editing the table view.
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
// Delete the row from the data source
tableView.deleteRows(at: [indexPath], with: .fade)
} else if editingStyle == .insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
*/
/*
// Override to support rearranging the table view.
override func tableView(_ tableView: UITableView, moveRowAt fromIndexPath: IndexPath, to: IndexPath) {
}
*/
/*
// Override to support conditional rearranging of the table view.
override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool {
// Return false if you do not want the item to be re-orderable.
return true
}
*/
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| mit | 84ea3bdb69e77ac1335bff74e05cdaf1 | 32.136842 | 136 | 0.67249 | 5.317568 | false | false | false | false |
inaka/PictureViewMaster-iOS | PictureViewMaster/PictureMasterView/PictureMasterViewController.swift | 1 | 14461 | //
// PictureMasterViewController.swift
// PictureViewMaster
//
// Created by El gera de la gente on 3/21/16.
// Copyright © 2016 Inaka. All rights reserved.
//
import UIKit
public class PictureMasterViewController: UIViewController, UIGestureRecognizerDelegate {
public struct Gestures: OptionSet {
public let rawValue: Int
public init (rawValue: Int) {
self.rawValue = rawValue
}
static let none = Gestures(rawValue: 0)
static let drag = Gestures(rawValue: 1 << 0)
static let rotate = Gestures(rawValue: 1 << 1)
static let zoom = Gestures(rawValue: 1 << 2)
static let doubleTap = Gestures(rawValue: 1 << 3)
static let backgroundTap = Gestures(rawValue: 1 << 4)
static let swipeOut = Gestures(rawValue: 1 << 5)
static let allGestures = Gestures(rawValue: Int.max)
}
struct OffsetDirection: OptionSet {
let rawValue: Int
static let inside = OffsetDirection(rawValue: 0)
static let up = OffsetDirection(rawValue: 1 << 0)
static let down = OffsetDirection(rawValue: 1 << 1)
static let right = OffsetDirection(rawValue: 1 << 2)
static let left = OffsetDirection(rawValue: 1 << 3)
}
@IBOutlet weak var backgroundView: UIView!
@IBOutlet weak var imageView: UIImageView!
private var enabledGestures = Gestures.allGestures
private var image: UIImage!
override public func viewDidLoad() {
super.viewDidLoad()
self.setupImageViewFrameAndImage(self.image)
self.addGestureRecognizers()
self.view.backgroundColor = UIColor.clear
self.view.isOpaque = false
}
public func showImage(_ image: UIImage, in viewController: UIViewController) {
self.image = image
viewController.definesPresentationContext = true
self.modalPresentationStyle = .overCurrentContext
viewController.present(self, animated: true, completion: nil)
}
public func showImage(_ image: UIImage, in viewController: UIViewController, with gestures: Gestures?) {
if let customGestures = gestures {
self.enabledGestures = customGestures
}else {
self.enabledGestures = .backgroundTap
}
self.showImage(image, in: viewController)
}
private func setupImageViewFrameAndImage(_ image: UIImage) {
self.imageView.image = image
self.resetViewFrame(self.imageView,
animated: false,
completion: { finished in
if !finished {
self.resetViewFrameAndRotation(self.imageView,
animated: false,
completion: { finished in
if finished {
print ("finished")
}})
}})
}
private func originalImageViewFitFrameForImage(_ image: UIImage) -> CGRect {
let screenSize = UIScreen.main.bounds
var frame = CGRect()
let heightRatio = image.size.height / image.size.width
let widthRatio = image.size.width / image.size.height
let screenRatio = screenSize.width / screenSize.height
if image.size.height == image.size.width {
if screenRatio >= 1 {
frame.size.height = screenSize.height
frame.size.width = screenSize.height
}else {
frame.size.height = screenSize.width
frame.size.width = screenSize.width
}
}else if image.size.height > image.size.width && widthRatio < screenRatio {
frame.size.height = screenSize.height
frame.size.width = frame.height * widthRatio
}else {
frame.size.width = screenSize.width
frame.size.height = frame.width * heightRatio
}
frame.origin.x = (screenSize.size.width / 2) - (frame.size.width / 2)
frame.origin.y = (screenSize.size.height / 2) - (frame.size.height / 2)
return frame
}
private func addGestureRecognizers() {
self.imageView.isUserInteractionEnabled = true
self.imageView.isMultipleTouchEnabled = true
if self.enabledGestures.contains(.doubleTap) {
let tapRecognizer = UITapGestureRecognizer(target: self, action: #selector(tapGesture(_:)))
tapRecognizer.numberOfTapsRequired = 2
self.imageView.addGestureRecognizer(tapRecognizer)
}
if self.enabledGestures.contains(.zoom) {
let pinchRecognizer = UIPinchGestureRecognizer(target: self, action: #selector(pinchGesture(_:)))
self.imageView.addGestureRecognizer(pinchRecognizer)
pinchRecognizer.delegate = self
}
if self.enabledGestures.contains(.drag) {
let dragRecognizer = UIPanGestureRecognizer(target: self, action: #selector(dragGesture(_:)))
self.imageView.addGestureRecognizer(dragRecognizer)
dragRecognizer.delegate = self
}
if self.enabledGestures.contains(.rotate) {
let rotateRecognizer = UIRotationGestureRecognizer(target: self, action: #selector(rotateGesture(_:)))
self.imageView.addGestureRecognizer(rotateRecognizer)
rotateRecognizer.delegate = self
}
if self.enabledGestures.contains(.backgroundTap) {
let tapBackgroundRecognizer = UITapGestureRecognizer(target: self, action: #selector(tapBackgroundGesture(_:)))
self.backgroundView.addGestureRecognizer(tapBackgroundRecognizer)
}
if self.enabledGestures.contains(.swipeOut) {
let swipeOutRecognizer = UISwipeGestureRecognizer(target: self, action: #selector(swipeOutGesture(_:)))
swipeOutRecognizer.direction = [.right, .left]
swipeOutRecognizer.numberOfTouchesRequired = 2
self.imageView.addGestureRecognizer(swipeOutRecognizer)
}
}
public func tapGesture(_ gesture: UITapGestureRecognizer) {
guard let view = gesture.view else { return }
self.resetViewFrameAndRotation(view, animated: true, completion: nil)
}
public func pinchGesture(_ gesture: UIPinchGestureRecognizer) {
guard let view = gesture.view else { return }
if self.hasToEnlargeView(gesture.view!) && gesture.state == .ended {
self.enlargeViewToMinimumSize(view)
return
}
view.transform = view.transform.scaledBy(x: gesture.scale, y: gesture.scale)
gesture.scale = 1
}
func dragGesture(_ gesture: UIPanGestureRecognizer) {
guard let view = gesture.view else { return }
if self.hasToEnlargeView(gesture.view!) && gesture.state == .ended {
self.enlargeViewToMinimumSize(view)
return
}
if gesture.state == .ended {
gesture.view!.isUserInteractionEnabled = false
self.moveInView(gesture.view!, fromDirection: self.offsetDirectionForView(gesture.view!),
withCompletion: { finish in
gesture.view!.isUserInteractionEnabled = true
})
return
}
let translation = gesture.translation(in: self.view)
view.center = CGPoint(x:view.center.x + translation.x,
y:view.center.y + translation.y)
gesture.setTranslation(CGPoint.zero, in: self.view)
}
func rotateGesture(_ gesture: UIRotationGestureRecognizer) {
guard let view = gesture.view else { return }
if self.hasToEnlargeView(gesture.view!) && gesture.state == .ended {
self.enlargeViewToMinimumSize(view)
return
}
view.transform = view.transform.rotated(by: gesture.rotation)
gesture.rotation = 0
}
func tapBackgroundGesture(_ gesture: UITapGestureRecognizer) {
self.dismiss(animated: false, completion: nil)
}
func swipeOutGesture(_ gesture: UITapGestureRecognizer) {
guard let view = gesture.view else { return }
if self.offsetDirectionForView(view) != .inside && gesture.state == .ended {
self.dismiss(animated: false, completion: nil)
}
}
private func offsetDirectionForView(_ view: UIView) -> OffsetDirection {
var multipleDirections: OffsetDirection = OffsetDirection.inside
let screenSize = UIScreen.main.bounds
if (view.frame.origin.x + view.frame.width) < screenSize.width && (view.frame.width >= screenSize.width) {
multipleDirections.insert(.right)
}
if (view.frame.origin.x > 0) && (view.frame.width >= screenSize.width) {
multipleDirections.insert(.left)
}
if (view.frame.origin.y + view.frame.height) < screenSize.height && (view.frame.height >= screenSize.height) {
multipleDirections.insert(.down)
}
if (view.frame.origin.y > 0) && (view.frame.height >= screenSize.height) {
multipleDirections.insert(.up)
}
return multipleDirections
}
private func moveInView(_ view: UIView, fromDirection offsetDirection: OffsetDirection, withCompletion completion: ((Bool) -> Void)?) {
if offsetDirection == .inside {
completion?(true)
return
}
var viewX: CGFloat = view.frame.origin.x
var viewY: CGFloat = view.frame.origin.y
let screenSize = UIScreen.main.bounds
if offsetDirection.contains(.down) {
viewY = screenSize.size.height - view.frame.height
}
if offsetDirection.contains(.up) {
viewY = 0
}
if offsetDirection.contains(.right) {
viewX = screenSize.size.width - view.frame.width
}
if offsetDirection.contains(.left) {
viewX = 0
}
UIView.animate(withDuration: 0.1, delay: 0.0, options: .curveEaseOut, animations: {
let frame = CGRect(x: viewX, y: viewY, width: view.frame.width, height: view.frame.height)
view.frame = frame
}, completion: completion)
}
private func hasToEnlargeView(_ view: UIView) -> Bool {
let screenSize = UIScreen.main.bounds
let smallerThanScreenWidth = (view.frame.width < screenSize.width)
let smallerThanScreenHeigth = (view.frame.height < screenSize.height)
return smallerThanScreenWidth && smallerThanScreenHeigth
}
private func enlargeViewToMinimumSize(_ view: UIView) {
self.resetViewFrame(view, animated: true, completion: nil)
}
private func resetViewFrame(_ view: UIView, animated: Bool, completion: ((Bool) -> Void)?) {
let duration = animated ? 0.2 : 0.0
UIView.animate(withDuration: duration, delay: 0.0, options: .curveEaseOut, animations: {
let imageView = view
view.frame = self.minimumSizeForView(imageView)
}, completion:completion)
}
private func minimumSizeForView(_ view: UIView) -> CGRect {
let screenSize = UIScreen.main.bounds
var frame = CGRect()
let heightRatio = view.frame.size.height / view.frame.size.width
let widthRatio = view.frame.size.width / view.frame.size.height
let screenRatio = screenSize.width / screenSize.height
if view.frame.size.height == view.frame.size.width {
if screenRatio >= 1 {
frame.size.height = screenSize.height
frame.size.width = screenSize.height
}else {
frame.size.height = screenSize.width
frame.size.width = screenSize.width
}
}else if view.frame.size.height > view.frame.size.width && widthRatio < screenRatio {
frame.size.height = screenSize.height
frame.size.width = frame.height * widthRatio
}else {
frame.size.width = screenSize.width
frame.size.height = frame.width * heightRatio
}
frame.origin.x = (screenSize.size.width / 2) - (frame.size.width / 2)
frame.origin.y = (screenSize.size.height / 2) - (frame.size.height / 2)
return frame
//
//
// let frameXOrigin = (screenSize.size.width / 2) - (screenSize.width / 2)
// let frameYOrigin = (screenSize.size.height / 2) - (screenSize.height / 2)
// if view.frame.size.height == view.frame.size.width {
// return CGRect(x: frameXOrigin, y: frameYOrigin, width: screenSize.width, height: screenSize.width)
// }else if view.frame.size.height > view.frame.size.width && widthRatio < screenRatio {
// return CGRect(x: frameXOrigin, y: frameYOrigin, width: screenSize.height * widthRatio, height: screenSize.height)
// }else {
// return CGRect(x: frameXOrigin, y: frameYOrigin, width: screenSize.width, height: screenSize.width * heightRatio)
// }
}
private func resetViewRotation(_ view: UIView, animated: Bool, completion: ((Bool) -> Void)?) {
let duration = animated ? 0.2 : 0.0
UIView.animate(withDuration: duration, delay: 0.0, options: .curveEaseOut, animations: {
let rotation = (atan2(view.transform.b, view.transform.a))
view.transform = view.transform.rotated(by: -rotation)
}, completion:completion)
}
private func resetViewFrameAndRotation(_ view: UIView, animated: Bool, completion: ((Bool) -> Void)?) {
self.resetViewRotation(view, animated: animated, completion: nil)
self.resetViewFrame(view, animated: animated, completion: completion)
}
//MARK: UIGestureRecognizerDelegate
public func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
return true
}
}
| apache-2.0 | 416973b2b34435c6204efca5a95817b4 | 41.280702 | 164 | 0.603734 | 4.895058 | false | false | false | false |
shadanan/mado | Mado/Registry.swift | 1 | 6789 | //
// Registry.swift
// Mado
//
// Created by Shad Sharma on 2/14/17.
// Copyright © 2017 Shad Sharma. All rights reserved.
//
import Cocoa
class Registry {
var registryItems: [RegistryItem] = []
init() {
load()
}
func save() {
print("Save registry")
var encodedRegistry: [[String: Any]] = []
for registryItem in registryItems {
encodedRegistry.append(registryItem.encode())
}
UserDefaults.standard.set(encodedRegistry, forKey: "registry")
}
func load() {
print("Load registry")
if let encodedRegistry = UserDefaults.standard.array(forKey: "registry") as? [[String: Any]] {
registryItems.removeAll()
for encodedRegistryItem in encodedRegistry {
if let registryItem = decode(encodedRegistryItem: encodedRegistryItem) {
registryItems.append(registryItem)
} else {
print("Failed to decode: \(encodedRegistryItem)")
reset()
return
}
}
} else {
reset()
}
}
func reset() {
print("Reset registry")
registryItems.removeAll()
let left = Resize(
title: "Left",
resizeSpec: ResizeSpec(xExpr: "0", yExpr: "0", wExpr: "W/2", hExpr: "H"),
shortcut: KeyboardShortcut(keyCode: 123, shiftDown: false, controlDown: true, optionDown: true, commandDown: false))
registryItems.append(left)
let right = Resize(
title: "Right",
resizeSpec: ResizeSpec(xExpr: "W/2", yExpr: "0", wExpr: "W/2", hExpr: "H"),
shortcut: KeyboardShortcut(keyCode: 124, shiftDown: false, controlDown: true, optionDown: true, commandDown: false))
registryItems.append(right)
let up = Resize(
title: "Up",
resizeSpec: ResizeSpec(xExpr: "0", yExpr: "H/2", wExpr: "W", hExpr: "H/2"),
shortcut: KeyboardShortcut(keyCode: 126, shiftDown: false, controlDown: true, optionDown: true, commandDown: false))
registryItems.append(up)
let down = Resize(
title: "Down",
resizeSpec: ResizeSpec(xExpr: "0", yExpr: "0", wExpr: "W", hExpr: "H/2"),
shortcut: KeyboardShortcut(keyCode: 125, shiftDown: false, controlDown: true, optionDown: true, commandDown: false))
registryItems.append(down)
registryItems.append(Separator.separator)
let topLeft = Resize(
title: "Top Left",
resizeSpec: ResizeSpec(xExpr: "0", yExpr: "H/2", wExpr: "W/2", hExpr: "H/2"),
shortcut: KeyboardShortcut(keyCode: 32, shiftDown: false, controlDown: true, optionDown: true, commandDown: false))
registryItems.append(topLeft)
let topRight = Resize(
title: "Top Right",
resizeSpec: ResizeSpec(xExpr: "W/2", yExpr: "H/2", wExpr: "W/2", hExpr: "H/2"),
shortcut: KeyboardShortcut(keyCode: 34, shiftDown: false, controlDown: true, optionDown: true, commandDown: false))
registryItems.append(topRight)
let bottomLeft = Resize(
title: "Bottom Left",
resizeSpec: ResizeSpec(xExpr: "0", yExpr: "0", wExpr: "W/2", hExpr: "H/2"),
shortcut: KeyboardShortcut(keyCode: 38, shiftDown: false, controlDown: true, optionDown: true, commandDown: false))
registryItems.append(bottomLeft)
let bottomRight = Resize(
title: "Bottom Right",
resizeSpec: ResizeSpec(xExpr: "W/2", yExpr: "0", wExpr: "W/2", hExpr: "H/2"),
shortcut: KeyboardShortcut(keyCode: 40, shiftDown: false, controlDown: true, optionDown: true, commandDown: false))
registryItems.append(bottomRight)
registryItems.append(Separator.separator)
let leftThird = Resize(
title: "Left Third",
resizeSpec: ResizeSpec(xExpr: "0", yExpr: "0", wExpr: "W/3", hExpr: "H"),
shortcut: KeyboardShortcut(keyCode: 2, shiftDown: false, controlDown: true, optionDown: true, commandDown: false))
registryItems.append(leftThird)
let centerThird = Resize(
title: "Center Third",
resizeSpec: ResizeSpec(xExpr: "W/3", yExpr: "0", wExpr: "W/3", hExpr: "H"),
shortcut: KeyboardShortcut(keyCode: 3, shiftDown: false, controlDown: true, optionDown: true, commandDown: false))
registryItems.append(centerThird)
let rightThird = Resize(
title: "Right Third",
resizeSpec: ResizeSpec(xExpr: "2W/3", yExpr: "0", wExpr: "W/3", hExpr: "H"),
shortcut: KeyboardShortcut(keyCode: 5, shiftDown: false, controlDown: true, optionDown: true, commandDown: false))
registryItems.append(rightThird)
let leftTwoThirds = Resize(
title: "Left Two Thirds",
resizeSpec: ResizeSpec(xExpr: "0", yExpr: "0", wExpr: "2W/3", hExpr: "H"),
shortcut: KeyboardShortcut(keyCode: 14, shiftDown: false, controlDown: true, optionDown: true, commandDown: false))
registryItems.append(leftTwoThirds)
let rightTwoThirds = Resize(
title: "Right Two Thirds",
resizeSpec: ResizeSpec(xExpr: "W/3", yExpr: "0", wExpr: "2W/3", hExpr: "H"),
shortcut: KeyboardShortcut(keyCode: 17, shiftDown: false, controlDown: true, optionDown: true, commandDown: false))
registryItems.append(rightTwoThirds)
registryItems.append(Separator.separator)
let center = Resize(
title: "Center",
resizeSpec: ResizeSpec(xExpr: "(W-w)/2", yExpr: "(H-h)/2", wExpr: "w", hExpr: "h"),
shortcut: KeyboardShortcut(keyCode: 8, shiftDown: false, controlDown: true, optionDown: true, commandDown: false))
registryItems.append(center)
let maximize = Resize(
title: "Maximize",
resizeSpec: ResizeSpec(xExpr: "0", yExpr: "0", wExpr: "W", hExpr: "H"),
shortcut: KeyboardShortcut(keyCode: 36, shiftDown: false, controlDown: true, optionDown: true, commandDown: false))
registryItems.append(maximize)
save()
}
func keyDown(event: CGEvent) -> Bool {
let shortcut = KeyboardShortcut.from(CGEvent: event)
print("Shortcut: \(shortcut) KeyCode: \(shortcut.keyCode)")
for resizePref in registryItems {
if resizePref.matches(shortcut: shortcut) {
resizePref.apply()
return true
}
}
return false
}
}
| mit | 601dda38e069a597526fa4e91860eeef | 39.646707 | 128 | 0.579847 | 4.106473 | false | false | false | false |
LedgerHQ/ledger-wallet-ios | ledger-wallet-ios/Managers/Pairing/PairingTransactionsManager.swift | 1 | 8300 | //
// IncomingTransactionsManager.swift
// ledger-wallet-ios
//
// Created by Nicolas Bigot on 02/02/2015.
// Copyright (c) 2015 Ledger. All rights reserved.
//
import Foundation
protocol PairingTransactionsManagerDelegate: class {
func pairingTransactionsManager(pairingTransactionsManager: PairingTransactionsManager, didReceiveNewTransactionInfo transactionInfo: PairingTransactionInfo)
func pairingTransactionsManager(pairingTransactionsManager: PairingTransactionsManager, dongleDidCancelCurrentTransactionInfo transactionInfo: PairingTransactionInfo)
}
final class PairingTransactionsManager: BasePairingManager {
weak var delegate: PairingTransactionsManagerDelegate? = nil
private var webSockets: [WebSocket: PairingKeychainItem] = [:]
private var webSocketsBaseURL: String! = nil
private var cryptor: PairingTransactionsCryptor! = nil
private var isConfirmingTransaction: Bool { return currentTransactionInfo != nil && currentTransactionWebSocket != nil && currentTransactionPairingKeychainItem != nil }
private var currentTransactionInfo: PairingTransactionInfo? = nil
private var currentTransactionWebSocket: WebSocket? = nil
private var currentTransactionPairingKeychainItem: PairingKeychainItem? = nil
// MARK: - Initialization
deinit {
stopListening()
}
}
extension PairingTransactionsManager {
// MARK: - Transactions management
func tryListening() -> Bool {
// create all webSockets
initilizeWebSockets()
return webSockets.count > 0
}
func stopListening() {
// destroy all webSockets
destroyWebSockets()
destroyCurrentTransactionWebSocket()
}
func restartListening() {
stopListening()
tryListening()
}
func confirmTransaction(transactionInfo: PairingTransactionInfo) {
handleTransaction(transactionInfo, confirm: true)
}
func rejectTransaction(transactionInfo: PairingTransactionInfo) {
handleTransaction(transactionInfo, confirm: false)
}
private func handleTransaction(transactionInfo: PairingTransactionInfo, confirm: Bool) {
if (!isConfirmingTransaction || transactionInfo !== currentTransactionInfo) {
return
}
// send response
var data:[String: AnyObject] = ["is_accepted": confirm]
if confirm {
data["pin"] = currentTransactionInfo!.pinCode
}
sendMessage(messageWithType(MessageType.Response, data: data), webSocket: currentTransactionWebSocket!)
// start listening
initilizeWebSockets(excepted: [currentTransactionPairingKeychainItem!])
// merge current transaction webSocket in newly listening webSockets
webSockets[currentTransactionWebSocket!] = currentTransactionPairingKeychainItem
// forget current transaction info
currentTransactionInfo = nil
currentTransactionWebSocket = nil
currentTransactionPairingKeychainItem = nil
}
private func initilizeWebSockets(excepted exceptions: [PairingKeychainItem]? = nil) {
// initialize websocket URL
if (webSocketsBaseURL == nil) { webSocketsBaseURL = LedgerWebSocketBaseURL }
// create cryptor
if (cryptor == nil) { cryptor = PairingTransactionsCryptor() }
// rebuild websockets
let exemptedPairingItem = exceptions ?? []
let pairingItems = PairingKeychainItem.fetchAll() as! [PairingKeychainItem]
for pairingItem in pairingItems {
if (exemptedPairingItem.contains(pairingItem)) {
continue
}
let webSocket = WebSocket(url: NSURL(string: webSocketsBaseURL)!.URLByAppendingPathComponent("/2fa/channels"))
webSocket.delegate = self
webSocket.connect()
webSockets[webSocket] = pairingItem
}
}
private func destroyWebSockets(excepted exceptions: [WebSocket]? = nil) {
// destroy webSockets
let exemptedWebSockets = exceptions ?? []
for (webSocket, _) in webSockets {
if (exemptedWebSockets.contains(webSocket)) {
continue
}
webSocket.delegate = nil
if webSocket.isConnected {
webSocket.disconnect()
}
}
webSockets.removeAll()
}
private func destroyCurrentTransactionWebSocket() {
currentTransactionWebSocket?.delegate = nil
if let isConnected = currentTransactionWebSocket?.isConnected {
if isConnected == true {
currentTransactionWebSocket?.disconnect()
}
}
currentTransactionWebSocket = nil
currentTransactionPairingKeychainItem = nil
currentTransactionInfo = nil
}
private func acceptTransactionInfo(transactionInfo: PairingTransactionInfo, fromWebSocket webSocket: WebSocket) {
// retain transaction info
currentTransactionInfo = transactionInfo
currentTransactionWebSocket = webSocket
currentTransactionPairingKeychainItem = webSockets[webSocket]!
// assign transaction info
transactionInfo.dongleName = currentTransactionPairingKeychainItem!.dongleName!
// destroy all webSockets excepted this one
destroyWebSockets(excepted: [webSocket])
// send accept
sendMessage(messageWithType(MessageType.Accept, data: nil), webSocket: webSocket)
// notify delegate
self.delegate?.pairingTransactionsManager(self, didReceiveNewTransactionInfo: currentTransactionInfo!)
}
}
extension PairingTransactionsManager {
// MARK: Messages management
override func handleRequestMessage(message: Message, webSocket: WebSocket) {
if (isConfirmingTransaction) {
return
}
// get base 16 string
if let dataString = message["second_factor_data"] as? String {
// get encrypted blob
if let blob = Crypto.Encode.dataFromBase16String(dataString) {
// get pairing item
if let pairingKeychainItem = webSockets[webSocket] {
// get transaction info from blob
if let transactionInfo = cryptor.transactionInfoFromEncryptedBlob(blob, pairingKey: pairingKeychainItem.pairingKey!) {
// accept transaction info
acceptTransactionInfo(transactionInfo, fromWebSocket: webSocket)
}
}
}
}
}
override func handleDisconnectMessage(message: Message, webSocket: WebSocket) {
if (isConfirmingTransaction) {
// notify delegate
self.delegate?.pairingTransactionsManager(self, dongleDidCancelCurrentTransactionInfo: currentTransactionInfo!)
// stop/start listening again
restartListening()
}
}
}
extension PairingTransactionsManager {
// MARK: - WebSocket delegate
override func handleWebSocketDidConnect(webSocket: WebSocket) {
if (!isConfirmingTransaction) {
// get pairing item
if let pairingKeychainItem = webSockets[webSocket] {
// join room
sendMessage(messageWithType(MessageType.Join, data: ["room": pairingKeychainItem.pairingId!]), webSocket: webSocket)
// send repeat message
sendMessage(messageWithType(MessageType.Repeat, data: nil), webSocket: webSocket)
}
}
}
override func handleWebSocket(webSocket: WebSocket, didDisconnectWithError error: NSError?) {
if (isConfirmingTransaction) {
// notify delegate
self.delegate?.pairingTransactionsManager(self, dongleDidCancelCurrentTransactionInfo: currentTransactionInfo!)
// stop/start listening again
restartListening()
}
else {
// perform reconnect
delayOnMainQueue(3.0) {
webSocket.connect()
}
}
}
} | mit | 962d688f6852707496ae35b21e7b2443 | 35.248908 | 172 | 0.648554 | 5.634759 | false | false | false | false |
gmunhoz/CollieGallery | Pod/Classes/CollieGalleryDefaultTransition.swift | 1 | 4696 | //
// CollieGalleryDefaultTransition.swift
//
// Copyright (c) 2016 Guilherme Munhoz <[email protected]>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import UIKit
internal class CollieGalleryDefaultTransition: CollieGalleryTransitionProtocol {
// MARK: - Private properties
fileprivate let minorScale = CGAffineTransform(scaleX: 0.1, y: 0.1)
fileprivate let offStage: CGFloat = 100.0
// MARK: - CollieGalleryTransitionProtocol
internal func animatePresentationWithTransitionContext(_ transitionContext: UIViewControllerContextTransitioning, duration: TimeInterval) {
let presentedController = transitionContext.viewController(forKey: UITransitionContextViewControllerKey.to) as! CollieGallery
let presentedControllerView = transitionContext.view(forKey: UITransitionContextViewKey.to)!
let containerView = transitionContext.containerView
presentedControllerView.alpha = 0.0
presentedController.pagingScrollView.transform = self.minorScale
presentedController.closeButton.center.x -= self.offStage
presentedController.actionButton?.center.x += self.offStage
presentedController.progressTrackView?.center.y += self.offStage
presentedController.captionView.center.y += self.offStage
containerView.addSubview(presentedControllerView)
UIView.animate(withDuration: duration, delay: 0.0, usingSpringWithDamping: 1.0, initialSpringVelocity: 0.0, options: .allowUserInteraction, animations: {
presentedControllerView.alpha = 1.0
presentedController.closeButton.center.x += self.offStage
presentedController.actionButton?.center.x -= self.offStage
presentedController.progressTrackView?.center.y -= self.offStage
presentedController.captionView.center.y -= self.offStage
presentedController.pagingScrollView.transform = CGAffineTransform.identity
}, completion: {(completed: Bool) -> Void in
transitionContext.completeTransition(completed)
})
}
internal func animateDismissalWithTransitionContext(_ transitionContext: UIViewControllerContextTransitioning, duration: TimeInterval) {
let presentingController = transitionContext.viewController(forKey: UITransitionContextViewControllerKey.from) as! CollieGallery
let presentingControllerView = transitionContext.view(forKey: UITransitionContextViewKey.from)!
let containerView = transitionContext.containerView
containerView.addSubview(presentingControllerView)
UIView.animate(withDuration: duration, delay: 0.0, usingSpringWithDamping: 1.0, initialSpringVelocity: 0.0, options: .allowUserInteraction, animations: {
presentingControllerView.alpha = 0.0
presentingController.closeButton.center.x -= self.offStage
presentingController.actionButton?.center.x += self.offStage
presentingController.progressTrackView?.center.y += self.offStage
presentingController.captionView.center.y += self.offStage
presentingController.pagingScrollView.transform = self.minorScale
}, completion: {(completed: Bool) -> Void in
if(transitionContext.transitionWasCancelled){
transitionContext.completeTransition(false)
}
else {
transitionContext.completeTransition(true)
}
})
}
}
| mit | e4cc30326b6e65992bce4d578f2e341c | 50.604396 | 161 | 0.708049 | 5.657831 | false | false | false | false |
coodly/SlimTimerAPI | Sources/DeleteTaskRequest.swift | 1 | 1908 | /*
* Copyright 2018 Coodly LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import Foundation
private let DeleteTaskPathBase = "/users/%@/tasks/%@"
public enum DeleteTaskResult {
case success
case failure(Error)
}
internal class DeleteTaskRequest: NetworkRequest<EmptySuccessResponse>, UserIdConsumer, AuthenticatedRequest {
var userId: Int!
internal var resultHandler: ((DeleteTaskResult) -> Void)?
private let task: Task
init(task: Task) {
self.task = task
}
override func performRequest() {
guard let entryId = task.id else {
Logging.log("Trying to delete task that was not created remotely. Just report that it's deleted")
resultHandler?(.success)
return
}
let path = String(format: DeleteTaskPathBase, NSNumber(value: userId), NSNumber(value: entryId))
DELETE(path)
}
override func handle(result: NetworkResult<EmptySuccessResponse>) {
if result.value?.success ?? false {
resultHandler?(.success)
} else if result.statusCode == 404 {
//TODO jaanus: check this. Trying to delete already deleted entry?
Logging.log("Got HTTP 404. No entry with given id")
resultHandler?(.success)
} else {
resultHandler?(.failure(result.error ?? .unknown))
}
}
}
| apache-2.0 | 8b9447b8c47fc2353a26bce6685369a1 | 31.896552 | 110 | 0.660377 | 4.642336 | false | false | false | false |
liqk2014/actor-platform | actor-apps/app-ios/Actor/Controllers Support/SearchSource.swift | 55 | 2946 | //
// Copyright (c) 2015 Actor LLC. <https://actor.im>
//
import Foundation
class SearchSource: NSObject, UISearchBarDelegate, UISearchDisplayDelegate, UITableViewDataSource, AMDisplayList_Listener {
private var displayList: AMBindedDisplayList!;
private let searchDisplay: UISearchDisplayController
init(searchDisplay: UISearchDisplayController){
self.searchDisplay = searchDisplay;
super.init()
self.displayList = buildDisplayList()
self.displayList.addListener(self)
searchDisplay.searchBar.delegate = self
searchDisplay.searchResultsDataSource = self
searchDisplay.delegate = self
}
func close() {
self.displayList.removeListener(self)
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if (section != 0) {
return 0;
}
return Int(displayList.size());
}
func onCollectionChanged() {
searchDisplay.searchResultsTableView.reloadData()
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var item: AnyObject? = objectAtIndexPath(indexPath)
var cell = buildCell(tableView, cellForRowAtIndexPath:indexPath, item:item);
bindCell(tableView, cellForRowAtIndexPath: indexPath, item: item, cell: cell);
return cell;
}
func buildDisplayList() -> AMBindedDisplayList {
fatalError("Not implemented");
}
func buildCell(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath, item: AnyObject?) -> UITableViewCell {
fatalError("Not implemented");
}
func bindCell(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath, item: AnyObject?, cell: UITableViewCell) {
fatalError("Not implemented");
}
func objectAtIndexPath(indexPath: NSIndexPath) -> AnyObject? {
return displayList.itemWithIndex(jint(indexPath.row));
}
func searchBar(searchBar: UISearchBar, textDidChange searchText: String) {
var normalized = searchText.trim().lowercaseString
if (normalized.size() > 0) {
displayList.initSearchWithQuery(normalized, withRefresh: false)
} else {
displayList.initEmpty()
}
}
func searchDisplayControllerWillBeginSearch(controller: UISearchDisplayController) {
MainAppTheme.search.applyStatusBar()
}
func searchDisplayControllerWillEndSearch(controller: UISearchDisplayController) {
MainAppTheme.navigation.applyStatusBar()
}
func searchDisplayController(controller: UISearchDisplayController, didShowSearchResultsTableView tableView: UITableView) {
for v in tableView.subviews {
if (v is UIImageView) {
(v as! UIImageView).alpha = 0;
}
}
}
} | mit | 19203d72a485ce9d83be490fa01f50d5 | 33.670588 | 130 | 0.671419 | 5.643678 | false | false | false | false |
Vaseltior/SFCore | SFCore/sources/_extensions/UInt+SFBoundi.swift | 1 | 1613 | //
// The MIT License (MIT)
//
// Copyright (c) 2015 Samuel GRAU
//
// 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.
//
//
// SFCore : UInt+SFBoundi.swift
//
// Created by Samuel Grau on 02/03/2015.
// Copyright (c) 2015 Samuel Grau. All rights reserved.
//
import Foundation
extension UInt {
public static func boundi(value: UInt, min: UInt, max: UInt) -> UInt {
var iMax = max
if (max < min) {
iMax = min
}
var bounded = value
if (bounded > iMax) {
bounded = iMax
}
if (bounded < min) {
bounded = min
}
return bounded
}
}
| mit | 113c01822da2f5d45d943a6326ccbabe | 30.627451 | 81 | 0.704278 | 4.083544 | false | false | false | false |
evering7/iSpeak8 | Pods/FeedKit/Sources/FeedKit/Models/RSS/RSSFeedCloud.swift | 2 | 4719 | //
// RSSFeedCloud.swift
//
// Copyright (c) 2017 Nuno Manuel Dias
//
// 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
/// Allows processes to register with a cloud to be notified of updates to
/// the channel, implementing a lightweight publish-subscribe protocol for
/// RSS feeds.
///
/// Example: <cloud domain="rpc.sys.com" port="80" path="/RPC2" registerProcedure="pingMe" protocol="soap"/>
///
/// <cloud> is an optional sub-element of <channel>.
///
/// It specifies a web service that supports the rssCloud interface which can
/// be implemented in HTTP-POST, XML-RPC or SOAP 1.1.
///
/// Its purpose is to allow processes to register with a cloud to be notified
/// of updates to the channel, implementing a lightweight publish-subscribe
/// protocol for RSS feeds.
///
/// <cloud domain="rpc.sys.com" port="80" path="/RPC2" registerProcedure="myCloud.rssPleaseNotify" protocol="xml-rpc" />
///
/// In this example, to request notification on the channel it appears in,
/// you would send an XML-RPC message to rpc.sys.com on port 80, with a path
/// of /RPC2. The procedure to call is myCloud.rssPleaseNotify.
///
/// A full explanation of this element and the rssCloud interface is here:
/// http://cyber.law.harvard.edu/rss/soapMeetsRss.html#rsscloudInterface
public class RSSFeedCloud {
/// The attributes of the `<channel>`'s `<cloud>` element.
public class Attributes {
/// The domain to register notification to.
public var domain: String?
/// The port to connect to.
public var port: Int?
/// The path to the RPC service. e.g. "/RPC2".
public var path: String?
/// The procedure to call. e.g. "myCloud.rssPleaseNotify" .
public var registerProcedure: String?
/// The `protocol` specification. Can be HTTP-POST, XML-RPC or SOAP 1.1 -
/// Note: "protocol" is a reserved keyword, so `protocolSpecification`
/// is used instead and refers to the `protocol` attribute of the `cloud`
/// element.
public var protocolSpecification: String?
}
/// The element's attributes.
public var attributes: Attributes?
}
// MARK: - Initializers
extension RSSFeedCloud {
convenience init(attributes attributeDict: [String : String]) {
self.init()
self.attributes = RSSFeedCloud.Attributes(attributes: attributeDict)
}
}
extension RSSFeedCloud.Attributes {
convenience init?(attributes attributeDict: [String : String]) {
if attributeDict.isEmpty {
return nil
}
self.init()
self.domain = attributeDict["domain"]
self.port = Int(attributeDict["port"] ?? "")
self.path = attributeDict["path"]
self.registerProcedure = attributeDict["registerProcedure"]
self.protocolSpecification = attributeDict["protocol"]
}
}
// MARK: - Equatable
extension RSSFeedCloud: Equatable {
public static func ==(lhs: RSSFeedCloud, rhs: RSSFeedCloud) -> Bool {
return lhs.attributes == rhs.attributes
}
}
extension RSSFeedCloud.Attributes: Equatable {
public static func ==(lhs: RSSFeedCloud.Attributes, rhs: RSSFeedCloud.Attributes) -> Bool {
return
lhs.domain == rhs.domain &&
lhs.port == rhs.port &&
lhs.path == rhs.path &&
lhs.registerProcedure == rhs.registerProcedure &&
lhs.protocolSpecification == rhs.protocolSpecification
}
}
| mit | 559551b2c9b6112af2e1488e76bdb702 | 34.75 | 120 | 0.656495 | 4.426829 | false | false | false | false |
tkremenek/swift | test/IRGen/prespecialized-metadata/struct-outmodule-resilient-1argument-1distinct_use-struct-outmodule-frozen-othermodule.swift | 16 | 1585 | // RUN: %empty-directory(%t)
// RUN: %target-build-swift -Xfrontend -prespecialize-generic-metadata -target %module-target-future %S/Inputs/struct-public-nonfrozen-1argument.swift -emit-library -o %t/%target-library-name(Generic) -emit-module -module-name Generic -emit-module-path %t/Generic.swiftmodule -enable-library-evolution
// RUN: %target-build-swift -Xfrontend -prespecialize-generic-metadata -target %module-target-future %S/Inputs/struct-public-frozen-0argument.swift -emit-library -o %t/%target-library-name(Argument) -emit-module -module-name Argument -emit-module-path %t/Argument.swiftmodule -enable-library-evolution
// RUN: %swift -prespecialize-generic-metadata -target %module-target-future -emit-ir %s -L %t -I %t -lGeneric -lArgument | %FileCheck %s -DINT=i%target-ptrsize -DALIGNMENT=%target-alignment
// REQUIRES: VENDOR=apple || OS=linux-gnu
// UNSUPPORTED: CPU=i386 && OS=ios
// UNSUPPORTED: CPU=armv7 && OS=ios
// UNSUPPORTED: CPU=armv7s && OS=ios
// CHECK-NOT: @"$s7Generic11OneArgumentVy0C07IntegerVGMN" =
@inline(never)
func consume<T>(_ t: T) {
withExtendedLifetime(t) { t in
}
}
import Generic
import Argument
// CHECK: define hidden swiftcc void @"$s4main4doityyF"() #{{[0-9]+}} {
// CHECK: [[METADATA:%[0-9]+]] = call %swift.type* @__swift_instantiateConcreteTypeFromMangledName({ i32, i32 }* @"$s7Generic11OneArgumentVy0C07IntegerVGMD")
// CHECK: call swiftcc void @"$s4main7consumeyyxlF"(%swift.opaque* noalias nocapture {{%[0-9]+}}, %swift.type* [[METADATA]])
// CHECK: }
func doit() {
consume( OneArgument(Integer(13)) )
}
doit()
| apache-2.0 | 59043578011f5d897afc564fd0e98e4a | 50.129032 | 301 | 0.728076 | 3.358051 | false | false | false | false |
srn214/Floral | Floral/Pods/Tiercel/Tiercel/Utility/FileChecksumHelper.swift | 1 | 2939 | //
// FileChecksumHelper.swift
// Tiercel
//
// Created by Daniels on 2019/1/22.
// Copyright © 2019 Daniels. 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
public enum FileVerificationType : Int {
case md5
case sha1
case sha256
case sha512
}
public class FileChecksumHelper {
private static let ioQueue: DispatchQueue = DispatchQueue(label: "com.Tiercel.FileChecksumHelper.ioQueue", attributes: .concurrent)
public class func validateFile(_ filePath: String,
code: String,
type: FileVerificationType,
_ completion: @escaping (Bool) -> ()) {
if code.isEmpty {
TiercelLog("verification code is empty")
completion(false)
return
}
ioQueue.async {
guard FileManager.default.fileExists(atPath: filePath) else {
TiercelLog("file does not exist, filePath: \(filePath)")
completion(false)
return
}
let url = URL(fileURLWithPath: filePath)
do {
let data = try Data(contentsOf: url, options: .mappedIfSafe)
var string: String
switch type {
case .md5:
string = data.tr.md5
case .sha1:
string = data.tr.sha1
case .sha256:
string = data.tr.sha256
case .sha512:
string = data.tr.sha512
}
let isCorrect = string.lowercased() == code.lowercased()
completion(isCorrect)
} catch {
TiercelLog("can't read data, error: \(error)")
completion(false)
}
}
}
}
| mit | 0c30006e0624c51cfabdff3b987b6d58 | 33.97619 | 135 | 0.595643 | 4.800654 | false | false | false | false |
JomiMoldes/MMOperationQueue | MMOperationQueue/Classes/MMAsynchronousOperation.swift | 1 | 2506 | import Foundation
public class MMAsynchronousOperation : Operation {
weak var delegate:MMOperationProtocol?
enum State {
case Ready, Executing, Finished
}
var state = State.Ready {
willSet{
switch (state, newValue as State) {
case (.Ready, .Ready):
break
case (.Ready, .Executing):
willChangeValue(forKey: "isExecuting")
case (.Ready, .Finished):
willChangeValue(forKey: "isFinished")
case (.Executing, .Finished):
willChangeValue(forKey: "isExecuting")
willChangeValue(forKey: "isFinished")
default:
fatalError()
}
}
didSet{
switch (oldValue as State, state) {
case (.Ready, .Ready):
break
case (.Ready, .Executing):
didChangeValue(forKey: "isExecuting")
case (.Ready, .Finished):
didChangeValue(forKey: "isFinished")
case (.Executing, .Finished):
didChangeValue(forKey: "isExecuting")
didChangeValue(forKey: "isFinished")
default:
fatalError()
}
}
}
override public var isExecuting: Bool {
return state == State.Executing
}
override public var isFinished: Bool {
return state == State.Finished
}
override public var isAsynchronous: Bool {
return true
}
override public func start() {
guard Thread.isMainThread == false else {
fatalError("you cannot call start from the main thread")
}
guard self.isCancelled == false else {
self.state = .Finished
return
}
self.state = .Ready
self.main()
}
override public func main() {
guard self.isCancelled == false else {
self.state = .Finished
return
}
self.state = .Executing
self.executeAsyncCode()
}
private func executeAsyncCode() {
guard self.isCancelled == false else {
self.state = .Finished
return
}
do {
try self.delegate?.execute()
}catch {
print("error when trying to execute operation")
self.cancel()
self.finishOperation()
}
}
func finishOperation() {
self.state = .Finished
}
} | mit | 3c0dd37c9263346e6201147ad7f91867 | 24.581633 | 68 | 0.517558 | 5.447826 | false | false | false | false |
jordane-quincy/M2_DevMobileIos | JSONProject/Demo/AccueilViewController.swift | 1 | 8324 | //
// AccueilViewController.swift
// Demo
//
// Created by morgan basset on 04/04/2017.
// Copyright © 2017 UVHC. All rights reserved.
//
import UIKit
class AccueilViewController: UIViewController, UIScrollViewDelegate {
var scrollView = UIScrollView()
var containerView = UIView()
let realmServices = RealmServices()
var jsonModel: JsonModel? = nil
var customNavigationController: UINavigationController? = nil
var person: Person? = nil
public func setupNavigationController(navigationController: UINavigationController){
self.customNavigationController = navigationController
}
public func setupPerson(person: Person?) {
self.person = person
}
override func viewDidLoad() {
super.viewDidLoad()
print("didLoad")
// We check in database if there are services
// If yes, we load the last used
let lastUsedServices = realmServices.getLastUsedBusinessServices()
if (lastUsedServices != nil) {
// Get the jsonModel
let jsonData = lastUsedServices?.jsonModelInString.data(using: .utf8)
let json = try? JSONSerialization.jsonObject(with: jsonData!, options: [])
do {
let jsonModel = try JsonModel(jsonContent: json as! [String: Any])
self.createViewFromJson(json: jsonModel)
} catch let serializationError {
//in case of unsuccessful deserialization
print(serializationError)
}
}
// setup swipe
let swipeRight = UISwipeGestureRecognizer(target: self, action: #selector(self.respondToSwipeGesture))
swipeRight.direction = UISwipeGestureRecognizerDirection.right
self.view.addGestureRecognizer(swipeRight)
let swipeLeft = UISwipeGestureRecognizer(target: self, action: #selector(self.respondToSwipeGesture))
swipeRight.direction = UISwipeGestureRecognizerDirection.left
self.view.addGestureRecognizer(swipeLeft)
}
// swipe function
func respondToSwipeGesture(gesture: UIGestureRecognizer) {
if let swipeGesture = gesture as? UISwipeGestureRecognizer {
switch swipeGesture.direction {
case UISwipeGestureRecognizerDirection.right:
// GO TO THE LEFT Pannel
DispatchQueue.main.async() {
self.tabBarController?.selectedIndex = 3
}
case UISwipeGestureRecognizerDirection.left:
// GO TO THE RIGHT Pannel
DispatchQueue.main.async() {
if (self.tabBarController?.tabBar.items?[1].isEnabled)! {
self.tabBarController?.selectedIndex = 1
}
else {
self.tabBarController?.selectedIndex = 3
}
}
default:
break
}
}
}
override func viewWillAppear(_ animated: Bool) {
// verify if the actual service in jsonModel was not deleted
if (jsonModel != nil) {
if (realmServices.serviceFree(title: (jsonModel?.title)!)) {
// Reset the view
self.containerView.subviews.forEach({ $0.removeFromSuperview() })
// affichage message pas de service chargé
let defaultMessage: UILabel = UILabel(frame: CGRect(x: 20, y: 20, width: 335, height: 30.00));
defaultMessage.text = "Pas de service chargé"
self.view.addSubview(containerView)
self.containerView.addSubview(defaultMessage)
}
}
else {
// affichage message pas de service chargé
let defaultMessage: UILabel = UILabel(frame: CGRect(x: 20, y: 20, width: 335, height: 30.00));
defaultMessage.text = "Pas de service chargé"
self.view.addSubview(containerView)
self.containerView.addSubview(defaultMessage)
}
// If it was deleted, delete the UI
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
scrollView.frame = view.bounds
containerView.frame = CGRect(x: 0, y: 0, width: scrollView.contentSize.width, height: scrollView.contentSize.height)
}
func goToSelectOfferView(_ sender: UIButton) {
// Redirect To Next Step
let selectOfferView = SelectOfferViewController(nibName: "SelectOfferViewController", bundle: nil)
selectOfferView.setupNavigationController(navigationController: self.customNavigationController!)
selectOfferView.setupCustomParent(customParent: self)
selectOfferView.createViewFromJson(json: self.jsonModel)
self.customNavigationController?.title = self.jsonModel?.title
self.customNavigationController?.pushViewController(selectOfferView, animated: true)
self.customNavigationController?.setNavigationBarHidden(false, animated: true)
}
func createViewFromJson(json: JsonModel?){
self.jsonModel = json
// Setup interface
DispatchQueue.main.async() {
// Reset the view
self.view.subviews.forEach({ $0.removeFromSuperview() })
// Setup scrollview
self.scrollView = UIScrollView()
self.scrollView.delegate = self
self.view.addSubview(self.scrollView)
self.containerView = UIView()
self.scrollView.addSubview(self.containerView)
// Ajout titre service
let title: UILabel = UILabel(frame: CGRect(x: 20, y: 20, width: 335, height: 30.00));
title.text = "Inscription au service : " + (json?.title)!
self.containerView.addSubview(title)
var imageHeight = 0.00
// Ajout de l'image du service
if (json?.icon != nil && json?.icon != "") {
let dataDecoded : Data = Data(base64Encoded: (json?.icon)!, options: .ignoreUnknownCharacters)!
let decodedimage = UIImage(data: dataDecoded)
let imageView = UIImageView(image: decodedimage!)
imageView.frame = CGRect(x: 20, y: 60, width: 200, height: 100)
imageHeight = 100.00
self.containerView.addSubview(imageView)
}
// Ajout description du service
var descriptionToLong = false
if ((json?.description.characters.count)! > 135) {
descriptionToLong = true
}
let description: UILabel = UILabel(frame: CGRect(x: 20, y: 70 + imageHeight, width: 335, height: descriptionToLong ? 100 + 20 : 100.00));
description.numberOfLines = 0
description.text = "Voici la description de ce service : \n" + (json?.description)!
self.containerView.addSubview(description)
// Start message
let startMessage: UILabel = UILabel(frame: CGRect(x: 20, y: descriptionToLong ? 150 + 20 + imageHeight : 150 + imageHeight, width: 335, height: 100.00))
startMessage.numberOfLines = 0
startMessage.text = "Pour vous inscrire à ce service cliquez sur \"Commencer\""
self.containerView.addSubview(startMessage)
// Ajout du bouton commencer
let statButton = UIButton(frame: CGRect(x: 130, y: descriptionToLong ? 250 + 20 + imageHeight : 250 + imageHeight, width: 335, height: 30.00))
statButton.setTitle("Commencer >", for: .normal)
statButton.addTarget(self, action: #selector(self.goToSelectOfferView(_:)), for: .touchUpInside)
statButton.setTitleColor(UIView().tintColor, for: .normal)
statButton.backgroundColor = UIColor.clear
self.containerView.addSubview(statButton)
// Set size fo scrollView
self.scrollView.contentSize = CGSize(width: 350, height: descriptionToLong ? 270 + 20 + imageHeight : 270 + imageHeight)
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| mit | 4d72ed5f6124083c63675cf085707faa | 42.549738 | 164 | 0.611806 | 5.134568 | false | false | false | false |
terut/Wayfaring | Wayfaring/Routes.swift | 1 | 2629 | //
// Routes.swift
// Wayfaring
//
// Copyright (c) 2015年 terut. All rights reserved.
//
import Foundation
open class Routes {
open static let sharedInstance = Routes()
fileprivate var routes = [Route]()
fileprivate init() {}
open func bootstrap(_ resources: [Resource]) {
for res in resources {
routes.append(Route(resource: res))
}
}
open func dispatch(_ urlString: String) -> (resource: Resource?, params: [String: AnyObject]?) {
if let url = URL(string: urlString) {
let path: String
if url.scheme == "http" || url.scheme == "https" {
path = "\(url.path)"
} else {
path = "/\(url.host!)\(url.path)"
}
if let route = searchRoute(path) {
var params = [String: AnyObject]()
if route.keys.count > 0 {
var values = Regex.capture(path, pattern: route.pattern)
for (i, key) in route.keys.enumerated() {
params[key] = values[i] as AnyObject?
}
}
for (key, val) in paramsFromQueryStringAndFragment(url) {
params[key] = val
}
if params.isEmpty {
return (route.resource, nil)
} else {
return (route.resource, params)
}
}
}
return (nil, nil)
}
fileprivate func searchRoute(_ path: String) -> Route? {
for route in self.routes {
if route.isMatch(path) {
return route
}
}
return nil
}
fileprivate func paramsFromQueryStringAndFragment(_ url: URL) -> [String: AnyObject] {
var params: [String: AnyObject] = [:]
let components = URLComponents(url: url, resolvingAgainstBaseURL: true)
if let items = components?.queryItems {
for item in items {
if let v = item.value {
params[item.name] = v as AnyObject?
} else {
params[item.name] = "" as AnyObject?
}
}
}
if let fragmentStr = components?.fragment {
let items = fragmentStr.components(separatedBy: "&")
if items.count > 0 {
for item in items {
let keyValue = item.components(separatedBy: "=")
params[keyValue[0]] = keyValue[1] as AnyObject?
}
}
}
return params
}
}
| mit | dd3c8f8a9b226dfabb77768f79823fd3 | 29.546512 | 100 | 0.478873 | 4.802559 | false | false | false | false |
johnno1962b/swift-corelibs-foundation | Foundation/CharacterSet.swift | 5 | 20742 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
private func _utfRangeToNSRange(_ inRange : Range<UnicodeScalar>) -> NSRange {
return NSMakeRange(Int(inRange.lowerBound.value), Int(inRange.upperBound.value - inRange.lowerBound.value))
}
private func _utfRangeToNSRange(_ inRange : ClosedRange<UnicodeScalar>) -> NSRange {
return NSMakeRange(Int(inRange.lowerBound.value), Int(inRange.upperBound.value - inRange.lowerBound.value + 1))
}
internal final class _SwiftNSCharacterSet : NSCharacterSet, _SwiftNativeFoundationType {
internal typealias ImmutableType = NSCharacterSet
internal typealias MutableType = NSMutableCharacterSet
var __wrapped : _MutableUnmanagedWrapper<ImmutableType, MutableType>
init(immutableObject: AnyObject) {
// Take ownership.
__wrapped = .Immutable(Unmanaged.passRetained(_unsafeReferenceCast(immutableObject, to: ImmutableType.self)))
super.init()
}
init(mutableObject: AnyObject) {
// Take ownership.
__wrapped = .Mutable(Unmanaged.passRetained(_unsafeReferenceCast(mutableObject, to: MutableType.self)))
super.init()
}
internal required init(unmanagedImmutableObject: Unmanaged<ImmutableType>) {
// Take ownership.
__wrapped = .Immutable(unmanagedImmutableObject)
super.init()
}
internal required init(unmanagedMutableObject: Unmanaged<MutableType>) {
// Take ownership.
__wrapped = .Mutable(unmanagedMutableObject)
super.init()
}
convenience required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
deinit {
releaseWrappedObject()
}
override func copy(with zone: NSZone? = nil) -> Any {
return _mapUnmanaged { $0.copy(with: zone) }
}
override func mutableCopy(with zone: NSZone? = nil) -> Any {
return _mapUnmanaged { $0.mutableCopy(with: zone) }
}
public override var classForCoder: AnyClass {
return NSCharacterSet.self
}
override var bitmapRepresentation: Data {
return _mapUnmanaged { $0.bitmapRepresentation }
}
override var inverted : CharacterSet {
return _mapUnmanaged { $0.inverted }
}
override func hasMemberInPlane(_ thePlane: UInt8) -> Bool {
return _mapUnmanaged {$0.hasMemberInPlane(thePlane) }
}
override func characterIsMember(_ member: unichar) -> Bool {
return _mapUnmanaged { $0.characterIsMember(member) }
}
override func longCharacterIsMember(_ member: UInt32) -> Bool {
return _mapUnmanaged { $0.longCharacterIsMember(member) }
}
override func isSuperset(of other: CharacterSet) -> Bool {
return _mapUnmanaged { $0.isSuperset(of: other) }
}
override var _cfObject: CFType {
// We cannot inherit super's unsafeBitCast(self, to: CFType.self) here, because layout of _SwiftNSCharacterSet
// is not compatible with CFCharacterSet. We need to bitcast the underlying NSCharacterSet instead.
return _mapUnmanaged { unsafeBitCast($0, to: CFType.self) }
}
}
/**
A `CharacterSet` represents a set of Unicode-compliant characters. Foundation types use `CharacterSet` to group characters together for searching operations, so that they can find any of a particular set of characters during a search.
This type provides "copy-on-write" behavior, and is also bridged to the Objective-C `NSCharacterSet` class.
*/
public struct CharacterSet : ReferenceConvertible, Equatable, Hashable, SetAlgebra, _MutablePairBoxing {
public typealias ReferenceType = NSCharacterSet
internal typealias SwiftNSWrapping = _SwiftNSCharacterSet
internal typealias ImmutableType = SwiftNSWrapping.ImmutableType
internal typealias MutableType = SwiftNSWrapping.MutableType
internal var _wrapped : _SwiftNSCharacterSet
// MARK: Init methods
internal init(_bridged characterSet: NSCharacterSet) {
// We must copy the input because it might be mutable; just like storing a value type in ObjC
_wrapped = _SwiftNSCharacterSet(immutableObject: characterSet.copy() as! NSObject)
}
/// Initialize an empty instance.
public init() {
_wrapped = _SwiftNSCharacterSet(immutableObject: NSCharacterSet())
}
/// Initialize with a range of integers.
///
/// It is the caller's responsibility to ensure that the values represent valid `UnicodeScalar` values, if that is what is desired.
public init(charactersIn range: Range<UnicodeScalar>) {
_wrapped = _SwiftNSCharacterSet(immutableObject: NSCharacterSet(range: _utfRangeToNSRange(range)))
}
/// Initialize with a closed range of integers.
///
/// It is the caller's responsibility to ensure that the values represent valid `UnicodeScalar` values, if that is what is desired.
public init(charactersIn range: ClosedRange<UnicodeScalar>) {
_wrapped = _SwiftNSCharacterSet(immutableObject: NSCharacterSet(range: _utfRangeToNSRange(range)))
}
/// Initialize with the characters in the given string.
///
/// - parameter string: The string content to inspect for characters.
public init(charactersIn string: String) {
_wrapped = _SwiftNSCharacterSet(immutableObject: NSCharacterSet(charactersIn: string))
}
/// Initialize with a bitmap representation.
///
/// This method is useful for creating a character set object with data from a file or other external data source.
/// - parameter data: The bitmap representation.
public init(bitmapRepresentation data: Data) {
_wrapped = _SwiftNSCharacterSet(immutableObject: NSCharacterSet(bitmapRepresentation: data))
}
/// Initialize with the contents of a file.
///
/// Returns `nil` if there was an error reading the file.
/// - parameter file: The file to read.
public init?(contentsOfFile file: String) {
if let interior = NSCharacterSet(contentsOfFile: file) {
_wrapped = _SwiftNSCharacterSet(immutableObject: interior)
} else {
return nil
}
}
public var hashValue: Int {
return _mapUnmanaged { $0.hashValue }
}
public var description: String {
return _mapUnmanaged { $0.description }
}
public var debugDescription: String {
return _mapUnmanaged { $0.debugDescription }
}
private init(reference: NSCharacterSet) {
_wrapped = _SwiftNSCharacterSet(immutableObject: reference)
}
// MARK: Static functions
/// Returns a character set containing the characters in Unicode General Category Cc and Cf.
public static var controlCharacters : CharacterSet {
return NSCharacterSet.controlCharacters
}
/// Returns a character set containing the characters in Unicode General Category Zs and `CHARACTER TABULATION (U+0009)`.
public static var whitespaces : CharacterSet {
return NSCharacterSet.whitespaces
}
/// Returns a character set containing characters in Unicode General Category Z*, `U+000A ~ U+000D`, and `U+0085`.
public static var whitespacesAndNewlines : CharacterSet {
return NSCharacterSet.whitespacesAndNewlines
}
/// Returns a character set containing the characters in the category of Decimal Numbers.
public static var decimalDigits : CharacterSet {
return NSCharacterSet.decimalDigits
}
/// Returns a character set containing the characters in Unicode General Category L* & M*.
public static var letters : CharacterSet {
return NSCharacterSet.letters
}
/// Returns a character set containing the characters in Unicode General Category Ll.
public static var lowercaseLetters : CharacterSet {
return NSCharacterSet.lowercaseLetters
}
/// Returns a character set containing the characters in Unicode General Category Lu and Lt.
public static var uppercaseLetters : CharacterSet {
return NSCharacterSet.uppercaseLetters
}
/// Returns a character set containing the characters in Unicode General Category M*.
public static var nonBaseCharacters : CharacterSet {
return NSCharacterSet.nonBaseCharacters
}
/// Returns a character set containing the characters in Unicode General Categories L*, M*, and N*.
public static var alphanumerics : CharacterSet {
return NSCharacterSet.alphanumerics
}
/// Returns a character set containing individual Unicode characters that can also be represented as composed character sequences (such as for letters with accents), by the definition of "standard decomposition" in version 3.2 of the Unicode character encoding standard.
public static var decomposables : CharacterSet {
return NSCharacterSet.decomposables
}
/// Returns a character set containing values in the category of Non-Characters or that have not yet been defined in version 3.2 of the Unicode standard.
public static var illegalCharacters : CharacterSet {
return NSCharacterSet.illegalCharacters
}
/// Returns a character set containing the characters in Unicode General Category P*.
public static var punctuationCharacters : CharacterSet {
return NSCharacterSet.punctuationCharacters
}
/// Returns a character set containing the characters in Unicode General Category Lt.
public static var capitalizedLetters : CharacterSet {
return NSCharacterSet.capitalizedLetters
}
/// Returns a character set containing the characters in Unicode General Category S*.
public static var symbols : CharacterSet {
return NSCharacterSet.symbols
}
/// Returns a character set containing the newline characters (`U+000A ~ U+000D`, `U+0085`, `U+2028`, and `U+2029`).
public static var newlines : CharacterSet {
return NSCharacterSet.newlines
}
// MARK: Static functions, from NSURL
/// Returns the character set for characters allowed in a user URL subcomponent.
public static var urlUserAllowed : CharacterSet {
return NSCharacterSet.urlUserAllowed
}
/// Returns the character set for characters allowed in a password URL subcomponent.
public static var urlPasswordAllowed : CharacterSet {
return NSCharacterSet.urlPasswordAllowed
}
/// Returns the character set for characters allowed in a host URL subcomponent.
public static var urlHostAllowed : CharacterSet {
return NSCharacterSet.urlHostAllowed
}
/// Returns the character set for characters allowed in a path URL component.
public static var urlPathAllowed : CharacterSet {
return NSCharacterSet.urlPathAllowed
}
/// Returns the character set for characters allowed in a query URL component.
public static var urlQueryAllowed : CharacterSet {
return NSCharacterSet.urlQueryAllowed
}
/// Returns the character set for characters allowed in a fragment URL component.
public static var urlFragmentAllowed : CharacterSet {
return NSCharacterSet.urlFragmentAllowed
}
// MARK: Immutable functions
/// Returns a representation of the `CharacterSet` in binary format.
public var bitmapRepresentation: Data {
return _mapUnmanaged { $0.bitmapRepresentation }
}
/// Returns an inverted copy of the receiver.
public var inverted : CharacterSet {
return _mapUnmanaged { $0.inverted }
}
/// Returns true if the `CharacterSet` has a member in the specified plane.
///
/// This method makes it easier to find the plane containing the members of the current character set. The Basic Multilingual Plane (BMP) is plane 0.
public func hasMember(inPlane plane: UInt8) -> Bool {
return _mapUnmanaged { $0.hasMemberInPlane(plane) }
}
// MARK: Mutable functions
/// Insert a range of integer values in the `CharacterSet`.
///
/// It is the caller's responsibility to ensure that the values represent valid `UnicodeScalar` values, if that is what is desired.
public mutating func insert(charactersIn range: Range<UnicodeScalar>) {
let nsRange = _utfRangeToNSRange(range)
_applyUnmanagedMutation {
$0.addCharacters(in: nsRange)
}
}
/// Insert a closed range of integer values in the `CharacterSet`.
///
/// It is the caller's responsibility to ensure that the values represent valid `UnicodeScalar` values, if that is what is desired.
public mutating func insert(charactersIn range: ClosedRange<UnicodeScalar>) {
let nsRange = _utfRangeToNSRange(range)
_applyUnmanagedMutation {
$0.addCharacters(in: nsRange)
}
}
/// Remove a range of integer values from the `CharacterSet`.
public mutating func remove(charactersIn range: Range<UnicodeScalar>) {
let nsRange = _utfRangeToNSRange(range)
_applyUnmanagedMutation {
$0.removeCharacters(in: nsRange)
}
}
/// Remove a closed range of integer values from the `CharacterSet`.
public mutating func remove(charactersIn range: ClosedRange<UnicodeScalar>) {
let nsRange = _utfRangeToNSRange(range)
_applyUnmanagedMutation {
$0.removeCharacters(in: nsRange)
}
}
/// Insert the values from the specified string into the `CharacterSet`.
public mutating func insert(charactersIn string: String) {
_applyUnmanagedMutation {
$0.addCharacters(in: string)
}
}
/// Remove the values from the specified string from the `CharacterSet`.
public mutating func remove(charactersIn string: String) {
_applyUnmanagedMutation {
$0.removeCharacters(in: string)
}
}
/// Invert the contents of the `CharacterSet`.
public mutating func invert() {
_applyUnmanagedMutation { $0.invert() }
}
// -----
// MARK: -
// MARK: SetAlgebraType
/// Insert a `UnicodeScalar` representation of a character into the `CharacterSet`.
///
/// `UnicodeScalar` values are available on `Swift.String.UnicodeScalarView`.
@discardableResult
public mutating func insert(_ character: UnicodeScalar) -> (inserted: Bool, memberAfterInsert: UnicodeScalar) {
let nsRange = NSMakeRange(Int(character.value), 1)
_applyUnmanagedMutation {
$0.addCharacters(in: nsRange)
}
// TODO: This should probably return the truth, but figuring it out requires two calls into NSCharacterSet
return (true, character)
}
/// Insert a `UnicodeScalar` representation of a character into the `CharacterSet`.
///
/// `UnicodeScalar` values are available on `Swift.String.UnicodeScalarView`.
@discardableResult
public mutating func update(with character: UnicodeScalar) -> UnicodeScalar? {
let nsRange = NSMakeRange(Int(character.value), 1)
_applyUnmanagedMutation {
$0.addCharacters(in: nsRange)
}
// TODO: This should probably return the truth, but figuring it out requires two calls into NSCharacterSet
return character
}
/// Remove a `UnicodeScalar` representation of a character from the `CharacterSet`.
///
/// `UnicodeScalar` values are available on `Swift.String.UnicodeScalarView`.
@discardableResult
public mutating func remove(_ character: UnicodeScalar) -> UnicodeScalar? {
// TODO: Add method to NSCharacterSet to do this in one call
let result : UnicodeScalar? = contains(character) ? character : nil
let r = NSMakeRange(Int(character.value), 1)
_applyUnmanagedMutation {
$0.removeCharacters(in: r)
}
return result
}
/// Test for membership of a particular `UnicodeScalar` in the `CharacterSet`.
public func contains(_ member: UnicodeScalar) -> Bool {
return _mapUnmanaged { $0.longCharacterIsMember(member.value) }
}
/// Returns a union of the `CharacterSet` with another `CharacterSet`.
public func union(_ other: CharacterSet) -> CharacterSet {
// The underlying collection does not have a method to return new CharacterSets with changes applied, so we will copy and apply here
var result = self
result.formUnion(other)
return result
}
/// Sets the value to a union of the `CharacterSet` with another `CharacterSet`.
public mutating func formUnion(_ other: CharacterSet) {
_applyUnmanagedMutation { $0.formUnion(with: other) }
}
/// Returns an intersection of the `CharacterSet` with another `CharacterSet`.
public func intersection(_ other: CharacterSet) -> CharacterSet {
// The underlying collection does not have a method to return new CharacterSets with changes applied, so we will copy and apply here
var result = self
result.formIntersection(other)
return result
}
/// Sets the value to an intersection of the `CharacterSet` with another `CharacterSet`.
public mutating func formIntersection(_ other: CharacterSet) {
_applyUnmanagedMutation {
$0.formIntersection(with: other)
}
}
/// Returns a `CharacterSet` created by removing elements in `other` from `self`.
public func subtracting(_ other: CharacterSet) -> CharacterSet {
return intersection(other.inverted)
}
/// Sets the value to a `CharacterSet` created by removing elements in `other` from `self`.
public mutating func subtract(_ other: CharacterSet) {
self = subtracting(other)
}
/// Returns an exclusive or of the `CharacterSet` with another `CharacterSet`.
public func symmetricDifference(_ other: CharacterSet) -> CharacterSet {
return union(other).subtracting(intersection(other))
}
/// Sets the value to an exclusive or of the `CharacterSet` with another `CharacterSet`.
public mutating func formSymmetricDifference(_ other: CharacterSet) {
self = symmetricDifference(other)
}
/// Returns true if `self` is a superset of `other`.
public func isSuperset(of other: CharacterSet) -> Bool {
return _mapUnmanaged { $0.isSuperset(of: other) }
}
/// Returns true if the two `CharacterSet`s are equal.
public static func ==(lhs : CharacterSet, rhs: CharacterSet) -> Bool {
return lhs._mapUnmanaged { $0.isEqual(rhs) }
}
}
// MARK: Objective-C Bridging
extension CharacterSet : _ObjectTypeBridgeable {
public static func _isBridgedToObjectiveC() -> Bool {
return true
}
public static func _getObjectiveCType() -> Any.Type {
return NSCharacterSet.self
}
@_semantics("convertToObjectiveC")
public func _bridgeToObjectiveC() -> NSCharacterSet {
return _wrapped
}
public static func _forceBridgeFromObjectiveC(_ input: NSCharacterSet, result: inout CharacterSet?) {
result = CharacterSet(_bridged: input)
}
public static func _conditionallyBridgeFromObjectiveC(_ input: NSCharacterSet, result: inout CharacterSet?) -> Bool {
result = CharacterSet(_bridged: input)
return true
}
public static func _unconditionallyBridgeFromObjectiveC(_ source: NSCharacterSet?) -> CharacterSet {
return CharacterSet(_bridged: source!)
}
}
extension CharacterSet : Codable {
private enum CodingKeys : Int, CodingKey {
case bitmap
}
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
let bitmap = try container.decode(Data.self, forKey: .bitmap)
self.init(bitmapRepresentation: bitmap)
}
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(self.bitmapRepresentation, forKey: .bitmap)
}
}
| apache-2.0 | a46f12a3e02365b7a7b2085566f4c97f | 38.284091 | 274 | 0.674429 | 5.251139 | false | false | false | false |
the-blue-alliance/the-blue-alliance-ios | Frameworks/TBAProtocols/Sources/Dateable.swift | 1 | 959 | import Foundation
public protocol Dateable {
var startDate: Date? { get }
var endDate: Date? { get }
}
extension Dateable {
public var dateString: String? {
guard let startDate = startDate, let endDate = endDate else {
return nil
}
let calendar = Calendar.current
let shortDateFormatter = DateFormatter()
shortDateFormatter.dateFormat = "MMM dd"
let longDateFormatter = DateFormatter()
longDateFormatter.dateFormat = "MMM dd, y"
if startDate == endDate {
return shortDateFormatter.string(from: endDate)
} else if calendar.component(.year, from: startDate) == calendar.component(.year, from: endDate) {
return "\(shortDateFormatter.string(from: startDate)) to \(shortDateFormatter.string(from: endDate))"
}
return "\(shortDateFormatter.string(from: startDate)) to \(longDateFormatter.string(from: endDate))"
}
}
| mit | d3eb54c29d7ad2a2ce0ee06b9a848681 | 29.935484 | 113 | 0.64755 | 4.771144 | false | false | false | false |
acrocat/EverLayout | Source/Resolvers/UILabel+PropertyMappable.swift | 1 | 3785 | // EverLayout
//
// Copyright (c) 2017 Dale Webster
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import UIKit
/*
Behaviour of UILabel when properties are mapped to and from it
*/
extension UILabel : TextMappable {
func mapText(_ text: String) {
self.text = text
}
func getMappedText() -> String? {
return self.text ?? ""
}
}
extension UILabel : TextColorMappable {
func mapTextColor(_ color: String) {
self.textColor = UIColor.color(fromName: color) ?? UIColor(hex: color)
}
func getMappedTextColor() -> String? {
return UIColor.name(ofColor: self.textColor)
}
}
extension UILabel : LineBreakModeMappable {
internal var lineBreakModes : [String : NSLineBreakMode] {
return [
"byWordWrapping": .byWordWrapping,
"byCharWrapping": .byCharWrapping,
"byClipping": .byClipping,
"byTruncatingHead": .byTruncatingHead,
"byTruncatingTail": .byTruncatingTail,
"byTruncatingMiddle": .byTruncatingMiddle
]
}
func mapLineBreakMode(_ lineBreakMode: String) {
if let breakMode = self.lineBreakModes[lineBreakMode] {
self.lineBreakMode = breakMode
}
}
func getMappedLineBreakMode() -> String? {
return self.lineBreakModes.filter { (key , value) -> Bool in
return value == self.lineBreakMode
}.first?.key
}
}
extension UILabel : TextAlignmentMappable {
internal var textAlignments : [String : NSTextAlignment] {
return [
"left": .left,
"center": .center,
"right": .right,
"justified": .justified,
"natural": .natural
]
}
func mapTextAlignment(_ textAlignment: String) {
if let alignment = self.textAlignments[textAlignment] {
self.textAlignment = alignment
}
}
func getMappedTextAlignment() -> String? {
return self.textAlignments.filter { (key , value) -> Bool in
return value == self.textAlignment
}.first?.key
}
}
extension UILabel : NumberOfLinesMappable {
func mapNumberOfLines(_ numberOfLines: String) {
if let linesInt = Int(numberOfLines) {
self.numberOfLines = linesInt
}
}
func getMappedNumberOfLines() -> String? {
return String(self.numberOfLines)
}
}
extension UILabel : FontSizeMappable {
func mapFontSize(_ fontSize: String) {
if let float = fontSize.toCGFloat() {
self.font = self.font.withSize(float)
}
}
func getMappedFontSize() -> String? {
return String(describing: self.font.pointSize)
}
}
| mit | 8d57468145c66b5f2dedf79ac4e16e64 | 31.913043 | 81 | 0.643065 | 4.667078 | false | false | false | false |
iStig/Uther_Swift | Pods/LTMorphingLabel/LTMorphingLabel/LTMorphingLabel+Fall.swift | 17 | 5028 | //
// LTMorphingLabel+Fall.swift
// https://github.com/lexrus/LTMorphingLabel
//
// The MIT License (MIT)
// Copyright (c) 2015 Lex Tang, http://LexTang.com
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the “Software”), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import UIKit
extension LTMorphingLabel {
func FallLoad() {
progressClosures["Fall\(LTMorphingPhaseManipulateProgress)"] = {
(index: Int, progress: Float, isNewChar: Bool) in
if isNewChar {
return min(1.0, max(0.0, progress - self.morphingCharacterDelay * Float(index) / 1.7))
}
let j: Float = Float(sin(Double(index))) * 1.7
return min(1.0, max(0.0001, progress + self.morphingCharacterDelay * Float(j)))
}
effectClosures["Fall\(LTMorphingPhaseDisappear)"] = {
(char:Character, index: Int, progress: Float) in
return LTCharacterLimbo(
char: char,
rect: self.previousRects[index],
alpha: CGFloat(1.0 - progress),
size: self.font.pointSize,
drawingProgress: CGFloat(progress))
}
effectClosures["Fall\(LTMorphingPhaseAppear)"] = {
(char:Character, index: Int, progress: Float) in
let currentFontSize = CGFloat(LTEasing.easeOutQuint(progress, 0.0, Float(self.font.pointSize)))
let yOffset = CGFloat(self.font.pointSize - currentFontSize)
return LTCharacterLimbo(
char: char,
rect: CGRectOffset(self.newRects[index], 0.0, yOffset),
alpha: CGFloat(self.morphingProgress),
size: currentFontSize,
drawingProgress: 0.0
)
}
drawingClosures["Fall\(LTMorphingPhaseDraw)"] = {
(charLimbo: LTCharacterLimbo) in
if charLimbo.drawingProgress > 0.0 {
let context = UIGraphicsGetCurrentContext()
var charRect = charLimbo.rect
CGContextSaveGState(context);
let charCenterX = charRect.origin.x + (charRect.size.width / 2.0)
var charBottomY = charRect.origin.y + charRect.size.height - self.font.pointSize / 6
var charColor = self.textColor
// Fall down if drawingProgress is more than 50%
if charLimbo.drawingProgress > 0.5 {
let ease = CGFloat(LTEasing.easeInQuint(Float(charLimbo.drawingProgress - 0.4), 0.0, 1.0, 0.5))
charBottomY = charBottomY + ease * 10.0
let fadeOutAlpha = min(1.0, max(0.0, charLimbo.drawingProgress * -2.0 + 2.0 + 0.01))
charColor = self.textColor.colorWithAlphaComponent(fadeOutAlpha)
}
charRect = CGRectMake(
charRect.size.width / -2.0,
charRect.size.height * -1.0 + self.font.pointSize / 6,
charRect.size.width,
charRect.size.height)
CGContextTranslateCTM(context, charCenterX, charBottomY)
let angle = Float(sin(Double(charLimbo.rect.origin.x)) > 0.5 ? 168 : -168)
let rotation = CGFloat(LTEasing.easeOutBack(min(1.0, Float(charLimbo.drawingProgress)), 0.0, 1.0) * angle)
CGContextRotateCTM(context, rotation * CGFloat(M_PI) / 180.0)
let s = String(charLimbo.char)
s.drawInRect(charRect, withAttributes: [
NSFontAttributeName: self.font.fontWithSize(charLimbo.size),
NSForegroundColorAttributeName: charColor
])
CGContextRestoreGState(context);
return true
}
return false
}
}
}
| mit | ce0e79d80f06ce0c897646ac68e82967 | 42.275862 | 122 | 0.57988 | 4.888023 | false | false | false | false |
borchero/WebParsing | WebParsing/WPPropertyList.swift | 1 | 2299 | // MIT License
//
// Copyright (c) 2017 Oliver Borchert ([email protected])
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
import CoreUtility
public struct WPPropertyList: WPElement {
public var value: WPValue<WPPropertyList>
private init() {
value = .undefined
}
public init(value: WPValue<WPPropertyList>) {
self.value = value
}
public init(_ any: Any) {
value = WPValue(object: any)
}
public init(reading data: Data) {
guard let object = try? PropertyListSerialization.propertyList(from: data, options: [], format: nil) else {
self.init()
return
}
self.init(object)
}
public init(reading url: URL) {
do {
self.init(reading: try Data(contentsOf: url))
} catch {
self.init()
}
}
public init(reading plist: String, from bundle: Bundle = .main) {
do {
self.init(reading: try bundle.url(forResource: plist, withExtension: ".plist").unwrap())
} catch {
self.init()
}
}
public func description(forOffset offset: String, prettyPrinted: Bool) -> String {
return "not implemented yet"
}
}
| mit | b8880b2a21bb6dec76bcfa0d7ae309ab | 31.842857 | 115 | 0.654197 | 4.455426 | false | false | false | false |
matthewpurcell/firefox-ios | Sync/Downloader.swift | 1 | 9128 | /* 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 XCGLogger
import Deferred
private let log = Logger.syncLogger
class BatchingDownloader<T: CleartextPayloadJSON> {
let client: Sync15CollectionClient<T>
let collection: String
let prefs: Prefs
var batch: [Record<T>] = []
func store(records: [Record<T>]) {
self.batch += records
}
func retrieve() -> [Record<T>] {
let ret = self.batch
self.batch = []
return ret
}
var _advance: (() -> ())?
func advance() {
guard let f = self._advance else {
return
}
self._advance = nil
f()
}
init(collectionClient: Sync15CollectionClient<T>, basePrefs: Prefs, collection: String) {
self.client = collectionClient
self.collection = collection
let branchName = "downloader." + collection + "."
self.prefs = basePrefs.branch(branchName)
log.info("Downloader configured with prefs '\(self.prefs.getBranchPrefix())'.")
}
static func resetDownloaderWithPrefs(basePrefs: Prefs, collection: String) {
// This leads to stupid paths like 'profile.sync.synchronizer.history..downloader.history..'.
// Sorry, but it's out in the world now...
let branchName = "downloader." + collection + "."
let prefs = basePrefs.branch(branchName)
let lm = prefs.timestampForKey("lastModified")
let bt = prefs.timestampForKey("baseTimestamp")
log.debug("Resetting downloader prefs \(prefs.getBranchPrefix()). Previous values: \(lm), \(bt).")
prefs.removeObjectForKey("nextOffset")
prefs.removeObjectForKey("offsetNewer")
prefs.removeObjectForKey("baseTimestamp")
prefs.removeObjectForKey("lastModified")
}
/**
* Clients should provide the same set of parameters alongside an `offset` as was
* provided with the initial request. The only thing that varies in our batch fetches
* is `newer`, so we track the original value alongside.
*/
var nextFetchParameters: (String, Timestamp)? {
get {
let o = self.prefs.stringForKey("nextOffset")
let n = self.prefs.timestampForKey("offsetNewer")
guard let offset = o, let newer = n else {
return nil
}
return (offset, newer)
}
set (value) {
if let (offset, newer) = value {
self.prefs.setString(offset, forKey: "nextOffset")
self.prefs.setTimestamp(newer, forKey: "offsetNewer")
} else {
self.prefs.removeObjectForKey("nextOffset")
self.prefs.removeObjectForKey("offsetNewer")
}
}
}
// Set after each batch, from record timestamps.
var baseTimestamp: Timestamp {
get {
return self.prefs.timestampForKey("baseTimestamp") ?? 0
}
set (value) {
self.prefs.setTimestamp(value ?? 0, forKey: "baseTimestamp")
}
}
// Only set at the end of a batch, from headers.
var lastModified: Timestamp {
get {
return self.prefs.timestampForKey("lastModified") ?? 0
}
set (value) {
self.prefs.setTimestamp(value ?? 0, forKey: "lastModified")
}
}
/**
* Call this when a significant structural server change has been detected.
*/
func reset() -> Success {
self.baseTimestamp = 0
self.lastModified = 0
self.nextFetchParameters = nil
self.batch = []
self._advance = nil
return succeed()
}
func go(info: InfoCollections, limit: Int) -> Deferred<Maybe<DownloadEndState>> {
guard let modified = info.modified(self.collection) else {
log.debug("No server modified time for collection \(self.collection).")
return deferMaybe(.NoNewData)
}
log.debug("Modified: \(modified); last \(self.lastModified).")
if modified == self.lastModified {
log.debug("No more data to batch-download.")
return deferMaybe(.NoNewData)
}
// If the caller hasn't advanced after the last batch, strange things will happen --
// potentially looping indefinitely. Warn.
if self._advance != nil && !self.batch.isEmpty {
log.warning("Downloading another batch without having advanced. This might be a bug.")
}
return self.downloadNextBatchWithLimit(limit, infoModified: modified)
}
// We're either fetching from our current base timestamp with no offset,
// or the timestamp we were using when we last saved an offset.
func fetchParameters() -> (String?, Timestamp) {
if let (offset, since) = self.nextFetchParameters {
return (offset, since)
}
return (nil, max(self.lastModified, self.baseTimestamp))
}
func downloadNextBatchWithLimit(limit: Int, infoModified: Timestamp) -> Deferred<Maybe<DownloadEndState>> {
let (offset, since) = self.fetchParameters()
log.debug("Fetching newer=\(since), offset=\(offset).")
let fetch = self.client.getSince(since, sort: SortOption.OldestFirst, limit: limit, offset: offset)
func handleFailure(err: MaybeErrorType) -> Deferred<Maybe<DownloadEndState>> {
log.debug("Handling failure.")
guard let badRequest = err as? BadRequestError<[Record<T>]> where badRequest.response.metadata.status == 412 else {
// Just pass through the failure.
return deferMaybe(err)
}
// Conflict. Start again.
log.warning("Server contents changed during offset-based batching. Stepping back.")
self.nextFetchParameters = nil
return deferMaybe(.Interrupted)
}
func handleSuccess(response: StorageResponse<[Record<T>]>) -> Deferred<Maybe<DownloadEndState>> {
log.debug("Handling success.")
let nextOffset = response.metadata.nextOffset
let responseModified = response.value.last?.modified
// Queue up our metadata advance. We wait until the consumer has fetched
// and processed this batch; they'll call .advance() on success.
self._advance = {
// Shift to the next offset. This might be nil, in which case… fine!
// Note that we preserve the previous 'newer' value from the offset or the original fetch,
// even as we update baseTimestamp.
self.nextFetchParameters = nextOffset == nil ? nil : (nextOffset!, since)
// If there are records, advance to just before the timestamp of the last.
// If our next fetch with X-Weave-Next-Offset fails, at least we'll start here.
//
// This approach is only valid if we're fetching oldest-first.
if let newBase = responseModified {
log.debug("Advancing baseTimestamp to \(newBase) - 1")
self.baseTimestamp = newBase - 1
}
if nextOffset == nil {
// If we can't get a timestamp from the header -- and we should always be able to --
// we fall back on the collection modified time in i/c, as supplied by the caller.
// In any case where there is no racing writer these two values should be the same.
// If they differ, the header should be later. If it's missing, and we use the i/c
// value, we'll simply redownload some records.
// All bets are off if we hit this case and are filtering somehow… don't do that.
let lm = response.metadata.lastModifiedMilliseconds
log.debug("Advancing lastModified to \(lm) ?? \(infoModified).")
self.lastModified = lm ?? infoModified
}
}
log.debug("Got success response with \(response.metadata.records) records.")
// Store the incoming records for collection.
self.store(response.value)
return deferMaybe(nextOffset == nil ? .Complete : .Incomplete)
}
return fetch.bind { result in
guard let response = result.successValue else {
return handleFailure(result.failureValue!)
}
return handleSuccess(response)
}
}
}
public enum DownloadEndState: String {
case Complete // We're done. Records are waiting for you.
case Incomplete // applyBatch was called, and we think there are more records.
case NoNewData // There were no records.
case Interrupted // We got a 412 conflict when fetching the next batch.
}
| mpl-2.0 | a44376eec0d942daf86ff24844f6f353 | 39.371681 | 127 | 0.599189 | 4.966794 | false | false | false | false |
TwoRingSoft/SemVer | Vrsnr/vrsn/main.swift | 1 | 4941 | //
// main.swift
// vrsn
//
// Created by Andrew McKnight on 6/26/16.
// Copyright © 2016 Two Ring Software. All rights reserved.
//
// `.-:///////:--` `-::///////:-.`
// .://-.`` `.-::/:-.` ``.-:/-.
// .//.` `-/:.`-/-` `./:.
// `//. TWO ./:` `:/. ./:`
// ./:` -/- ./- `:/`
// `/: -+- ./. :/`
// :+` // // `+-
// // `+- RING -+` //
// // `+- -+` //
// :+` // :/ `+-
// `/: .+- ./. :/`
// ./:` -/- ./- `:/`
// `:/. ./:` `:/. SOFT ./:`
// .//.` `-/-`.:/-` `.::.
// `-/:-.`` `.-:/::-.` ``.-:/-`
// `.-:::////::-.` `.-::////:::-.`
import Foundation
checkForDebugMode()
// check for options that should halt the program without computation
checkForHelp()
checkForVersion()
// check for some options that affect requirement to read/write file later.
//
// precedence: --read > --try == --current-version
let readOnlyFromFile = isRead()
var versionString: String?
var dryRun = false
if !readOnlyFromFile {
versionString = Flags.value(forOptionalFlag: Flag.custom) ?? Flags.value(forOptionalFlag: Flag.currentVersion)
dryRun = isDryRun()
}
// get path to file containing source definition if we are reading or writing files...
//
// fileReadRequired: if the --read option is specified or there is no --current-version specified, we must read from the file
// fileWriteRequired: if --try is not specified, we must write to the file
//
// if either fileReadRequired or fileWriteRequired are true, --file and --key are required
var path: String?
var file: File?
var key: String?
let fileReadRequired = versionString == nil || readOnlyFromFile
let fileWriteRequired = !dryRun
if fileReadRequired || fileWriteRequired {
path = Flags.value(forNonoptionalFlag: Flag.file)
file = try! createFileForPath(path!)
key = Flags.value(forOptionalFlag: Flag.key)
}
// not required
var identifier = Flags.value(forOptionalFlag: Flag.prereleaseIdentifier)
var metadata = Flags.value(forOptionalFlag: Flag.buildMetadata)
// if no version override was specified with --current-version, get it from the file now
let versionType = getVersionType()
if versionString == nil {
guard let specifiedFile = file else {
print("Need to specify either a file containing version info or a value for \(Flag.currentVersion.short)/\(Flag.currentVersion.long).")
exit(ErrorCode.noVersionInformationSource.rawValue)
}
versionString = try! specifiedFile.versionStringForKey(key, versionType: versionType)
}
// FIXME: generics abuses incoming!
func doWork<V>() -> V where V: Version {
// extract the version from the file, optionally calculating the next version according to arguments
let original = try! V.parseFromString(versionString!)
var new: V?
if Arguments.contains(Flag.custom) {
new = original
} else if !readOnlyFromFile {
switch(versionType) {
case .Numeric:
new = original.nextVersion(0, prereleaseIdentifier: identifier, buildMetadata: metadata)
case .Semantic:
new = original.nextVersion(getRevType(), prereleaseIdentifier: identifier, buildMetadata: metadata)
}
}
// output or replace new version in file
if dryRun {
print(NSString(format: "%@", new!.description))
} else if readOnlyFromFile {
print(NSString(format: "%@", original.description))
} else {
try! file!.replaceVersionString(original, new: new!, key: key)
if key == nil {
key = file?.defaultKeyForVersionType(versionType)
}
print(NSString(format: "Updated %@ from %@ to %@ in %@", key!, original.description, new!.description, path!))
}
return original
}
//
// FIXME: vv generics abuses vv
//
// We have some generic functions that need to infer the template type, but I guess I haven't done so correctly yet, maybe using associatedType in the protocols with typealiases here? Will probably involve generic-izing the remainder of the protocol/shared functions etc
//
// So, for now we assign the result to a specific version type instead of something of type Version. This way the compiler infers the right type to use, and passes it back via the doWork()'s templated return type, which propogates to everything else from there.
//
switch versionType {
case .Numeric:
let _: NumericVersion = doWork()
case .Semantic:
let _: SemanticVersion = doWork()
}
//
// FIXME: ^^ generics abuses ^^
//
| apache-2.0 | 2b46409f0d1e0f33fef2775ede9c0823 | 37.897638 | 270 | 0.576721 | 4.175824 | false | false | false | false |
woohyuknrg/GithubTrending | githubTests/PullRequestSpec.swift | 1 | 1435 | import Quick
import Nimble
@testable import github
class PullRequestSpec: QuickSpec {
override func spec() {
describe("PullRequest") {
var sut: PullRequest!
let json = ["title" : "bananas",
"user" : [
"login" : "john",
],
"createdAt" : "2008-11-14T03:57:43Z"] as [String : Any]
beforeSuite {
sut = PullRequest.fromJSON(json)
}
context("when deserializing") {
it("should have valid title") {
expect(sut.title) == "bananas"
}
it("should have valid author") {
expect(sut.author) == "john"
}
it("should have valid creation date") {
var components = DateComponents()
components.day = 14
components.month = 11
components.year = 2008
components.hour = 3
components.minute = 57
components.second = 43
components.timeZone = TimeZone(secondsFromGMT: 0)
let date = Calendar.current.date(from: components)
expect(sut.date) == date
}
}
}
}
}
| mit | d2acce2df66b82a79822e64d89f412f1 | 31.613636 | 71 | 0.41324 | 5.694444 | false | false | false | false |
xedin/swift | test/IDE/print_property_wrappers.swift | 1 | 950 | // RUN: %empty-directory(%t)
// Directly printing the type-checked AST
// RUN: %target-swift-ide-test -print-ast-typechecked -source-filename %s | %FileCheck %s
@propertyWrapper
struct Wrapper<Value> {
var _stored: Value?
var value: Value {
get {
return _stored!
}
set {
_stored = newValue
}
}
init() {
self._stored = nil
}
init(initialValue: Value) {
self._stored = initialValue
}
init(closure: () -> Value) {
self._stored = closure()
}
}
func foo() -> Int { return 17 }
// CHECK: struct HasWrappers {
struct HasWrappers {
// CHECK: @Wrapper var x: Int {
// CHECK-NEXT: get
// CHECK: var $x: Wrapper<Int>
@Wrapper(closure: foo)
var x: Int
@Wrapper
var y = true
@Wrapper
var z: String
// Memberwise initializer.
// CHECK: init(x: Wrapper<Int> = Wrapper(closure: foo), y: Bool = true, z: String)
}
func trigger() {
_ = HasWrappers(y: false, z: "hello")
}
| apache-2.0 | 5ec31bd83589ab506d2e613d3ae273cc | 16.272727 | 89 | 0.602105 | 3.287197 | false | false | false | false |
RoRoche/iOSSwiftStarter | iOSSwiftStarter/Pods/CoreStore/CoreStore/Internal/NSManagedObjectContext+Querying.swift | 1 | 13568 | //
// NSManagedObjectContext+Querying.swift
// CoreStore
//
// Copyright © 2015 John Rommel Estropia
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
import Foundation
import CoreData
// MARK: - NSManagedObjectContext
internal extension NSManagedObjectContext {
// MARK: Internal
internal func fetchExisting<T: NSManagedObject>(object: T) -> T? {
if object.objectID.temporaryID {
do {
try withExtendedLifetime(self) { (context: NSManagedObjectContext) -> Void in
try context.obtainPermanentIDsForObjects([object])
}
}
catch {
CoreStore.handleError(
error as NSError,
"Failed to obtain permanent ID for object."
)
return nil
}
}
do {
let existingObject = try self.existingObjectWithID(object.objectID)
return (existingObject as! T)
}
catch {
CoreStore.handleError(
error as NSError,
"Failed to load existing \(typeName(object)) in context."
)
return nil
}
}
internal func fetchOne<T: NSManagedObject>(from: From<T>, _ fetchClauses: FetchClause...) -> T? {
return self.fetchOne(from, fetchClauses)
}
internal func fetchOne<T: NSManagedObject>(from: From<T>, _ fetchClauses: [FetchClause]) -> T? {
let fetchRequest = CoreStoreFetchRequest()
from.applyToFetchRequest(fetchRequest, context: self)
fetchRequest.fetchLimit = 1
fetchRequest.resultType = .ManagedObjectResultType
for clause in fetchClauses {
clause.applyToFetchRequest(fetchRequest)
}
var fetchResults: [T]?
var fetchError: NSError?
self.performBlockAndWait {
do {
fetchResults = try self.executeFetchRequest(fetchRequest) as? [T]
}
catch {
fetchError = error as NSError
}
}
if fetchResults == nil {
CoreStore.handleError(
fetchError ?? NSError(coreStoreErrorCode: .UnknownError),
"Failed executing fetch request."
)
return nil
}
return fetchResults?.first
}
internal func fetchAll<T: NSManagedObject>(from: From<T>, _ fetchClauses: FetchClause...) -> [T]? {
return self.fetchAll(from, fetchClauses)
}
internal func fetchAll<T: NSManagedObject>(from: From<T>, _ fetchClauses: [FetchClause]) -> [T]? {
let fetchRequest = CoreStoreFetchRequest()
from.applyToFetchRequest(fetchRequest, context: self)
fetchRequest.fetchLimit = 0
fetchRequest.resultType = .ManagedObjectResultType
for clause in fetchClauses {
clause.applyToFetchRequest(fetchRequest)
}
var fetchResults: [T]?
var fetchError: NSError?
self.performBlockAndWait {
do {
fetchResults = try self.executeFetchRequest(fetchRequest) as? [T]
}
catch {
fetchError = error as NSError
}
}
if fetchResults == nil {
CoreStore.handleError(
fetchError ?? NSError(coreStoreErrorCode: .UnknownError),
"Failed executing fetch request."
)
return nil
}
return fetchResults
}
internal func fetchCount<T: NSManagedObject>(from: From<T>, _ fetchClauses: FetchClause...) -> Int? {
return self.fetchCount(from, fetchClauses)
}
internal func fetchCount<T: NSManagedObject>(from: From<T>, _ fetchClauses: [FetchClause]) -> Int? {
let fetchRequest = CoreStoreFetchRequest()
from.applyToFetchRequest(fetchRequest, context: self)
for clause in fetchClauses {
clause.applyToFetchRequest(fetchRequest)
}
var count = 0
var error: NSError?
self.performBlockAndWait {
count = self.countForFetchRequest(fetchRequest, error: &error)
}
if count == NSNotFound {
CoreStore.handleError(
error ?? NSError(coreStoreErrorCode: .UnknownError),
"Failed executing fetch request."
)
return nil
}
return count
}
internal func fetchObjectID<T: NSManagedObject>(from: From<T>, _ fetchClauses: FetchClause...) -> NSManagedObjectID? {
return self.fetchObjectID(from, fetchClauses)
}
internal func fetchObjectID<T: NSManagedObject>(from: From<T>, _ fetchClauses: [FetchClause]) -> NSManagedObjectID? {
let fetchRequest = CoreStoreFetchRequest()
from.applyToFetchRequest(fetchRequest, context: self)
fetchRequest.fetchLimit = 1
fetchRequest.resultType = .ManagedObjectIDResultType
for clause in fetchClauses {
clause.applyToFetchRequest(fetchRequest)
}
var fetchResults: [NSManagedObjectID]?
var fetchError: NSError?
self.performBlockAndWait {
do {
fetchResults = try self.executeFetchRequest(fetchRequest) as? [NSManagedObjectID]
}
catch {
fetchError = error as NSError
}
}
if fetchResults == nil {
CoreStore.handleError(
fetchError ?? NSError(coreStoreErrorCode: .UnknownError),
"Failed executing fetch request."
)
return nil
}
return fetchResults?.first
}
internal func fetchObjectIDs<T: NSManagedObject>(from: From<T>, _ fetchClauses: FetchClause...) -> [NSManagedObjectID]? {
return self.fetchObjectIDs(from, fetchClauses)
}
internal func fetchObjectIDs<T: NSManagedObject>(from: From<T>, _ fetchClauses: [FetchClause]) -> [NSManagedObjectID]? {
let fetchRequest = CoreStoreFetchRequest()
from.applyToFetchRequest(fetchRequest, context: self)
fetchRequest.fetchLimit = 0
fetchRequest.resultType = .ManagedObjectIDResultType
for clause in fetchClauses {
clause.applyToFetchRequest(fetchRequest)
}
var fetchResults: [NSManagedObjectID]?
var fetchError: NSError?
self.performBlockAndWait {
do {
fetchResults = try self.executeFetchRequest(fetchRequest) as? [NSManagedObjectID]
}
catch {
fetchError = error as NSError
}
}
if fetchResults == nil {
CoreStore.handleError(
fetchError ?? NSError(coreStoreErrorCode: .UnknownError),
"Failed executing fetch request."
)
return nil
}
return fetchResults
}
internal func deleteAll<T: NSManagedObject>(from: From<T>, _ deleteClauses: DeleteClause...) -> Int? {
return self.deleteAll(from, deleteClauses)
}
internal func deleteAll<T: NSManagedObject>(from: From<T>, _ deleteClauses: [DeleteClause]) -> Int? {
let fetchRequest = CoreStoreFetchRequest()
from.applyToFetchRequest(fetchRequest, context: self)
fetchRequest.fetchLimit = 0
fetchRequest.resultType = .ManagedObjectResultType
fetchRequest.returnsObjectsAsFaults = true
fetchRequest.includesPropertyValues = false
for clause in deleteClauses {
clause.applyToFetchRequest(fetchRequest)
}
var numberOfDeletedObjects: Int?
var fetchError: NSError?
self.performBlockAndWait {
autoreleasepool {
do {
let fetchResults = try self.executeFetchRequest(fetchRequest) as? [T] ?? []
for object in fetchResults {
self.deleteObject(object)
}
numberOfDeletedObjects = fetchResults.count
}
catch {
fetchError = error as NSError
}
}
}
if numberOfDeletedObjects == nil {
CoreStore.handleError(
fetchError ?? NSError(coreStoreErrorCode: .UnknownError),
"Failed executing fetch request."
)
return nil
}
return numberOfDeletedObjects
}
internal func queryValue<T: NSManagedObject, U: SelectValueResultType>(from: From<T>, _ selectClause: Select<U>, _ queryClauses: QueryClause...) -> U? {
return self.queryValue(from, selectClause, queryClauses)
}
internal func queryValue<T: NSManagedObject, U: SelectValueResultType>(from: From<T>, _ selectClause: Select<U>, _ queryClauses: [QueryClause]) -> U? {
let fetchRequest = CoreStoreFetchRequest()
from.applyToFetchRequest(fetchRequest, context: self)
fetchRequest.fetchLimit = 0
selectClause.applyToFetchRequest(fetchRequest)
for clause in queryClauses {
clause.applyToFetchRequest(fetchRequest)
}
var fetchResults: [AnyObject]?
var fetchError: NSError?
self.performBlockAndWait {
do {
fetchResults = try self.executeFetchRequest(fetchRequest)
}
catch {
fetchError = error as NSError
}
}
if let fetchResults = fetchResults {
if let rawResult = fetchResults.first as? NSDictionary,
let rawObject: AnyObject = rawResult[selectClause.keyPathForFirstSelectTerm()] {
return Select<U>.ReturnType.fromResultObject(rawObject)
}
return nil
}
CoreStore.handleError(
fetchError ?? NSError(coreStoreErrorCode: .UnknownError),
"Failed executing fetch request."
)
return nil
}
internal func queryAttributes<T: NSManagedObject>(from: From<T>, _ selectClause: Select<NSDictionary>, _ queryClauses: QueryClause...) -> [[NSString: AnyObject]]? {
return self.queryAttributes(from, selectClause, queryClauses)
}
internal func queryAttributes<T: NSManagedObject>(from: From<T>, _ selectClause: Select<NSDictionary>, _ queryClauses: [QueryClause]) -> [[NSString: AnyObject]]? {
let fetchRequest = CoreStoreFetchRequest()
from.applyToFetchRequest(fetchRequest, context: self)
fetchRequest.fetchLimit = 0
selectClause.applyToFetchRequest(fetchRequest)
for clause in queryClauses {
clause.applyToFetchRequest(fetchRequest)
}
var fetchResults: [AnyObject]?
var fetchError: NSError?
self.performBlockAndWait {
do {
fetchResults = try self.executeFetchRequest(fetchRequest)
}
catch {
fetchError = error as NSError
}
}
if let fetchResults = fetchResults {
return Select<NSDictionary>.ReturnType.fromResultObjects(fetchResults)
}
CoreStore.handleError(
fetchError ?? NSError(coreStoreErrorCode: .UnknownError),
"Failed executing fetch request."
)
return nil
}
}
| apache-2.0 | 8956d065c44c224329a97ddd968900eb | 31.149289 | 168 | 0.551854 | 6.172429 | false | false | false | false |
lotpb/iosSQLswift | mySQLswift/NotificationController.swift | 1 | 9445 | //
// NotificationController.swift
// mySQLswift
//
// Created by Peter Balsamo on 12/20/15.
// Copyright © 2015 Peter Balsamo. All rights reserved.
//
import UIKit
class NotificationController: UIViewController {
let celltitle = UIFont.systemFontOfSize(18, weight: UIFontWeightRegular)
@IBOutlet weak var customMessage: UITextField!
@IBOutlet weak var datePicker: UIDatePicker!
@IBOutlet weak var frequencySegmentedControl : UISegmentedControl!
@IBOutlet weak var saveButton: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
let titleButton: UIButton = UIButton(frame: CGRectMake(0, 0, 100, 32))
titleButton.setTitle("myNotification", forState: UIControlState.Normal)
titleButton.titleLabel?.font = Font.navlabel
titleButton.titleLabel?.textAlignment = NSTextAlignment.Center
titleButton.setTitleColor(UIColor.whiteColor(), forState: UIControlState.Normal)
//titleButton.addTarget(self, action: Selector(), forControlEvents: UIControlEvents.TouchUpInside)
self.navigationItem.titleView = titleButton
let actionButton = UIBarButtonItem(barButtonSystemItem: .Action, target: self, action: #selector(NotificationController.actionButton))
let editButton = UIBarButtonItem(barButtonSystemItem: .Edit, target: self, action: #selector(NotificationController.editButton))
let buttons:NSArray = [editButton, actionButton]
self.navigationItem.rightBarButtonItems = buttons as? [UIBarButtonItem]
self.customMessage.clearButtonMode = .Always
self.customMessage!.font = celltitle
self.customMessage.placeholder = "enter notification"
self.saveButton.setTitleColor(UIColor.orangeColor(), forState: UIControlState.Normal)
self.saveButton.backgroundColor = UIColor.whiteColor()
self.saveButton.layer.cornerRadius = 24.0
self.saveButton.layer.borderColor = UIColor.orangeColor().CGColor
self.saveButton.layer.borderWidth = 3.0
UITextField.appearance().tintColor = UIColor.orangeColor()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
navigationController?.hidesBarsOnSwipe = true
self.navigationController?.navigationBar.tintColor = UIColor.whiteColor()
self.navigationController?.navigationBar.barTintColor = UIColor(white:0.45, alpha:1.0)
}
// MARK: - localNotification
/*
override class func initialize() {
var onceToken: dispatch_once_t = 0
dispatch_once(&onceToken) {
self.sendNotification()
}
} */
@IBAction func sendNotification(sender:AnyObject) {
let notifications:UILocalNotification = UILocalNotification()
//notifications.timeZone = NSTimeZone.localTimeZone()
//notifications.timeZone = NSTimeZone.systemTimeZone()
notifications.timeZone = NSTimeZone.defaultTimeZone()
notifications.fireDate = fixedNotificationDate(datePicker.date)
switch(frequencySegmentedControl.selectedSegmentIndex){
case 0:
notifications.repeatInterval = NSCalendarUnit(rawValue: 0)
break;
case 1:
notifications.repeatInterval = .Day
break;
case 2:
notifications.repeatInterval = .Weekday
break;
case 3:
notifications.repeatInterval = .Year
break;
default:
notifications.repeatInterval = NSCalendarUnit(rawValue: 0)
break;
}
notifications.alertBody = customMessage.text
notifications.alertAction = "Hey you! Yeah you! Swipe to unlock!"
notifications.category = "status"
notifications.userInfo = [ "cause": "inactiveMembership"]
notifications.applicationIconBadgeNumber = UIApplication.sharedApplication().applicationIconBadgeNumber + 1
notifications.soundName = "Tornado.caf"
UIApplication.sharedApplication().scheduleLocalNotification(notifications)
self.customMessage.text = ""
}
func memberNotification() {
let localNotification: UILocalNotification = UILocalNotification()
localNotification.alertAction = "Membership Status"
localNotification.alertBody = "Our system has detected that your membership is inactive."
localNotification.fireDate = NSDate(timeIntervalSinceNow: 15)
localNotification.timeZone = NSTimeZone.defaultTimeZone()
localNotification.category = "status"
localNotification.userInfo = ["cause": "inactiveMembership"]
localNotification.applicationIconBadgeNumber = UIApplication.sharedApplication().applicationIconBadgeNumber + 1
localNotification.soundName = "Tornado.caf"
UIApplication.sharedApplication().scheduleLocalNotification(localNotification)
}
func newBlogNotification() {
let localNotification: UILocalNotification = UILocalNotification()
localNotification.alertAction = "Blog Post"
localNotification.alertBody = "New Blog Posted at TheLight"
localNotification.fireDate = NSDate(timeIntervalSinceNow: 15)
localNotification.timeZone = NSTimeZone.defaultTimeZone()
localNotification.applicationIconBadgeNumber = UIApplication.sharedApplication().applicationIconBadgeNumber + 1
localNotification.soundName = UILocalNotificationDefaultSoundName
UIApplication.sharedApplication().scheduleLocalNotification(localNotification)
}
func HeyYouNotification() {
let localNotification: UILocalNotification = UILocalNotification()
localNotification.alertAction = "be awesome!"
localNotification.alertBody = "Hey you! Yeah you! Swipe to unlock!"
localNotification.fireDate = NSDate(timeIntervalSinceNow: 15)
localNotification.timeZone = NSTimeZone.defaultTimeZone()
localNotification.userInfo = ["CustomField1": "w00t"]
localNotification.applicationIconBadgeNumber = UIApplication.sharedApplication().applicationIconBadgeNumber + 1
localNotification.soundName = "Tornado.caf"
UIApplication.sharedApplication().scheduleLocalNotification(localNotification)
}
func promoNotification() {
let localNotification: UILocalNotification = UILocalNotification()
localNotification.alertAction = "TheLight!"
localNotification.alertBody = "Forget Something? Come back and SAVE 15% with Promo Code MYCART"
localNotification.fireDate = NSDate(timeIntervalSinceNow: 15)
localNotification.timeZone = NSTimeZone.defaultTimeZone()
localNotification.userInfo = ["CustomField1": "w00t"]
localNotification.applicationIconBadgeNumber = UIApplication.sharedApplication().applicationIconBadgeNumber + 1
localNotification.soundName = "Tornado.caf"
UIApplication.sharedApplication().scheduleLocalNotification(localNotification)
}
//Here we are going to set the value of second to zero
func fixedNotificationDate(dateToFix: NSDate) -> NSDate {
let dateComponents: NSDateComponents = NSCalendar.currentCalendar().components([NSCalendarUnit.Day, NSCalendarUnit.Month, NSCalendarUnit.Year, NSCalendarUnit.Hour, NSCalendarUnit.Minute], fromDate: dateToFix)
dateComponents.second = 0
let fixedDate: NSDate = NSCalendar.currentCalendar().dateFromComponents(dateComponents)!
return fixedDate
}
// MARK: - Button
func actionButton(sender: AnyObject) {
let alertController = UIAlertController(title:nil, message:nil, preferredStyle: .ActionSheet)
let buttonSix = UIAlertAction(title: "Membership Status", style: .Default, handler: { (action) -> Void in
self.memberNotification()
})
let newBog = UIAlertAction(title: "New Blog Posted", style: .Default, handler: { (action) -> Void in
self.newBlogNotification()
})
let heyYou = UIAlertAction(title: "Hey You", style: .Default, handler: { (action) -> Void in
self.HeyYouNotification()
})
let promo = UIAlertAction(title: "Promo Code", style: .Default, handler: { (action) -> Void in
self.promoNotification()
})
let buttonCancel = UIAlertAction(title: "Cancel", style: .Cancel) { (action) -> Void in
//print("Cancel Button Pressed")
}
alertController.addAction(buttonSix)
alertController.addAction(newBog)
alertController.addAction(heyYou)
alertController.addAction(promo)
alertController.addAction(buttonCancel)
if let popoverController = alertController.popoverPresentationController {
popoverController.barButtonItem = sender as? UIBarButtonItem
}
self.presentViewController(alertController, animated: true, completion: nil)
}
func editButton(sender:AnyObject) {
self.performSegueWithIdentifier("notificationdetailsegue", sender: self)
}
}
| gpl-2.0 | 9c14109a5fa3283e7292c4d695c80077 | 41.927273 | 216 | 0.688056 | 5.887781 | false | false | false | false |
rsbauer/Newsy | Newsy/Classes/Services/ABCNewsService.swift | 1 | 995 | //
// ABCNews.swift
// Newsy
//
// Created by Astro on 8/20/15.
// Copyright (c) 2015 Rock Solid Bits. All rights reserved.
//
import Foundation
import ObjectMapper
class ABCNewsService: NewsServiceProtocol {
func url() -> String {
var feedURL = ""
var feedsPlist: NSDictionary?
if let path = NSBundle.mainBundle().pathForResource("feeds", ofType: "plist") {
feedsPlist = NSDictionary(contentsOfFile: path)
}
if let feedDictionary = feedsPlist {
feedURL = feedDictionary.objectForKey("iphone") as! String
}
return feedURL
}
func returnType() -> AnyObject {
return Feed()
}
func mapResult(json: AnyObject?) -> AnyObject? {
let jsonDictionary:NSDictionary = json as! NSDictionary
if let newsFeed = Mapper<Feed>().map(jsonDictionary.objectForKey("config")) {
return newsFeed
}
return Feed()
}
} | mit | 112c8ff44ab712cedb94123648de710a | 23.9 | 87 | 0.588945 | 4.760766 | false | false | false | false |
GrandCentralBoard/GrandCentralBoard | GrandCentralBoard/Widgets/Watch/View/FlashingAnimationController.swift | 2 | 1174 | //
// Created by Oktawian Chojnacki on 06.04.2016.
// Copyright © 2016 Oktawian Chojnacki. All rights reserved.
//
import UIKit
final class FlashingAnimationController {
private weak var view: UIView?
private let interval: NSTimeInterval
private let alphaDepth: CGFloat
private let animationKey = "layerAnimation"
required init(view: UIView, interval: NSTimeInterval, alphaDepth: CGFloat) {
self.view = view
self.interval = interval
self.alphaDepth = alphaDepth
}
func startFlashing() {
let pulseAnimation = CABasicAnimation(keyPath: "opacity")
pulseAnimation.duration = interval
pulseAnimation.fromValue = 1
pulseAnimation.toValue = alphaDepth
pulseAnimation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)
pulseAnimation.autoreverses = true
pulseAnimation.repeatCount = FLT_MAX
pulseAnimation.removedOnCompletion = false
view?.layer.addAnimation(pulseAnimation, forKey: animationKey)
}
func stopFlashing() {
view?.layer.removeAnimationForKey(animationKey)
view?.alpha = 1
}
}
| gpl-3.0 | 3833fb282cf4dfa3ff2834ec38888a2d | 29.868421 | 104 | 0.702472 | 5.167401 | false | false | false | false |
vapor/vapor | Sources/Vapor/HTTP/Server/HTTPServerRequestDecoder.swift | 1 | 12661 | import NIO
import NIOHTTP1
final class HTTPServerRequestDecoder: ChannelDuplexHandler, RemovableChannelHandler {
typealias InboundIn = HTTPServerRequestPart
typealias InboundOut = Request
typealias OutboundIn = Never
enum RequestState {
case ready
case awaitingBody(Request)
case awaitingEnd(Request, ByteBuffer)
case streamingBody(Request.BodyStream)
case skipping
}
var requestState: RequestState
var bodyStreamState: HTTPBodyStreamState
var logger: Logger {
self.application.logger
}
var application: Application
init(application: Application) {
self.application = application
self.requestState = .ready
self.bodyStreamState = .init()
}
func channelRead(context: ChannelHandlerContext, data: NIOAny) {
assert(context.channel.eventLoop.inEventLoop)
let part = self.unwrapInboundIn(data)
self.logger.trace("Decoded HTTP part: \(part)")
switch part {
case .head(let head):
switch self.requestState {
case .ready:
let request = Request(
application: self.application,
method: head.method,
url: .init(string: head.uri),
version: head.version,
headersNoUpdate: head.headers,
remoteAddress: context.channel.remoteAddress,
logger: self.application.logger,
byteBufferAllocator: context.channel.allocator,
on: context.channel.eventLoop
)
switch head.version.major {
case 2:
request.isKeepAlive = true
default:
request.isKeepAlive = head.isKeepAlive
}
self.requestState = .awaitingBody(request)
default: assertionFailure("Unexpected state: \(self.requestState)")
}
case .body(let buffer):
switch self.requestState {
case .ready, .awaitingEnd:
assertionFailure("Unexpected state: \(self.requestState)")
case .awaitingBody(let request):
// We cannot assume that a request's content-length represents the length of all of the body
// because when a request is g-zipped, content-length refers to the gzipped length.
// Therefore, we can receive data after our expected end-of-request
// When decompressing data, more bytes come out than came in, so content-length does not represent the maximum length
if request.headers.first(name: .contentLength) == buffer.readableBytes.description {
self.requestState = .awaitingEnd(request, buffer)
} else {
let stream = Request.BodyStream(on: context.eventLoop, byteBufferAllocator: context.channel.allocator)
request.bodyStorage = .stream(stream)
self.requestState = .streamingBody(stream)
context.fireChannelRead(self.wrapInboundOut(request))
self.handleBodyStreamStateResult(
context: context,
self.bodyStreamState.didReadBytes(buffer),
stream: stream
)
}
case .streamingBody(let stream):
self.handleBodyStreamStateResult(
context: context,
self.bodyStreamState.didReadBytes(buffer),
stream: stream
)
case .skipping: break
}
case .end(let tailHeaders):
assert(tailHeaders == nil, "Tail headers are not supported.")
switch self.requestState {
case .ready: assertionFailure("Unexpected state: \(self.requestState)")
case .awaitingBody(let request):
context.fireChannelRead(self.wrapInboundOut(request))
case .awaitingEnd(let request, let buffer):
request.bodyStorage = .collected(buffer)
context.fireChannelRead(self.wrapInboundOut(request))
case .streamingBody(let stream):
self.handleBodyStreamStateResult(
context: context,
self.bodyStreamState.didEnd(),
stream: stream
)
case .skipping: break
}
self.requestState = .ready
}
}
func read(context: ChannelHandlerContext) {
switch self.requestState {
case .streamingBody(let stream):
self.handleBodyStreamStateResult(
context: context,
self.bodyStreamState.didReceiveReadRequest(),
stream: stream
)
default:
context.read()
}
}
func errorCaught(context: ChannelHandlerContext, error: Error) {
switch self.requestState {
case .streamingBody(let stream):
self.handleBodyStreamStateResult(
context: context,
self.bodyStreamState.didError(error),
stream: stream
)
default:
break
}
context.fireErrorCaught(error)
}
func channelInactive(context: ChannelHandlerContext) {
switch self.requestState {
case .streamingBody(let stream):
self.handleBodyStreamStateResult(
context: context,
self.bodyStreamState.didEnd(),
stream: stream
)
default:
break
}
context.fireChannelInactive()
}
func handleBodyStreamStateResult(
context: ChannelHandlerContext,
_ result: HTTPBodyStreamState.Result,
stream: Request.BodyStream
) {
switch result.action {
case .nothing: break
case .write(let buffer):
stream.write(.buffer(buffer)).whenComplete { writeResult in
switch writeResult {
case .failure(let error):
self.handleBodyStreamStateResult(
context: context,
self.bodyStreamState.didError(error),
stream: stream
)
case .success: break
}
self.handleBodyStreamStateResult(
context: context,
self.bodyStreamState.didWrite(),
stream: stream
)
}
case .close(let maybeError):
if let error = maybeError {
stream.write(.error(error), promise: nil)
} else {
stream.write(.end, promise: nil)
}
}
if result.callRead {
context.read()
}
}
func userInboundEventTriggered(context: ChannelHandlerContext, event: Any) {
switch event {
case is HTTPServerResponseEncoder.ResponseEndSentEvent:
switch self.requestState {
case .streamingBody(let bodyStream):
// Response ended during request stream.
if !bodyStream.isBeingRead {
self.logger.trace("Response already sent, draining unhandled request stream.")
bodyStream.read { _, promise in
promise?.succeed(())
}
}
case .awaitingBody, .awaitingEnd:
// Response ended before request started streaming.
self.logger.trace("Response already sent, skipping request body.")
self.requestState = .skipping
case .ready, .skipping:
// Response ended after request had been read.
break
}
case is ChannelShouldQuiesceEvent:
switch self.requestState {
case .ready:
self.logger.trace("Closing keep-alive HTTP connection since server is going away")
context.channel.close(mode: .all, promise: nil)
default:
self.logger.debug("A request is currently in-flight")
context.fireUserInboundEventTriggered(event)
}
default:
self.logger.trace("Unhandled user event: \(event)")
}
}
}
extension HTTPPart: CustomStringConvertible {
public var description: String {
switch self {
case .head(let head):
return "head: \(head)"
case .body(let body):
return "body: \(body)"
case .end(let headers):
if let headers = headers {
return "end: \(headers)"
} else {
return "end"
}
}
}
}
struct HTTPBodyStreamState: CustomStringConvertible {
struct Result {
enum Action {
case nothing
case write(ByteBuffer)
case close(Error?)
}
let action: Action
let callRead: Bool
}
private struct BufferState {
var bufferedWrites: CircularBuffer<ByteBuffer>
var heldUpRead: Bool
var hasClosed: Bool
mutating func append(_ buffer: ByteBuffer) {
self.bufferedWrites.append(buffer)
}
var isEmpty: Bool {
return self.bufferedWrites.isEmpty
}
mutating func removeFirst() -> ByteBuffer {
return self.bufferedWrites.removeFirst()
}
}
private enum State {
case idle
case writing(BufferState)
case error(Error)
}
private var state: State
var description: String {
"\(self.state)"
}
init() {
self.state = .idle
}
mutating func didReadBytes(_ buffer: ByteBuffer) -> Result {
switch self.state {
case .idle:
self.state = .writing(.init(
bufferedWrites: .init(),
heldUpRead: false,
hasClosed: false
))
return .init(action: .write(buffer), callRead: false)
case .writing(var buffers):
buffers.append(buffer)
self.state = .writing(buffers)
return .init(action: .nothing, callRead: false)
case .error:
return .init(action: .nothing, callRead: false)
}
}
mutating func didReceiveReadRequest() -> Result {
switch self.state {
case .idle:
return .init(action: .nothing, callRead: true)
case .writing(var buffers):
buffers.heldUpRead = true
self.state = .writing(buffers)
return .init(action: .nothing, callRead: false)
case .error:
return .init(action: .nothing, callRead: false)
}
}
mutating func didEnd() -> Result {
switch self.state {
case .idle:
return .init(action: .close(nil), callRead: false)
case .writing(var buffers):
buffers.hasClosed = true
self.state = .writing(buffers)
return .init(action: .nothing, callRead: false)
case .error:
return .init(action: .nothing, callRead: false)
}
}
mutating func didError(_ error: Error) -> Result {
switch self.state {
case .idle:
self.state = .error(error)
return .init(action: .close(error), callRead: false)
case .writing:
self.state = .error(error)
return .init(action: .nothing, callRead: false)
case .error:
return .init(action: .nothing, callRead: false)
}
}
mutating func didWrite() -> Result {
switch self.state {
case .idle:
self.illegalTransition()
case .writing(var buffers):
if buffers.isEmpty {
self.state = .idle
return .init(
action: buffers.hasClosed ? .close(nil) : .nothing,
callRead: buffers.heldUpRead
)
} else {
let first = buffers.removeFirst()
self.state = .writing(buffers)
return .init(action: .write(first), callRead: false)
}
case .error(let error):
return .init(action: .close(error), callRead: false)
}
}
private func illegalTransition(_ function: String = #function) -> Never {
preconditionFailure("illegal transition \(function) in \(self)")
}
}
| mit | ea5d228aee49cd2cbb68fc08edde6e23 | 33.687671 | 133 | 0.543164 | 5.290848 | false | false | false | false |
networkextension/SSencrypt | ENV/SFEnv.swift | 1 | 4076 | //
// SFEnv.swift
// Surf
//
//Copyright (c) 2016, networkextension
//All rights reserved.
//
//Redistribution and use in source and binary forms, with or without
//modification, are permitted provided that the following conditions are met:
//
//* Redistributions of source code must retain the above copyright notice, this
//list of conditions and the following disclaimer.
//
//* Redistributions in binary form must reproduce the above copyright notice,
//this list of conditions and the following disclaimer in the documentation
//and/or other materials provided with the distribution.
//
//* Neither the name of SSencrypt nor the names of its
//contributors may be used to endorse or promote products derived from
//this software without specific prior written permission.
//
//THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
//AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
//IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
//DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
//FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
//DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
//SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
//CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
//OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
//OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
import Foundation
import NetworkExtension
import Darwin
enum SFNetWorkIPType:Int32,CustomStringConvertible {
case ipv4 = 2//AF_INET
case ipv6 = 30//AF_INET6
internal var description: String {
switch self {
case .ipv4:return "IPV4"
case .ipv6:return "IPV6"
}
}
init(ip:String) {
var sin = sockaddr_in()
var sin6 = sockaddr_in6()
var t:Int32 = 0
if ip.withCString({ cstring in inet_pton(AF_INET6, cstring, &sin6.sin6_addr) }) == 1 {
// IPv6 peer.
t = AF_INET6
}
else if ip.withCString({ cstring in inet_pton(AF_INET, cstring, &sin.sin_addr) }) == 1 {
// IPv4 peer.
t = AF_INET
}
self = SFNetWorkIPType.init(rawValue: t)!
}
}
//物理层type
enum SFNetWorkType:Int,CustomStringConvertible {
case wifi = 0
case bluetooth = 1
case cell = 2
case cellshare = 3 //cell share 模式
internal var description: String {
switch self {
case .wifi:return "WI-FI"
case .bluetooth:return "BlueTooth"
case .cell:return "Cell"
case .cellshare:return "Cell Share"
}
}
init(interface:String) {
var t = -1
switch interface {
case "en0":
t = 0
case "awdl0":
t = 0
case "pdp_ip0":
t = 2
case "pdp_ip1":
t = 3
default:
t = 1
}
self = SFNetWorkType.init(rawValue: t)!
}
}
class SFEnv {
static let env:SFEnv = SFEnv()
var session:SFVPNSession = SFVPNSession()
var ipType:SFNetWorkIPType = .ipv4
var hwType:SFNetWorkType = .cell
init() {
}
func updateEnv(ip:String,interface:String){
ipType = SFNetWorkIPType.init(ip: ip)
hwType = SFNetWorkType.init(interface: interface)
}
func updateEnvIP(ip:String){
if !ip.isEmpty{
ipType = SFNetWorkIPType.init(ip: ip)
}
}
func updateEnvHW(interface:String){
hwType = SFNetWorkType.init(interface: interface)
}
func updateEnvHWWithPath(path:NWPath?){
if let p = path{
if p.expensive {
hwType = .cell
}else {
hwType = .wifi
}
AxLogger.log("Now Network Type: \(hwType.description)",level:.Info)
SFNetworkInterfaceManager.instances.updateIPAddress()
}
}
}
| bsd-3-clause | af4db22956474a86208476ebed1a249a | 30.276923 | 96 | 0.630103 | 4.001969 | false | false | false | false |
kesun421/firefox-ios | Client/Frontend/Home/HistoryPanel.swift | 1 | 24244 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import UIKit
import Shared
import Storage
import XCGLogger
import Deferred
private typealias SectionNumber = Int
private typealias CategoryNumber = Int
private typealias CategorySpec = (section: SectionNumber?, rows: Int, offset: Int)
private struct HistoryPanelUX {
static let WelcomeScreenItemTextColor = UIColor.gray
static let WelcomeScreenItemWidth = 170
static let IconSize = 23
static let IconBorderColor = UIColor(white: 0, alpha: 0.1)
static let IconBorderWidth: CGFloat = 0.5
}
private func getDate(_ dayOffset: Int) -> Date {
let calendar = Calendar(identifier: Calendar.Identifier.gregorian)
let nowComponents = (calendar as NSCalendar).components([.year, .month, .day], from: Date())
let today = calendar.date(from: nowComponents)!
return (calendar as NSCalendar).date(byAdding: NSCalendar.Unit.day, value: dayOffset, to: today, options: [])!
}
class HistoryPanel: SiteTableViewController, HomePanel {
weak var homePanelDelegate: HomePanelDelegate?
private var currentSyncedDevicesCount: Int?
var events = [NotificationFirefoxAccountChanged, NotificationPrivateDataClearedHistory, NotificationDynamicFontChanged]
var refreshControl: UIRefreshControl?
fileprivate lazy var longPressRecognizer: UILongPressGestureRecognizer = {
return UILongPressGestureRecognizer(target: self, action: #selector(HistoryPanel.longPress(_:)))
}()
private lazy var emptyStateOverlayView: UIView = self.createEmptyStateOverlayView()
private let QueryLimit = 100
private let NumSections = 5
private let Today = getDate(0)
private let Yesterday = getDate(-1)
private let ThisWeek = getDate(-7)
private var categories: [CategorySpec] = [CategorySpec]() // Category number (index) -> (UI section, row count, cursor offset).
private var sectionLookup = [SectionNumber: CategoryNumber]() // Reverse lookup from UI section to data category.
var syncDetailText = ""
var hasRecentlyClosed: Bool {
return self.profile.recentlyClosedTabs.tabs.count > 0
}
// MARK: - Lifecycle
init() {
super.init(nibName: nil, bundle: nil)
events.forEach { NotificationCenter.default.addObserver(self, selector: #selector(HistoryPanel.notificationReceived(_:)), name: $0, object: nil) }
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
tableView.addGestureRecognizer(longPressRecognizer)
tableView.accessibilityIdentifier = "History List"
updateSyncedDevicesCount().uponQueue(DispatchQueue.main) { result in
self.updateNumberOfSyncedDevices(self.currentSyncedDevicesCount)
}
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
// Add a refresh control if the user is logged in and the control was not added before. If the user is not
// logged in, remove any existing control but only when it is not currently refreshing. Otherwise, wait for
// the refresh to finish before removing the control.
if profile.hasSyncableAccount() && refreshControl == nil {
addRefreshControl()
} else if refreshControl?.isRefreshing == false {
removeRefreshControl()
}
if profile.hasSyncableAccount() {
syncDetailText = " "
updateSyncedDevicesCount().uponQueue(DispatchQueue.main) { result in
self.updateNumberOfSyncedDevices(self.currentSyncedDevicesCount)
}
} else {
syncDetailText = ""
}
}
@objc fileprivate func longPress(_ longPressGestureRecognizer: UILongPressGestureRecognizer) {
guard longPressGestureRecognizer.state == UIGestureRecognizerState.began else { return }
let touchPoint = longPressGestureRecognizer.location(in: tableView)
guard let indexPath = tableView.indexPathForRow(at: touchPoint) else { return }
if indexPath.section != 0 {
presentContextMenu(for: indexPath)
}
}
// MARK: - History Data Store
func updateNumberOfSyncedDevices(_ count: Int?) {
if let count = count, count > 0 {
syncDetailText = String.localizedStringWithFormat(Strings.SyncedTabsTableViewCellDescription, count)
} else {
syncDetailText = ""
}
self.tableView.reloadRows(at: [IndexPath(row: 1, section: 0)], with: .automatic)
}
func updateSyncedDevicesCount() -> Success {
return chainDeferred(self.profile.getCachedClientsAndTabs()) { tabsAndClients in
self.currentSyncedDevicesCount = tabsAndClients.count
return succeed()
}
}
func notificationReceived(_ notification: Notification) {
reloadData()
switch notification.name {
case NotificationFirefoxAccountChanged, NotificationPrivateDataClearedHistory:
if self.profile.hasSyncableAccount() {
resyncHistory()
}
break
case NotificationDynamicFontChanged:
if emptyStateOverlayView.superview != nil {
emptyStateOverlayView.removeFromSuperview()
}
emptyStateOverlayView = createEmptyStateOverlayView()
resyncHistory()
break
default:
// no need to do anything at all
print("Error: Received unexpected notification \(notification.name)")
break
}
}
private func fetchData() -> Deferred<Maybe<Cursor<Site>>> {
return profile.history.getSitesByLastVisit(QueryLimit)
}
private func setData(_ data: Cursor<Site>) {
self.data = data
self.computeSectionOffsets()
}
func resyncHistory() {
profile.syncManager.syncHistory().uponQueue(DispatchQueue.main) { result in
if result.isSuccess {
self.reloadData()
} else {
self.endRefreshing()
}
self.updateSyncedDevicesCount().uponQueue(DispatchQueue.main) { result in
self.updateNumberOfSyncedDevices(self.currentSyncedDevicesCount)
}
}
}
// MARK: - Refreshing TableView
func addRefreshControl() {
let refresh = UIRefreshControl()
refresh.addTarget(self, action: #selector(HistoryPanel.refresh), for: UIControlEvents.valueChanged)
self.refreshControl = refresh
self.tableView.refreshControl = refresh
}
func removeRefreshControl() {
self.tableView.refreshControl = nil
self.refreshControl = nil
}
func endRefreshing() {
// Always end refreshing, even if we failed!
self.refreshControl?.endRefreshing()
// Remove the refresh control if the user has logged out in the meantime
if !self.profile.hasSyncableAccount() {
self.removeRefreshControl()
}
}
@objc func refresh() {
self.refreshControl?.beginRefreshing()
resyncHistory()
}
override func reloadData() {
self.fetchData().uponQueue(DispatchQueue.main) { result in
if let data = result.successValue {
self.setData(data)
self.tableView.reloadData()
self.updateEmptyPanelState()
}
self.endRefreshing()
}
}
// MARK: - Empty State
private func updateEmptyPanelState() {
if data.count == 0 {
if self.emptyStateOverlayView.superview == nil {
self.tableView.addSubview(self.emptyStateOverlayView)
self.emptyStateOverlayView.snp.makeConstraints { make -> Void in
make.left.right.bottom.equalTo(self.view)
make.top.equalTo(self.view).offset(100)
}
}
} else {
self.tableView.alwaysBounceVertical = true
self.emptyStateOverlayView.removeFromSuperview()
}
}
private func createEmptyStateOverlayView() -> UIView {
let overlayView = UIView()
overlayView.backgroundColor = UIColor.white
let welcomeLabel = UILabel()
overlayView.addSubview(welcomeLabel)
welcomeLabel.text = Strings.HistoryPanelEmptyStateTitle
welcomeLabel.textAlignment = NSTextAlignment.center
welcomeLabel.font = DynamicFontHelper.defaultHelper.DeviceFontLight
welcomeLabel.textColor = HistoryPanelUX.WelcomeScreenItemTextColor
welcomeLabel.numberOfLines = 0
welcomeLabel.adjustsFontSizeToFitWidth = true
welcomeLabel.snp.makeConstraints { make in
make.centerX.equalTo(overlayView)
// Sets proper top constraint for iPhone 6 in portait and for iPad.
make.centerY.equalTo(overlayView).offset(HomePanelUX.EmptyTabContentOffset).priority(100)
// Sets proper top constraint for iPhone 4, 5 in portrait.
make.top.greaterThanOrEqualTo(overlayView).offset(50)
make.width.equalTo(HistoryPanelUX.WelcomeScreenItemWidth)
}
return overlayView
}
// MARK: - TableView Row Helpers
func computeSectionOffsets() {
var counts = [Int](repeating: 0, count: NumSections)
// Loop over all the data. Record the start of each "section" of our list.
for i in 0..<data.count {
if let site = data[i] {
counts[categoryForDate(site.latestVisit!.date) + 1] += 1
}
}
var section = 0
var offset = 0
self.categories = [CategorySpec]()
for i in 0..<NumSections {
let count = counts[i]
if i == 0 {
sectionLookup[section] = i
section += 1
}
if count > 0 {
self.categories.append((section: section, rows: count, offset: offset))
sectionLookup[section] = i
offset += count
section += 1
} else {
self.categories.append((section: nil, rows: 0, offset: offset))
}
}
}
fileprivate func siteForIndexPath(_ indexPath: IndexPath) -> Site? {
let offset = self.categories[sectionLookup[indexPath.section]!].offset
return data[indexPath.row + offset]
}
private func categoryForDate(_ date: MicrosecondTimestamp) -> Int {
let date = Double(date)
if date > (1000000 * Today.timeIntervalSince1970) {
return 0
}
if date > (1000000 * Yesterday.timeIntervalSince1970) {
return 1
}
if date > (1000000 * ThisWeek.timeIntervalSince1970) {
return 2
}
return 3
}
private func isInCategory(_ date: MicrosecondTimestamp, category: Int) -> Bool {
return self.categoryForDate(date) == category
}
// UI sections disappear as categories empty. We need to translate back and forth.
private func uiSectionToCategory(_ section: SectionNumber) -> CategoryNumber {
for i in 0..<self.categories.count {
if let s = self.categories[i].section, s == section {
return i
}
}
return 0
}
private func categoryToUISection(_ category: CategoryNumber) -> SectionNumber? {
return self.categories[category].section
}
// MARK: - TableView Delegate / DataSource
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = super.tableView(tableView, cellForRowAt: indexPath)
cell.accessoryType = UITableViewCellAccessoryType.none
if indexPath.section == 0 {
cell.imageView!.layer.borderWidth = 0
return indexPath.row == 0 ? configureRecentlyClosed(cell, for: indexPath) : configureSyncedTabs(cell, for: indexPath)
} else {
return configureSite(cell, for: indexPath)
}
}
func configureRecentlyClosed(_ cell: UITableViewCell, for indexPath: IndexPath) -> UITableViewCell {
cell.accessoryType = UITableViewCellAccessoryType.disclosureIndicator
cell.textLabel!.text = Strings.RecentlyClosedTabsButtonTitle
cell.detailTextLabel!.text = ""
cell.imageView!.image = UIImage(named: "recently_closed")
cell.imageView?.backgroundColor = UIColor.white
if !hasRecentlyClosed {
cell.textLabel?.alpha = 0.5
cell.imageView!.alpha = 0.5
cell.selectionStyle = .none
}
cell.accessibilityIdentifier = "HistoryPanel.recentlyClosedCell"
return cell
}
func configureSyncedTabs(_ cell: UITableViewCell, for indexPath: IndexPath) -> UITableViewCell {
cell.accessoryType = UITableViewCellAccessoryType.disclosureIndicator
cell.textLabel!.text = Strings.SyncedTabsTableViewCellTitle
cell.detailTextLabel!.text = self.syncDetailText
cell.imageView!.image = UIImage(named: "synced_devices")
cell.imageView?.backgroundColor = UIColor.white
cell.accessibilityIdentifier = "HistoryPanel.syncedDevicesCell"
return cell
}
func configureSite(_ cell: UITableViewCell, for indexPath: IndexPath) -> UITableViewCell {
if let site = siteForIndexPath(indexPath), let cell = cell as? TwoLineTableViewCell {
cell.setLines(site.title, detailText: site.url)
cell.imageView!.layer.borderColor = HistoryPanelUX.IconBorderColor.cgColor
cell.imageView!.layer.borderWidth = HistoryPanelUX.IconBorderWidth
cell.imageView?.setIcon(site.icon, forURL: site.tileURL, completed: { (color, url) in
if site.tileURL == url {
cell.imageView?.image = cell.imageView?.image?.createScaled(CGSize(width: HistoryPanelUX.IconSize, height: HistoryPanelUX.IconSize))
cell.imageView?.backgroundColor = color
cell.imageView?.contentMode = .center
}
})
}
return cell
}
func numberOfSectionsInTableView(_ tableView: UITableView) -> Int {
var count = 1
for category in self.categories where category.rows > 0 {
count += 1
}
return count
}
func tableView(_ tableView: UITableView, didSelectRowAtIndexPath indexPath: IndexPath) {
if indexPath.section == 0 {
self.tableView.deselectRow(at: indexPath, animated: true)
return indexPath.row == 0 ? self.showRecentlyClosed() : self.showSyncedTabs()
}
if let site = self.siteForIndexPath(indexPath), let url = URL(string: site.url) {
let visitType = VisitType.typed // Means History, too.
if let homePanelDelegate = homePanelDelegate {
homePanelDelegate.homePanel(self, didSelectURL: url, visitType: visitType)
}
return
}
print("Error: No site or no URL when selecting row.")
}
func pinTopSite(_ site: Site) {
_ = profile.history.addPinnedTopSite(site).value
}
func showSyncedTabs() {
let nextController = RemoteTabsPanel()
nextController.homePanelDelegate = self.homePanelDelegate
nextController.profile = self.profile
self.refreshControl?.endRefreshing()
self.navigationController?.pushViewController(nextController, animated: true)
}
func showRecentlyClosed() {
guard hasRecentlyClosed else {
return
}
let nextController = RecentlyClosedTabsPanel()
nextController.homePanelDelegate = self.homePanelDelegate
nextController.profile = self.profile
self.refreshControl?.endRefreshing()
self.navigationController?.pushViewController(nextController, animated: true)
}
func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
var title = String()
switch sectionLookup[section]! {
case 0: return nil
case 1: title = NSLocalizedString("Today", comment: "History tableview section header")
case 2: title = NSLocalizedString("Yesterday", comment: "History tableview section header")
case 3: title = NSLocalizedString("Last week", comment: "History tableview section header")
case 4: title = NSLocalizedString("Last month", comment: "History tableview section header")
default:
assertionFailure("Invalid history section \(section)")
}
return title
}
override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
if section == 0 {
return nil
}
return super.tableView(tableView, viewForHeaderInSection: section)
}
override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
if section == 0 {
return 0
}
return super.tableView(tableView, heightForHeaderInSection: section)
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if section == 0 {
return 2
}
return self.categories[uiSectionToCategory(section)].rows
}
func tableView(_ tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: IndexPath) {
// Intentionally blank. Required to use UITableViewRowActions
}
fileprivate func removeHistoryForURLAtIndexPath(indexPath: IndexPath) {
if let site = self.siteForIndexPath(indexPath) {
// Why the dispatches? Because we call success and failure on the DB
// queue, and so calling anything else that calls through to the DB will
// deadlock. This problem will go away when the history API switches to
// Deferred instead of using callbacks.
self.profile.history.removeHistoryForURL(site.url)
.upon { res in
self.fetchData().uponQueue(DispatchQueue.main) { result in
// If a section will be empty after removal, we must remove the section itself.
if let data = result.successValue {
let oldCategories = self.categories
self.data = data
self.computeSectionOffsets()
let sectionsToDelete = NSMutableIndexSet()
var rowsToDelete = [IndexPath]()
let sectionsToAdd = NSMutableIndexSet()
var rowsToAdd = [IndexPath]()
for (index, category) in self.categories.enumerated() {
let oldCategory = oldCategories[index]
// don't bother if we're not displaying this category
if oldCategory.section == nil && category.section == nil {
continue
}
// 1. add a new section if the section didn't previously exist
if oldCategory.section == nil && category.section != oldCategory.section {
sectionsToAdd.add(category.section!)
}
// 2. add a new row if there are more rows now than there were before
if oldCategory.rows < category.rows {
rowsToAdd.append(IndexPath(row: category.rows-1, section: category.section!))
}
// if we're dealing with the section where the row was deleted:
// 1. if the category no longer has a section, then we need to delete the entire section
// 2. delete a row if the number of rows has been reduced
// 3. delete the selected row and add a new one on the bottom of the section if the number of rows has stayed the same
if oldCategory.section == indexPath.section {
if category.section == nil {
sectionsToDelete.add(indexPath.section)
} else if oldCategory.section == category.section {
if oldCategory.rows > category.rows {
rowsToDelete.append(indexPath)
} else if category.rows == oldCategory.rows {
rowsToDelete.append(indexPath)
rowsToAdd.append(IndexPath(row: category.rows-1, section: indexPath.section))
}
}
}
}
self.tableView.beginUpdates()
if sectionsToAdd.count > 0 {
self.tableView.insertSections(sectionsToAdd as IndexSet, with: UITableViewRowAnimation.left)
}
if sectionsToDelete.count > 0 {
self.tableView.deleteSections(sectionsToDelete as IndexSet, with: UITableViewRowAnimation.right)
}
if !rowsToDelete.isEmpty {
self.tableView.deleteRows(at: rowsToDelete, with: UITableViewRowAnimation.right)
}
if !rowsToAdd.isEmpty {
self.tableView.insertRows(at: rowsToAdd, with: UITableViewRowAnimation.right)
}
self.tableView.endUpdates()
self.updateEmptyPanelState()
}
}
}
}
}
func tableView(_ tableView: UITableView, editActionsForRowAtIndexPath indexPath: IndexPath) -> [AnyObject]? {
if indexPath.section == 0 {
return []
}
let title = NSLocalizedString("Delete", tableName: "HistoryPanel", comment: "Action button for deleting history entries in the history panel.")
let delete = UITableViewRowAction(style: UITableViewRowActionStyle.default, title: title, handler: { (action, indexPath) in
self.removeHistoryForURLAtIndexPath(indexPath: indexPath)
})
return [delete]
}
}
extension HistoryPanel: HomePanelContextMenu {
func presentContextMenu(for site: Site, with indexPath: IndexPath, completionHandler: @escaping () -> PhotonActionSheet?) {
guard let contextMenu = completionHandler() else { return }
self.present(contextMenu, animated: true, completion: nil)
}
func getSiteDetails(for indexPath: IndexPath) -> Site? {
return siteForIndexPath(indexPath)
}
func getContextMenuActions(for site: Site, with indexPath: IndexPath) -> [PhotonActionSheetItem]? {
guard var actions = getDefaultContextMenuActions(for: site, homePanelDelegate: homePanelDelegate) else { return nil }
let removeAction = PhotonActionSheetItem(title: Strings.DeleteFromHistoryContextMenuTitle, iconString: "action_delete", handler: { action in
self.removeHistoryForURLAtIndexPath(indexPath: indexPath)
})
let pinTopSite = PhotonActionSheetItem(title: Strings.PinTopsiteActionTitle, iconString: "action_pin", handler: { action in
self.pinTopSite(site)
})
actions.append(pinTopSite)
actions.append(removeAction)
return actions
}
}
| mpl-2.0 | 2e9c2a06f488e24249c4a24c3b2a8a6e | 41.236934 | 154 | 0.612811 | 5.750474 | false | false | false | false |
ijoshsmith/swift-places | SwiftPlaces/SearchViewController.swift | 1 | 3962 | //
// ViewController.swift
// SwiftPlaces
//
// Created by Joshua Smith on 7/25/14.
// Copyright (c) 2014 iJoshSmith. All rights reserved.
//
import UIKit
/** Shows a search bar and lists places found by postal code. */
class SearchViewController: UIViewController, UITableViewDelegate, UISearchBarDelegate
{
override func viewDidLoad()
{
super.viewDidLoad()
navigationItem.title = "Search"
dataSource = PlaceDataSource(tableView: tableView)
tableView.dataSource = dataSource
tableView.delegate = self
// Allow the primary and detail views to show simultaneously.
splitViewController!.preferredDisplayMode = .AllVisible
// Show an "empty view" on the right-hand side, only on an iPad.
if UIDevice.currentDevice().userInterfaceIdiom == UIUserInterfaceIdiom.Pad
{
let emptyVC = storyboard!.instantiateViewControllerWithIdentifier("EmptyPlaceViewController") as! UIViewController
splitViewController!.showDetailViewController(emptyVC, sender: self)
}
}
// MARK: - UITableViewDelegate
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath)
{
let placeVC = storyboard!.instantiateViewControllerWithIdentifier("PlaceViewController") as! PlaceViewController
placeVC.place = dataSource.places[indexPath.row]
showDetailViewController(placeVC, sender: self)
}
// MARK: - UISearchBarDelegate
// Called when the keyboard search button is pressed.
func searchBarSearchButtonClicked(searchBar: UISearchBar)
{
let input = searchBar.text?
.stringByTrimmingCharactersInSet(
NSCharacterSet.whitespaceCharacterSet())
if let postalCode = input
{
if performSearchForPostalCode(postalCode)
{
searchBar.resignFirstResponder()
}
else
{
let image = UIImage(named: "ErrorColor")
searchBar.showErrorMessage("Numbers only!", backgroundImage: image)
}
}
}
// MARK: - Search service
private func performSearchForPostalCode(postalCode: String) -> Bool
{
let valid = postalCode.toInt() != nil
if valid
{
let url = URLFactory.searchWithPostalCode(postalCode)
JSONService
.GET(url)
.success({json in {self.makePlaces(json)} ~> {self.showPlaces($0)}})
.failure(onFailure, queue: NSOperationQueue.mainQueue())
}
return valid
}
private func makePlaces(json: AnyObject) -> [Place]
{
if let places = BuildPlacesFromJSON(json) as? [Place]
{
if let unique = NSSet(array: places).allObjects as? [Place]
{
return unique.sorted { $0.name < $1.name }
}
}
return []
}
private func showPlaces(places: [Place])
{
dataSource.places = places
}
private func onFailure(statusCode: Int, error: NSError?)
{
println("HTTP status code \(statusCode)")
let
title = "Error",
msg = error?.localizedDescription ?? "An error occurred.",
alert = UIAlertController(
title: title,
message: msg,
preferredStyle: .Alert)
alert.addAction(UIAlertAction(
title: "OK",
style: .Default,
handler: { _ in
self.dismissViewControllerAnimated(true, completion: nil)
}))
presentViewController(alert, animated: true, completion: nil)
}
// MARK: - State
private var dataSource: PlaceDataSource!
@IBOutlet private weak var searchBar: UISearchBar!
@IBOutlet private weak var tableView: UITableView!
}
| mit | 734314bd139b17f95dea57019f13fafb | 30.19685 | 126 | 0.601212 | 5.472376 | false | false | false | false |
UW-AppDEV/AUXWave | AUXWave/PlayerControlBar.swift | 1 | 2530 | //
// PlayerControlBar.swift
// AUXWave
//
// Created by Nico Cvitak on 2015-03-14.
// Copyright (c) 2015 UW-AppDEV. All rights reserved.
//
import UIKit
class PlayerControlBar: UIToolbar {
private var playButton: UIBarButtonItem?
private var pauseButton: UIBarButtonItem?
private var backButton: UIBarButtonItem?
private var nextButton: UIBarButtonItem?
private let fixedSpace: UIBarButtonItem = {
let space = UIBarButtonItem(barButtonSystemItem: .FixedSpace, target: nil, action: nil)
space.width = 42
return space
}()
var player: PlaylistPlayer?
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
playButton = UIBarButtonItem(barButtonSystemItem: .Play, target: self, action: "play")
pauseButton = UIBarButtonItem(barButtonSystemItem: .Pause, target: self, action: "pause")
backButton = UIBarButtonItem(barButtonSystemItem: .Rewind, target: self, action: "back")
nextButton = UIBarButtonItem(barButtonSystemItem: .FastForward, target: self, action: "next")
self.items = [
UIBarButtonItem(barButtonSystemItem: .FlexibleSpace, target: nil, action: nil),
backButton!,
fixedSpace,
playButton!,
fixedSpace,
nextButton!,
UIBarButtonItem(barButtonSystemItem: .FlexibleSpace, target: nil, action: nil)
]
self.setBackgroundImage(UIImage(), forToolbarPosition: .Any, barMetrics: .Default)
self.backgroundColor = UIColor.clearColor()
self.clipsToBounds = true
}
/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
override func drawRect(rect: CGRect) {
// Drawing code
}
*/
func play() {
if let player = self.player {
if player.paused() {
player.play()
self.items?[3] = pauseButton!
}
}
}
func pause() {
if let player = self.player {
if !player.paused() {
player.pause()
self.items?[3] = playButton!
}
}
}
func back() {
if let player = self.player {
player.previousTrack()
}
}
func next() {
if let player = self.player {
player.nextTrack()
}
}
}
| gpl-2.0 | 947dfe8378c8bf1bd34152d74a3061c3 | 27.426966 | 101 | 0.583004 | 5.0499 | false | false | false | false |
leo150/Pelican | Sources/Pelican/Session/Modules/Monitors/Flood.swift | 1 | 2565 | //
// Flood.swift
// Pelican
//
// Created by Takanu Kyriako on 20/08/2017.
//
import Foundation
import Vapor
/**
Used for monitoring and controlling updates sent to a session by a user.
*/
public class Flood {
/// The currently active set of limits.
var monitors: [FloodMonitor] = []
init() { }
/**
Adds a new flood monitor to the class. If the criteria for the flood monitor you're attempting to add match a
monitor thats already being used, a new monitor will not be created.
*/
public func add(type: [UpdateType], hits: Int, duration: Duration, action: @escaping () -> ()) {
let monitor = FloodMonitor(type: type, hits: hits, duration: duration, action: action)
if monitors.contains(monitor) { return }
monitors.append(monitor)
}
/**
Uses an update to attempt bumping the hits on any monitors currently being used, where the
update is applicable to them.
*/
public func bump(_ update: Update) {
monitors.forEach( { $0.bump(update) } )
}
}
/**
Defines a set of rules that a FloodLimit class can check for.
*/
public class FloodMonitor: Equatable {
// CRITERIA
var type: [UpdateType] = []
var hits: Int
var duration: Duration
var action: () -> ()
// CURRENT STATE
var currentTime: Date = Date()
var currentHits: Int = 0
var actionExecuted: Bool = false
/**
Creates a new FloodMonitor type.
*/
init(type: [UpdateType], hits: Int, duration: Duration, action: @escaping () -> ()) {
self.type = type
self.hits = hits
self.duration = duration
self.action = action
}
/**
Uses an update to attempt bumping the hits that have occurred on the monitor, in an attempt to trigger
the action belonging to it.
*/
public func bump(_ update: Update) {
// Check that we can actually bump the monitor
if self.type.contains(update.type) == false { return }
// If so, check the times and hits
if Date().timeIntervalSince1970 > (currentTime.timeIntervalSince1970 + duration.rawValue) {
reset()
return
}
// Otherwise bump the hits and check if we've hit the requirement for the action to be triggered.
currentHits += 1
if currentHits >= hits && actionExecuted == false {
action()
actionExecuted = true
}
}
/**
Resets all state variables
*/
public func reset() {
currentTime = Date()
currentHits = 0
actionExecuted = false
}
public static func ==(lhs: FloodMonitor, rhs: FloodMonitor) -> Bool {
if lhs.type == rhs.type &&
lhs.hits == rhs.hits &&
lhs.duration == rhs.duration { return true }
return false
}
}
| mit | a3451ca02a49f52f858f41591d8db7a8 | 20.923077 | 111 | 0.669006 | 3.513699 | false | false | false | false |
raymondshadow/SwiftDemo | SwiftApp/Pods/RxSwift/RxSwift/Observables/Generate.swift | 4 | 3363 | //
// Generate.swift
// RxSwift
//
// Created by Krunoslav Zaher on 9/2/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
extension ObservableType {
/**
Generates an observable sequence by running a state-driven loop producing the sequence's elements, using the specified scheduler
to run the loop send out observer messages.
- seealso: [create operator on reactivex.io](http://reactivex.io/documentation/operators/create.html)
- parameter initialState: Initial state.
- parameter condition: Condition to terminate generation (upon returning `false`).
- parameter iterate: Iteration step function.
- parameter scheduler: Scheduler on which to run the generator loop.
- returns: The generated sequence.
*/
public static func generate(initialState: E, condition: @escaping (E) throws -> Bool, scheduler: ImmediateSchedulerType = CurrentThreadScheduler.instance, iterate: @escaping (E) throws -> E) -> Observable<E> {
return Generate(initialState: initialState, condition: condition, iterate: iterate, resultSelector: { $0 }, scheduler: scheduler)
}
}
final private class GenerateSink<S, O: ObserverType>: Sink<O> {
typealias Parent = Generate<S, O.E>
private let _parent: Parent
private var _state: S
init(parent: Parent, observer: O, cancel: Cancelable) {
self._parent = parent
self._state = parent._initialState
super.init(observer: observer, cancel: cancel)
}
func run() -> Disposable {
return self._parent._scheduler.scheduleRecursive(true) { isFirst, recurse -> Void in
do {
if !isFirst {
self._state = try self._parent._iterate(self._state)
}
if try self._parent._condition(self._state) {
let result = try self._parent._resultSelector(self._state)
self.forwardOn(.next(result))
recurse(false)
}
else {
self.forwardOn(.completed)
self.dispose()
}
}
catch let error {
self.forwardOn(.error(error))
self.dispose()
}
}
}
}
final private class Generate<S, E>: Producer<E> {
fileprivate let _initialState: S
fileprivate let _condition: (S) throws -> Bool
fileprivate let _iterate: (S) throws -> S
fileprivate let _resultSelector: (S) throws -> E
fileprivate let _scheduler: ImmediateSchedulerType
init(initialState: S, condition: @escaping (S) throws -> Bool, iterate: @escaping (S) throws -> S, resultSelector: @escaping (S) throws -> E, scheduler: ImmediateSchedulerType) {
self._initialState = initialState
self._condition = condition
self._iterate = iterate
self._resultSelector = resultSelector
self._scheduler = scheduler
super.init()
}
override func run<O : ObserverType>(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == E {
let sink = GenerateSink(parent: self, observer: observer, cancel: cancel)
let subscription = sink.run()
return (sink: sink, subscription: subscription)
}
}
| apache-2.0 | 7533562cf3d77915c5556fe41971c6f3 | 37.643678 | 213 | 0.614218 | 4.816619 | false | false | false | false |
zach-freeman/swift-localview | localview/FlickrConstants.swift | 1 | 1202 | //
// FlickrConstants.swift
// localview
//
// Created by Zach Freeman on 8/13/15.
// Copyright (c) 2021 sparkwing. All rights reserved.
//
import UIKit
class FlickrConstants: NSObject {
static let kFlickrApiKey: String = "==redacted=="
static let kFlickrUrl: String = "https://www.flickr.com/services/rest/"
static let kSearchMethod: String = "flickr.photos.search"
static let kFormatType: String = "json"
static let kJsonCallback: Int = 1
static let kPrivacyFilter: Int = 1
static let kNumberOfPhotos: String = "100"
static let kFlickrPhotoSourceHost: String = "static.flickr.com"
static let kTitleNotAvailable: String = "Title not available"
static let kSmallImageSize: FlickrApiUtils.FlickrPhotoSize = FlickrApiUtils.FlickrPhotoSize.photoSizeSmallSquare75
static let kBigImageSize: FlickrApiUtils.FlickrPhotoSize = FlickrApiUtils.FlickrPhotoSize.photoSizeLarge1024
static let kMaxTitleSize: String = """
UmjLyNul3eFoj5zVivYVfR18coNUSInD3rRO2ABzwSDzigNATEJTam0HlMVwcoY0LBeK4m4Zhwu0ZC7S24GrONKymeEXVUMDst97IN96caaZw44c94ClHK1X
6sIpSvoSqVejiTu6Fscq12zIi2zwHjROVYwhH4mcvUgGLz3Q06ZCq8fuxwUGBcK3n9h6SXqj3EnRjHF182yXoNN9eM4PW3ZUHgh0y449WnAHpTIex46ys8q3
itu9GTTSPXGeVLG
"""
}
| mit | 2f2fa7c5df897d50989db34d67ebdd30 | 41.928571 | 120 | 0.810316 | 2.868735 | false | false | false | false |
creatubbles/ctb-api-swift | CreatubblesAPIClientUnitTests/Spec/Gallery/FavoriteGalleryRequestSpec.swift | 1 | 2446 | //
// FavoriteGalleryRequestSpec.swift
// CreatubblesAPIClient
//
// Copyright (c) 2017 Creatubbles Pte. Ltd.
//
// 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 Quick
import Nimble
@testable import CreatubblesAPIClient
class FavoriteGalleryRequestSpec: QuickSpec {
override func spec() {
let galleryId = "galleryId"
describe("Favorite gallery request") {
it("Should have proper endpoint for gallery") {
let request = FavoriteGalleryRequest(galleryId: galleryId)
expect(request.endpoint) == "galleries/\(galleryId)/favorite"
}
it("Should have proper method") {
let request = FavoriteGalleryRequest(galleryId: galleryId)
expect(request.method) == RequestMethod.post
}
}
describe("Remove favorite gallery request") {
it("Should have proper endpoint for gallery") {
let request = RemoveFavoriteGalleryRequest(galleryId: galleryId)
expect(request.endpoint) == "galleries/\(galleryId)/favorite"
}
it("Should have proper method") {
let request = RemoveFavoriteGalleryRequest(galleryId: galleryId)
expect(request.method) == RequestMethod.delete
}
}
}
}
| mit | 1890c13006ed1b1a13ec640fbc3bbd0e | 39.098361 | 81 | 0.6574 | 4.931452 | false | false | false | false |
ifeherva/HSTracker | HSTracker/Core/Paths.swift | 2 | 2361 | //
// Paths.swift
// HSTracker
//
// Created by Benjamin Michotte on 29/10/16.
// Copyright © 2016 Benjamin Michotte. All rights reserved.
//
import Foundation
/**
Helper object for system folder locations
*/
class Paths {
static let HSTracker: URL = {
let paths = FileManager.default.urls(for: .applicationSupportDirectory,
in: .userDomainMask)
let applicationSupport = paths[0]
return applicationSupport.appendingPathComponent("HSTracker", isDirectory: true)
}()
static let cards: URL = {
return HSTracker.appendingPathComponent("cards", isDirectory: true)
}()
static let tiles: URL = {
return HSTracker.appendingPathComponent("tiles", isDirectory: true)
}()
static let decks: URL = {
return HSTracker.appendingPathComponent("decks", isDirectory: true)
}()
static let replays: URL = {
return HSTracker.appendingPathComponent("replays", isDirectory: true)
}()
static let tmpReplays: URL = {
return replays.appendingPathComponent("tmp", isDirectory: true)
}()
static let cardJson: URL = {
return HSTracker.appendingPathComponent("json", isDirectory: true)
}()
static let arenaJson: URL = {
return HSTracker.appendingPathComponent("arena", isDirectory: true)
}()
static let logs: URL = {
let paths = FileManager.default.urls(for: .libraryDirectory,
in: .userDomainMask)
let libraryDirectory = paths[0]
return libraryDirectory.appendingPathComponent("Logs/HSTracker", isDirectory: true)
}()
/**
Creates folders at all path object location
*/
static func initDirs() {
let paths = [cards, decks, replays, cardJson, logs, tmpReplays, tiles, arenaJson]
let fileManager = FileManager.default
for path in paths {
if fileManager.fileExists(atPath: path.absoluteString) { continue }
do {
try FileManager.default
.createDirectory(at: path,
withIntermediateDirectories: true,
attributes: nil)
} catch {
logger.error("Can not create directory \(path) : \(error)")
}
}
}
}
| mit | 750571246e14d02a77bff57f5d086ac1 | 30.466667 | 91 | 0.598305 | 5.064378 | false | false | false | false |
sucrewar/SwiftUEx | SwiftEx/Classes/UIImageEffects.swift | 1 | 12352 | import UIKit
import Accelerate
public extension UIImageView {
public func roundendImageField() -> UIImageView {
self.layer.cornerRadius = self.frame.size.width / 2
self.clipsToBounds = true
return self
}
}
public extension UIImage {
public func imageRotatedByDegrees(degrees: CGFloat, flip: Bool) -> UIImage {
let degreesToRadians: (CGFloat) -> CGFloat = {
return $0 / 180.0 * CGFloat(M_PI)
}
// calculate the size of the rotated view's containing box for our drawing space
let rotatedViewBox = UIView(frame: CGRect(origin: CGPoint.zero, size: size))
let t = CGAffineTransformMakeRotation(degreesToRadians(degrees))
rotatedViewBox.transform = t
let rotatedSize = rotatedViewBox.frame.size
// Create the bitmap context
UIGraphicsBeginImageContext(rotatedSize)
let bitmap = UIGraphicsGetCurrentContext()
// Move the origin to the middle of the image so we will rotate and scale around the center.
CGContextTranslateCTM(bitmap, rotatedSize.width / 2.0, rotatedSize.height / 2.0)
// // Rotate the image context
CGContextRotateCTM(bitmap, degreesToRadians(degrees))
// Now, draw the rotated/scaled image into the context
var yFlip: CGFloat
if(flip) {
yFlip = CGFloat(-1.0)
} else {
yFlip = CGFloat(1.0)
}
CGContextScaleCTM(bitmap, yFlip, -1.0)
CGContextDrawImage(bitmap, CGRectMake(-size.width / 2, -size.height / 2, size.width, size.height), CGImage)
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return newImage
}
public func toBase64() -> String {
let imageData = UIImagePNGRepresentation(self)!
return imageData.base64EncodedStringWithOptions(.Encoding64CharacterLineLength)
}
public func applyLightEffect() -> UIImage? {
return applyBlurWithRadius(30, tintColor: UIColor(white: 1.0, alpha: 0.3), saturationDeltaFactor: 1.8)
}
public func applyExtraLightEffect() -> UIImage? {
return applyBlurWithRadius(20, tintColor: UIColor(white: 0.97, alpha: 0.82), saturationDeltaFactor: 1.8)
}
public func applyDarkEffect() -> UIImage? {
return applyBlurWithRadius(20, tintColor: UIColor(white: 0.11, alpha: 0.73), saturationDeltaFactor: 1.8)
}
public func applyTintEffectWithColor(tintColor: UIColor) -> UIImage? {
let effectColorAlpha: CGFloat = 0.6
var effectColor = tintColor
let componentCount = CGColorGetNumberOfComponents(tintColor.CGColor)
if componentCount == 2 {
var b: CGFloat = 0
if tintColor.getWhite(&b, alpha: nil) {
effectColor = UIColor(white: b, alpha: effectColorAlpha)
}
} else {
var red: CGFloat = 0
var green: CGFloat = 0
var blue: CGFloat = 0
if tintColor.getRed(&red, green: &green, blue: &blue, alpha: nil) {
effectColor = UIColor(red: red, green: green, blue: blue, alpha: effectColorAlpha)
}
}
return applyBlurWithRadius(10, tintColor: effectColor, saturationDeltaFactor: -1.0, maskImage: nil)
}
public func applyBlurWithRadius(blurRadius: CGFloat, tintColor: UIColor?, saturationDeltaFactor: CGFloat, maskImage: UIImage? = nil) -> UIImage? {
if (size.width < 1 || size.height < 1) {
print("*** error: invalid size: \(size.width) x \(size.height). Both dimensions must be >= 1: \(self)")
return nil
}
if self.CGImage == nil {
print("*** error: image must be backed by a CGImage: \(self)")
return nil
}
if maskImage != nil && maskImage!.CGImage == nil {
print("*** error: maskImage must be backed by a CGImage: \(maskImage)")
return nil
}
let __FLT_EPSILON__ = CGFloat(FLT_EPSILON)
let screenScale = UIScreen.mainScreen().scale
let imageRect = CGRect(origin: CGPoint.zero, size: size)
var effectImage = self
let hasBlur = blurRadius > __FLT_EPSILON__
let hasSaturationChange = fabs(saturationDeltaFactor - 1.0) > __FLT_EPSILON__
if hasBlur || hasSaturationChange {
func createEffectBuffer(context: CGContext) -> vImage_Buffer {
let data = CGBitmapContextGetData(context)
let width = vImagePixelCount(CGBitmapContextGetWidth(context))
let height = vImagePixelCount(CGBitmapContextGetHeight(context))
let rowBytes = CGBitmapContextGetBytesPerRow(context)
return vImage_Buffer(data: data, height: height, width: width, rowBytes: rowBytes)
}
UIGraphicsBeginImageContextWithOptions(size, false, screenScale)
let effectInContext = UIGraphicsGetCurrentContext()
CGContextScaleCTM(effectInContext, 1.0, -1.0)
CGContextTranslateCTM(effectInContext, 0, -size.height)
CGContextDrawImage(effectInContext, imageRect, self.CGImage)
var effectInBuffer = createEffectBuffer(effectInContext!)
UIGraphicsBeginImageContextWithOptions(size, false, screenScale)
let effectOutContext = UIGraphicsGetCurrentContext()
var effectOutBuffer = createEffectBuffer(effectOutContext!)
if hasBlur {
let inputRadius = blurRadius * screenScale
var radius = UInt32(floor(inputRadius * 3.0 * CGFloat(sqrt(2 * M_PI)) / 4 + 0.5))
if radius % 2 != 1 {
radius += 1
}
let imageEdgeExtendFlags = vImage_Flags(kvImageEdgeExtend)
vImageBoxConvolve_ARGB8888(&effectInBuffer, &effectOutBuffer, nil, 0, 0, radius, radius, nil, imageEdgeExtendFlags)
vImageBoxConvolve_ARGB8888(&effectOutBuffer, &effectInBuffer, nil, 0, 0, radius, radius, nil, imageEdgeExtendFlags)
vImageBoxConvolve_ARGB8888(&effectInBuffer, &effectOutBuffer, nil, 0, 0, radius, radius, nil, imageEdgeExtendFlags)
}
var effectImageBuffersAreSwapped = false
if hasSaturationChange {
let s: CGFloat = saturationDeltaFactor
let floatingPointSaturationMatrix: [CGFloat] = [
0.0722 + 0.9278 * s, 0.0722 - 0.0722 * s, 0.0722 - 0.0722 * s, 0,
0.7152 - 0.7152 * s, 0.7152 + 0.2848 * s, 0.7152 - 0.7152 * s, 0,
0.2126 - 0.2126 * s, 0.2126 - 0.2126 * s, 0.2126 + 0.7873 * s, 0,
0, 0, 0, 1
]
let divisor: CGFloat = 256
let matrixSize = floatingPointSaturationMatrix.count
var saturationMatrix = [Int16](count: matrixSize, repeatedValue: 0)
for i: Int in 0 ..< matrixSize {
saturationMatrix[i] = Int16(round(floatingPointSaturationMatrix[i] * divisor))
}
if hasBlur {
vImageMatrixMultiply_ARGB8888(&effectOutBuffer, &effectInBuffer, saturationMatrix, Int32(divisor), nil, nil, vImage_Flags(kvImageNoFlags))
effectImageBuffersAreSwapped = true
} else {
vImageMatrixMultiply_ARGB8888(&effectInBuffer, &effectOutBuffer, saturationMatrix, Int32(divisor), nil, nil, vImage_Flags(kvImageNoFlags))
}
}
if !effectImageBuffersAreSwapped {
effectImage = UIGraphicsGetImageFromCurrentImageContext()
}
UIGraphicsEndImageContext()
if effectImageBuffersAreSwapped {
effectImage = UIGraphicsGetImageFromCurrentImageContext()
}
UIGraphicsEndImageContext()
}
UIGraphicsBeginImageContextWithOptions(size, false, screenScale)
let outputContext = UIGraphicsGetCurrentContext()
CGContextScaleCTM(outputContext, 1.0, -1.0)
CGContextTranslateCTM(outputContext, 0, -size.height)
CGContextDrawImage(outputContext, imageRect, self.CGImage)
if hasBlur {
CGContextSaveGState(outputContext)
if let image = maskImage {
CGContextClipToMask(outputContext, imageRect, image.CGImage)
}
CGContextDrawImage(outputContext, imageRect, effectImage.CGImage)
CGContextRestoreGState(outputContext)
}
if let color = tintColor {
CGContextSaveGState(outputContext)
CGContextSetFillColorWithColor(outputContext, color.CGColor)
CGContextFillRect(outputContext, imageRect)
CGContextRestoreGState(outputContext)
}
let outputImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return outputImage
}
public func roundedImage () -> UIImage {
let rect = CGRect(origin:CGPoint(x: 0, y: 0), size: self.size)
UIGraphicsBeginImageContextWithOptions(self.size, false, 1)
UIBezierPath(
roundedRect: rect,
cornerRadius: self.size.height
).addClip()
self.drawInRect(rect)
return UIGraphicsGetImageFromCurrentImageContext()
}
public func resizeImage(newWidth: CGFloat) -> UIImage {
let scale = newWidth / self.size.width
let newHeight = self.size.height * scale
UIGraphicsBeginImageContext(CGSize(width: newWidth, height: newHeight))
self.drawInRect(CGRect(x: 0, y: 0, width: newWidth, height: newHeight))
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return newImage
}
public func scaleImage(toSize newSize: CGSize) -> (UIImage) {
let newRect = CGRectIntegral(CGRectMake(0, 0, newSize.width, newSize.height))
UIGraphicsBeginImageContextWithOptions(newSize, false, 0)
let context = UIGraphicsGetCurrentContext()
CGContextSetInterpolationQuality(context, .High)
let flipVertical = CGAffineTransformMake(1, 0, 0, -1, 0, newSize.height)
CGContextConcatCTM(context, flipVertical)
CGContextDrawImage(context, newRect, self.CGImage)
let newImage = UIImage(CGImage: CGBitmapContextCreateImage(context)!)
UIGraphicsEndImageContext()
return newImage
}
public func RBSquareImageTo(size: CGSize) -> UIImage? {
return self.RBSquareImage()?.RBResizeImage(size)
}
public func RBSquareImage() -> UIImage? {
let originalWidth = self.size.width
let originalHeight = self.size.height
var edge: CGFloat
if originalWidth > originalHeight {
edge = originalHeight
} else {
edge = originalWidth
}
let posX = (originalWidth - edge) / 2.0
let posY = (originalHeight - edge) / 2.0
let cropSquare = CGRect(x: posX, y: posY, width: edge, height: edge)
let imageRef = CGImageCreateWithImageInRect(self.CGImage, cropSquare)
return UIImage(CGImage: imageRef!, scale: UIScreen.mainScreen().scale, orientation: self.imageOrientation)
}
public func RBResizeImage(targetSize: CGSize) -> UIImage {
let size = self.size
let widthRatio = targetSize.width / self.size.width
let heightRatio = targetSize.height / self.size.height
// Figure out what our orientation is, and use that to form the rectangle
var newSize: CGSize
if(widthRatio > heightRatio) {
newSize = CGSizeMake(size.width * heightRatio, size.height * heightRatio)
} else {
newSize = CGSizeMake(size.width * widthRatio, size.height * widthRatio)
}
// This is the rect that we've calculated out and this is what is actually used below
let rect = CGRectMake(0, 0, newSize.width, newSize.height)
// Actually do the resizing to the rect using the ImageContext stuff
UIGraphicsBeginImageContextWithOptions(newSize, false, UIScreen.mainScreen().scale)
self.drawInRect(rect)
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return newImage
}
}
| mit | 70c92dcc53afb33d1d7d2717830729f9 | 42.957295 | 158 | 0.633177 | 5.20742 | false | false | false | false |
LaurentiuUngur/LUAutocompleteView | Sources/LUAutocompleteView.swift | 1 | 9588 | //
// LUAutocompleteView.swift
// LUAutocompleteView
//
// Created by Laurentiu Ungur on 24/04/2017.
// Copyright © 2017 Laurentiu Ungur. All rights reserved.
//
/// Highly configurable autocomplete view that is attachable to any `UITextField`.
open class LUAutocompleteView: UIView {
// MARK: - Public Properties
/// The object that acts as the data source of the autocomplete view.
public weak var dataSource: LUAutocompleteViewDataSource?
/// The object that acts as the delegate of the autocomplete view.
public weak var delegate: LUAutocompleteViewDelegate?
/** The time interval responsible for regulating the rate of calling data source function.
If typing stops for a time interval greater than `throttleTime`, then the data source function will be called.
Default value is `0.4`.
*/
public var throttleTime: TimeInterval = 0.4
/// The maximum height of autocomplete view. Default value is `200.0`.
public var maximumHeight: CGFloat = 200.0
/// A boolean value that determines whether the view should hide after a suggestion is selected. Default value is `true`.
public var shouldHideAfterSelecting = true
/** The attributes for the text suggestions.
- Note: This property will be ignored if `autocompleteCell` is not `nil`.
*/
public var textAttributes: [NSAttributedString.Key: Any]?
/// The text field to which the autocomplete view will be attached.
public weak var textField: UITextField? {
didSet {
guard let textField = textField else {
return
}
textField.addTarget(self, action: #selector(textFieldEditingChanged), for: .editingChanged)
textField.addTarget(self, action: #selector(textFieldEditingEnded), for: .editingDidEnd)
setupConstraints()
}
}
/** A `LUAutocompleteTableViewCell` subclass that will be used to show a text suggestion.
Set your own in order to customise the appearance.
Default value is `nil`, which means the default one will be used.
- Note: `textAttributes` will be ignored if this property is not `nil`
*/
public var autocompleteCell: LUAutocompleteTableViewCell.Type? {
didSet {
guard let autocompleteCell = autocompleteCell else {
return
}
tableView.register(autocompleteCell, forCellReuseIdentifier: LUAutocompleteView.cellIdentifier)
tableView.reloadData()
}
}
/// The height of each row (that is, table cell) in the autocomplete table view. Default value is `40.0`.
public var rowHeight: CGFloat = 40.0 {
didSet {
tableView.rowHeight = rowHeight
}
}
// MARK: - Private Properties
private let tableView = UITableView()
private var heightConstraint: NSLayoutConstraint?
private static let cellIdentifier = "AutocompleteCellIdentifier"
private var elements = [String]() {
didSet {
tableView.reloadData()
height = tableView.contentSize.height
}
}
private var height: CGFloat = 0 {
didSet {
guard height != oldValue else {
return
}
guard let superview = superview else {
heightConstraint?.constant = (height > maximumHeight) ? maximumHeight : height
return
}
superview.layoutIfNeeded()
UIView.animate(withDuration: 0.2) {
self.heightConstraint?.constant = (self.height > self.maximumHeight) ? self.maximumHeight : self.height
superview.layoutIfNeeded()
}
}
}
// MARK: - Init
/** Initializes and returns a table view object having the given frame and style.
- Parameters:
- frame: A rectangle specifying the initial location and size of the table view in its superview’s coordinates. The frame of the table view changes as table cells are added and deleted.
- style: A constant that specifies the style of the table view. See `UITableViewStyle` for descriptions of valid constants.
- Returns: Returns an initialized `UITableView` object, or `nil` if the object could not be successfully initialized.
*/
public override init(frame: CGRect) {
super.init(frame: frame)
commonInit()
}
/** Returns an object initialized from data in a given unarchiver.
- Parameter coder: An unarchiver object.
- Retunrs: `self`, initialized using the data in *decoder*.
*/
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
commonInit()
}
// MARK: - Private Functions
private func commonInit() {
addSubview(tableView)
tableView.register(UITableViewCell.self, forCellReuseIdentifier: LUAutocompleteView.cellIdentifier)
tableView.dataSource = self
tableView.delegate = self
tableView.rowHeight = rowHeight
tableView.tableFooterView = UIView()
tableView.separatorInset = .zero
tableView.contentInset = .zero
tableView.bounces = false
}
private func setupConstraints() {
guard let textField = textField else {
assertionFailure("Sanity check")
return
}
tableView.removeConstraints(tableView.constraints)
removeConstraints(self.constraints)
tableView.translatesAutoresizingMaskIntoConstraints = false
translatesAutoresizingMaskIntoConstraints = false
heightConstraint = heightAnchor.constraint(equalToConstant: 0)
let constraints = [
tableView.leadingAnchor.constraint(equalTo: leadingAnchor),
tableView.trailingAnchor.constraint(equalTo: trailingAnchor),
tableView.topAnchor.constraint(equalTo: topAnchor),
tableView.bottomAnchor.constraint(equalTo: bottomAnchor),
leadingAnchor.constraint(equalTo: textField.leadingAnchor),
trailingAnchor.constraint(equalTo: textField.trailingAnchor),
topAnchor.constraint(equalTo: textField.bottomAnchor),
heightConstraint!
]
NSLayoutConstraint.activate(constraints)
}
@objc private func textFieldEditingChanged() {
NSObject.cancelPreviousPerformRequests(withTarget: self, selector: #selector(getElements), object: nil)
perform(#selector(getElements), with: nil, afterDelay: throttleTime)
}
@objc private func getElements() {
guard let dataSource = dataSource else {
return
}
guard let text = textField?.text, !text.isEmpty else {
elements.removeAll()
return
}
dataSource.autocompleteView(self, elementsFor: text) { [weak self] elements in
self?.elements = elements
}
}
@objc private func textFieldEditingEnded() {
height = 0
}
}
// MARK: - UITableViewDataSource
extension LUAutocompleteView: UITableViewDataSource {
/** Tells the data source to return the number of rows in a given section of a table view.
- Parameters:
- tableView: The table-view object requesting this information.
- section: An index number identifying a section of `tableView`.
- Returns: The number of rows in `section`.
*/
public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return !(textField?.text?.isEmpty ?? true) ? elements.count : 0
}
/** Asks the data source for a cell to insert in a particular location of the table view.
- Parameters:
- tableView: A table-view object requesting the cell.
- indexPath: An index path locating a row in `tableView`.
- Returns: An object inheriting from `UITableViewCell` that the table view can use for the specified row. An assertion is raised if you return `nil`.
*/
public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let cell = tableView.dequeueReusableCell(withIdentifier: LUAutocompleteView.cellIdentifier) else {
assertionFailure("Cell shouldn't be nil")
return UITableViewCell()
}
guard indexPath.row < elements.count else {
assertionFailure("Sanity check")
return cell
}
let text = elements[indexPath.row]
guard autocompleteCell != nil, let customCell = cell as? LUAutocompleteTableViewCell else {
cell.textLabel?.attributedText = NSAttributedString(string: text, attributes: textAttributes)
cell.selectionStyle = .none
return cell
}
customCell.set(text: text)
return customCell
}
}
// MARK: - UITableViewDelegate
extension LUAutocompleteView: UITableViewDelegate {
/** Tells the delegate that the specified row is now selected.
- Parameters:
- tableView: A table-view object informing the delegate about the new row selection.
- indexPath: An index path locating the new selected row in `tableView`.
*/
public func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
guard indexPath.row < elements.count else {
assertionFailure("Sanity check")
return
}
if shouldHideAfterSelecting {
height = 0
}
textField?.text = elements[indexPath.row]
delegate?.autocompleteView(self, didSelect: elements[indexPath.row])
}
}
| mit | 4d63a9edd1c81b7aefd629bb1d350f44 | 35.299242 | 195 | 0.660545 | 5.271177 | false | false | false | false |
ios-archy/Sinaweibo_swift | SinaWeibo_swift/SinaWeibo_swift/Classess/Home/Photobrowser/PhotoBrowserController.swift | 1 | 6205 | //
// PhotoBrowserController.swift
// SinaWeibo_swift
//
// Created by archy on 16/11/21.
// Copyright © 2016年 archy. All rights reserved.
//
import UIKit
import SnapKit
import SVProgressHUD
private let PhotoBrowserCell = "PhotoBrowserCell"
class PhotoBrowserController: UIViewController {
//MARK: -- 定义属性
var indexPath : NSIndexPath
var picUrls : [NSURL]
//MARK: -- 懒加载属性
private lazy var collectionView : UICollectionView = UICollectionView(frame: CGRectZero ,collectionViewLayout:PhotoBrowserCollectionViewLayout() )
private lazy var closeBtn :UIButton = UIButton (bgColor: UIColor.darkGrayColor(), fontsize: 14, titel: "关闭")
private lazy var savaBtn : UIButton = UIButton (bgColor: UIColor.darkGrayColor(), fontsize: 14, titel: "保存")
//MARK: --自定义构造函数
init(indexPath : NSIndexPath , picUrl : [NSURL])
{
self.indexPath = indexPath
self.picUrls = picUrl
super.init(nibName: nil, bundle: nil)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
//设置UI界面
setupUI()
//设置滚动到对应的图片
collectionView.scrollToItemAtIndexPath(indexPath, atScrollPosition: .Left, animated: false)
}
}
extension PhotoBrowserController {
private func setupUI() {
//1.添加子控件
view.addSubview(collectionView)
view.addSubview(closeBtn)
view.addSubview(savaBtn)
//2.设置frame
collectionView.frame = view.bounds
closeBtn.frame = CGRect(x: 20, y: (view.bounds.height-20-32), width: 90, height: 32)
savaBtn.frame = CGRect(x: view.bounds.width-110, y: (view.bounds.height-20-32), width: 90, height: 32)
// closeBtn.snp_makeConstraints { (make) -> Void in
// make.left.equalTo(20)
// make.bottom.equalTo(-20)
// make.size.equalTo(CGSize(width: 90, height: 32))
// }
// savaBtn.snp_makeConstraints { (make) -> Void in
// make.right.equalTo(-20)
// make.bottom.equalTo(closeBtn.snp_bottom)
// make.size.equalTo(closeBtn.snp_size)
// }
//3.设置collectionView的属性
collectionView.registerClass(PhotoBrowserViewCell.self, forCellWithReuseIdentifier: PhotoBrowserCell)
collectionView.dataSource = self
collectionView.delegate = self
//4.监听两个按钮的点击
closeBtn.addTarget(self, action: "closeBtnClick", forControlEvents: .TouchUpInside)
savaBtn.addTarget(self, action: "saveBtnClick", forControlEvents: .TouchUpInside)
}
}
//MARK: --事件监听函数
extension PhotoBrowserController {
@objc private func closeBtnClick (){
dismissViewControllerAnimated(true, completion: nil)
}
@objc private func saveBtnClick() {
// print("saveBtnClick")
//1.获取当前正在显示的image
let cell = collectionView.visibleCells().first as! PhotoBrowserViewCell
guard let image = cell.imageView.image else {
return
}
//2.将iamge对象保存相册
UIImageWriteToSavedPhotosAlbum(image, self, "image:didFinishedSavingWithError:contextInfo:", nil)
}
@objc private func image(image : UIImage ,didFinishedSavingWithError error : NSError?, contextInfo : AnyObject) {
var showInfo = ""
if error != nil {
showInfo = "保存失败"
}
else {
showInfo = "保存成功"
}
SVProgressHUD.showInfoWithStatus(showInfo)
}
}
//MARK: --实现collectionView的数据源方法
extension PhotoBrowserController : UICollectionViewDataSource ,UICollectionViewDelegate {
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return picUrls.count
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
//1.创建cell
let cell = collectionView.dequeueReusableCellWithReuseIdentifier(PhotoBrowserCell, forIndexPath: indexPath) as! PhotoBrowserViewCell
//2.给cell设置数据
// cell.backgroundColor = indexPath.item % 2 == 0 ? UIColor.redColor() : UIColor.orangeColor()
cell.picURL = picUrls[indexPath.item]
cell.delegate = self
return cell
}
}
extension PhotoBrowserController : PhotoBrowserViewCellDelegate {
func imageViewClick() {
closeBtnClick()
}
}
//MARK: --遵守AnimatorDisMissDelegate
extension PhotoBrowserController : AnimatorDismissDelegate
{
func indexPathForDismissView() -> NSIndexPath {
//1.获取当前正在显示的indexPath
let cell = collectionView.visibleCells().first!
return collectionView.indexPathForCell(cell)!
}
func imageViewForDismissView() -> UIImageView {
//1.闯将UIImageView
let imageView = UIImageView()
//2.设置imageView的frame
let cell = collectionView.visibleCells().first as! PhotoBrowserViewCell
imageView.frame = cell.imageView.frame
imageView.image = cell.imageView.image
//3.设置imageview的属性
imageView.contentMode = .ScaleAspectFill
imageView.clipsToBounds = true
return imageView
}
}
class PhotoBrowserCollectionViewLayout : UICollectionViewFlowLayout {
override func prepareLayout() {
super.prepareLayout()
//1.设置itemSize
itemSize = collectionView!.frame.size
minimumInteritemSpacing = 0
minimumLineSpacing = 0
scrollDirection = .Horizontal
//2.设置collectionView的属性
collectionView?.pagingEnabled = true
collectionView?.showsHorizontalScrollIndicator = false
collectionView?.showsVerticalScrollIndicator = false
}
} | mit | ab0be842fd2dd5214e28ff3c9735e49b | 28.735 | 150 | 0.644971 | 5.069054 | false | false | false | false |
AlphaJian/LarsonApp | LarsonApp/LarsonApp/Class/JobDetail/WorkOrderViews/WorkOrderTableView.swift | 1 | 8713 | //
// WorkOrderTableView.swift
// LarsonApp
//
// Created by Perry Z Chen on 11/10/16.
// Copyright © 2016 Jian Zhang. All rights reserved.
//
import UIKit
enum EnumTableViewCell: Int{
case CallNumberCell = 0
case StationCell
case SiteAddressCell
case ZipCell
case phoneNumCell
case techNumCell
case ServiceDescCell
case WorkDescCell
case AddPartsCell
case OptionCell
case SectionCount
}
class WorkOrderTableView: UITableView {
var model: AppointmentModel?
var partItems: [Int] = [Int]()
weak var vc: JobDetailViewController?
var removeItemAlertHandler: ReturnBlock?
/*
// Only override draw() if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
override func draw(_ rect: CGRect) {
// Drawing code
}
*/
override init(frame: CGRect, style: UITableViewStyle) {
super.init(frame: frame, style: style)
self.delegate = self
self.dataSource = self
self.backgroundColor = UIColor(red: 236.0/255.0, green: 240/255.0, blue: 241/255.0, alpha: 1.0)
self.register(UINib(nibName: "StaticWorkOrderCell", bundle: nil), forCellReuseIdentifier: "StaticWorkOrderCell")
self.register(UINib(nibName: "InputWorkOrderCell", bundle: nil), forCellReuseIdentifier: "InputWorkOrderCell")
self.register(UINib(nibName: "AddPartsCell", bundle: nil), forCellReuseIdentifier: "AddPartsCell")
self.register(UINib(nibName: "PartItemCell", bundle: nil), forCellReuseIdentifier: "PartItemCell")
self.register(UINib(nibName: "WorkOrderOptionCell", bundle: nil), forCellReuseIdentifier: "WorkOrderOptionCell")
self.rowHeight = UITableViewAutomaticDimension
self.estimatedRowHeight = 60.0
self.separatorStyle = .none
// NotificationCenter.default.addObserver(self, selector: #selector(keyboardChangeFrame(notification:)), name: .UIKeyboardWilflChangeFrame, object: nil)
}
func keyboardChangeFrame(notification: Notification) {
let dicUserInfo = notification.userInfo
print(dicUserInfo?[UIKeyboardAnimationDurationUserInfoKey] ?? 48)
}
required init?(coder aDecoder: NSCoder) {
fatalError("")
}
}
extension WorkOrderTableView : UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if section == EnumTableViewCell.AddPartsCell.rawValue {
return 1 + partItems.count
} else {
return 1
}
}
func numberOfSections(in tableView: UITableView) -> Int {
return EnumTableViewCell.SectionCount.rawValue
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if indexPath.section == EnumTableViewCell.CallNumberCell.rawValue {
let cell = tableView.dequeueReusableCell(withIdentifier: "StaticWorkOrderCell", for: indexPath) as! StaticWorkOrderCell
cell.initUI(parameter: ("Call Number", (self.model?.telephoneNumber)!))
return cell
} else if indexPath.section == EnumTableViewCell.StationCell.rawValue {
let cell = tableView.dequeueReusableCell(withIdentifier: "StaticWorkOrderCell", for: indexPath) as! StaticWorkOrderCell
cell.initUI(parameter: ("Station Number", (self.model?.stationNumber)!))
return cell
} else if indexPath.section == EnumTableViewCell.SiteAddressCell.rawValue {
let cell = tableView.dequeueReusableCell(withIdentifier: "StaticWorkOrderCell", for: indexPath) as! StaticWorkOrderCell
cell.initUI(parameter: ("Site Address", (self.model?.customerAddress)!))
return cell
} else if indexPath.section == EnumTableViewCell.ZipCell.rawValue {
let cell = tableView.dequeueReusableCell(withIdentifier: "StaticWorkOrderCell", for: indexPath) as! StaticWorkOrderCell
cell.initUI(parameter: ("Zip Code", (self.model?.zipCode)!))
return cell
} else if indexPath.section == EnumTableViewCell.phoneNumCell.rawValue {
let cell = tableView.dequeueReusableCell(withIdentifier: "StaticWorkOrderCell", for: indexPath) as! StaticWorkOrderCell
cell.initUI(parameter: ("Phone Number", (self.model?.telephoneNumber)!))
return cell
} else if indexPath.section == EnumTableViewCell.ServiceDescCell.rawValue {
let cell = tableView.dequeueReusableCell(withIdentifier: "InputWorkOrderCell", for: indexPath) as! InputWorkOrderCell
cell.initUI(parameter: ("Service Description", ""))
cell.textViewUpdateBlock = { (str: AnyObject) in
self.updateCellWithTVEdit()
}
return cell
} else if indexPath.section == EnumTableViewCell.WorkDescCell.rawValue {
let cell = tableView.dequeueReusableCell(withIdentifier: "InputWorkOrderCell", for: indexPath) as! InputWorkOrderCell
cell.initUI(parameter: ("Description of Work", ""))
cell.textViewUpdateBlock = { (str: AnyObject) in
self.updateCellWithTVEdit()
}
return cell
} else if indexPath.section == EnumTableViewCell.AddPartsCell.rawValue {
if indexPath.row == 0 {
let cell = tableView.dequeueReusableCell(withIdentifier: "AddPartsCell", for: indexPath) as! AddPartsCell
cell.initUI(parameter: ("Add Parts Used"))
return cell
} else {
let cell = tableView.dequeueReusableCell(withIdentifier: "PartItemCell", for: indexPath) as! PartItemCell
unowned let wself = self
cell.removeItemBlock = { (str: AnyObject) in
wself.showRemoveItemAlert(title: "Are you sure delete?", indexToDelete: indexPath as NSIndexPath)
}
return cell
}
} else if indexPath.section == EnumTableViewCell.OptionCell.rawValue {
let cell = tableView.dequeueReusableCell(withIdentifier: "WorkOrderOptionCell", for: indexPath) as! WorkOrderOptionCell
// cell.initUI(parameter: ("Add Parts Used"))
return cell
}
else {
let cell = tableView.dequeueReusableCell(withIdentifier: "StaticWorkOrderCell", for: indexPath) as! StaticWorkOrderCell
cell.initUI(parameter: ("Tech Number", (self.model?.techNumber)!))
return cell
}
}
// update cell after edit textview
func updateCellWithTVEdit() {
let currentOffset = self.contentOffset
UIView.setAnimationsEnabled(false)
self.beginUpdates()
self.endUpdates()
UIView.setAnimationsEnabled(true)
self.setContentOffset(currentOffset, animated: false)
}
// 删除某个row
func showRemoveItemAlert(title: String, indexToDelete: NSIndexPath) {
let alertVC = UIAlertController(title: title, message: "", preferredStyle: .alert)
let confirmAction = UIAlertAction(title: "ok", style: .default, handler: { (alert) in
// 使用beginUpdates会crush,原因是indexpath没更新,
// http://stackoverflow.com/questions/4497925/how-to-delete-a-row-from-uitableview
// 直接用reloadData
let indexPath = NSIndexPath(row: indexToDelete.row, section: indexToDelete.section)
self.partItems.remove(at: indexPath.row-1)
self.deleteRows(at: [indexPath as IndexPath], with: .automatic)
self.reloadData()
})
let cancelAction = UIAlertAction(title: "cancel", style: .cancel, handler: { (alert) in
print(alert)
})
alertVC.addAction(confirmAction)
alertVC.addAction(cancelAction)
if vc != nil {
vc?.present(alertVC, animated: true, completion: nil)
}
}
}
extension WorkOrderTableView : UITableViewDelegate {
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if indexPath.section == EnumTableViewCell.AddPartsCell.rawValue && indexPath.row == 0 {
self.partItems.append(1)
let indexPathItem = NSIndexPath(row: 1, section: indexPath.section)
tableView.beginUpdates()
tableView.insertRows(at: [indexPathItem as IndexPath], with: .automatic)
tableView.endUpdates()
// scroll to the item that just added
// tableView.scrollToRow(at: indexPathItem as IndexPath, at: .bottom, animated: true)
}
}
}
| apache-2.0 | 17b570c4bf35a7ad128b07689ebd543a | 44.424084 | 159 | 0.657446 | 4.868687 | false | false | false | false |
thomasvl/swift-protobuf | Sources/SwiftProtobufCore/DoubleParser.swift | 3 | 2114 | // Sources/SwiftProtobuf/DoubleParser.swift - Generally useful mathematical functions
//
// Copyright (c) 2014 - 2019 Apple Inc. and the project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See LICENSE.txt for license information:
// https://github.com/apple/swift-protobuf/blob/main/LICENSE.txt
//
// -----------------------------------------------------------------------------
///
/// Numeric parsing helper for float and double strings
///
// -----------------------------------------------------------------------------
import Foundation
/// Support parsing float/double values from UTF-8
internal class DoubleParser {
// Temporary buffer so we can null-terminate the UTF-8 string
// before calling the C standard libray to parse it.
// In theory, JSON writers should be able to represent any IEEE Double
// in at most 25 bytes, but many writers will emit more digits than
// necessary, so we size this generously.
private var work =
UnsafeMutableBufferPointer<Int8>.allocate(capacity: 128)
deinit {
work.deallocate()
}
func utf8ToDouble(bytes: UnsafeRawBufferPointer,
start: UnsafeRawBufferPointer.Index,
end: UnsafeRawBufferPointer.Index) -> Double? {
return utf8ToDouble(bytes: UnsafeRawBufferPointer(rebasing: bytes[start..<end]))
}
func utf8ToDouble(bytes: UnsafeRawBufferPointer) -> Double? {
// Reject unreasonably long or short UTF8 number
if work.count <= bytes.count || bytes.count < 1 {
return nil
}
UnsafeMutableRawBufferPointer(work).copyMemory(from: bytes)
work[bytes.count] = 0
// Use C library strtod() to parse it
var e: UnsafeMutablePointer<Int8>? = work.baseAddress
let d = strtod(work.baseAddress!, &e)
// Fail if strtod() did not consume everything we expected
// or if strtod() thought the number was out of range.
if e != work.baseAddress! + bytes.count || !d.isFinite {
return nil
}
return d
}
}
| apache-2.0 | 169c6fdf0544463a9456b393ec4d9822 | 36.087719 | 88 | 0.613056 | 4.870968 | false | false | false | false |
CQH/iOS-Sounds-and-Ringtones | iOS Sounds and Ringtones/FilesTableViewController.swift | 1 | 3751 | //
// FilesTableViewController.swift
// iOS Sounds and Ringtones
//
// Created by Carleton Hall on 10/15/16.
// Copyright © 2016 Carleton Hall. All rights reserved.
//
import UIKit
import AVFoundation
class FilesTableViewController: UITableViewController {
// MARK: - Class Variables
///App Controller singleton
let appController = AppController.sharedInstance()
///The directory where sound files are located.
var directory: NSDictionary!
///The files in the directory
var files: [String] = []
// MARK: - View Controller Setup
override func viewDidLoad() {
super.viewDidLoad()
if #available(iOS 11.0, *) {
self.navigationItem.largeTitleDisplayMode = .always
}
files = directory["files"] as! [String]
}
override func viewWillAppear(_ animated: Bool) {
appController.userDefaults.synchronize()
if let bookmarks: [String] = appController.userDefaults.object(forKey: "bookmarkedSoundFiles") as? [String] {
appController.bookmarkedFiles = bookmarks
}
}
override func viewWillDisappear(_ animated: Bool) {
appController.userDefaults.set(appController.bookmarkedFiles, forKey: "bookmarkedSoundFiles")
appController.userDefaults.synchronize()
}
// MARK: - Table view data source
override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return directory["path"] as? String
}
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return files.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let dir: String = directory["path"] as! String
let fileName: String = files[indexPath.row]
let filePath: String = "\(dir)/\(fileName)"
let cell = tableView.dequeueReusableCell(withIdentifier: "sound", for: indexPath) as! SoundTableViewCell
cell.fileNameLabel.text = fileName
cell.filePathLabel.text = filePath
return cell
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
//Play the sound
let dir: String = directory["path"] as! String
let fileName: String = files[indexPath.row]
let fileURL: URL = URL(fileURLWithPath: "\(dir)/\(fileName)")
do {
appController.audioPlayer = try AVAudioPlayer(contentsOf: fileURL)
appController.audioPlayer.play()
} catch {
debugPrint("\(error)")
}
}
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
tableView.deleteRows(at: [indexPath], with: .fade)
} else if editingStyle == .insert {
}
}
override func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? {
let bookmarkAction: UITableViewRowAction = UITableViewRowAction(style: UITableViewRowActionStyle.normal, title: "Bookmark" , handler: { (action:UITableViewRowAction, indexPath:IndexPath) -> Void in
let dir: String = self.directory["path"] as! String
let fileName: String = self.files[indexPath.row]
let filePath: String = "\(dir)/\(fileName)"
self.appController.bookmarkedFiles.append(filePath)
tableView.setEditing(false, animated: true)
})
return [bookmarkAction]
}
}
| mit | b6c29a0d5886b23709c4a6713ae943a0 | 36.5 | 205 | 0.6568 | 5.165289 | false | false | false | false |
felixjendrusch/Pistachiargo | Pistachiargo/JSONValueTransformers.swift | 2 | 14488 | // Copyright (c) 2015 Felix Jendrusch. All rights reserved.
import Foundation
import Result
import ValueTransformer
import Monocle
import Pistachio
import Argo
public let ErrorDomain = "PistachiargoErrorDomain"
public let ErrorInvalidInput = 1
public struct JSONValueTransformers {
public static let nsNumber: ReversibleValueTransformer<NSNumber, JSONValue, NSError> = ReversibleValueTransformer(transformClosure: { value in
return Result.success(.JSONNumber(value))
}, reverseTransformClosure: { transformedValue in
switch transformedValue {
case let .JSONNumber(value):
return Result.success(value)
default:
let userInfo = [
NSLocalizedDescriptionKey: NSLocalizedString("Could not transform JSONValue to NSNumber", comment: ""),
NSLocalizedFailureReasonErrorKey: String(format: NSLocalizedString("Expected a .JSONNumber, got: %@.", comment: ""), transformedValue.description)
]
return Result.failure(NSError(domain: ErrorDomain, code: ErrorInvalidInput, userInfo: userInfo))
}
})
public static func number() -> ReversibleValueTransformer<Int8, JSONValue, NSError> {
return NSNumberValueTransformers.char() >>> nsNumber
}
public static func number() -> ReversibleValueTransformer<UInt8, JSONValue, NSError> {
return NSNumberValueTransformers.unsignedChar() >>> nsNumber
}
public static func number() -> ReversibleValueTransformer<Int16, JSONValue, NSError> {
return NSNumberValueTransformers.short() >>> nsNumber
}
public static func number() -> ReversibleValueTransformer<UInt16, JSONValue, NSError> {
return NSNumberValueTransformers.unsignedShort() >>> nsNumber
}
public static func number() -> ReversibleValueTransformer<Int32, JSONValue, NSError> {
return NSNumberValueTransformers.int() >>> nsNumber
}
public static func number() -> ReversibleValueTransformer<UInt32, JSONValue, NSError> {
return NSNumberValueTransformers.unsignedInt() >>> nsNumber
}
public static func number() -> ReversibleValueTransformer<Int, JSONValue, NSError> {
return NSNumberValueTransformers.long() >>> nsNumber
}
public static func number() -> ReversibleValueTransformer<UInt, JSONValue, NSError> {
return NSNumberValueTransformers.unsignedLong() >>> nsNumber
}
public static func number() -> ReversibleValueTransformer<Int64, JSONValue, NSError> {
return NSNumberValueTransformers.longLong() >>> nsNumber
}
public static func number() -> ReversibleValueTransformer<UInt64, JSONValue, NSError> {
return NSNumberValueTransformers.unsignedLongLong() >>> nsNumber
}
public static func number() -> ReversibleValueTransformer<Float, JSONValue, NSError> {
return NSNumberValueTransformers.float() >>> nsNumber
}
public static func number() -> ReversibleValueTransformer<Double, JSONValue, NSError> {
return NSNumberValueTransformers.double() >>> nsNumber
}
public static func number() -> ReversibleValueTransformer<Bool, JSONValue, NSError> {
return NSNumberValueTransformers.bool() >>> nsNumber
}
public static let bool: ReversibleValueTransformer<Bool, JSONValue, NSError> = ReversibleValueTransformer(transformClosure: { value in
return Result.success(.JSONNumber(value))
}, reverseTransformClosure: { transformedValue in
switch transformedValue {
case let .JSONNumber(value):
return Result.success(value.boolValue)
default:
let userInfo = [
NSLocalizedDescriptionKey: NSLocalizedString("Could not transform JSONValue to Bool", comment: ""),
NSLocalizedFailureReasonErrorKey: String(format: NSLocalizedString("Expected a .JSONNumber, got: %@.", comment: ""), transformedValue.description)
]
return Result.failure(NSError(domain: ErrorDomain, code: ErrorInvalidInput, userInfo: userInfo))
}
})
public static let string: ReversibleValueTransformer<String, JSONValue, NSError> = ReversibleValueTransformer(transformClosure: { value in
return Result.success(.JSONString(value))
}, reverseTransformClosure: { transformedValue in
switch transformedValue {
case let .JSONString(value):
return Result.success(value)
default:
let userInfo = [
NSLocalizedDescriptionKey: NSLocalizedString("Could not transform JSONValue to String", comment: ""),
NSLocalizedFailureReasonErrorKey: String(format: NSLocalizedString("Expected a .JSONString, got: %@.", comment: ""), transformedValue.description)
]
return Result.failure(NSError(domain: ErrorDomain, code: ErrorInvalidInput, userInfo: userInfo))
}
})
public static let dictionary: ReversibleValueTransformer<[String: JSONValue], JSONValue, NSError> = ReversibleValueTransformer(transformClosure: { value in
return Result.success(.JSONObject(value))
}, reverseTransformClosure: { transformedValue in
switch transformedValue {
case let .JSONObject(value):
return Result.success(value)
default:
let userInfo = [
NSLocalizedDescriptionKey: NSLocalizedString("Could not transform JSONValue to [String: JSONValue]", comment: ""),
NSLocalizedFailureReasonErrorKey: String(format: NSLocalizedString("Expected a .JSONObject, got: %@.", comment: ""), transformedValue.description)
]
return Result.failure(NSError(domain: ErrorDomain, code: ErrorInvalidInput, userInfo: userInfo))
}
})
public static let array: ReversibleValueTransformer<[JSONValue], JSONValue, NSError> = ReversibleValueTransformer(transformClosure: { value in
return Result.success(.JSONArray(value))
}, reverseTransformClosure: { transformedValue in
switch transformedValue {
case let .JSONArray(value):
return Result.success(value)
default:
let userInfo = [
NSLocalizedDescriptionKey: NSLocalizedString("Could not transform JSONValue to [JSONValue]", comment: ""),
NSLocalizedFailureReasonErrorKey: String(format: NSLocalizedString("Expected a .JSONArray, got: %@.", comment: ""), transformedValue.description)
]
return Result.failure(NSError(domain: ErrorDomain, code: ErrorInvalidInput, userInfo: userInfo))
}
})
}
public func JSONNumber<A>(lens: Lens<A, Int8>) -> Lens<Result<A, NSError>, Result<JSONValue, NSError>> {
return map(lens, JSONValueTransformers.number())
}
public func JSONNumber<A>(lens: Lens<A, Int8?>, defaultTransformedValue: JSONValue = .JSONNumber(0)) -> Lens<Result<A, NSError>, Result<JSONValue, NSError>> {
return map(lens, lift(JSONValueTransformers.number(), defaultTransformedValue: defaultTransformedValue))
}
public func JSONNumber<A>(lens: Lens<A, UInt8>) -> Lens<Result<A, NSError>, Result<JSONValue, NSError>> {
return map(lens, JSONValueTransformers.number())
}
public func JSONNumber<A>(lens: Lens<A, UInt8?>, defaultTransformedValue: JSONValue = .JSONNumber(0)) -> Lens<Result<A, NSError>, Result<JSONValue, NSError>> {
return map(lens, lift(JSONValueTransformers.number(), defaultTransformedValue: defaultTransformedValue))
}
public func JSONNumber<A>(lens: Lens<A, Int16>) -> Lens<Result<A, NSError>, Result<JSONValue, NSError>> {
return map(lens, JSONValueTransformers.number())
}
public func JSONNumber<A>(lens: Lens<A, Int16?>, defaultTransformedValue: JSONValue = .JSONNumber(0)) -> Lens<Result<A, NSError>, Result<JSONValue, NSError>> {
return map(lens, lift(JSONValueTransformers.number(), defaultTransformedValue: defaultTransformedValue))
}
public func JSONNumber<A>(lens: Lens<A, UInt16>) -> Lens<Result<A, NSError>, Result<JSONValue, NSError>> {
return map(lens, JSONValueTransformers.number())
}
public func JSONNumber<A>(lens: Lens<A, UInt16?>, defaultTransformedValue: JSONValue = .JSONNumber(0)) -> Lens<Result<A, NSError>, Result<JSONValue, NSError>> {
return map(lens, lift(JSONValueTransformers.number(), defaultTransformedValue: defaultTransformedValue))
}
public func JSONNumber<A>(lens: Lens<A, Int32>) -> Lens<Result<A, NSError>, Result<JSONValue, NSError>> {
return map(lens, JSONValueTransformers.number())
}
public func JSONNumber<A>(lens: Lens<A, Int32?>, defaultTransformedValue: JSONValue = .JSONNumber(0)) -> Lens<Result<A, NSError>, Result<JSONValue, NSError>> {
return map(lens, lift(JSONValueTransformers.number(), defaultTransformedValue: defaultTransformedValue))
}
public func JSONNumber<A>(lens: Lens<A, UInt32>) -> Lens<Result<A, NSError>, Result<JSONValue, NSError>> {
return map(lens, JSONValueTransformers.number())
}
public func JSONNumber<A>(lens: Lens<A, UInt32?>, defaultTransformedValue: JSONValue = .JSONNumber(0)) -> Lens<Result<A, NSError>, Result<JSONValue, NSError>> {
return map(lens, lift(JSONValueTransformers.number(), defaultTransformedValue: defaultTransformedValue))
}
public func JSONNumber<A>(lens: Lens<A, Int>) -> Lens<Result<A, NSError>, Result<JSONValue, NSError>> {
return map(lens, JSONValueTransformers.number())
}
public func JSONNumber<A>(lens: Lens<A, Int?>, defaultTransformedValue: JSONValue = .JSONNumber(0)) -> Lens<Result<A, NSError>, Result<JSONValue, NSError>> {
return map(lens, lift(JSONValueTransformers.number(), defaultTransformedValue: defaultTransformedValue))
}
public func JSONNumber<A>(lens: Lens<A, UInt>) -> Lens<Result<A, NSError>, Result<JSONValue, NSError>> {
return map(lens, JSONValueTransformers.number())
}
public func JSONNumber<A>(lens: Lens<A, UInt?>, defaultTransformedValue: JSONValue = .JSONNumber(0)) -> Lens<Result<A, NSError>, Result<JSONValue, NSError>> {
return map(lens, lift(JSONValueTransformers.number(), defaultTransformedValue: defaultTransformedValue))
}
public func JSONNumber<A>(lens: Lens<A, Int64>) -> Lens<Result<A, NSError>, Result<JSONValue, NSError>> {
return map(lens, JSONValueTransformers.number())
}
public func JSONNumber<A>(lens: Lens<A, Int64?>, defaultTransformedValue: JSONValue = .JSONNumber(0)) -> Lens<Result<A, NSError>, Result<JSONValue, NSError>> {
return map(lens, lift(JSONValueTransformers.number(), defaultTransformedValue: defaultTransformedValue))
}
public func JSONNumber<A>(lens: Lens<A, UInt64>) -> Lens<Result<A, NSError>, Result<JSONValue, NSError>> {
return map(lens, JSONValueTransformers.number())
}
public func JSONNumber<A>(lens: Lens<A, UInt64?>, defaultTransformedValue: JSONValue = .JSONNumber(0)) -> Lens<Result<A, NSError>, Result<JSONValue, NSError>> {
return map(lens, lift(JSONValueTransformers.number(), defaultTransformedValue: defaultTransformedValue))
}
public func JSONNumber<A>(lens: Lens<A, Float>) -> Lens<Result<A, NSError>, Result<JSONValue, NSError>> {
return map(lens, JSONValueTransformers.number())
}
public func JSONNumber<A>(lens: Lens<A, Float?>, defaultTransformedValue: JSONValue = .JSONNumber(0.0)) -> Lens<Result<A, NSError>, Result<JSONValue, NSError>> {
return map(lens, lift(JSONValueTransformers.number(), defaultTransformedValue: defaultTransformedValue))
}
public func JSONNumber<A>(lens: Lens<A, Double>) -> Lens<Result<A, NSError>, Result<JSONValue, NSError>> {
return map(lens, JSONValueTransformers.number())
}
public func JSONNumber<A>(lens: Lens<A, Double?>, defaultTransformedValue: JSONValue = .JSONNumber(0.0)) -> Lens<Result<A, NSError>, Result<JSONValue, NSError>> {
return map(lens, lift(JSONValueTransformers.number(), defaultTransformedValue: defaultTransformedValue))
}
public func JSONNumber<A>(lens: Lens<A, Bool>) -> Lens<Result<A, NSError>, Result<JSONValue, NSError>> {
return map(lens, JSONValueTransformers.number())
}
public func JSONNumber<A>(lens: Lens<A, Bool?>, defaultTransformedValue: JSONValue = .JSONNumber(0)) -> Lens<Result<A, NSError>, Result<JSONValue, NSError>> {
return map(lens, lift(JSONValueTransformers.number(), defaultTransformedValue: defaultTransformedValue))
}
public func JSONBool<A>(lens: Lens<A, Bool>) -> Lens<Result<A, NSError>, Result<JSONValue, NSError>> {
return map(lens, JSONValueTransformers.bool)
}
public func JSONBool<A>(lens: Lens<A, Bool?>, defaultTransformedValue: JSONValue = .JSONNumber(false)) -> Lens<Result<A, NSError>, Result<JSONValue, NSError>> {
return map(lens, lift(JSONValueTransformers.bool, defaultTransformedValue: defaultTransformedValue))
}
public func JSONString<A>(lens: Lens<A, String>) -> Lens<Result<A, NSError>, Result<JSONValue, NSError>> {
return map(lens, JSONValueTransformers.string)
}
public func JSONString<A>(lens: Lens<A, String?>, defaultTransformedValue: JSONValue = .JSONString("")) -> Lens<Result<A, NSError>, Result<JSONValue, NSError>> {
return map(lens, lift(JSONValueTransformers.string, defaultTransformedValue: defaultTransformedValue))
}
public func JSONObject<A, T: AdapterType where T.TransformedValueType == JSONValue, T.ErrorType == NSError>(lens: Lens<A, T.ValueType>) -> (adapter: T) -> Lens<Result<A, NSError>, Result<JSONValue, NSError>> {
return { adapter in
return map(lens, adapter)
}
}
public func JSONObject<A, T: AdapterType where T.TransformedValueType == JSONValue, T.ErrorType == NSError>(lens: Lens<A, T.ValueType?>, defaultTransformedValue: JSONValue = .JSONNull) -> (adapter: T) -> Lens<Result<A, NSError>, Result<JSONValue, NSError>> {
return { adapter in
return map(lens, lift(adapter, defaultTransformedValue: defaultTransformedValue))
}
}
public func JSONArray<A, T: AdapterType where T.TransformedValueType == JSONValue, T.ErrorType == NSError>(lens: Lens<A, [T.ValueType]>) -> (adapter: T) -> Lens<Result<A, NSError>, Result<JSONValue, NSError>> {
return { adapter in
return map(lens, lift(adapter) >>> JSONValueTransformers.array)
}
}
public func JSONArray<A, T: AdapterType where T.TransformedValueType == JSONValue, T.ErrorType == NSError>(lens: Lens<A, [T.ValueType]?>, defaultTransformedValue: JSONValue = .JSONNull) -> (adapter: T) -> Lens<Result<A, NSError>, Result<JSONValue, NSError>> {
return { adapter in
return map(lens, lift(lift(adapter) >>> JSONValueTransformers.array, defaultTransformedValue: defaultTransformedValue))
}
}
| mit | 56be4ef7b5a14e9ac94ff3782c64c5ff | 48.958621 | 259 | 0.717559 | 4.506376 | false | false | false | false |
WOWRead/iOS | App/AddCameraViewController.swift | 1 | 2460 | //
// AddCameraViewController.swift
// App
//
// Created by Remi Robert on 24/03/16.
// Copyright © 2016 Remi Robert. All rights reserved.
//
import UIKit
import Parse
import SnapKit
import RxSwift
import AVFoundation
import CameraEngine
class AddCameraViewController: UIViewController, UIViewControllerCoordinable {
private let disposeBag = DisposeBag()
private var layerPreview: AVCaptureVideoPreviewLayer!
lazy var borderTop: UIView! = self.initBorder()
lazy var borderBottom: UIView! = self.initBorder()
private var constraintTopHeigh: Constraint!
private var constraintBottomHeight: Constraint!
private func initBorder() -> UIView {
let view = UIView()
view.backgroundColor = UIColor.blackColor()
return view
}
override func viewDidAppear(animated: Bool) {
self.constraintTopHeigh.updateOffset(0)
self.constraintBottomHeight.updateOffset(0)
UIView.animateWithDuration(0.75) {
self.view.layoutIfNeeded()
}
}
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = UIColor.blackColor()
CameraManager.observableCode().subscribeNext { code in
if let code = code {
PFCloud.callFunctionInBackground("findISBN", withParameters: ["code": code], block: { (respnose: AnyObject?, error: NSError?) in
})
}
}.addDisposableTo(self.disposeBag)
self.view.addSubview(self.borderTop)
self.borderTop.snp_makeConstraints { (make) in
make.width.equalTo(self.view)
self.constraintTopHeigh = make.height.equalTo(CGRectGetHeight(UIScreen.mainScreen().bounds) / 2).constraint
make.top.equalTo(self.view)
}
self.view.addSubview(self.borderBottom)
self.borderBottom.snp_makeConstraints { (make) in
make.width.equalTo(self.view)
self.constraintBottomHeight = make.height.equalTo(CGRectGetHeight(UIScreen.mainScreen().bounds) / 2).constraint
make.bottom.equalTo(self.view)
}
}
func start() {
self.layerPreview = CameraManager.sharedInstance.previewLayer
self.layerPreview.frame = self.view.bounds
self.view.layer.insertSublayer(self.layerPreview, atIndex: 0)
self.view.layer.masksToBounds = true
}
}
| mit | de4592ffc0f1b8cd61aebd478dd2ed5a | 32.22973 | 144 | 0.649044 | 4.784047 | false | false | false | false |
walmartlabs-asdaios/SwiftPromises | SwiftPromisesDemo/TimeoutNetworkCallDemoViewController.swift | 1 | 2423 | //
// TimeoutNetworkCallDemoViewController.swift
// SwiftPromises
//
// Created by Douglas Sjoquist on 3/1/15.
// Copyright (c) 2015 Ivy Gulch LLC. All rights reserved.
//
import UIKit
import SwiftPromises
class TimeoutNetworkCallDemoViewController: BaseDemoViewController {
@IBOutlet var timeoutStepper:UIStepper?
@IBOutlet var timeoutLabel:UILabel?
@IBOutlet var urlTextField:UITextField?
@IBOutlet var urlStatusImageView:UIImageView?
@IBOutlet var finalStatusImageView:UIImageView?
var timeoutTimer:NSTimer?
override func viewWillAppear(animated: Bool) {
urlTextField!.text = "http://cnn.com"
super.viewWillAppear(animated)
}
override func readyToStart() -> Bool {
return (urlTextField!.value != nil)
}
override func updateUI() {
super.updateUI()
timeoutLabel!.text = "Timeout: \(timeoutStepper!.value)"
}
func startTimer(promise:Promise<NSData>) {
timeoutTimer = NSTimer.scheduledTimerWithTimeInterval(timeoutStepper!.value, target:self, selector:"handleTimeoutTimer:", userInfo:promise, repeats:false)
}
func stopTimer() {
timeoutTimer?.invalidate()
timeoutTimer = nil
}
func handleTimeoutTimer(timer:NSTimer) {
let promise = timer.userInfo as! Promise<NSData>
promise.reject(NSError(domain:"Timeout before completion", code:-1, userInfo:nil))
}
override func start() {
clearStatus()
clearLog()
startActivityIndicator()
if let text = urlTextField?.text, url = NSURL(string:text) {
let urlPromise = loadURLPromise(url)
startTimer(urlPromise)
urlPromise.then(
{ [weak self] value in
self?.log("final success")
self?.finalStatusImageView!.setStatus(true)
self?.stopActivityIndicator()
self?.stopTimer()
return .Value(value)
}, reject: { [weak self] error in
self?.log("final error: \(error)")
self?.finalStatusImageView!.setStatus(false)
self?.stopActivityIndicator()
self?.stopTimer()
return .Error(error)
}
)
}
}
@IBAction func timeoutStepperAction(stepper:UIStepper) {
updateUI()
}
}
| mit | e6935e028b521a1c566fdbe6225a887b | 28.192771 | 162 | 0.608337 | 4.995876 | false | false | false | false |
OscarSwanros/swift | test/IDE/print_type_interface.swift | 18 | 3283 |
public struct A {
public func fa() {}
}
extension A {
public func fea1() {}
}
extension A {
public func fea2() {}
}
class C1 {
func f1() {
var abcd : A
abcd.fa()
var intarr : [Int]
intarr.append(1)
}
}
// RUN: %target-swift-ide-test -print-type-interface -pos=15:6 -source-filename %s | %FileCheck %s -check-prefix=TYPE1
// RUN: %target-swift-ide-test -print-type-interface -usr=_TtV20print_type_interface1A -module-name print_type_interface -source-filename %s | %FileCheck %s -check-prefix=TYPE1
// TYPE1: public struct A {
// TYPE1: public func fa()
// TYPE1: public func fea1()
// TYPE1: public func fea2()
// TYPE1: }
public protocol P1 { }
public class T1 : P1 { }
public class D<T> { public func foo() {}}
class C2 {
func f() {
let D1 = D<T1>()
let D2 = D<Int>()
D1.foo()
D2.foo()
}
}
// RUN: %target-swift-ide-test -print-type-interface -pos=37:6 -source-filename %s | %FileCheck %s -check-prefix=TYPE2
// RUN: %target-swift-ide-test -print-type-interface -usr=_TtGC20print_type_interface1DCS_2T1_ -module-name print_type_interface -source-filename %s | %FileCheck %s -check-prefix=TYPE2
// RUN: %target-swift-ide-test -print-type-interface -pos=38:6 -source-filename %s | %FileCheck %s -check-prefix=TYPE3
// RUN: %target-swift-ide-test -print-type-interface -usr=_TtGC20print_type_interface1DSi_ -module-name print_type_interface -source-filename %s | %FileCheck %s -check-prefix=TYPE3
extension D where T : P1 {
public func conditionalFunc1() {}
public func conditionalFunc2(t : T) -> T {return t}
}
extension D {
public func unconditionalFunc1(){}
public func unconditionalFunc2(t : T) -> T {return t}
}
// TYPE2: public class D<T1> {
// TYPE2: public func foo()
// TYPE2: public func conditionalFunc1()
// TYPE2: public func conditionalFunc2(t: T1) -> T1
// TYPE2: public func unconditionalFunc1()
// TYPE2: public func unconditionalFunc2(t: T1) -> T1
// TYPE2: }
// TYPE3: public class D<Int> {
// TYPE3: public func foo()
// TYPE3: public func unconditionalFunc1()
// TYPE3: public func unconditionalFunc2(t: Int) -> Int
// TYPE3: }
// RUN: %target-swift-ide-test -print-type-interface -usr=_TtGSaSi_ -module-name print_type_interface -source-filename %s | %FileCheck %s -check-prefix=TYPE4
// TYPE4-DAG: public typealias Index = Int
// TYPE4-DAG: public func min() -> Int?
// TYPE4-DAG: public mutating func insert<C>(contentsOf newElements: C, at i: Int)
// TYPE4-DAG: public mutating func removeFirst(_ n: Int)
// TYPE4-DAG: public func makeIterator() -> IndexingIterator<Array<Int>>
// TYPE4-NOT: public func joined
// RUN: %target-swift-ide-test -print-type-interface -usr=_TtGSaSS_ -module-name print_type_interface -source-filename %s | %FileCheck %s -check-prefix=TYPE5
// TYPE5-DAG: public func prefix(_ maxLength: Int) -> ArraySlice<String>
// TYPE5-DAG: public func suffix(_ maxLength: Int) -> ArraySlice<String>
// TYPE5-DAG: public func split(separator: String, maxSplits: Int = default, omittingEmptySubsequences: Bool = default) -> [ArraySlice<String>]
// TYPE5-DAG: public func formIndex(_ i: inout Int, offsetBy n: Int)
// TYPE5-DAG: public func distance(from start: Int, to end: Int) -> Int
// TYPE5-DAG: public func joined(separator: String = default) -> String
| apache-2.0 | 6df05615097eeac22f8e8bfdd1ffeb78 | 37.623529 | 184 | 0.68809 | 3.017463 | false | true | false | false |
wfleming/pico-block | pblock/RuleParser/ABPRuleFileParser.swift | 1 | 1635 | //
// ABPRuleFileParser.swift
// pblock
//
// Created by Will Fleming on 8/22/15.
// Copyright © 2015 PBlock. All rights reserved.
//
import Foundation
/**
Parse an entire set of ABP rules using ABPRuleParser
*/
class ABPRuleFileParser: RuleFileParserProtocol {
private var lines: Array<String>
private var rules: Array<ParsedRule>? = nil
required init(fileSource: String) {
self.lines = fileSource.componentsSeparatedByCharactersInSet(
NSCharacterSet.newlineCharacterSet()
)
}
convenience required init(fileURL: NSURL) {
let fileContents = try! String(contentsOfURL: fileURL, encoding: NSUTF8StringEncoding)
self.init(fileSource: fileContents)
}
func parsedRules() -> Array<ParsedRule> {
if let r = rules {
return r
}
let strip = { (line: String) -> String in
line.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet())
}
let isComment = { (line: String) -> Bool in
(line.hasPrefix("#") && !line.hasPrefix("##")) || line.hasPrefix("!")
}
let isRule = { (line: String) -> Bool in !isComment(line) && "" != line }
let ruleFromLine = { (line: String) -> ParsedRule? in
do {
return try ABPRuleParser(line).parsedRule()
} catch let error {
dlog("rule parser threw exception occurred: $\(error)\n")
}
return nil
}
let isNotNil = { (rule: ParsedRule?) -> Bool in nil != rule }
let unwrapRule = { (rule: ParsedRule?) -> ParsedRule in rule! }
rules = lines.map(strip).filter(isRule).map(ruleFromLine).filter(isNotNil).map(unwrapRule)
return rules!
}
}
| mit | 8fca220cb9e036dadbf4915f2b6d71d5 | 27.172414 | 94 | 0.657283 | 3.918465 | false | false | false | false |
longjianjiang/Drizzling | Drizzling/Drizzling/Extension/MyUtils.swift | 1 | 8641 | //
// MyUtils.swift
// Drizzling
//
// Created by longjianjiang on 2017/2/26.
// Copyright © 2017年 Jiang. All rights reserved.
//
import Foundation
import UIKit
import CoreText
// if the city's name is beijingshi, then delete shi
extension String {
func transformToPinYin()->String{
let mutableString = NSMutableString(string: self)
CFStringTransform(mutableString, nil, kCFStringTransformToLatin, false)
CFStringTransform(mutableString, nil, kCFStringTransformStripDiacritics, false)
let string = String(mutableString).replacingOccurrences(of: " ", with: "")
let index = string.index(string.endIndex, offsetBy: -3)
return string.substring(to: index)
}
}
extension CAGradientLayer {
static func gradientLayer(with gradient: Gradient) -> CAGradientLayer {
let gradientLayer = CAGradientLayer()
gradientLayer.colors = [gradient.startColor.cgColor, gradient.endColor.cgColor]
gradientLayer.startPoint = CGPoint(x: 0.5, y: 0)
gradientLayer.endPoint = CGPoint(x: 0.5, y: 1)
gradientLayer.locations = [0.4, 1]
return gradientLayer
}
}
extension Range where Bound == String.Index {
var nsRange:NSRange {
return NSRange(location: self.lowerBound.encodedOffset,
length: self.upperBound.encodedOffset -
self.lowerBound.encodedOffset)
}
}
extension UILabel {
private var hightlightStr: String? {
get {
return objc_getAssociatedObject(self, LJConstants.RuntimePropertyKey.kHighlightStrKey!) as? String
}
set {
objc_setAssociatedObject(self, LJConstants.RuntimePropertyKey.kHighlightStrKey!, newValue, .OBJC_ASSOCIATION_COPY_NONATOMIC)
}
}
private var highlightStrTapAction: (() -> Void)? {
get {
return objc_getAssociatedObject(self, LJConstants.RuntimePropertyKey.kHightlightStrTapActionKey!) as? (() -> Void)
}
set {
objc_setAssociatedObject(self, LJConstants.RuntimePropertyKey.kHightlightStrTapActionKey!, newValue, .OBJC_ASSOCIATION_COPY_NONATOMIC)
}
}
func boundingRectForCharacterRange(range: NSRange) -> CGRect? {
guard let attributedText = attributedText else { return nil }
let textStorage = NSTextStorage(attributedString: attributedText)
let layoutManager = NSLayoutManager()
textStorage.addLayoutManager(layoutManager)
let textContainer = NSTextContainer(size: bounds.size)
textContainer.lineFragmentPadding = 0.0
layoutManager.addTextContainer(textContainer)
var glyphRange = NSRange()
var lineRange = NSRange()
// Convert the range for glyphs.
layoutManager.characterRange(forGlyphRange: range, actualGlyphRange: &glyphRange)
let highlightStartRect = layoutManager.lineFragmentUsedRect(forGlyphAt: glyphRange.location, effectiveRange: &lineRange)
let highlightEndRect = layoutManager.lineFragmentRect(forGlyphAt: glyphRange.location, effectiveRange: &lineRange)
print("highlightStartRect : \(highlightStartRect)")
print("highlightEndRect : \(highlightEndRect)")
print(layoutManager.boundingRect(forGlyphRange: glyphRange, in: textContainer))
return layoutManager.boundingRect(forGlyphRange: glyphRange, in: textContainer)
}
func getLineBounds(line: UnsafeRawPointer, point: CGPoint) -> CGRect {
var ascent: CGFloat = 0
var descent: CGFloat = 0
var leading: CGFloat = 0
let lineRef = unsafeBitCast(line,to: CTLine.self)
let width = (CGFloat)(CTLineGetTypographicBounds(lineRef, &ascent, &descent, &leading))
let height = ascent + fabs(descent) + leading
return CGRect(x: point.x, y: point.y, width: width, height: height)
}
func isTouchInHighlightArea(point: CGPoint) -> Bool {
let frameSetter = CTFramesetterCreateWithAttributedString(attributedText!)
var path = CGMutablePath()
path.addRect(CGRect(x: 0, y: 0, width: bounds.size.width, height: bounds.size.height))
var frame = CTFramesetterCreateFrame(frameSetter, CFRangeMake(0, 0), path, nil)
let range = CTFrameGetVisibleStringRange(frame)
if (attributedText?.length)! > range.length {
print("______")
var m_font : UIFont
let n_font = self.attributedText?.attribute(NSAttributedStringKey.font, at: 0, effectiveRange: nil)
if n_font != nil {
m_font = n_font as! UIFont
}else if (self.font != nil) {
m_font = self.font!
}else {
m_font = UIFont.systemFont(ofSize: 17)
}
path = CGMutablePath()
path.addRect(CGRect(x: 0, y: 0, width: self.bounds.size.width, height: self.bounds.size.height + m_font.lineHeight), transform: CGAffineTransform.identity)
frame = CTFramesetterCreateFrame(frameSetter, CFRangeMake(0, 0), path, nil)
} else {
print("++++++")
}
let lines = CTFrameGetLines(frame)
let lineCount = CFArrayGetCount(lines)
if lineCount < 1 {
return false
}
var origins = CGPoint()
let lineOrigins = withUnsafeMutablePointer(to: &origins) { $0 }
CTFrameGetLineOrigins(frame, CFRangeMake(0, 0), lineOrigins)
let transform = CGAffineTransform(translationX: 0, y: bounds.height).scaledBy(x: 1.0, y: -1.0)
for i in 0..<lineCount {
let linePoint = lineOrigins[i]
let line = CFArrayGetValueAtIndex(lines, i)
let flippedRect = getLineBounds(line: line!, point: linePoint)
var rect = flippedRect.applying(transform)
rect = rect.insetBy(dx: 0, dy: 0)
rect = rect.offsetBy(dx: 0, dy: 0)
let style = attributedText?.attribute(NSAttributedStringKey.paragraphStyle, at: 0, effectiveRange: nil) as? NSParagraphStyle
let lineSpace: CGFloat
if let style = style {
lineSpace = style.lineSpacing
} else {
lineSpace = 0
}
let lineOutSpace: CGFloat = (bounds.height - lineSpace * (CGFloat)(lineCount - 1) - rect.height * (CGFloat)(lineCount)) / 2.0
rect.origin.y = lineOutSpace + rect.height * (CGFloat)(i) + lineSpace * (CGFloat)(i)
if rect.contains(point) {
let relativePoint = CGPoint(x: point.x - rect.minX,
y: point.y - rect.minY)
let lineRef = unsafeBitCast(line,to: CTLine.self)
var index = CTLineGetStringIndexForPosition(lineRef, relativePoint)
var offset: CGFloat = 0
CTLineGetOffsetForStringIndex(lineRef, index, &offset)
if offset > relativePoint.x {
index = index - 1
}
let range = text?.range(of: hightlightStr!)
let highlightRange = NSRange(range!, in: text!) //text?.range(of: hightlightStr!)?.nsRange
if NSLocationInRange(index, highlightRange) {
return true
}
}
}
return false
}
func setFont(_ size: CGFloat, text: String, hightlight: String, highlightTapAction: @escaping (() -> Void)) {
hightlightStr = hightlight
highlightStrTapAction = highlightTapAction
isUserInteractionEnabled = true
let font = UIFont(name: "Helvetica", size:size)
let attributedStr = NSMutableAttributedString(string: text, attributes: [
NSAttributedStringKey.font: font!,
NSAttributedStringKey.foregroundColor: UIColor.black])
let range = text.range(of: hightlight)
attributedStr.setAttributes([
NSAttributedStringKey.foregroundColor: UIColor.blue], range: (range?.nsRange)!)
attributedText = attributedStr
}
open override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
let touch = touches.first
let point = touch?.location(in: self)
if isTouchInHighlightArea(point: point!) {
highlightStrTapAction!()
}
}
}
| apache-2.0 | 04bc130ce85830afb8a0dffa80d0a924 | 38.623853 | 167 | 0.607432 | 4.975806 | false | false | false | false |
garthmac/ChemicalVisualizer | Molecules.swift | 1 | 49372 | //
// Molecules.swift
// ChemicalVisualizer Copyright (c) 2015 Garth MacKenzie
//
// Created by iMac 27 on 2015-12-01.
//
//
import Foundation
import SceneKit
class Molecules {
class func wiki() -> String { return "https://en.wikipedia.org/wiki/" }
// class func bacteriaMolecule() -> SCNNode { // http://www.chemspider.com/Chemical-Structure.3628289.html
// //20 Bacteria (Streptomyces cremeus NRRL 3241) Formula: C8H6N2O4
// let bacteriaMolecule = SCNNode()
// _ = nodeWithAtom(Atoms.carbonAtom(), molecule: bacteriaMolecule, position: SCNVector3Make(-0.4697, 0.3029, -0.8452))
// _ = nodeWithAtom(Atoms.carbonAtom(), molecule: bacteriaMolecule, position: SCNVector3Make( 1.6890, 0.3905, 0.3540))
// _ = nodeWithAtom(Atoms.carbonAtom(), molecule: bacteriaMolecule, position: SCNVector3Make( 1.6678, 1.3574, -0.8016))
// _ = nodeWithAtom(Atoms.carbonAtom(), molecule: bacteriaMolecule, position: SCNVector3Make( 0.4618, 1.4047, -1.3980))
// _ = nodeWithAtom(Atoms.hydrogenAtom(), molecule: bacteriaMolecule, position: SCNVector3Make(-0.0018, -0.7292, -1.1224))
// _ = nodeWithAtom(Atoms.hydrogenAtom(), molecule: bacteriaMolecule, position: SCNVector3Make( 2.5430, 1.9817, -1.0202))
// _ = nodeWithAtom(Atoms.hydrogenAtom(), molecule: bacteriaMolecule, position: SCNVector3Make( 0.0629, 2.1406, -2.1001))
// _ = nodeWithAtom(Atoms.nitrogenAtom(), molecule: bacteriaMolecule, position: SCNVector3Make( 2.4386, -0.7326, 0.3247))
// _ = nodeWithAtom(Atoms.oxygenAtom(), molecule: bacteriaMolecule, position: SCNVector3Make( 3.4824, -0.6489, -0.3557))
// _ = nodeWithAtom(Atoms.oxygenAtom(), molecule: bacteriaMolecule, position: SCNVector3Make( 2.1007, -1.7333, 1.0042))
// _ = nodeWithAtom(Atoms.carbonAtom(), molecule: bacteriaMolecule, position: SCNVector3Make( 0.4696, 0.3029, 0.8452))
// _ = nodeWithAtom(Atoms.carbonAtom(), molecule: bacteriaMolecule, position: SCNVector3Make(-1.6890, 0.3905, -0.3540))
// _ = nodeWithAtom(Atoms.carbonAtom(), molecule: bacteriaMolecule, position: SCNVector3Make(-1.6678, 1.3574, 0.8016))
// _ = nodeWithAtom(Atoms.carbonAtom(), molecule: bacteriaMolecule, position: SCNVector3Make(-0.4619, 1.4047, 1.3980))
// _ = nodeWithAtom(Atoms.hydrogenAtom(), molecule: bacteriaMolecule, position: SCNVector3Make( 0.0016, -0.7292, 1.1225))
// _ = nodeWithAtom(Atoms.hydrogenAtom(), molecule: bacteriaMolecule, position: SCNVector3Make(-2.5430, 1.9817, 1.0201))
// _ = nodeWithAtom(Atoms.hydrogenAtom(), molecule: bacteriaMolecule, position: SCNVector3Make(-0.0629, 2.1406, 2.1001))
// _ = nodeWithAtom(Atoms.nitrogenAtom(), molecule: bacteriaMolecule, position: SCNVector3Make(-2.4386, -0.7327, -0.3247))
// _ = nodeWithAtom(Atoms.oxygenAtom(), molecule: bacteriaMolecule, position: SCNVector3Make(-3.4823, -0.6489, 0.3557))
// _ = nodeWithAtom(Atoms.oxygenAtom(), molecule: bacteriaMolecule, position: SCNVector3Make(-2.1006, -1.7334, -1.0041))
// bacteriaMolecule.pivot = SCNMatrix4MakeRotation(Float(M_PI_2), 1, 0, 0)
// let spin = CABasicAnimation(keyPath: "rotation")
// // Use from-to to explicitly make a full rotation around y
// spin.fromValue = NSValue(SCNVector4: SCNVector4(x: 0, y: 1, z: 0, w: 0))
// spin.toValue = NSValue(SCNVector4: SCNVector4(x: 0, y: 1, z: 0, w: Float(2 * M_PI)))
// spin.duration = 3
// spin.repeatCount = .infinity
// bacteriaMolecule.addAnimation(spin, forKey: "spin around")
// return bacteriaMolecule
// }
class func benzeneMolecule() -> SCNNode { // https://en.wikipedia.org/wiki/Benzene
//12 Benzene(aromatic hydrocarbon)\nFormula: C6H6
let benzeneMolecule = SCNNode()
benzeneMolecule.name = wiki() + "Benzene"
_ = nodeWithAtom(Atoms.carbonAtom(), molecule: benzeneMolecule, position: SCNVector3Make(0, 1.40272, 0))
_ = nodeWithAtom(Atoms.hydrogenAtom(), molecule: benzeneMolecule, position: SCNVector3Make(0, 2.49029, 0))
_ = nodeWithAtom(Atoms.carbonAtom(), molecule: benzeneMolecule, position: SCNVector3Make(-1.21479, 0.70136, 0))
_ = nodeWithAtom(Atoms.hydrogenAtom(), molecule: benzeneMolecule, position: SCNVector3Make(-2.15666, 1.24515, 0))
_ = nodeWithAtom(Atoms.carbonAtom(), molecule: benzeneMolecule, position: SCNVector3Make(-1.21479, -0.70136, 0))
_ = nodeWithAtom(Atoms.hydrogenAtom(), molecule: benzeneMolecule, position: SCNVector3Make(-2.15666, -1.24515, 0))
_ = nodeWithAtom(Atoms.carbonAtom(), molecule: benzeneMolecule, position: SCNVector3Make(0, -1.40272, 0))
_ = nodeWithAtom(Atoms.hydrogenAtom(), molecule: benzeneMolecule, position: SCNVector3Make(0, -2.49029, 0))
_ = nodeWithAtom(Atoms.carbonAtom(), molecule: benzeneMolecule, position: SCNVector3Make(1.21479, -0.70136, 0))
_ = nodeWithAtom(Atoms.hydrogenAtom(), molecule: benzeneMolecule, position: SCNVector3Make(2.15666, -1.24515, 0))
_ = nodeWithAtom(Atoms.carbonAtom(), molecule: benzeneMolecule, position: SCNVector3Make(1.21479, 0.70136, 0))
_ = nodeWithAtom(Atoms.hydrogenAtom(), molecule: benzeneMolecule, position: SCNVector3Make(2.15666, 1.24515, 0))
// 12 C6H6
// benzene example http://openbabel.org/wiki/XYZ_(format)#Input_Format
// C 0.00000 1.40272 0.00000
// H 0.00000 2.49029 0.00000
// C -1.21479 0.70136 0.00000
// H -2.15666 1.24515 0.00000
// C -1.21479 -0.70136 0.00000
// H -2.15666 -1.24515 0.00000
// C 0.00000 -1.40272 0.00000
// H 0.00000 -2.49029 0.00000
// C 1.21479 -0.70136 0.00000
// H 2.15666 -1.24515 0.00000
// C 1.21479 0.70136 0.00000
// H 2.15666 1.24515 0
benzeneMolecule.pivot = SCNMatrix4MakeRotation(Float(M_PI_2), 1, 0, 0)
let spin = CABasicAnimation(keyPath: "rotation")
// Use from-to to explicitly make a full rotation around y
spin.fromValue = NSValue(SCNVector4: SCNVector4(x: 1, y: 0, z: 0, w: 0))
spin.toValue = NSValue(SCNVector4: SCNVector4(x: 1, y: 0, z: 0, w: Float(2 * M_PI)))
spin.duration = 3
spin.repeatCount = .infinity
benzeneMolecule.addAnimation(spin, forKey: "spin around")
return benzeneMolecule
}
class func caffeineMolecule() -> SCNNode { // https://en.wikipedia.org/wiki/Caffeine
// 24 C8H10N4O2 http://examples.yourdictionary.com/examples-of-organic-compound.html
//Chemcraft/samples/MultXYZ/caffeine.xyz http://www.chemcraftprog.com
let caffeineMolecule = SCNNode()
caffeineMolecule.name = wiki() + "Caffeine"
_ = nodeWithAtom(Atoms.carbonAtom(), molecule: caffeineMolecule, position: SCNVector3Make(0.9163192029, 0.1723652799, 0.0000538537))
_ = nodeWithAtom(Atoms.carbonAtom(), molecule: caffeineMolecule, position: SCNVector3Make(0.3509083411, -1.0602209706, 0.0000405782))
_ = nodeWithAtom(Atoms.carbonAtom(), molecule: caffeineMolecule, position: SCNVector3Make(-1.8294812579, -0.1530826679, 0.0000937309))
_ = nodeWithAtom(Atoms.oxygenAtom(), molecule: caffeineMolecule, position: SCNVector3Make(-3.0416705675, -0.2543508127, 0.0001152929))
_ = nodeWithAtom(Atoms.nitrogenAtom(), molecule: caffeineMolecule, position: SCNVector3Make(-0.9968950055, -1.2504609345, 0.0000451826))
_ = nodeWithAtom(Atoms.nitrogenAtom(), molecule: caffeineMolecule, position: SCNVector3Make(-1.2199179912, 1.1012515026, 0.0001177418))
_ = nodeWithAtom(Atoms.carbonAtom(), molecule: caffeineMolecule, position: SCNVector3Make(0.1505912656, 1.3709444647, 0.0000634254))
_ = nodeWithAtom(Atoms.oxygenAtom(), molecule: caffeineMolecule, position: SCNVector3Make(0.5918714543, 2.5088521310, 0.0000452654))
_ = nodeWithAtom(Atoms.nitrogenAtom(), molecule: caffeineMolecule, position: SCNVector3Make(2.2838824225, -0.0357752199, 0.0000392411))
_ = nodeWithAtom(Atoms.nitrogenAtom(), molecule: caffeineMolecule, position: SCNVector3Make(1.3069147912, -2.0280391296, 0.0000175093))
_ = nodeWithAtom(Atoms.carbonAtom(), molecule: caffeineMolecule, position: SCNVector3Make(2.4553849204, -1.3717111960, 0.0000200731))
_ = nodeWithAtom(Atoms.carbonAtom(), molecule: caffeineMolecule, position: SCNVector3Make(3.3065784847, 1.0144397214, 0.0000527820))
_ = nodeWithAtom(Atoms.carbonAtom(), molecule: caffeineMolecule, position: SCNVector3Make(-1.5644361354, -2.6074506413, 0.0000156331))
_ = nodeWithAtom(Atoms.carbonAtom(), molecule: caffeineMolecule, position: SCNVector3Make(-2.1509960993, 2.2480522409, 0.0001828341))
_ = nodeWithAtom(Atoms.hydrogenAtom(), molecule: caffeineMolecule, position: SCNVector3Make(3.4163727057, -1.8273821969, 0.0000098208))
_ = nodeWithAtom(Atoms.hydrogenAtom(), molecule: caffeineMolecule, position: SCNVector3Make(3.1942693393, 1.6328430162, 0.8769638077))
_ = nodeWithAtom(Atoms.hydrogenAtom(), molecule: caffeineMolecule, position: SCNVector3Make(3.1939698529, 1.6331304053, -0.8766120781))
_ = nodeWithAtom(Atoms.hydrogenAtom(), molecule: caffeineMolecule, position: SCNVector3Make(4.2800507157, 0.5472366162, -0.0001862080))
_ = nodeWithAtom(Atoms.hydrogenAtom(), molecule: caffeineMolecule, position: SCNVector3Make(-1.2346715300, -3.1405469521, 0.8799452405))
_ = nodeWithAtom(Atoms.hydrogenAtom(), molecule: caffeineMolecule, position: SCNVector3Make(-1.2348358395, -3.1404521906, -0.8800330469))
_ = nodeWithAtom(Atoms.hydrogenAtom(), molecule: caffeineMolecule, position: SCNVector3Make(-2.6354685610, -2.5062107159, 0.0001156051))
_ = nodeWithAtom(Atoms.hydrogenAtom(), molecule: caffeineMolecule, position: SCNVector3Make(-2.7781103774, 2.2063254642, 0.8776070691))
_ = nodeWithAtom(Atoms.hydrogenAtom(), molecule: caffeineMolecule, position: SCNVector3Make(-2.7779874036, 2.2065320421, -0.8773401308))
_ = nodeWithAtom(Atoms.hydrogenAtom(), molecule: caffeineMolecule, position: SCNVector3Make(-1.5564081395, 3.1433564463, 0.0003242258))
caffeineMolecule.pivot = SCNMatrix4MakeRotation(Float(M_PI_2), 1, 0, 0)
let spin = CABasicAnimation(keyPath: "rotation")
// Use from-to to explicitly make a full rotation around y
spin.fromValue = NSValue(SCNVector4: SCNVector4(x: 1, y: 0, z: 0, w: 0))
spin.toValue = NSValue(SCNVector4: SCNVector4(x: 1, y: 0, z: 0, w: Float(2 * M_PI)))
spin.duration = 3
spin.repeatCount = .infinity
caffeineMolecule.addAnimation(spin, forKey: "spin around")
return caffeineMolecule
}
class func ethanolMolecule() -> SCNNode { // https://en.wikipedia.org/wiki/Ethanol
//9 drinking alcohol Formula: C2H6O
let ethanolMolecule = SCNNode()
ethanolMolecule.name = wiki() + "Ethanol"
_ = nodeWithAtom(Atoms.carbonAtom(), molecule: ethanolMolecule, position: SCNVector3Make(-0.70, 0.86, -0.36))
_ = nodeWithAtom(Atoms.carbonAtom(), molecule: ethanolMolecule, position: SCNVector3Make( 0.18, -0.18, 0.34))
_ = nodeWithAtom(Atoms.oxygenAtom(), molecule: ethanolMolecule, position: SCNVector3Make( 0.12, -1.43, -0.34))
_ = nodeWithAtom(Atoms.hydrogenAtom(), molecule: ethanolMolecule, position: SCNVector3Make(-0.67, 1.83, 0.20))
_ = nodeWithAtom(Atoms.hydrogenAtom(), molecule: ethanolMolecule, position: SCNVector3Make(-1.75, 0.48, -0.38))
_ = nodeWithAtom(Atoms.hydrogenAtom(), molecule: ethanolMolecule, position: SCNVector3Make(-0.35, 1.03, -1.40))
_ = nodeWithAtom(Atoms.hydrogenAtom(), molecule: ethanolMolecule, position: SCNVector3Make(-0.19, -0.32, 1.38))
_ = nodeWithAtom(Atoms.hydrogenAtom(), molecule: ethanolMolecule, position: SCNVector3Make( 1.24, 0.18, 0.36))
_ = nodeWithAtom(Atoms.hydrogenAtom(), molecule: ethanolMolecule, position: SCNVector3Make( 0.67, -2.03, 0.18))
ethanolMolecule.pivot = SCNMatrix4MakeRotation(Float(M_PI_2), 1, 0, 0)
let spin = CABasicAnimation(keyPath: "rotation")
// Use from-to to explicitly make a full rotation around y
spin.fromValue = NSValue(SCNVector4: SCNVector4(x: 1, y: 0, z: 0, w: 0))
spin.toValue = NSValue(SCNVector4: SCNVector4(x: 1, y: 0, z: 0, w: Float(2 * M_PI)))
spin.duration = 3
spin.repeatCount = .infinity
ethanolMolecule.addAnimation(spin, forKey: "spin around")
return ethanolMolecule
}
class func enprofyllineMolecule() -> SCNNode { // https://en.wikipedia.org/wiki/Enprofylline
// Enprofylline is a xanthine derivative used in the treatment of asthma, which acts as a bronchodilator Molar mass: 194.19 g/mol
//24 Formula C8H10N4O2
let enprofyllineMolecule = SCNNode()
enprofyllineMolecule.name = wiki() + "Enprofylline"
_ = nodeWithAtom(Atoms.carbonAtom(), molecule: enprofyllineMolecule, position: SCNVector3Make( 0.48, 0.37, 0.05))
_ = nodeWithAtom(Atoms.carbonAtom(), molecule: enprofyllineMolecule, position: SCNVector3Make( 1.37, 1.41, 0.07))
_ = nodeWithAtom(Atoms.carbonAtom(), molecule: enprofyllineMolecule, position: SCNVector3Make(-1.38, 1.89, 0.06))
_ = nodeWithAtom(Atoms.nitrogenAtom(), molecule: enprofyllineMolecule, position: SCNVector3Make( 1.21, -0.75, 0.06))
_ = nodeWithAtom(Atoms.nitrogenAtom(), molecule: enprofyllineMolecule, position: SCNVector3Make( 2.63, 0.95, 0.10))
_ = nodeWithAtom(Atoms.carbonAtom(), molecule: enprofyllineMolecule, position: SCNVector3Make( 2.51, -0.39, 0.09))
_ = nodeWithAtom(Atoms.nitrogenAtom(), molecule: enprofyllineMolecule, position: SCNVector3Make(-0.92, 0.57, 0.03))
_ = nodeWithAtom(Atoms.carbonAtom(), molecule: enprofyllineMolecule, position: SCNVector3Make(-1.96, -0.48, -0.03))
_ = nodeWithAtom(Atoms.oxygenAtom(), molecule: enprofyllineMolecule, position: SCNVector3Make(-2.56, 2.11, 0.05))
_ = nodeWithAtom(Atoms.nitrogenAtom(), molecule: enprofyllineMolecule, position: SCNVector3Make(-0.49, 2.97, 0.09))
_ = nodeWithAtom(Atoms.carbonAtom(), molecule: enprofyllineMolecule, position: SCNVector3Make( 0.88, 2.78, 0.08))
_ = nodeWithAtom(Atoms.oxygenAtom(), molecule: enprofyllineMolecule, position: SCNVector3Make( 1.65, 3.71, 0.06))
_ = nodeWithAtom(Atoms.carbonAtom(), molecule: enprofyllineMolecule, position: SCNVector3Make(-1.42,-1.91, 0.04))
_ = nodeWithAtom(Atoms.carbonAtom(), molecule: enprofyllineMolecule, position: SCNVector3Make(-2.56,-2.92, 0.06))
_ = nodeWithAtom(Atoms.hydrogenAtom(), molecule: enprofyllineMolecule, position: SCNVector3Make( 0.87,-1.69, 0.06))
_ = nodeWithAtom(Atoms.hydrogenAtom(), molecule: enprofyllineMolecule, position: SCNVector3Make( 3.37,-1.10, 0.11))
_ = nodeWithAtom(Atoms.hydrogenAtom(), molecule: enprofyllineMolecule, position: SCNVector3Make(-2.59,-0.36,-0.88))
_ = nodeWithAtom(Atoms.hydrogenAtom(), molecule: enprofyllineMolecule, position: SCNVector3Make(-2.59,-0.34, 0.93))
_ = nodeWithAtom(Atoms.hydrogenAtom(), molecule: enprofyllineMolecule, position: SCNVector3Make(-0.85, 3.91, 0.10))
_ = nodeWithAtom(Atoms.hydrogenAtom(), molecule: enprofyllineMolecule, position: SCNVector3Make(-0.82,-2.04, 0.97))
_ = nodeWithAtom(Atoms.hydrogenAtom(), molecule: enprofyllineMolecule, position: SCNVector3Make(-0.79,-2.10,-0.86))
_ = nodeWithAtom(Atoms.hydrogenAtom(), molecule: enprofyllineMolecule, position: SCNVector3Make(-2.98,-3.05,-0.97))
_ = nodeWithAtom(Atoms.hydrogenAtom(), molecule: enprofyllineMolecule, position: SCNVector3Make(-3.37,-2.55, 0.73))
_ = nodeWithAtom(Atoms.hydrogenAtom(), molecule: enprofyllineMolecule, position: SCNVector3Make(-2.20,-3.91, 0.43))
enprofyllineMolecule.pivot = SCNMatrix4MakeRotation(Float(M_PI_2), 1, 0, 0)
let spin = CABasicAnimation(keyPath: "rotation")
// Use from-to to explicitly make a full rotation around y
spin.fromValue = NSValue(SCNVector4: SCNVector4(x: 1, y: 0, z: 0, w: 0))
spin.toValue = NSValue(SCNVector4: SCNVector4(x: 1, y: 0, z: 0, w: Float(2 * M_PI)))
spin.duration = 3
spin.repeatCount = .infinity
enprofyllineMolecule.addAnimation(spin, forKey: "spin around")
return enprofyllineMolecule
}
class func fructoseMolecule() -> SCNNode { // https://en.wikipedia.org/wiki/Fructose
//24 Fructose(fruit sugar)\nFormula: C6H12O6
let fructoseMolecule = SCNNode()
fructoseMolecule.name = wiki() + "Fructose"
_ = nodeWithAtom(Atoms.carbonAtom(), molecule: fructoseMolecule, position: SCNVector3Make(-0.80, -1.78, -0.2))
_ = nodeWithAtom(Atoms.carbonAtom(), molecule: fructoseMolecule, position: SCNVector3Make(-1.53, -0.66, -0.8))
_ = nodeWithAtom(Atoms.oxygenAtom(), molecule: fructoseMolecule, position: SCNVector3Make(-1.67, -2.63, 0.52))
_ = nodeWithAtom(Atoms.carbonAtom(), molecule: fructoseMolecule, position: SCNVector3Make(-0.70, 0.58, -0.56))
_ = nodeWithAtom(Atoms.carbonAtom(), molecule: fructoseMolecule, position: SCNVector3Make(-1.59, 1.71, -0.04))
_ = nodeWithAtom(Atoms.carbonAtom(), molecule: fructoseMolecule, position: SCNVector3Make( 0.23, -1.16, 0.72))
_ = nodeWithAtom(Atoms.oxygenAtom(), molecule: fructoseMolecule, position: SCNVector3Make(-0.09, 1.01, -1.76))
_ = nodeWithAtom(Atoms.oxygenAtom(), molecule: fructoseMolecule, position: SCNVector3Make( 0.31, 0.26, 0.42))
_ = nodeWithAtom(Atoms.oxygenAtom(), molecule: fructoseMolecule, position: SCNVector3Make(-0.90, 2.94, -0.04))
_ = nodeWithAtom(Atoms.oxygenAtom(), molecule: fructoseMolecule, position: SCNVector3Make(-1.72, -0.86, -2.2))
_ = nodeWithAtom(Atoms.carbonAtom(), molecule: fructoseMolecule, position: SCNVector3Make( 1.59, -1.82, 0.51))
_ = nodeWithAtom(Atoms.oxygenAtom(), molecule: fructoseMolecule, position: SCNVector3Make( 2.56, -1.31, 1.40))
_ = nodeWithAtom(Atoms.hydrogenAtom(), molecule: fructoseMolecule, position: SCNVector3Make(-0.30, -2.39, -0.99))
_ = nodeWithAtom(Atoms.hydrogenAtom(), molecule: fructoseMolecule, position: SCNVector3Make(-2.54, -0.55, -0.34))
_ = nodeWithAtom(Atoms.hydrogenAtom(), molecule: fructoseMolecule, position: SCNVector3Make(-2.23, -3.03, -0.15))
_ = nodeWithAtom(Atoms.hydrogenAtom(), molecule: fructoseMolecule, position: SCNVector3Make(-1.90, 1.47, 1.01))
_ = nodeWithAtom(Atoms.hydrogenAtom(), molecule: fructoseMolecule, position: SCNVector3Make(-2.50, 1.79, -0.68))
_ = nodeWithAtom(Atoms.hydrogenAtom(), molecule: fructoseMolecule, position: SCNVector3Make(-0.08, -1.30, 1.78))
_ = nodeWithAtom(Atoms.hydrogenAtom(), molecule: fructoseMolecule, position: SCNVector3Make( 0.61, 0.37, -1.91))
_ = nodeWithAtom(Atoms.hydrogenAtom(), molecule: fructoseMolecule, position: SCNVector3Make(-0.57, 3.03, -0.94))
_ = nodeWithAtom(Atoms.hydrogenAtom(), molecule: fructoseMolecule, position: SCNVector3Make(-2.56, -1.32, -2.27))
_ = nodeWithAtom(Atoms.hydrogenAtom(), molecule: fructoseMolecule, position: SCNVector3Make( 1.92, -1.62, -0.54))
_ = nodeWithAtom(Atoms.hydrogenAtom(), molecule: fructoseMolecule, position: SCNVector3Make( 1.49, -2.92, 0.66))
_ = nodeWithAtom(Atoms.hydrogenAtom(), molecule: fructoseMolecule, position: SCNVector3Make( 2.28, -1.60, 2.27))
fructoseMolecule.pivot = SCNMatrix4MakeRotation(Float(M_PI_2), 1, 0, 0)
let spin = CABasicAnimation(keyPath: "rotation")
// Use from-to to explicitly make a full rotation around y
spin.fromValue = NSValue(SCNVector4: SCNVector4(x: 0, y: 1, z: 0, w: 0))
spin.toValue = NSValue(SCNVector4: SCNVector4(x: 0, y: 1, z: 0, w: Float(2 * M_PI)))
spin.duration = 3
spin.repeatCount = .infinity
fructoseMolecule.addAnimation(spin, forKey: "spin around")
return fructoseMolecule
}
class func glyphosateMolecule() -> SCNNode { // https://en.wikipedia.org/wiki/Glyphosate
//18 (Monsanto Roundup) Chemical formula C3H8NO5P
let glyphosateMolecule = SCNNode()
glyphosateMolecule.name = wiki() + "Glyphosate"
_ = nodeWithAtom(Atoms.carbonAtom(), molecule: glyphosateMolecule, position: SCNVector3Make(-3.00, 0.68, -0.07))
_ = nodeWithAtom(Atoms.carbonAtom(), molecule: glyphosateMolecule, position: SCNVector3Make(-1.75, 0.52, 0.77))
_ = nodeWithAtom(Atoms.oxygenAtom(), molecule: glyphosateMolecule, position: SCNVector3Make(-3.35, -0.28, -0.97))
_ = nodeWithAtom(Atoms.oxygenAtom(), molecule: glyphosateMolecule, position: SCNVector3Make(-3.70, 1.66, 0.07))
_ = nodeWithAtom(Atoms.nitrogenAtom(), molecule: glyphosateMolecule, position: SCNVector3Make(-0.55, 0.56, -0.07))
_ = nodeWithAtom(Atoms.carbonAtom(), molecule: glyphosateMolecule, position: SCNVector3Make( 0.64, 0.28, 0.74))
_ = nodeWithAtom(Atoms.phosphorusAtom(), molecule: glyphosateMolecule, position: SCNVector3Make( 2.15, 0.21, -0.25))
_ = nodeWithAtom(Atoms.oxygenAtom(), molecule: glyphosateMolecule, position: SCNVector3Make( 2.45, 1.54, -0.76))
_ = nodeWithAtom(Atoms.oxygenAtom(), molecule: glyphosateMolecule, position: SCNVector3Make( 1.91, -0.82, -1.50))
_ = nodeWithAtom(Atoms.oxygenAtom(), molecule: glyphosateMolecule, position: SCNVector3Make( 3.41, -0.31, 0.65))
_ = nodeWithAtom(Atoms.hydrogenAtom(), molecule: glyphosateMolecule, position: SCNVector3Make(-1.70, 1.35, 1.50))
_ = nodeWithAtom(Atoms.hydrogenAtom(), molecule: glyphosateMolecule, position: SCNVector3Make(-1.80, -0.45, 1.31))
_ = nodeWithAtom(Atoms.hydrogenAtom(), molecule: glyphosateMolecule, position: SCNVector3Make(-4.15, -0.18, -1.49))
_ = nodeWithAtom(Atoms.hydrogenAtom(), molecule: glyphosateMolecule, position: SCNVector3Make(-0.47, 1.52, -0.38))
_ = nodeWithAtom(Atoms.hydrogenAtom(), molecule: glyphosateMolecule, position: SCNVector3Make( 0.76, 1.09, 1.50))
_ = nodeWithAtom(Atoms.hydrogenAtom(), molecule: glyphosateMolecule, position: SCNVector3Make( 0.50, -0.69, 1.26))
_ = nodeWithAtom(Atoms.hydrogenAtom(), molecule: glyphosateMolecule, position: SCNVector3Make( 1.70, -1.66, -1.09))
_ = nodeWithAtom(Atoms.hydrogenAtom(), molecule: glyphosateMolecule, position: SCNVector3Make(-4.15, -0.34, 0.04))
glyphosateMolecule.pivot = SCNMatrix4MakeRotation(Float(M_PI_2), 1, 0, 0)
let spin = CABasicAnimation(keyPath: "rotation")
// Use from-to to explicitly make a full rotation around y
spin.fromValue = NSValue(SCNVector4: SCNVector4(x: 1, y: 0, z: 0, w: 0))
spin.toValue = NSValue(SCNVector4: SCNVector4(x: 1, y: 0, z: 0, w: Float(2 * M_PI)))
spin.duration = 3
spin.repeatCount = .infinity
glyphosateMolecule.addAnimation(spin, forKey: "spin around")
return glyphosateMolecule
}
class func hydrogenPeroxideMolecule() -> SCNNode { // https://en.wikipedia.org/wiki/Hydrogen_peroxide
//4 Hydrogen peroxide(disinfectant)\nFormula: H2O2
let hydrogenPeroxideMolecule = SCNNode()
hydrogenPeroxideMolecule.name = wiki() + "Hydrogen_peroxide"
_ = nodeWithAtom(Atoms.oxygenAtom(), molecule: hydrogenPeroxideMolecule, position: SCNVector3Make( -0.39, -0.62, 0.36))
_ = nodeWithAtom(Atoms.oxygenAtom(), molecule: hydrogenPeroxideMolecule, position: SCNVector3Make( 0.39, 0.63, 0.24))
_ = nodeWithAtom(Atoms.hydrogenAtom(), molecule: hydrogenPeroxideMolecule, position: SCNVector3Make( -0.05, -1.18, -0.34))
_ = nodeWithAtom(Atoms.hydrogenAtom(), molecule: hydrogenPeroxideMolecule, position: SCNVector3Make( -0.13, 1.18, -0.36))
hydrogenPeroxideMolecule.pivot = SCNMatrix4MakeRotation(Float(M_PI_2), 1, 0, 0)
let spin = CABasicAnimation(keyPath: "rotation")
// Use from-to to explicitly make a full rotation around y
spin.fromValue = NSValue(SCNVector4: SCNVector4(x: 1, y: 0, z: 0, w: 0))
spin.toValue = NSValue(SCNVector4: SCNVector4(x: 1, y: 0, z: 0, w: Float(2 * M_PI)))
spin.duration = 3
spin.repeatCount = .infinity
hydrogenPeroxideMolecule.addAnimation(spin, forKey: "spin around")
return hydrogenPeroxideMolecule
}
class func ibuprofenMolecule() -> SCNNode { // https://en.wikipedia.org/wiki/Ibuprofen
//33 Ibuprofen(Advil) Formula: C13H18O2
let ibuprofenMolecule = SCNNode()
ibuprofenMolecule.name = wiki() + "Ibuprofen"
_ = nodeWithAtom(Atoms.carbonAtom(), molecule: ibuprofenMolecule, position: SCNVector3Make( 1.05, -1.13, -0.25))
_ = nodeWithAtom(Atoms.carbonAtom(), molecule: ibuprofenMolecule, position: SCNVector3Make( 1.62, 0.17, -0.20))
_ = nodeWithAtom(Atoms.carbonAtom(), molecule: ibuprofenMolecule, position: SCNVector3Make(-0.31, -1.30, -0.59))
_ = nodeWithAtom(Atoms.carbonAtom(), molecule: ibuprofenMolecule, position: SCNVector3Make( 0.82, 1.30, -0.50))
_ = nodeWithAtom(Atoms.carbonAtom(), molecule: ibuprofenMolecule, position: SCNVector3Make(-1.11, -0.17, -0.90))
_ = nodeWithAtom(Atoms.carbonAtom(), molecule: ibuprofenMolecule, position: SCNVector3Make(-0.55, 1.13, -0.86))
_ = nodeWithAtom(Atoms.carbonAtom(), molecule: ibuprofenMolecule, position: SCNVector3Make(-2.61, -0.35, -1.30))
_ = nodeWithAtom(Atoms.carbonAtom(), molecule: ibuprofenMolecule, position: SCNVector3Make(-3.63, 0.20, -0.24))
_ = nodeWithAtom(Atoms.carbonAtom(), molecule: ibuprofenMolecule, position: SCNVector3Make(-3.39, 1.72, 0.08))
_ = nodeWithAtom(Atoms.carbonAtom(), molecule: ibuprofenMolecule, position: SCNVector3Make(-5.08, 0.03, -0.80))
_ = nodeWithAtom(Atoms.carbonAtom(), molecule: ibuprofenMolecule, position: SCNVector3Make( 4.05, -0.54, -0.66))
_ = nodeWithAtom(Atoms.carbonAtom(), molecule: ibuprofenMolecule, position: SCNVector3Make( 3.11, 0.38, 0.17))
_ = nodeWithAtom(Atoms.oxygenAtom(), molecule: ibuprofenMolecule, position: SCNVector3Make( 3.66, -1.66, -1.01))
_ = nodeWithAtom(Atoms.oxygenAtom(), molecule: ibuprofenMolecule, position: SCNVector3Make( 5.32, -0.10, -1.02))
_ = nodeWithAtom(Atoms.carbonAtom(), molecule: ibuprofenMolecule, position: SCNVector3Make( 3.35, 0.13, 1.69))
_ = nodeWithAtom(Atoms.hydrogenAtom(), molecule: ibuprofenMolecule, position: SCNVector3Make( 1.70, -2.04, 0.0))
_ = nodeWithAtom(Atoms.hydrogenAtom(), molecule: ibuprofenMolecule, position: SCNVector3Make(-0.76, -2.35, -0.63))
_ = nodeWithAtom(Atoms.hydrogenAtom(), molecule: ibuprofenMolecule, position: SCNVector3Make( 1.26, 2.35, -0.47))
_ = nodeWithAtom(Atoms.hydrogenAtom(), molecule: ibuprofenMolecule, position: SCNVector3Make(-1.18, 2.03, -1.11))
_ = nodeWithAtom(Atoms.hydrogenAtom(), molecule: ibuprofenMolecule, position: SCNVector3Make(-2.79, 0.20, -2.28))
_ = nodeWithAtom(Atoms.hydrogenAtom(), molecule: ibuprofenMolecule, position: SCNVector3Make(-2.81, -1.46, -1.45))
_ = nodeWithAtom(Atoms.hydrogenAtom(), molecule: ibuprofenMolecule, position: SCNVector3Make(-3.50, -0.39, 0.73))
_ = nodeWithAtom(Atoms.hydrogenAtom(), molecule: ibuprofenMolecule, position: SCNVector3Make(-4.22, 2.12, 0.75))
_ = nodeWithAtom(Atoms.hydrogenAtom(), molecule: ibuprofenMolecule, position: SCNVector3Make(-2.39, 1.83, 0.61))
_ = nodeWithAtom(Atoms.hydrogenAtom(), molecule: ibuprofenMolecule, position: SCNVector3Make(-3.39, 2.32, -0.89))
_ = nodeWithAtom(Atoms.hydrogenAtom(), molecule: ibuprofenMolecule, position: SCNVector3Make(-5.63, -0.78, -0.22))
_ = nodeWithAtom(Atoms.hydrogenAtom(), molecule: ibuprofenMolecule, position: SCNVector3Make(-5.63, 1.02, -0.68))
_ = nodeWithAtom(Atoms.hydrogenAtom(), molecule: ibuprofenMolecule, position: SCNVector3Make(-5.05, -0.26, -1.90))
_ = nodeWithAtom(Atoms.hydrogenAtom(), molecule: ibuprofenMolecule, position: SCNVector3Make( 3.37, 1.47, -0.08))
_ = nodeWithAtom(Atoms.hydrogenAtom(), molecule: ibuprofenMolecule, position: SCNVector3Make( 5.63, 0.79, -0.74))
_ = nodeWithAtom(Atoms.hydrogenAtom(), molecule: ibuprofenMolecule, position: SCNVector3Make( 3.37, -0.98, 1.92))
_ = nodeWithAtom(Atoms.hydrogenAtom(), molecule: ibuprofenMolecule, position: SCNVector3Make( 2.52, 0.63, 2.28))
_ = nodeWithAtom(Atoms.hydrogenAtom(), molecule: ibuprofenMolecule, position: SCNVector3Make( 4.35, 0.58, 2.00))
ibuprofenMolecule.pivot = SCNMatrix4MakeRotation(Float(M_PI_2), 1, 0, 0)
let spin = CABasicAnimation(keyPath: "rotation")
// Use from-to to explicitly make a full rotation around y
spin.fromValue = NSValue(SCNVector4: SCNVector4(x: 1, y: 0, z: 0, w: 0))
spin.toValue = NSValue(SCNVector4: SCNVector4(x: 1, y: 0, z: 0, w: Float(2 * M_PI)))
spin.duration = 3
spin.repeatCount = .infinity
ibuprofenMolecule.addAnimation(spin, forKey: "spin around")
return ibuprofenMolecule
}
class func isooctaneMolecule() -> SCNNode { // https://en.wikipedia.org/wiki/2,2,4-Trimethylpentane
//26 Isooctane(gasoline)\nFormula (CH₃)₃CCH₂CH(CH₃)₂ C8H18
let isooctaneMolecule = SCNNode()
isooctaneMolecule.name = wiki() + "2,2,4-Trimethylpentane"
_ = nodeWithAtom(Atoms.carbonAtom(), molecule: isooctaneMolecule, position: SCNVector3Make( 0.23, 2.06, 0.47))
_ = nodeWithAtom(Atoms.carbonAtom(), molecule: isooctaneMolecule, position: SCNVector3Make( 1.06, 0.85, 0.05))
_ = nodeWithAtom(Atoms.carbonAtom(), molecule: isooctaneMolecule, position: SCNVector3Make( 0.31, -0.02, -1.0))
_ = nodeWithAtom(Atoms.carbonAtom(), molecule: isooctaneMolecule, position: SCNVector3Make( 1.43, 0.04, 1.3))
_ = nodeWithAtom(Atoms.carbonAtom(), molecule: isooctaneMolecule, position: SCNVector3Make( 2.35, 1.36, -0.59))
_ = nodeWithAtom(Atoms.carbonAtom(), molecule: isooctaneMolecule, position: SCNVector3Make(-0.81, -0.99, -0.52))
_ = nodeWithAtom(Atoms.carbonAtom(), molecule: isooctaneMolecule, position: SCNVector3Make(-0.26, -2.20, 0.23))
_ = nodeWithAtom(Atoms.carbonAtom(), molecule: isooctaneMolecule, position: SCNVector3Make(-1.84, -0.28, 0.36))
_ = nodeWithAtom(Atoms.hydrogenAtom(), molecule: isooctaneMolecule, position: SCNVector3Make( 0.38, 2.28, 1.55))
_ = nodeWithAtom(Atoms.hydrogenAtom(), molecule: isooctaneMolecule, position: SCNVector3Make(-0.85, 1.86, 0.29))
_ = nodeWithAtom(Atoms.hydrogenAtom(), molecule: isooctaneMolecule, position: SCNVector3Make( 0.53, 2.96, -0.12))
_ = nodeWithAtom(Atoms.hydrogenAtom(), molecule: isooctaneMolecule, position: SCNVector3Make( 1.07, -0.64, -1.54))
_ = nodeWithAtom(Atoms.hydrogenAtom(), molecule: isooctaneMolecule, position: SCNVector3Make(-0.16, 0.68, -1.72))
_ = nodeWithAtom(Atoms.hydrogenAtom(), molecule: isooctaneMolecule, position: SCNVector3Make( 0.53, -0.17, 1.91))
_ = nodeWithAtom(Atoms.hydrogenAtom(), molecule: isooctaneMolecule, position: SCNVector3Make( 2.14, 0.65, 1.91))
_ = nodeWithAtom(Atoms.hydrogenAtom(), molecule: isooctaneMolecule, position: SCNVector3Make( 1.92, -0.91, 1.01))
_ = nodeWithAtom(Atoms.hydrogenAtom(), molecule: isooctaneMolecule, position: SCNVector3Make( 2.90, 2.03, 0.11))
_ = nodeWithAtom(Atoms.hydrogenAtom(), molecule: isooctaneMolecule, position: SCNVector3Make( 2.10, 1.93, -1.51))
_ = nodeWithAtom(Atoms.hydrogenAtom(), molecule: isooctaneMolecule, position: SCNVector3Make( 3.01, 0.51, -0.86))
_ = nodeWithAtom(Atoms.hydrogenAtom(), molecule: isooctaneMolecule, position: SCNVector3Make(-1.32, -1.37, -1.43))
_ = nodeWithAtom(Atoms.hydrogenAtom(), molecule: isooctaneMolecule, position: SCNVector3Make( 0.15, -1.92, 1.22))
_ = nodeWithAtom(Atoms.hydrogenAtom(), molecule: isooctaneMolecule, position: SCNVector3Make( 0.54, -2.66, -0.39))
_ = nodeWithAtom(Atoms.hydrogenAtom(), molecule: isooctaneMolecule, position: SCNVector3Make(-1.07, -2.94, 0.39))
_ = nodeWithAtom(Atoms.hydrogenAtom(), molecule: isooctaneMolecule, position: SCNVector3Make(-1.36, 0.15, 1.26))
_ = nodeWithAtom(Atoms.hydrogenAtom(), molecule: isooctaneMolecule, position: SCNVector3Make(-2.61, -1.02, 0.66))
_ = nodeWithAtom(Atoms.hydrogenAtom(), molecule: isooctaneMolecule, position: SCNVector3Make(-2.33, 0.54, -0.21))
isooctaneMolecule.pivot = SCNMatrix4MakeRotation(Float(M_PI_2), 1, 0, 0)
let spin = CABasicAnimation(keyPath: "rotation")
// Use from-to to explicitly make a full rotation around y
spin.fromValue = NSValue(SCNVector4: SCNVector4(x: 1, y: 0, z: 0, w: 0))
spin.toValue = NSValue(SCNVector4: SCNVector4(x: 1, y: 0, z: 0, w: Float(2 * M_PI)))
spin.duration = 3
spin.repeatCount = .infinity
isooctaneMolecule.addAnimation(spin, forKey: "spin around")
return isooctaneMolecule
}
class func methaneMolecule() -> SCNNode { // https://en.wikipedia.org/wiki/Methane
//5 Methane(natural gas) Formula: CH4
let methaneMolecule = SCNNode()
methaneMolecule.name = wiki() + "Methane"
_ = nodeWithAtom(Atoms.carbonAtom(), molecule: methaneMolecule, position: SCNVector3Make(0, 0, 0))
_ = nodeWithAtom(Atoms.hydrogenAtom(), molecule: methaneMolecule, position: SCNVector3Make(0, 0, 1.089))
_ = nodeWithAtom(Atoms.hydrogenAtom(), molecule: methaneMolecule, position: SCNVector3Make(1.026719, 0,-0.363))
_ = nodeWithAtom(Atoms.hydrogenAtom(), molecule: methaneMolecule, position: SCNVector3Make(-0.51336, -0.889165, -0.363))
_ = nodeWithAtom(Atoms.hydrogenAtom(), molecule: methaneMolecule, position: SCNVector3Make(-0.51336, 0.889165, -0.363))
// 5 methane molecule (in ångströms) https://en.wikipedia.org/wiki/XYZ_file_format
// C 0.000000 0.000000 0.000000
// H 0.000000 0.000000 1.089000
// H 1.026719 0.000000 -0.363000
// H -0.513360 -0.889165 -0.363000
// H -0.513360 0.889165 -0.363000
methaneMolecule.pivot = SCNMatrix4MakeRotation(Float(M_PI_2), 1, 0, 0)
let spin = CABasicAnimation(keyPath: "rotation")
// Use from-to to explicitly make a full rotation around y
spin.fromValue = NSValue(SCNVector4: SCNVector4(x: 1, y: 0, z: 0, w: 0))
spin.toValue = NSValue(SCNVector4: SCNVector4(x: 1, y: 0, z: 0, w: Float(2 * M_PI)))
spin.duration = 3
spin.repeatCount = .infinity
methaneMolecule.addAnimation(spin, forKey: "spin around")
return methaneMolecule
}
class func ptfeMolecule() -> SCNNode { // https://en.wikipedia.org/wiki/Polytetrafluoroethylene
//6 Polytetrafluoroethylene\n(Teflon) synthetic fluoropolymer of tetrafluoroethylene Formula: (C2F4)n
let ptfeMolecule = SCNNode()
ptfeMolecule.name = wiki() + "Polytetrafluoroethylene"
// 2 double bond Carbon + 4 Flourine repeating structure
_ = nodeWithAtom(Atoms.fluorineAtom(), molecule: ptfeMolecule, position: SCNVector3Make( 0.79, -1.56, -0.25))
_ = nodeWithAtom(Atoms.fluorineAtom(), molecule: ptfeMolecule, position: SCNVector3Make(-1.44, -0.99, -0.23))
_ = nodeWithAtom(Atoms.carbonAtom(), molecule: ptfeMolecule, position: SCNVector3Make(-0.16, -0.64, -0.12))
_ = nodeWithAtom(Atoms.carbonAtom(), molecule: ptfeMolecule, position: SCNVector3Make( 0.16, 0.64, 0.12))
_ = nodeWithAtom(Atoms.fluorineAtom(), molecule: ptfeMolecule, position: SCNVector3Make(-0.79, 1.56, 0.25))
_ = nodeWithAtom(Atoms.fluorineAtom(), molecule: ptfeMolecule, position: SCNVector3Make( 1.44, 0.99, 0.22))
ptfeMolecule.pivot = SCNMatrix4MakeRotation(Float(M_PI_2), 1, 0, 0)
let spin = CABasicAnimation(keyPath: "rotation")
// Use from-to to explicitly make a full rotation around y
spin.fromValue = NSValue(SCNVector4: SCNVector4(x: 1, y: 0, z: 0, w: 0))
spin.toValue = NSValue(SCNVector4: SCNVector4(x: 1, y: 0, z: 0, w: Float(2 * M_PI)))
spin.duration = 3
spin.repeatCount = .infinity
ptfeMolecule.addAnimation(spin, forKey: "spin around")
return ptfeMolecule
}
class func phosphoricAcidMolecule() -> SCNNode { // https://en.wikipedia.org/wiki/Phosphoric_acid
//8 Phosphoric acid(mineral acid)\nFormula: H3PO4
let phosphoricAcidMolecule = SCNNode()
phosphoricAcidMolecule.name = wiki() + "Phosphoric_acid"
_ = nodeWithAtom(Atoms.phosphorusAtom(), molecule: phosphoricAcidMolecule, position: SCNVector3Make( -0.07, 0.15, 0))
_ = nodeWithAtom(Atoms.oxygenAtom(), molecule: phosphoricAcidMolecule, position: SCNVector3Make( 0.99, 1.22, 0.64))
_ = nodeWithAtom(Atoms.oxygenAtom(), molecule: phosphoricAcidMolecule, position: SCNVector3Make(-1.13, 0.93, -0.99))
_ = nodeWithAtom(Atoms.oxygenAtom(), molecule: phosphoricAcidMolecule, position: SCNVector3Make( 0.75, -0.98, -0.86))
_ = nodeWithAtom(Atoms.oxygenAtom(), molecule: phosphoricAcidMolecule, position: SCNVector3Make(-0.81, -0.49, 1.07))
_ = nodeWithAtom(Atoms.hydrogenAtom(), molecule: phosphoricAcidMolecule, position: SCNVector3Make(1.56, 0.69, 1.2))
_ = nodeWithAtom(Atoms.hydrogenAtom(), molecule: phosphoricAcidMolecule, position: SCNVector3Make(-1.56, 1.57, -0.42))
_ = nodeWithAtom(Atoms.hydrogenAtom(), molecule: phosphoricAcidMolecule, position: SCNVector3Make(0.07, -1.57, -1.2))
// 4 phosphorus molecule (in ångströms) https://en.wikipedia.org/wiki/Tetrahedron
// (+1, +1, +1);
// (−1, −1, +1);
// (−1, +1, −1);
// (+1, −1, −1)
// Point the pyramid in the -z direction
phosphoricAcidMolecule.pivot = SCNMatrix4MakeRotation(Float(M_PI_2), 1, 0, 0)
let spin = CABasicAnimation(keyPath: "rotation")
// Use from-to to explicitly make a full rotation around y
spin.fromValue = NSValue(SCNVector4: SCNVector4(x: 0, y: 1, z: 0, w: 0))
spin.toValue = NSValue(SCNVector4: SCNVector4(x: 0, y: 1, z: 0, w: Float(2 * M_PI)))
spin.duration = 3
spin.repeatCount = .infinity
phosphoricAcidMolecule.addAnimation(spin, forKey: "spin around")
return phosphoricAcidMolecule
}
class func pyrazineMolecule() -> SCNNode { // https://en.wikipedia.org/wiki/Pyrazine
//33 Pyrazine(antibiotic)\nFormula: C4H4N2
let pyrazineMolecule = SCNNode()
pyrazineMolecule.name = wiki() + "Pyrazine"
_ = nodeWithAtom(Atoms.carbonAtom(), molecule: pyrazineMolecule, position: SCNVector3Make( 1.21, -0.68, 0.02))
_ = nodeWithAtom(Atoms.carbonAtom(), molecule: pyrazineMolecule, position: SCNVector3Make( 1.19, 0.71, -0.02))
_ = nodeWithAtom(Atoms.nitrogenAtom(), molecule: pyrazineMolecule, position: SCNVector3Make( 0.01, -1.39, 0.04))
_ = nodeWithAtom(Atoms.nitrogenAtom(), molecule: pyrazineMolecule, position: SCNVector3Make(-0.01, 1.39, -0.04))
_ = nodeWithAtom(Atoms.carbonAtom(), molecule: pyrazineMolecule, position: SCNVector3Make(-1.19, -0.71, 0.02))
_ = nodeWithAtom(Atoms.carbonAtom(), molecule: pyrazineMolecule, position: SCNVector3Make(-1.21, 0.68, -0.02))
_ = nodeWithAtom(Atoms.hydrogenAtom(), molecule: pyrazineMolecule, position: SCNVector3Make( 2.17, -1.23, 0.03))
_ = nodeWithAtom(Atoms.hydrogenAtom(), molecule: pyrazineMolecule, position: SCNVector3Make( 2.15, 1.27, -0.04))
_ = nodeWithAtom(Atoms.hydrogenAtom(), molecule: pyrazineMolecule, position: SCNVector3Make(-2.15, -1.27, 0.04))
_ = nodeWithAtom(Atoms.hydrogenAtom(), molecule: pyrazineMolecule, position: SCNVector3Make(-2.17, 1.23, -0.03))
pyrazineMolecule.pivot = SCNMatrix4MakeRotation(Float(M_PI_2), 1, 0, 0)
let spin = CABasicAnimation(keyPath: "rotation")
// Use from-to to explicitly make a full rotation around y
spin.fromValue = NSValue(SCNVector4: SCNVector4(x: 1, y: 0, z: 0, w: 0))
spin.toValue = NSValue(SCNVector4: SCNVector4(x: 1, y: 0, z: 0, w: Float(2 * M_PI)))
spin.duration = 3
spin.repeatCount = .infinity
pyrazineMolecule.addAnimation(spin, forKey: "spin around")
return pyrazineMolecule
}
class func sodiumTriphosphateMolecule() -> SCNNode { // https://en.wikipedia.org/wiki/Sodium_triphosphate
//18 Sodium triphosphate(detergent)\nFormula Na5P3O10
let sodiumTriphosphateMolecule = SCNNode()
sodiumTriphosphateMolecule.name = wiki() + "Sodium_triphosphate"
_ = nodeWithAtom(Atoms.oxygenAtom(), molecule: sodiumTriphosphateMolecule, position: SCNVector3Make( 1.05, -1.13, -0.25))
_ = nodeWithAtom(Atoms.oxygenAtom(), molecule: sodiumTriphosphateMolecule, position: SCNVector3Make( 1.62, 0.17, -0.20))
_ = nodeWithAtom(Atoms.oxygenAtom(), molecule: sodiumTriphosphateMolecule, position: SCNVector3Make(-0.31, -1.30, -0.59))
_ = nodeWithAtom(Atoms.carbonAtom(), molecule: sodiumTriphosphateMolecule, position: SCNVector3Make( 0.82, 1.30, -0.50))
_ = nodeWithAtom(Atoms.oxygenAtom(), molecule: sodiumTriphosphateMolecule, position: SCNVector3Make(-1.11, -0.17, -0.90))
_ = nodeWithAtom(Atoms.carbonAtom(), molecule: sodiumTriphosphateMolecule, position: SCNVector3Make(-0.55, 1.13, -0.86))
_ = nodeWithAtom(Atoms.carbonAtom(), molecule: sodiumTriphosphateMolecule, position: SCNVector3Make(-2.61, -0.35, -1.30))
_ = nodeWithAtom(Atoms.oxygenAtom(), molecule: sodiumTriphosphateMolecule, position: SCNVector3Make(-3.63, 0.20, -0.24))
_ = nodeWithAtom(Atoms.oxygenAtom(), molecule: sodiumTriphosphateMolecule, position: SCNVector3Make(-3.39, 1.72, 0.08))
_ = nodeWithAtom(Atoms.oxygenAtom(), molecule: sodiumTriphosphateMolecule, position: SCNVector3Make(-5.08, 0.03, -0.80))
_ = nodeWithAtom(Atoms.oxygenAtom(), molecule: sodiumTriphosphateMolecule, position: SCNVector3Make( 4.05, -0.54, -0.66))
_ = nodeWithAtom(Atoms.oxygenAtom(), molecule: sodiumTriphosphateMolecule, position: SCNVector3Make( 3.11, 0.38, 0.17))
_ = nodeWithAtom(Atoms.oxygenAtom(), molecule: sodiumTriphosphateMolecule, position: SCNVector3Make( 3.66, -1.66, -1.01))
_ = nodeWithAtom(Atoms.sodiumAtom(), molecule: sodiumTriphosphateMolecule, position: SCNVector3Make( 3.37, 1.47, -0.08))
_ = nodeWithAtom(Atoms.sodiumAtom(), molecule: sodiumTriphosphateMolecule, position: SCNVector3Make( 5.63, 0.79, -0.74))
_ = nodeWithAtom(Atoms.sodiumAtom(), molecule: sodiumTriphosphateMolecule, position: SCNVector3Make( 3.37, -0.98, 1.92))
_ = nodeWithAtom(Atoms.sodiumAtom(), molecule: sodiumTriphosphateMolecule, position: SCNVector3Make( 2.52, 0.63, 2.28))
_ = nodeWithAtom(Atoms.sodiumAtom(), molecule: sodiumTriphosphateMolecule, position: SCNVector3Make( 4.35, 0.58, 2.00))
sodiumTriphosphateMolecule.pivot = SCNMatrix4MakeRotation(Float(M_PI_2), 1, 0, 0)
let spin = CABasicAnimation(keyPath: "rotation")
// Use from-to to explicitly make a full rotation around y
spin.fromValue = NSValue(SCNVector4: SCNVector4(x: 1, y: 0, z: 0, w: 0))
spin.toValue = NSValue(SCNVector4: SCNVector4(x: 1, y: 0, z: 0, w: Float(2 * M_PI)))
spin.duration = 3
spin.repeatCount = .infinity
sodiumTriphosphateMolecule.addAnimation(spin, forKey: "spin around")
return sodiumTriphosphateMolecule
}
class func teaTreeOilMolecule() -> SCNNode { // https://en.wikipedia.org/wiki/Terpinen-4-ol
//29 C10H18O Terpinen-4-ol is a terpene with a molecular weight of 154.249. It has an antibacterial and antifungal effect. It is considered the primary active ingredient of tea tree oil
let teaTreeOilMolecule = SCNNode()
teaTreeOilMolecule.name = wiki() + "Terpinen-4-ol"
_ = nodeWithAtom(Atoms.carbonAtom(), molecule: teaTreeOilMolecule, position: SCNVector3Make( 0.56, 0.69, 0.19))
_ = nodeWithAtom(Atoms.carbonAtom(), molecule: teaTreeOilMolecule, position: SCNVector3Make( 1.33, 0.66, -0.13))
_ = nodeWithAtom(Atoms.carbonAtom(), molecule: teaTreeOilMolecule, position: SCNVector3Make(-0.78, -0.05, 1.05))
_ = nodeWithAtom(Atoms.carbonAtom(), molecule: teaTreeOilMolecule, position: SCNVector3Make( 1.56, -0.76, -0.57))
_ = nodeWithAtom(Atoms.carbonAtom(), molecule: teaTreeOilMolecule, position: SCNVector3Make(-0.51, -1.52, 0.65))
_ = nodeWithAtom(Atoms.carbonAtom(), molecule: teaTreeOilMolecule, position: SCNVector3Make( 0.71, -1.75, -0.23))
_ = nodeWithAtom(Atoms.carbonAtom(), molecule: teaTreeOilMolecule, position: SCNVector3Make( 2.76, -1.07, -1.43))
_ = nodeWithAtom(Atoms.carbonAtom(), molecule: teaTreeOilMolecule, position: SCNVector3Make(-1.66, 0.64, -0.03))
_ = nodeWithAtom(Atoms.carbonAtom(), molecule: teaTreeOilMolecule, position: SCNVector3Make(-3.02, -0.04, -0.22))
_ = nodeWithAtom(Atoms.carbonAtom(), molecule: teaTreeOilMolecule, position: SCNVector3Make(-1.90, 2.10, 0.36))
_ = nodeWithAtom(Atoms.oxygenAtom(), molecule: teaTreeOilMolecule, position: SCNVector3Make(-1.47, -0.03, 2.30))
_ = nodeWithAtom(Atoms.hydrogenAtom(), molecule: teaTreeOilMolecule, position: SCNVector3Make( 0.38, 1.75, 1.47))
_ = nodeWithAtom(Atoms.hydrogenAtom(), molecule: teaTreeOilMolecule, position: SCNVector3Make( 1.17, 0.21, 1.98))
_ = nodeWithAtom(Atoms.hydrogenAtom(), molecule: teaTreeOilMolecule, position: SCNVector3Make( 2.31, 1.16, 0.02))
_ = nodeWithAtom(Atoms.hydrogenAtom(), molecule: teaTreeOilMolecule, position: SCNVector3Make( 0.76, 1.20, -0.92))
_ = nodeWithAtom(Atoms.hydrogenAtom(), molecule: teaTreeOilMolecule, position: SCNVector3Make(-1.41, -1.91, 0.12))
_ = nodeWithAtom(Atoms.hydrogenAtom(), molecule: teaTreeOilMolecule, position: SCNVector3Make(-0.37, -2.10, 1.59))
_ = nodeWithAtom(Atoms.hydrogenAtom(), molecule: teaTreeOilMolecule, position: SCNVector3Make( 0.92, -2.78, -0.60))
_ = nodeWithAtom(Atoms.hydrogenAtom(), molecule: teaTreeOilMolecule, position: SCNVector3Make( 3.70, -0.93, -0.85))
_ = nodeWithAtom(Atoms.hydrogenAtom(), molecule: teaTreeOilMolecule, position: SCNVector3Make( 2.76, -0.39, -2.30))
_ = nodeWithAtom(Atoms.hydrogenAtom(), molecule: teaTreeOilMolecule, position: SCNVector3Make( 2.72, -2.12, -1.79))
_ = nodeWithAtom(Atoms.hydrogenAtom(), molecule: teaTreeOilMolecule, position: SCNVector3Make(-1.13, 0.58, -1.01))
_ = nodeWithAtom(Atoms.hydrogenAtom(), molecule: teaTreeOilMolecule, position: SCNVector3Make(-3.50, -0.25, 0.76))
_ = nodeWithAtom(Atoms.hydrogenAtom(), molecule: teaTreeOilMolecule, position: SCNVector3Make(-2.89, -0.99, -0.79))
_ = nodeWithAtom(Atoms.hydrogenAtom(), molecule: teaTreeOilMolecule, position: SCNVector3Make(-3.70, 0.63, -0.80))
_ = nodeWithAtom(Atoms.hydrogenAtom(), molecule: teaTreeOilMolecule, position: SCNVector3Make(-1.56, 2.29, 1.40))
_ = nodeWithAtom(Atoms.hydrogenAtom(), molecule: teaTreeOilMolecule, position: SCNVector3Make(-2.99, 2.32, 0.29))
_ = nodeWithAtom(Atoms.hydrogenAtom(), molecule: teaTreeOilMolecule, position: SCNVector3Make(-1.34, 2.78, -0.32))
_ = nodeWithAtom(Atoms.hydrogenAtom(), molecule: teaTreeOilMolecule, position: SCNVector3Make(-2.24, 0.52, 2.16))
teaTreeOilMolecule.pivot = SCNMatrix4MakeRotation(Float(M_PI_2), 1, 0, 0)
let spin = CABasicAnimation(keyPath: "rotation")
// Use from-to to explicitly make a full rotation around y
spin.fromValue = NSValue(SCNVector4: SCNVector4(x: 1, y: 0, z: 0, w: 0))
spin.toValue = NSValue(SCNVector4: SCNVector4(x: 1, y: 0, z: 0, w: Float(2 * M_PI)))
spin.duration = 3
spin.repeatCount = .infinity
teaTreeOilMolecule.addAnimation(spin, forKey: "spin around")
return teaTreeOilMolecule
}
class func nodeWithAtom(atom: SCNGeometry, molecule: SCNNode, position: SCNVector3) -> SCNNode {
let node = SCNNode(geometry: atom)
node.position = position
molecule.addChildNode(node)
return node
}
}
| mit | 5a453b0dfe49d9286f80f41356e030ab | 89.876611 | 194 | 0.673368 | 2.72359 | false | false | false | false |
PJayRushton/TeacherTools | Pods/Whisper/Source/WhistleFactory.swift | 4 | 5595 | import UIKit
public enum WhistleAction {
case present
case show(TimeInterval)
}
let whistleFactory = WhistleFactory()
open class WhistleFactory: UIViewController {
open lazy var whistleWindow: UIWindow = UIWindow()
public struct Dimensions {
static var notchHeight: CGFloat {
if UIApplication.shared.statusBarFrame.height > 20 {
return 32.0
} else {
return 0.0
}
}
}
open lazy var titleLabelHeight = CGFloat(20.0)
open lazy var titleLabel: UILabel = {
let label = UILabel()
label.textAlignment = .center
return label
}()
open fileprivate(set) lazy var tapGestureRecognizer: UITapGestureRecognizer = { [unowned self] in
let gesture = UITapGestureRecognizer()
gesture.addTarget(self, action: #selector(WhistleFactory.handleTapGestureRecognizer))
return gesture
}()
open fileprivate(set) var murmur: Murmur?
open var viewController: UIViewController?
open var hideTimer = Timer()
private weak var previousKeyWindow: UIWindow?
// MARK: - Initializers
override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
super.init(nibName: nil, bundle: nil)
setupWindow()
view.clipsToBounds = true
view.addSubview(titleLabel)
view.addGestureRecognizer(tapGestureRecognizer)
NotificationCenter.default.addObserver(self, selector: #selector(WhistleFactory.orientationDidChange), name: NSNotification.Name.UIDeviceOrientationDidChange, object: nil)
}
public required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
deinit {
NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIDeviceOrientationDidChange, object: nil)
}
// MARK: - Configuration
open func whistler(_ murmur: Murmur, action: WhistleAction) {
self.murmur = murmur
titleLabel.text = murmur.title
titleLabel.font = murmur.font
titleLabel.textColor = murmur.titleColor
view.backgroundColor = murmur.backgroundColor
whistleWindow.backgroundColor = murmur.backgroundColor
moveWindowToFront()
setupFrames()
switch action {
case .show(let duration):
show(duration: duration)
default:
present()
}
}
// MARK: - Setup
open func setupWindow() {
whistleWindow.addSubview(self.view)
whistleWindow.clipsToBounds = true
moveWindowToFront()
}
func moveWindowToFront() {
whistleWindow.windowLevel = view.isiPhoneX ? UIWindowLevelNormal : UIWindowLevelStatusBar
setNeedsStatusBarAppearanceUpdate()
}
open override var preferredStatusBarStyle: UIStatusBarStyle {
return UIApplication.shared.statusBarStyle
}
open func setupFrames() {
whistleWindow = UIWindow()
setupWindow()
let labelWidth = UIScreen.main.bounds.width
let defaultHeight = titleLabelHeight
if let text = titleLabel.text {
let neededDimensions =
NSString(string: text).boundingRect(
with: CGSize(width: labelWidth, height: CGFloat.infinity),
options: NSStringDrawingOptions.usesLineFragmentOrigin,
attributes: [NSAttributedStringKey.font: titleLabel.font],
context: nil
)
titleLabelHeight = CGFloat(neededDimensions.size.height)
titleLabel.numberOfLines = 0 // Allows unwrapping
if titleLabelHeight < defaultHeight {
titleLabelHeight = defaultHeight
}
} else {
titleLabel.sizeToFit()
}
whistleWindow.frame = CGRect(x: 0, y: 0,
width: labelWidth,
height: titleLabelHeight + Dimensions.notchHeight)
view.frame = whistleWindow.bounds
titleLabel.frame = CGRect(
x: 0.0,
y: Dimensions.notchHeight,
width: view.bounds.width,
height: titleLabelHeight
)
}
// MARK: - Movement methods
public func show(duration: TimeInterval) {
present()
calm(after: duration)
}
public func present() {
hideTimer.invalidate()
if UIApplication.shared.keyWindow != whistleWindow {
previousKeyWindow = UIApplication.shared.keyWindow
}
let initialOrigin = whistleWindow.frame.origin.y
whistleWindow.frame.origin.y = initialOrigin - titleLabelHeight - Dimensions.notchHeight
whistleWindow.isHidden = false
UIView.animate(withDuration: 0.2, animations: {
self.whistleWindow.frame.origin.y = initialOrigin
})
}
public func hide() {
let finalOrigin = view.frame.origin.y - titleLabelHeight - Dimensions.notchHeight
UIView.animate(withDuration: 0.2, animations: {
self.whistleWindow.frame.origin.y = finalOrigin
}, completion: { _ in
if let window = self.previousKeyWindow {
window.isHidden = false
self.whistleWindow.windowLevel = UIWindowLevelNormal - 1
self.previousKeyWindow = nil
window.rootViewController?.setNeedsStatusBarAppearanceUpdate()
}
})
}
public func calm(after: TimeInterval) {
hideTimer.invalidate()
hideTimer = Timer.scheduledTimer(timeInterval: after, target: self, selector: #selector(WhistleFactory.timerDidFire), userInfo: nil, repeats: false)
}
// MARK: - Timer methods
@objc public func timerDidFire() {
hide()
}
@objc func orientationDidChange() {
if whistleWindow.isKeyWindow {
setupFrames()
hide()
}
}
// MARK: - Gesture methods
@objc fileprivate func handleTapGestureRecognizer() {
guard let murmur = murmur else { return }
murmur.action?()
}
}
| mit | 31fe5d9db2f6ce47adad1aa1f9c28d6c | 26.160194 | 175 | 0.685255 | 4.839965 | false | false | false | false |
iSapozhnik/SILoadingControllerDemo | LoadingControllerDemo/LoadingControllerDemo/LoadingController/Views/LoadingViews/StrokeLoadingView.swift | 1 | 1196 | //
// StrokeLoadingView.swift
// LoadingControllerDemo
//
// Created by Sapozhnik Ivan on 28.06.16.
// Copyright © 2016 Sapozhnik Ivan. All rights reserved.
//
import UIKit
class StrokeLoadingView: LoadingView, Animatable {
var activity = StrokeActivityView()
var strokeColor = UIColor.darkGrayColor() {
didSet(color) {
activity.strokeColor = color
}
}
override init(frame: CGRect) {
super.init(frame: frame)
defaultInitializer()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
defaultInitializer()
}
private func defaultInitializer() {
backgroundColor = UIColor(white: 0.9, alpha: 1.0)
let size = defaultActivitySize
activity.frame = CGRectMake(0, 0, size.width, size.height)
addSubview(activity)
}
override func layoutSubviews() {
super.layoutSubviews()
activity.center = CGPointMake(CGRectGetMidX(bounds), CGRectGetMidY(bounds))
}
func startAnimating() {
let delay = 0.0 * Double(NSEC_PER_SEC)
let time = dispatch_time(DISPATCH_TIME_NOW, Int64(delay))
dispatch_after(time, dispatch_get_main_queue(), {
self.activity.animating = true
})
}
func stopAnimating() {
activity.animating = false
}
}
| mit | 05b8163d3a9e63642108c1264c3067c0 | 21.12963 | 77 | 0.711297 | 3.483965 | false | false | false | false |
javierlopeza/VerboAppiOS | Verbo Tabs/Colegio.swift | 1 | 6496 | //
// cursos.swift
// Verbo Tabs
//
// Created by Javier López Achondo on 05-01-16.
// Copyright © 2016 Javier López Achondo. All rights reserved.
//
import Foundation
public class Colegio {
// Lista de Cursos del Colegio
class func cursos_horario() -> [String] {
let lista_cursos = ["Pre Kinder A", "Pre Kinder B", "Pre Kinder C", "Pre Kinder D", "Pre Kinder E",
"Kinder A", "Kinder B", "Kinder C", "Kinder D", "Kinder E",
"1º Básico A", "1º Básico B", "1º Básico C", "1º Básico D", "1º Básico E",
"2º Básico A", "2º Básico B", "2º Básico C", "2º Básico D", "2º Básico E",
"3º Básico A", "3º Básico B", "3º Básico C", "3º Básico D", "3º Básico E",
"4º Básico A", "4º Básico B", "4º Básico C", "4º Básico D",
"5º Básico A", "5º Básico B", "5º Básico C", "5º Básico D",
"6º Básico A", "6º Básico B", "6º Básico C", "6º Básico D",
"7º Básico A", "7º Básico B", "7º Básico C", "7º Básico D",
"8º Básico A", "8º Básico B", "8º Básico C", "8º Básico D",
"1º Medio A", "1º Medio B", "1º Medio C", "1º Medio D",
"2º Medio A", "2º Medio B", "2º Medio C", "2º Medio D",
"3º Medio A", "3º Medio B", "3º Medio C", "3º Medio D", "3º Medio E",
"4º Medio A", "4º Medio B", "4º Medio C", "4º Medio D", "4º Medio E"]
return lista_cursos
}
// Lista de cursos con calendario
class func cursos_calendario() -> [String] {
let lista_cursos = [
"1º Básico A", "1º Básico B", "1º Básico C", "1º Básico D", "1º Básico E",
"2º Básico A", "2º Básico B", "2º Básico C", "2º Básico D", "2º Básico E",
"3º Básico A", "3º Básico B", "3º Básico C", "3º Básico D", "3º Básico E",
"4º Básico A", "4º Básico B", "4º Básico C", "4º Básico D",
"5º Básico A", "5º Básico B", "5º Básico C", "5º Básico D",
"6º Básico A", "6º Básico B", "6º Básico C", "6º Básico D",
"7º Básico A", "7º Básico B", "7º Básico C", "7º Básico D",
"8º Básico A", "8º Básico B", "8º Básico C", "8º Básico D",
"1º Medio A", "1º Medio B", "1º Medio C", "1º Medio D",
"2º Medio A", "2º Medio B", "2º Medio C", "2º Medio D",
"3º Medio A", "3º Medio B", "3º Medio C", "3º Medio D", "3º Medio E",
"4º Medio A", "4º Medio B", "4º Medio C", "4º Medio D", "4º Medio E"]
return lista_cursos
}
// Recibe un curso y retorna el URL de su Horario como String
class func cursoHorarioURL(curso_seleccionado : String) -> String {
if curso_seleccionado.rangeOfString("Kinder") != nil {
let curso_str = curso_seleccionado.lowercaseString.stringByReplacingOccurrencesOfString(" ", withString: "")
let url_str = "http://www.cvd.cl/wp-content/uploads/2014/10/" + curso_str + "_1.pdf"
return url_str
}
if curso_seleccionado.rangeOfString("Básico") != nil {
var curso_str = curso_seleccionado
.stringByReplacingOccurrencesOfString("º", withString: "")
.stringByReplacingOccurrencesOfString("á", withString: "a")
.stringByReplacingOccurrencesOfString(" ", withString: "_")
if ((curso_seleccionado.rangeOfString("1") != nil)||(curso_seleccionado.rangeOfString("2") != nil)||(curso_seleccionado.rangeOfString("3") != nil)||(curso_seleccionado.rangeOfString("4") != nil)) {
curso_str = curso_str.stringByReplacingOccurrencesOfString("1", withString: "I")
.stringByReplacingOccurrencesOfString("2", withString: "II")
.stringByReplacingOccurrencesOfString("3", withString: "III")
.stringByReplacingOccurrencesOfString("4", withString: "IV")
let url_str = "http://www.cvd.cl/wp-content/uploads/2014/10/" + curso_str + "_2015.pdf"
return url_str
}
else {
curso_str = curso_str.stringByReplacingOccurrencesOfString("5", withString: "V")
.stringByReplacingOccurrencesOfString("6", withString: "VI")
.stringByReplacingOccurrencesOfString("7", withString: "VII")
.stringByReplacingOccurrencesOfString("8", withString: "VIII")
let url_str = "http://www.cvd.cl/wp-content/uploads/2014/10/" + curso_str + "_20151.pdf"
return url_str
}
}
if curso_seleccionado.rangeOfString("Medio") != nil {
let curso_str = curso_seleccionado.stringByReplacingOccurrencesOfString("º", withString: "").stringByReplacingOccurrencesOfString(" ", withString: "_").uppercaseString
let url_str = "http://www.cvd.cl/wp-content/uploads/2014/10/" + curso_str + "_20151.pdf"
return url_str
}
return "none"
}
// Recibe un curso y retorna el URL de su Calendario como String
class func cursoCalendarioURL(curso_seleccionado : String) -> String {
if (curso_seleccionado.rangeOfString("Básico") != nil){
let sigla = curso_seleccionado.stringByReplacingOccurrencesOfString(" ", withString: "").stringByReplacingOccurrencesOfString("ºBásico", withString: "b").lowercaseString
if Int(String(curso_seleccionado[curso_seleccionado.startIndex.advancedBy(0)])) <= 4 {
let ciclo = "bas1"
let url = "http://www.cvd-colegio.cl/intranet/escolar/" + ciclo + "/" + sigla + "/Lists/Calendario/calendar.aspx"
return url
}
else {
let ciclo = "bas2"
let url = "http://www.cvd-colegio.cl/intranet/escolar/" + ciclo + "/" + sigla + "/Lists/Calendario/calendar.aspx"
return url
}
}
else if (curso_seleccionado.rangeOfString("Medio") != nil){
let sigla = curso_seleccionado.stringByReplacingOccurrencesOfString(" ", withString: "").stringByReplacingOccurrencesOfString("ºMedio", withString: "m").lowercaseString
let url = "http://www.cvd-colegio.cl/intranet/escolar/emedia/" + sigla + "/Lists/Calendario/calendar.aspx"
return url
}
return "none"
}
}
| cc0-1.0 | fc548d81c36fbf97f9fbb98444a10d1e | 52.466102 | 209 | 0.573308 | 3.242035 | false | false | false | false |
thelowlypeon/bikeshare-kit | BikeshareKit/BikeshareKit/Sync/BSServiceSync.swift | 1 | 3027 | //
// BSServiceSync.swift
// BikeshareKit
//
// Created by Peter Compernolle on 12/19/15.
// Copyright © 2015 Out of Something, LLC. All rights reserved.
//
import Foundation
extension BSManager {
public func syncServices(_ callback: ((Error?) -> Void)? = nil) {
print("Syncing services...")
BSRouter.services.request(self.syncServicesCompletionHandler(callback))
}
internal func syncServicesCompletionHandler(_ callback: ((Error?) -> Void)? = nil) -> ((Data?, URLResponse?, Error?) -> Void) {
return {[weak self](data, response, error) in
guard let `self` = self else { return }
if error != nil {
callback?(error)
} else if let failure = BSRouter.validateResponse(data, response: response) {
callback?(failure)
} else {
do {
let json = try JSONSerialization.jsonObject(with: data!, options: .allowFragments)
callback?(self.handleSuccessResponse(json as AnyObject?))
} catch {
callback?(BSErrorType.InvalidResponse)
}
}
}
}
internal func handleSuccessResponse(_ JSON: Any?) -> Error? {
if let json = (JSON as? NSArray) as? [NSDictionary] {
let retrievedServices = Set(json.map{BSService(data: $0)}.filter{$0 != nil}.map{$0!})
print("initial count: \(self.services.count), retrieved \(retrievedServices.count)")
//determine new services, add at the end
let servicesToAdd = retrievedServices.subtracting(self.services)
print("found \(servicesToAdd.count) services to add")
//remove old
let servicesToRemove = self.services.subtracting(retrievedServices)
self.services.subtract(servicesToRemove)
print("just removed outdated services. current count: \(self.services.count)")
//update existing
let servicesToUpdate = retrievedServices.intersection(self.services)
print("updating \(servicesToUpdate.count) services")
for rhs in servicesToUpdate {
let index = self.services.index(of: rhs)!
self.services[index].replace(withService: rhs)
}
//add new
print("adding \(servicesToAdd.count) services")
self.services.formUnion(servicesToAdd)
print("final count: \(self.services.count)")
self.refreshFavoriteService()
servicesUpdatedAt = Date()
return nil
} else {
return BSErrorType.InvalidResponse
}
}
internal func refreshFavoriteService() {
if self.favoriteService != nil {
if let index = self.services.index(of: self.favoriteService!) {
self.favoriteService!.replace(withService: self.services[index])
} else {
self.favoriteService = nil
}
}
}
}
| mit | b4a85ae2bc6cf39cfb80ba811b745b03 | 34.6 | 131 | 0.582617 | 4.810811 | false | false | false | false |
yura-voevodin/personal-website-on-swift | Sources/App/Middlewares/MySessionsMiddleware.swift | 1 | 1020 | //
// MySessionsMiddleware.swift
// PersonalWebSiteOnSwift
//
// Created by Yura Voevodin on 21.05.17.
//
//
import HTTP
final class MySessionsMiddleware: Middleware {
func respond(to request: Request, chainingTo next: Responder) throws -> Response {
let response = try next.respond(to: request)
if let (day, month, year) = Date().calendarComponents {
do {
if let session = try Session.makeQuery()
.filter("year", year)
.filter("month", month)
.filter("day", day)
.first() {
session.requests += 1
try session.save()
} else {
let newSession = Session(day: day, month: month, year: year, requests: 1)
try newSession.save()
}
} catch {
print(error.localizedDescription)
}
}
return response
}
}
| mit | d431293b564de080b59e659ebbe10504 | 27.333333 | 93 | 0.486275 | 4.811321 | false | false | false | false |
mrdepth/Neocom | Neocom/Neocom/Home/Combine+Extensions.swift | 2 | 5779 | //
// Combine+Extensions.swift
// Neocom
//
// Created by Artem Shimanski on 11/22/19.
// Copyright © 2019 Artem Shimanski. All rights reserved.
//
import Foundation
import Combine
import CoreData
extension Publisher where Failure: Error {
func asResult() -> Publishers.Catch<Publishers.Map<Self, Result<Self.Output, Self.Failure>>, Just<Result<Self.Output, Self.Failure>>> {
return map{Result.success($0)}.catch{Just(Result.failure($0))}
}
}
extension Publisher {
func tryGet<S, F: Error>() -> Publishers.MapError<Publishers.TryMap<Self, S>, F> where Output == Result<S, F>, Failure == Never {
tryMap {try $0.get()}.mapError{$0 as! F}
}
}
extension Result {
var value: Success? {
switch self {
case let .success(value):
return value
default:
return nil
}
}
var error: Failure? {
switch self {
case let .failure(error):
return error
default:
return nil
}
}
}
extension NSManagedObjectContext: Scheduler {
public func schedule(after date: DispatchQueue.SchedulerTimeType, interval: DispatchQueue.SchedulerTimeType.Stride, tolerance: DispatchQueue.SchedulerTimeType.Stride, options: SchedulerOptions?, _ action: @escaping () -> Void) -> Cancellable {
DispatchQueue.main.schedule(after: date, interval: interval, tolerance: tolerance, options: nil) {
self.perform(action)
}
}
public func schedule(after date: DispatchQueue.SchedulerTimeType, tolerance: DispatchQueue.SchedulerTimeType.Stride, options: SchedulerOptions?, _ action: @escaping () -> Void) {
DispatchQueue.main.schedule(after: date, tolerance: tolerance, options: nil) {
self.perform(action)
}
}
public func schedule(options: SchedulerOptions?, _ action: @escaping () -> Void) {
self.perform(action)
}
public var now: DispatchQueue.SchedulerTimeType {
DispatchQueue.main.now
}
public var minimumTolerance: DispatchQueue.SchedulerTimeType.Stride {
DispatchQueue.main.minimumTolerance
}
public typealias SchedulerTimeType = DispatchQueue.SchedulerTimeType
public typealias SchedulerOptions = Never
}
extension Progress {
func performAsCurrent<ReturnType>(withPendingUnitCount unitCount: Int64, totalUnitCount: Int64, using work: (Progress) throws -> ReturnType) rethrows -> ReturnType {
try performAsCurrent(withPendingUnitCount: unitCount) {
try work(Progress(totalUnitCount: totalUnitCount))
}
}
}
struct FileChangesPublisher: Publisher {
typealias Output = Void
typealias Failure = RuntimeError
var path: String
var eventMask: DispatchSource.FileSystemEvent = .all
func receive<S>(subscriber: S) where S : Subscriber, Self.Failure == S.Failure, Self.Output == S.Input {
subscriber.receive(subscription: FileChangesPublisherSubscription(subscriber: subscriber, path: path, eventMask: eventMask))
}
private class FileChangesPublisherSubscription<S: Subscriber>: Subscription where S.Failure == Failure, S.Input == Output {
var source: DispatchSourceFileSystemObject?
func cancel() {
source?.cancel()
source = nil
}
private var demand = Subscribers.Demand.none
private var parentFolderSubscription: AnyCancellable?
private func makeSource() -> DispatchSourceFileSystemObject? {
let fd = open(path, O_EVTONLY)
guard fd >= 0 else {return nil}
let source = DispatchSource.makeFileSystemObjectSource(fileDescriptor: fd, eventMask: eventMask, queue: .main)
source.setCancelHandler {
close(fd)
}
source.setEventHandler { [weak self] in
guard let strongSelf = self else {return}
if strongSelf.demand > 0 {
strongSelf.demand -= 1
strongSelf.demand += strongSelf.subscriber.receive()
}
}
source.resume()
return source
}
func request(_ demand: Subscribers.Demand) {
self.demand = demand
if source == nil {
if let source = makeSource() {
self.source = source
}
else {
let path = URL(fileURLWithPath: self.path).deletingLastPathComponent().path
guard path != "/" else {
subscriber.receive(completion: .failure(RuntimeError.fileNotFound(path)))
return
}
parentFolderSubscription = FileChangesPublisher(path: path).sink(receiveCompletion: { [weak self] (completion) in
if case .failure = completion {
self?.subscriber.receive(completion: completion)
}
}) { [weak self] () in
if let source = self?.makeSource() {
self?.source = source
_ = self?.subscriber.receive(())
self?.parentFolderSubscription = nil
}
}
}
}
}
var subscriber: S
var path: String
var eventMask: DispatchSource.FileSystemEvent
init(subscriber: S, path: String, eventMask: DispatchSource.FileSystemEvent) {
self.subscriber = subscriber
self.path = path
self.eventMask = eventMask
}
}
}
| lgpl-2.1 | e618acac8859ee2c0e80856337910ccc | 33.392857 | 247 | 0.587054 | 5.191375 | false | false | false | false |
Eonil/ImageCacheUtility.Swift | ImageCacheUtilityTestdrive/ViewController.swift | 1 | 1178 | //
// ViewController.swift
// ImageCacheUtilityTestdrive
//
// Created by Hoon H. on 2015/12/06.
// Copyright © 2015 Eonil. All rights reserved.
//
import UIKit
import ImageCacheUtility
import ImageCacheUtilityUI
class ViewController: UIViewController {
// let cache = InMemoryImageCache(configuration: GenerationalCacheConfiguration(segmentSize: 16, maxSegmentCount: 16, maxTotalCount: 128))
let imageView = AutoresamplingImageView()
let addrDisp = ImageAddressDisplayController()
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = UIColor.whiteColor()
view.addSubview(imageView)
addrDisp.imageView = imageView
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
imageView.frame = UIEdgeInsetsInsetRect(view.bounds, UIEdgeInsets(top: 20 + 44 + 30, left: 30, bottom: 30, right: 30))
imageView.backgroundColor = UIColor.grayColor()
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
addrDisp.URL = NSURL(string: "https://placehold.it/350x150")
addrDisp.URL = NSURL(string: "https://placehold.it/400x400")
addrDisp.URL = NSURL(string: "https://placehold.it/350x150")
}
}
| mit | e96c5d57b98ac9dd5801ac132377a06d | 30.810811 | 138 | 0.761257 | 3.809061 | false | true | false | false |
audiokit/AudioKit | Sources/AudioKit/Nodes/Mixing/StereoFieldLimiter.swift | 1 | 2149 | // Copyright AudioKit. All Rights Reserved. Revision History at http://github.com/AudioKit/AudioKit/
import AVFoundation
import CAudioKit
/// Stereo StereoFieldLimiter
///
public class StereoFieldLimiter: Node, AudioUnitContainer, Toggleable {
/// Unique four-letter identifier "sflm"
public static let ComponentDescription = AudioComponentDescription(effect: "sflm")
/// Internal type of audio unit for this node
public typealias AudioUnitType = InternalAU
/// Internal audio unit
public private(set) var internalAU: AudioUnitType?
// MARK: - Properties
/// Specification details for amount
public static let amountDef = NodeParameterDef(
identifier: "amount",
name: "Limiting amount",
address: akGetParameterAddress("StereoFieldLimiterParameterAmount"),
range: 0.0...1.0,
unit: .generic,
flags: .default)
/// Limiting Factor
@Parameter public var amount: AUValue
// MARK: - Audio Unit
/// Internal audio unit for stereo field limiter
public class InternalAU: AudioUnitBase {
/// Get an array of the parameter definitions
/// - Returns: Array of parameter definitions
public override func getParameterDefs() -> [NodeParameterDef] {
[StereoFieldLimiter.amountDef]
}
/// Create stereo field limiter DSP
/// - Returns: DSP Reference
public override func createDSP() -> DSPRef {
akCreateDSP("StereoFieldLimiterDSP")
}
}
// MARK: - Initialization
/// Initialize this stereo field limiter node
///
/// - Parameters:
/// - input: Node whose output will be amplified
/// - amount: limit factor (Default: 1, Minimum: 0)
///
public init(_ input: Node, amount: AUValue = 1) {
super.init(avAudioNode: AVAudioNode())
instantiateAudioUnit { avAudioUnit in
self.avAudioUnit = avAudioUnit
self.avAudioNode = avAudioUnit
self.internalAU = avAudioUnit.auAudioUnit as? AudioUnitType
self.amount = amount
}
connections.append(input)
}
}
| mit | 9d49d5984d0ae863a057b7d85839d77e | 29.7 | 100 | 0.649604 | 5.141148 | false | false | false | false |
oskarpearson/rileylink_ios | MinimedKit/Messages/MeterMessage.swift | 1 | 1028 | //
// MeterMessageBody.swift
// RileyLink
//
// Created by Pete Schwamb on 3/10/16.
// Copyright © 2016 Pete Schwamb. All rights reserved.
//
import Foundation
public class MeterMessage {
let length = 7
public let glucose: Int
public let ackFlag: Bool
let rxData: Data
public required init?(rxData: Data) {
self.rxData = rxData
if rxData.count == length,
let packetType = PacketType(rawValue: rxData[0]), packetType == .meter
{
let flags = ((rxData[4] as UInt8) & 0b110) >> 1
ackFlag = flags == 0x03
glucose = Int((rxData[4] as UInt8) & 0b1) << 8 + Int(rxData[4] as UInt8)
} else {
ackFlag = false
glucose = 0
return nil
}
}
public var txData: Data {
return rxData
}
public var dictionaryRepresentation: [String: Any] {
return [
"glucose": glucose,
"ackFlag": ackFlag,
]
}
}
| mit | 60f7dcff9ca9a1da76ff66dcfa3629d5 | 21.822222 | 84 | 0.529698 | 4.043307 | false | false | false | false |
AlesTsurko/AudioKit | Tests/Tests/AKMoogLadder.swift | 2 | 1789 | //
// main.swift
// AudioKit
//
// Created by Nick Arner and Aurelius Prochazka on 12/21/14.
// Copyright (c) 2014 Aurelius Prochazka. All rights reserved.
//
import Foundation
let testDuration: Float = 10.0
class Instrument : AKInstrument {
var auxilliaryOutput = AKAudio()
override init() {
super.init()
let phasor = AKPhasor()
auxilliaryOutput = AKAudio.globalParameter()
assignOutput(auxilliaryOutput, to:phasor)
}
}
class Processor : AKInstrument {
init(audioSource: AKAudio) {
super.init()
let resonance = AKLine(
firstPoint: 0.1.ak,
secondPoint: 1.0.ak,
durationBetweenPoints: testDuration.ak
)
let cutoffFrequency = AKLine(
firstPoint: 100.ak,
secondPoint: 10000.ak,
durationBetweenPoints: testDuration.ak
)
let moogLadder = AKMoogLadder(input: audioSource)
moogLadder.resonance = resonance
moogLadder.cutoffFrequency = cutoffFrequency
setAudioOutput(moogLadder)
enableParameterLog(
"Resonance = ",
parameter: moogLadder.resonance,
timeInterval:0.2
)
enableParameterLog(
"Cutoff Frequency = ",
parameter: moogLadder.cutoffFrequency,
timeInterval:0.2
)
resetParameter(audioSource)
}
}
AKOrchestra.testForDuration(testDuration)
let instrument = Instrument()
let processor = Processor(audioSource: instrument.auxilliaryOutput)
AKOrchestra.addInstrument(instrument)
AKOrchestra.addInstrument(processor)
processor.play()
instrument.play()
let manager = AKManager.sharedManager()
while(manager.isRunning) {} //do nothing
println("Test complete!")
| lgpl-3.0 | a0c57d9eca99bbc17e8a6fa3fd1da907 | 22.233766 | 67 | 0.641699 | 4.969444 | false | true | false | false |
maryamfekri/MFCameraManager | CustomCameraManagerClass/ScanBarcodeCameraManager.swift | 1 | 16533 | //
// ScanBarcodeCameraManager.swift
// sampleCameraManager
//
// Created by Maryam on 3/3/17.
// Copyright © 2017 Maryam. All rights reserved.
//
import Foundation
import AVFoundation
import UIKit
open class ScanBarcodeCameraManager: NSObject, AVCaptureMetadataOutputObjectsDelegate {
private var cameraPosition: CameraDevice?
private var cameraView: UIView?
weak private var previewLayer: AVCaptureVideoPreviewLayer!
//Private variables that cannot be accessed by other classes in any way.
fileprivate var metaDataOutput: AVCaptureMetadataOutput?
fileprivate var stillImageOutput: AVCaptureStillImageOutput?
fileprivate var captureSession: AVCaptureSession!
weak var delegate: ScanBarcodeCameraManagerDelegate?
private var captureDevice: AVCaptureDevice!
private var isFocusMode = false
private var isAutoUpdateLensPosition = false
private var lensPosition: Float = 0
private var isBusy = false
private var focusMarkLayer = FocusMarker()
private var focusLine = FocusLine()
private var imageOrientation: UIImageOrientation {
let currentDevice: UIDevice = UIDevice.current
let orientation: UIDeviceOrientation = currentDevice.orientation
if self.cameraPosition == .back {
switch orientation {
case .portrait:
return .right
case .portraitUpsideDown:
return .left
case .landscapeRight:
return .down
case .landscapeLeft:
return .up
default:
return .right
}
} else {
switch orientation {
case .portrait:
return .leftMirrored
case .portraitUpsideDown:
return .rightMirrored
case .landscapeRight:
return .upMirrored
case .landscapeLeft:
return .downMirrored
default:
return .leftMirrored
}
}
}
open func startRunning() {
if captureSession?.isRunning != true {
captureSession.startRunning()
}
}
open func stopRunning() {
if captureSession?.isRunning == true {
captureSession.stopRunning()
}
}
open func updatePreviewFrame() {
if cameraView != nil {
self.previewLayer?.frame = cameraView!.bounds
self.focusMarkLayer.frame = cameraView!.bounds
self.focusLine.frame = cameraView!.bounds
}
}
open func transitionCamera() {
if let connection = self.previewLayer?.connection {
let currentDevice: UIDevice = UIDevice.current
let orientation: UIDeviceOrientation = currentDevice.orientation
let previewLayerConnection: AVCaptureConnection = connection
if previewLayerConnection.isVideoOrientationSupported {
switch orientation {
case .portrait:
previewLayerConnection.videoOrientation = AVCaptureVideoOrientation.portrait
case .landscapeRight:
previewLayerConnection.videoOrientation = AVCaptureVideoOrientation.landscapeLeft
case .landscapeLeft:
previewLayerConnection.videoOrientation = AVCaptureVideoOrientation.landscapeRight
case .portraitUpsideDown:
previewLayerConnection.videoOrientation = AVCaptureVideoOrientation.portraitUpsideDown
default:
previewLayerConnection.videoOrientation = AVCaptureVideoOrientation.portrait
}
}
}
}
func autoUpdateLensPosition() {
self.lensPosition += 0.01
if self.lensPosition > 1 {
self.lensPosition = 0
}
if let device = self.captureDevice {
do {
try device.lockForConfiguration()
device.setFocusModeLocked(lensPosition: self.lensPosition, completionHandler: nil)
device.unlockForConfiguration()
} catch _ {
}
}
if captureSession.isRunning {
let when = DispatchTime.now() + Double(Int64(10 * Double(USEC_PER_SEC))) / Double(NSEC_PER_SEC)
DispatchQueue.main.asyncAfter(deadline: when, execute: {
self.autoUpdateLensPosition()
})
}
}
@objc func onTap(_ gesture: UITapGestureRecognizer) {
let tapPoint = gesture.location(in: self.cameraView)
let focusPoint = CGPoint(
x: tapPoint.x / self.cameraView!.bounds.size.width,
y: tapPoint.y / self.cameraView!.bounds.size.height)
if let device = self.captureDevice {
do {
try device.lockForConfiguration()
if device.isFocusPointOfInterestSupported {
device.focusPointOfInterest = focusPoint
} else {
print("Focus point of interest not supported.")
}
if self.isFocusMode {
if device.isFocusModeSupported(.locked) {
device.focusMode = .locked
} else {
print("Locked focus not supported.")
}
if !self.isAutoUpdateLensPosition {
self.isAutoUpdateLensPosition = true
DispatchQueue.main.async(execute: { () -> Void in
self.autoUpdateLensPosition()
})
}
} else {
if device.isFocusModeSupported(.continuousAutoFocus) {
device.focusMode = .continuousAutoFocus
} else if device.isFocusModeSupported(.autoFocus) {
device.focusMode = .autoFocus
} else {
print("Auto focus not supported.")
}
}
if device.isAutoFocusRangeRestrictionSupported {
device.autoFocusRangeRestriction = .none
} else {
print("Auto focus range restriction not supported.")
}
device.unlockForConfiguration()
self.focusMarkLayer.point = tapPoint
} catch _ {
}
}
}
open func enableTorchMode(with level: Float) {
for testedDevice in AVCaptureDevice.devices(for: AVMediaType.video) {
if (testedDevice as AnyObject).position == AVCaptureDevice.Position.back
&& self.cameraPosition == .back {
let currentDevice = testedDevice
if currentDevice.isTorchAvailable
&& currentDevice.isTorchModeSupported(AVCaptureDevice.TorchMode.auto) {
do {
try currentDevice.lockForConfiguration()
if currentDevice.isTorchActive {
currentDevice.torchMode = AVCaptureDevice.TorchMode.off
} else {
try currentDevice.setTorchModeOn(level: level)
}
currentDevice.unlockForConfiguration()
} catch {
print("torch can not be enable")
}
}
}
}
}
open func getImage(croppWith rect: CGRect? = nil,
completion: @escaping MFCameraMangerCompletion) {
guard let videoConnection = stillImageOutput?.connection(with: .video) else {
completion(nil, MFCameraError.noVideoConnection)
return
}
stillImageOutput?
.captureStillImageAsynchronously(from: videoConnection) { (imageDataSampleBuffer, error) -> Void in
guard let imageDataSampleBuffer = imageDataSampleBuffer,
let imageData = AVCaptureStillImageOutput.jpegStillImageNSDataRepresentation(imageDataSampleBuffer),
let capturedImage: UIImage = UIImage(data: imageData) else {
completion(nil, MFCameraError.noImageCapture)
return
}
// The image returned in initialImageData will be larger than what
// is shown in the AVCaptureVideoPreviewLayer, so we need to crop it.
do {
let croppedImage = try self.crop(image: capturedImage,
withRect: rect ?? self.cameraView?.frame ?? .zero)
completion(croppedImage, error)
} catch {
completion(nil, error)
}
}
}
private func crop(image: UIImage, withRect rect: CGRect) throws -> UIImage {
let originalSize: CGSize
// Calculate the fractional size that is shown in the preview
guard let metaRect = previewLayer?.metadataOutputRectConverted(fromLayerRect: rect) else {
throw MFCameraError.noMetaRect
}
if image.imageOrientation == UIImageOrientation.left
|| image.imageOrientation == UIImageOrientation.right {
// For these images (which are portrait), swap the size of the
// image, because here the output image is actually rotated
// relative to what you see on screen.
originalSize = CGSize(width: image.size.height,
height: image.size.width)
} else {
originalSize = image.size
}
let x = metaRect.origin.x * originalSize.width
let y = metaRect.origin.y * originalSize.height
// metaRect is fractional, that's why we multiply here.
let cropRect: CGRect = CGRect( x: x,
y: y,
width: metaRect.size.width * originalSize.width,
height: metaRect.size.height * originalSize.height).integral
guard let cropedCGImage = image.cgImage?.cropping(to: cropRect) else {
throw MFCameraError.crop
}
return UIImage(cgImage: cropedCGImage,
scale: 1,
orientation: imageOrientation)
}
open func captureSetup(in cameraView: UIView, with cameraPosition: AVCaptureDevice.Position? = .back) throws {
self.cameraView = cameraView
self.captureSession = AVCaptureSession()
switch cameraPosition! {
case .back:
try captureSetup(withDevicePosition: .back)
self.cameraPosition = .back
case .front:
try captureSetup(withDevicePosition: .front)
self.cameraPosition = .front
default:
try captureSetup(withDevicePosition: .back)
}
let tapGestureRecognizer = UITapGestureRecognizer(target: self,
action: #selector(ScanBarcodeCameraManager.onTap(_:)))
self.cameraView?.addGestureRecognizer(tapGestureRecognizer)
}
private func getDevice(withPosition position: AVCaptureDevice.Position) throws -> AVCaptureDevice {
if #available(iOS 10.0, *) {
guard let device = AVCaptureDevice.default(.builtInWideAngleCamera, for: .video, position: position) else {
throw MFCameraError.noDevice
}
return device
} else {
guard let device = AVCaptureDevice
.devices(for: .video)
.first(where: {device in
device.position == position
}) else {
throw MFCameraError.noDevice
}
return device
}
}
/**
this func will setup the camera and capture session and add to cameraView
*/
fileprivate func captureSetup(withDevicePosition position: AVCaptureDevice.Position) throws {
captureSession.stopRunning()
captureSession = AVCaptureSession()
previewLayer?.removeFromSuperlayer()
// device
let captureDevice: AVCaptureDevice = try getDevice(withPosition: position)
//Input
let deviceInput = try AVCaptureDeviceInput(device: captureDevice)
//Output
metaDataOutput = AVCaptureMetadataOutput()
// Remove previous added inputs from session
if self.metaDataOutput?.metadataObjectsDelegate == nil
|| self.metaDataOutput?.metadataObjectsCallbackQueue == nil {
let queue = DispatchQueue(label: "com.pdq.rsbarcodes.metadata",
attributes: .concurrent)
self.metaDataOutput?.setMetadataObjectsDelegate(self, queue: queue)
}
// Remove previous added outputs from session
var metadataObjectTypes: [AnyObject]?
for output in self.captureSession.outputs {
metadataObjectTypes = (output as AnyObject).metadataObjectTypes as [AnyObject]?
self.captureSession.removeOutput(output )
}
//Output stillImage
self.stillImageOutput = AVCaptureStillImageOutput()
self.stillImageOutput?.outputSettings = [AVVideoCodecKey: AVVideoCodecJPEG]
if captureSession.canAddInput(deviceInput) {
captureSession.addInput(deviceInput)
}
if self.captureSession.canAddOutput(self.metaDataOutput!) {
self.captureSession.addOutput(self.metaDataOutput!)
if let metadataObjectTypes = metadataObjectTypes as? [AVMetadataObject.ObjectType] {
self.metaDataOutput?.metadataObjectTypes = metadataObjectTypes
} else {
self.metaDataOutput?.metadataObjectTypes = self.metaDataOutput?.availableMetadataObjectTypes
}
}
if captureSession.canAddOutput(self.stillImageOutput!) {
captureSession.addOutput(self.stillImageOutput!)
}
//To get the highest quality of bufferData add below code
// captureSession.sessionPreset = AVCaptureSessionPresetPhoto
previewLayer = AVCaptureVideoPreviewLayer(session: captureSession)
if let cameraView = cameraView {
previewLayer?.frame = cameraView.bounds
}
previewLayer?.videoGravity = AVLayerVideoGravity.resizeAspectFill
cameraView?.layer.addSublayer(previewLayer)
focusMarkLayer.frame = self.cameraView?.bounds ?? .zero
cameraView?.layer.insertSublayer(self.focusMarkLayer, above: self.previewLayer)
self.focusLine.frame = self.cameraView?.bounds ?? .zero
self.cameraView?.layer.insertSublayer(self.focusLine, above: self.previewLayer)
//to detect orientation of device and to show the AVCapture as the orientation is
previewLayer.connection?.videoOrientation = UIDevice.current.orientation.avCaptureVideoOrientation
self.captureSession.startRunning()
}
public func metadataOutput(_ captureOutput: AVCaptureMetadataOutput,
didOutput metadataObjects: [AVMetadataObject],
from connection: AVCaptureConnection) {
if !isBusy {
isBusy = true
var barcodeObjects = [AVMetadataMachineReadableCodeObject]()
var corners = [[Any]]()
for metadataObject in metadataObjects {
if let videoPreviewLayer = self.previewLayer {
if let transformedMetadataObject = videoPreviewLayer
.transformedMetadataObject(for: metadataObject ) {
if let barcodeObject = transformedMetadataObject as? AVMetadataMachineReadableCodeObject {
barcodeObjects.append(barcodeObject)
corners.append(barcodeObject.corners)
}
}
}
}
self.focusLine.corners = corners
if !barcodeObjects.isEmpty {
self.getImage { (image, _) in
self.delegate?.scanBarcodeCameraManagerDidRecognizeBarcode(barcode: barcodeObjects, image: image)
self.isBusy = false
self.focusLine.corners = []
}
}
}
}
}
| mit | 5f13cc7100157ee42aa448b48b6a7d4d | 39.819753 | 120 | 0.58293 | 6.198725 | false | false | false | false |
vGubriienko/Patterns | Patterns/Observer-WeatherStation.playground/Sources/DisplayElement.swift | 1 | 2468 | import Foundation
public protocol DisplayElement {
func display()
}
public class CurrentConditionsDisplay: DisplayElement, Observer {
private var temperature: Float = 0
private var humidity: Float = 0
private var weatherData: Observable
public init(weatherData: Observable) {
self.weatherData = weatherData
weatherData.registerObserver(self)
}
public func display() {
print("Current conditions: \(temperature)C˚ / \(humidity)%")
}
public func update(subject: Observable) {
if let weatherData = weatherData as? WeatherData where weatherData === subject {
temperature = weatherData.temperature
humidity = weatherData.humidity
display()
}
}
deinit {
weatherData.removeObserver(self)
}
}
public class StatisticsDisplay: DisplayElement, Observer {
private var minTemperature: Float?
private var maxTemperature: Float?
private var avgTemperature: Float = 0
private var iterationIndex = 0
private var weatherData: Observable
public init(weatherData: Observable) {
self.weatherData = weatherData
self.weatherData.registerObserver(self)
}
public func display() {
var maxTempStr = "NA"
if let maxTemperature = maxTemperature {
maxTempStr = String(maxTemperature)
}
var minTempStr = "NA"
if let minTemperature = minTemperature {
minTempStr = String(minTemperature)
}
print("Avg/Max/Min temperature = \(avgTemperature)/\(maxTempStr)/\(minTempStr)")
}
public func update(subject: Observable) {
if let weatherData = weatherData as? WeatherData where weatherData === subject {
let temperature = weatherData.temperature
if temperature <= minTemperature ?? temperature {
minTemperature = temperature
}
if temperature >= maxTemperature ?? temperature {
maxTemperature = temperature
}
avgTemperature = avgTemperature + Float(1.0) / (Float(iterationIndex) + Float(1.0)) * (temperature - avgTemperature)
iterationIndex += 1
display()
}
}
deinit {
weatherData.removeObserver(self)
}
}
| mit | 93ed77e716fca36ea462c2f10ae2384e | 25.526882 | 128 | 0.591001 | 5.658257 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.