repo_name
stringlengths
6
91
ref
stringlengths
12
59
path
stringlengths
7
936
license
stringclasses
15 values
copies
stringlengths
1
3
content
stringlengths
61
711k
hash
stringlengths
32
32
line_mean
float64
4.88
60.8
line_max
int64
12
421
alpha_frac
float64
0.1
0.92
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
liuweihaocool/iOS_06_liuwei
refs/heads/master
新浪微博_swift/新浪微博_swift/AppDelegate.swift
apache-2.0
1
// // AppDelegate.swift // 新浪微博_swift // // Created by liuwei on 15/11/22. // Copyright © 2015年 liuwei. All rights reserved. // //LWCollectionViewController(collectionViewLayout: UICollectionViewLayout() 流水布局 //外部提供流水布局 但是不太好 流水布局需要设置参数 让调用的人来设置参数 封装的不是特别好 import UIKit @UIApplicationMain //https://git.oschina.net/czbkiosweibo/GZWeibo666.git git 教师案例fd class AppDelegate: UIResponder, UIApplicationDelegate { // 声明变量window var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { appsetup() window = UIWindow(frame: UIScreen.mainScreen().bounds)//创建window window?.backgroundColor = UIColor.whiteColor() /// 创建 tabBarVC 控制器 // let tabBarVC = LWFeatureController() /// 设置 tarBarVC 为根控制器 window?.rootViewController = defaultController() window?.makeKeyAndVisible()//设置keywindow和显示 return true } // MARK: - 判断进入哪个控制器 private func defaultController() -> UIViewController { // 用户是否登录,加载到账户就表示登录 if !LWUserAccount.userLogin { return LWMainTarbarController() } // return isNewFeature() ? LWFeatureController() : LWWelcomeController() } private func switchRootViewController(isMain: Bool) { print(isMain) window?.rootViewController = isMain ? LWMainTarbarController() : LWWelcomeController() } class func switchRootViewController(isMain: Bool) { (UIApplication.sharedApplication().delegate as! AppDelegate).switchRootViewController(isMain) } ///判断是否是新版本 private func isNewFeature() -> Bool{ //获取当前版本 let currentVersion = Double(NSBundle.mainBundle().infoDictionary!["CFBundleShortVersionString"] as! String)! // 获取上次版本(从偏好设置) let sandboxVersionKey = "sandboxVersionKey" //上次的版本号 let sandboxVersion = NSUserDefaults.standardUserDefaults().doubleForKey(sandboxVersionKey) // 保存当前版本 NSUserDefaults.standardUserDefaults().setDouble(currentVersion, forKey: sandboxVersionKey) NSUserDefaults.standardUserDefaults().synchronize() return currentVersion != sandboxVersion } func appsetup() { let bar = UINavigationBar.appearance() bar.tintColor = UIColor.orangeColor() } func applicationWillResignActive(application: UIApplication) { } func applicationDidEnterBackground(application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
1ef423bfc2e90cde12b2fe6947d0c596
37.851064
218
0.700986
false
false
false
false
donbytyqi/WatchBox
refs/heads/master
WatchBox Reborn/Extensions.swift
mit
1
// // Extensions.swift // WatchBox Reborn // // Created by Don Bytyqi on 5/2/17. // Copyright © 2017 Don Bytyqi. All rights reserved. // import UIKit let imageCache = NSCache<AnyObject, AnyObject>() class CoverImage: UIImageView { var coverImageURL: String? func downloadImageFrom(urlString: String) { UIApplication.shared.isNetworkActivityIndicatorVisible = true coverImageURL = urlString guard let url = URL(string: urlString) else { return } image = UIImage(named: "nocover") if let isCachedImage = imageCache.object(forKey: urlString as AnyObject) { self.image = isCachedImage as? UIImage UIApplication.shared.isNetworkActivityIndicatorVisible = false return } UIApplication.shared.isNetworkActivityIndicatorVisible = true URLSession.shared.dataTask(with: url) { (data, response, error) in if error != nil { print(error!) } DispatchQueue.main.async { guard let imageData = data else { return } let cachedImage = UIImage(data: imageData) if self.coverImageURL == urlString { self.image = cachedImage UIApplication.shared.isNetworkActivityIndicatorVisible = false } UIApplication.shared.isNetworkActivityIndicatorVisible = true imageCache.setObject(cachedImage!, forKey: urlString as AnyObject) UIApplication.shared.isNetworkActivityIndicatorVisible = false } }.resume() } } public func addBlur(toView: UIView) { let blurEffect = UIBlurEffect(style: .dark) let blurView = UIVisualEffectView(effect: blurEffect) blurView.frame = toView.bounds blurView.autoresizingMask = [.flexibleWidth, .flexibleHeight] toView.addSubview(blurView) } extension UIView { func searchVisualEffectsSubview() -> UIVisualEffectView? { if let visualEffectView = self as? UIVisualEffectView { return visualEffectView } else { for subview in subviews { if let found = subview.searchVisualEffectsSubview() { return found } } } return nil } } extension UISearchBar { func cancelButton(_ isEnabled: Bool) { for subview in self.subviews { for button in subview.subviews { if button.isKind(of: UIButton.self) { let cancelButton = button as! UIButton cancelButton.isEnabled = isEnabled } } } } } class Alert: NSObject { func show(title: String, message: String, controller: UIViewController) { let alert = UIAlertController(title: title, message: message, preferredStyle: .alert) alert.addAction(UIAlertAction(title: "Ok", style: .cancel, handler: nil)) controller.present(alert, animated: true, completion: nil) } }
c39b48045afa9251222def13f933e502
28.432432
93
0.573003
false
false
false
false
RoverPlatform/rover-ios
refs/heads/master
Sources/Foundation/Attributes.swift
apache-2.0
1
// // Attributes.swift // RoverFoundation // // Created by Sean Rucker on 2018-07-24. // Copyright © 2018 Rover Labs Inc. All rights reserved. // import Foundation import os // We have a strong guarantee that this will complete. Very deterministic, done in static context at startup, so silence the force try warning. // swiftlint:disable:next force_try private let roverKeyRegex = try! NSRegularExpression(pattern: "^[a-zA-Z_][a-zA-Z_0-9]*$") /// Wraps a [String: Any], a dictionary of values, but enables use of both NSCoding and Codable. Enforces the Rover limitations on allowed types and nesting thereof (not readily capturable in the Swift type system) at runtime. /// /// Note that there are several constraints here, enforced by the Rover cloud API itself, not expressed in the Swift type. Namely, arrays may not be present within dictionaries or other arrays. These are checked at runtime. /// /// Thus: /// /// * `String` /// * `Int` /// * `Double` /// * `Bool` /// * `[String]` /// * `[Int]` /// * `[Double]` /// * `[Bool]` /// * `[String: Any]` (where Any may be any of these given types) public class Attributes: NSObject, NSCoding, Codable, RawRepresentable, ExpressibleByDictionaryLiteral { public var rawValue: [String: Any] public required init(rawValue: [String: Any]) { // transform nested dictionaries to Attributes, if needed. let nestedDictionariesTransformedToAttributes = rawValue.mapValues { value -> Any in if let dictionary = value as? [String: Any] { return Attributes(rawValue: dictionary) as Any? ?? Attributes() } else { return value } } self.rawValue = Attributes.validateDictionary(nestedDictionariesTransformedToAttributes) } public required init(dictionaryLiteral elements: (String, Any)...) { let dictionary = elements.reduce(into: [String: Any]()) { result, element in let (key, value) = element result[key] = value } // transform nested dictionaries to Attributes, if needed. let nestedDictionariesTransformedToAttributes = dictionary.mapValues { value -> Any in if let dictionary = value as? [String: Any] { return Attributes(rawValue: dictionary) as Any? ?? Attributes() } else { return value } } self.rawValue = Attributes.validateDictionary(nestedDictionariesTransformedToAttributes) } // // MARK: Subscript // public subscript(index: String) -> Any? { get { return rawValue[index] } set(newValue) { rawValue[index] = newValue } } // // MARK: NSCoding // public func encode(with aCoder: NSCoder) { var boolToBoolean: ((Any) -> Any) boolToBoolean = { anyValue in switch anyValue { case let value as Bool: return BooleanValue(value) case let value as [Bool]: return value.map { BooleanValue($0) } default: return anyValue } } let nsDictionary = self.rawValue.mapValues(boolToBoolean) as Dictionary aCoder.encode(nsDictionary) } public required init?(coder aDecoder: NSCoder) { guard let nsDictionary = aDecoder.decodeObject() as? NSDictionary else { return nil } let dictionary = nsDictionary.dictionaryWithValues(forKeys: nsDictionary.allKeys as! [String]) func transformDictionary(dictionary: [String: Any]) -> [String: Any] { return dictionary.reduce(into: [String: Any]()) { result, element in switch element.value { // handle our custom boxed Boolean value type: case let value as BooleanValue: result[element.key] = value.value case let array as [BooleanValue]: result[element.key] = array.map { $0.value } case let attributesDictionary as Attributes: // if a nested dictionary is already attributes, then pass it through. result[element.key] = attributesDictionary default: result[element.key] = element.value } } } self.rawValue = Attributes.validateDictionary(transformDictionary(dictionary: dictionary)) super.init() } fileprivate static func validateDictionary(_ dictionary: [String: Any]) -> [String: Any] { var transformed: [String: Any] = [:] // This is a set of mappings of types, which makes for a long closure body, so silence the closure length warning. // swiftlint:disable:next closure_body_length dictionary.forEach { key, value in let swiftRange = Range(uncheckedBounds: (key.startIndex, key.endIndex)) let nsRange = NSRange(swiftRange, in: key) if roverKeyRegex.matches(in: key, range: nsRange).isEmpty { assertionFailureEmitter("Invalid key: \(key)") return } if let nestedDictionary = value as? Attributes { transformed[key] = nestedDictionary return } if !( value is Double || value is Int || value is String || value is Bool || value is [Double] || value is [Int] || value is [String] || value is [Bool] ) { let valueType = type(of: value) assertionFailureEmitter("Invalid value for key \(key) with unsupported type: \(String(describing: valueType))") return } transformed[key] = value } return transformed } // // MARK: Codable // /// This implementation of CodingKey allows for handling data without strongly and statically typed keys with Codable. struct DynamicCodingKeys: CodingKey { var stringValue: String init(stringValue: String) { self.stringValue = stringValue } var intValue: Int? { return nil } init?(intValue: Int) { return nil } } public required init(from decoder: Decoder) throws { func fromKeyedDecoder(_ container: KeyedDecodingContainer<Attributes.DynamicCodingKeys>) throws -> Attributes { var assembledHash = [String: Any]() // This is a set of mappings of types, which makes for a long closure body, so silence the closure length warning. // swiftlint:disable:next closure_body_length try container.allKeys.forEach { key in let keyString = key.stringValue // primitive values: if let value = try? container.decode(Bool.self, forKey: key) { assembledHash[keyString] = value return } if let value = try? container.decode(Int.self, forKey: key) { assembledHash[keyString] = value return } if let value = try? container.decode(String.self, forKey: key) { assembledHash[keyString] = value return } // now try probing for an embedded dict. if let dictionary = try? container.nestedContainer(keyedBy: DynamicCodingKeys.self, forKey: key) { assembledHash[keyString] = try fromKeyedDecoder(dictionary) return } // we also support arrays of primitive values: if let array = try? container.decode([String].self, forKey: key) { assembledHash[keyString] = array return } if let array = try? container.decode([Bool].self, forKey: key) { assembledHash[keyString] = array return } if let array = try? container.decode([Int].self, forKey: key) { assembledHash[keyString] = array return } if let array = try? container.decode([Double].self, forKey: key) { assembledHash[keyString] = array return } throw DecodingError.dataCorruptedError(forKey: key, in: container, debugDescription: "Expected one of Int, String, Double, Bool, or an Array thereof.") } return Attributes(rawValue: assembledHash) } let container = try decoder.container(keyedBy: DynamicCodingKeys.self) self.rawValue = try fromKeyedDecoder(container).rawValue } public func encode(to encoder: Encoder) throws { /// nested function for recursing through the dictionary and populating the Encoder with it, doing the necessary type coercions on the way. func encodeToContainer(dictionary: [String: Any], container: inout KeyedEncodingContainer<Attributes.DynamicCodingKeys>) throws { // This is a set of mappings of types, which makes for a long closure body, so silence the function length warning. // swiftlint:disable:next closure_body_length try dictionary.forEach { codingKey, value in let key = DynamicCodingKeys(stringValue: codingKey) switch value { case let value as Int: try container.encode(value, forKey: key) case let value as Bool: try container.encode(value, forKey: key) case let value as String: try container.encode(value, forKey: key) case let value as Double: try container.encode(value, forKey: key) case let value as [Int]: try container.encode(value, forKey: key) case let value as [Bool]: try container.encode(value, forKey: key) case let value as [Double]: try container.encode(value, forKey: key) case let value as [String]: try container.encode(value, forKey: key) case let value as Attributes: var nestedContainer = container.nestedContainer(keyedBy: DynamicCodingKeys.self, forKey: key) try encodeToContainer(dictionary: value.rawValue, container: &nestedContainer) default: let context = EncodingError.Context(codingPath: container.codingPath, debugDescription: "Unexpected attribute value type. Expected one of Int, String, Double, Boolean, or an array thereof, or a dictionary of all of the above including arrays. Got \(type(of: value))") throw EncodingError.invalidValue(value, context) } } } var container = encoder.container(keyedBy: DynamicCodingKeys.self) try encodeToContainer(dictionary: self.rawValue, container: &container) } override init() { rawValue = [:] super.init() } static func wasAssertionThrown(operation: () -> Void) -> Bool { let originalEmitter = assertionFailureEmitter var thrown = false assertionFailureEmitter = { message in os_log("Attributes assertion thrown: %s", message) thrown = true } operation() assertionFailureEmitter = originalEmitter return thrown } /// Needed so tests can override the method of emitting assertion failures. private static var assertionFailureEmitter: (String) -> Void = { message in assertionFailure(message) } } class BooleanValue: NSObject, NSCoding { var value: Bool func encode(with aCoder: NSCoder) { aCoder.encode(value, forKey: "value") } required init?(coder aDecoder: NSCoder) { value = aDecoder.decodeBool(forKey: "value") } init(_ value: Bool) { self.value = value } }
6d9534271c6bbd1db0bbc41133bc2205
38.611285
287
0.565211
false
false
false
false
ben-ng/swift
refs/heads/master
validation-test/compiler_crashers_fixed/01085-swift-declcontext-lookupqualified.swift
apache-2.0
1
// 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 https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // RUN: not %target-swift-frontend %s -typecheck struct B<T : A> { func f<g>() -> (g, g -> g) -> g { d j d.i = { } { g) { h } } protocol f { } class d: f{ class func i {} struct d<f : e,e where g.h == f.h> { } } protocol a { typeal= D>(e: A.B) { } } } override func d() -> String { func} func b((Any, c))(Any, AnyObject func g<T where T.E == F>(f: B<T>) { } struct c<S: Sequence, T where Optional<T> == S.Iterator.Element>
2dd071fba0233f3d34c22df166a3ae76
22.454545
79
0.643411
false
false
false
false
JohnSansoucie/MyProject2
refs/heads/master
BlueCap/Utils/UITableViewControllerExtensions.swift
mit
1
// // UITableViewControllerExtensions.swift // BlueCap // // Created by Troy Stribling on 9/27/14. // Copyright (c) 2014 gnos.us. All rights reserved. // import UIKit extension UITableViewController { func updateWhenActive() { if UIApplication.sharedApplication().applicationState == .Active { self.tableView.reloadData() } } func styleNavigationBar() { let font = UIFont(name:"Thonburi", size:20.0) var titleAttributes : [NSObject:AnyObject] if var defaultTitleAttributes = UINavigationBar.appearance().titleTextAttributes { titleAttributes = defaultTitleAttributes } else { titleAttributes = [NSObject:AnyObject]() } titleAttributes[NSFontAttributeName] = font self.navigationController?.navigationBar.titleTextAttributes = titleAttributes } func styleUIBarButton(button:UIBarButtonItem) { let font = UIFont(name:"Thonburi", size:16.0) var titleAttributes : [NSObject:AnyObject] if var defaultitleAttributes = button.titleTextAttributesForState(UIControlState.Normal) { titleAttributes = defaultitleAttributes } else { titleAttributes = [NSObject:AnyObject]() } titleAttributes[NSFontAttributeName] = font button.setTitleTextAttributes(titleAttributes, forState:UIControlState.Normal) } }
c5b87972693d430f24810fdc89651fb5
32.904762
98
0.672051
false
false
false
false
pyromobile/nubomedia-ouatclient-src
refs/heads/master
ios/LiveTales-smartphones/uoat/NotificationModel.swift
apache-2.0
2
// // NotificationModel.swift // uoat // // Created by Pyro User on 28/7/16. // Copyright © 2016 Zed. All rights reserved. // import Foundation enum NotificationType { case Undefined case ReadingRoom case PlayingRoom case FriendShip } class NotificationModel { class func getAllByUser(userId:String, onNotificationsReady:(notifications:[NotificationType:[Notification]])->Void) { var notificationsByType:[NotificationType:[Notification]] = [NotificationType:[Notification]]() let criteria:[String:AnyObject] = ["to":"pub_\(userId)"] let query = KuasarsQuery( criteria, retrievingFields: nil ) as KuasarsQuery KuasarsEntity.query( query, entityType: "requests", occEnabled: false, completion:{ (response:KuasarsResponse!, error:KuasarsError!) -> Void in if( error != nil ) { print( "Error from kuasars: \(error.description)" ) } else { let entities = response.contentObjects as! [KuasarsEntity] for entity:KuasarsEntity in entities { let id:String = entity.ID let type:String = (entity.customData![TypeField])! as! String let from:String = (entity.customData![FromField])! as! String let to:String = (entity.customData![ToField])! as! String var roomId:String = "" if( type == ReadingRoom || type == PlayingRoom ) { roomId = (entity.customData![RoomIdField])! as! String } let typed = getTypeByName(type) let notification = Notification( id:id, type:typed, from:from, to:to, roomId:roomId ) if var _ = notificationsByType[typed] { notificationsByType[typed]?.append( notification ) } else { notificationsByType[typed] = [notification] } } } onNotificationsReady( notifications:notificationsByType ) }) } class func getNickNamesFromNotifications( notifications:[Notification], onNotificationsReady:(notifications:[Notification])->Void ) { let batch = KuasarsBatch() for notification:Notification in notifications { let friendId:String = notification.getFrom() let criteria:[String:AnyObject] = ["id":"\(friendId)"] let query = KuasarsQuery( criteria, retrievingFields: nil ) as KuasarsQuery let request:KuasarsRequest = KuasarsServices.queryEntities(query, type: "users", occEnabled: false) batch.addRequest(request) } batch.performRequests({ (response:KuasarsResponse!, error:KuasarsError!) in if( error != nil ) { print( "Error from kuasars: \(error.description)" ) } else { let responses = response.contentObjects as! [NSDictionary] for index in 0 ..< responses.count { let rsp:NSDictionary = responses[index] as NSDictionary let body:[NSDictionary] = rsp["body"] as! [NSDictionary] let friendNick = body[0]["nick"] as! String print("Request Amigo :\(friendNick)") notifications[index].nickNameFrom = friendNick } } onNotificationsReady( notifications: notifications ) }) } class func getNickNamesFromSentNotifications( notifications:[Notification], onNotificationsReady:(notifications:[Notification])->Void ) { let batch = KuasarsBatch() for notification:Notification in notifications { let friendId:String = notification.getTo() let criteria:[String:AnyObject] = ["id":"\(friendId)"] let query = KuasarsQuery( criteria, retrievingFields: nil ) as KuasarsQuery let request:KuasarsRequest = KuasarsServices.queryEntities(query, type: "users", occEnabled: false) batch.addRequest(request) } batch.performRequests({ (response:KuasarsResponse!, error:KuasarsError!) in if( error != nil ) { print( "Error from kuasars: \(error.description)" ) } else { let responses = response.contentObjects as! [NSDictionary] for index in 0 ..< responses.count { let rsp:NSDictionary = responses[index] as NSDictionary let body:[NSDictionary] = rsp["body"] as! [NSDictionary] let friendNick = body[0]["nick"] as! String print("Request Amigo :\(friendNick)") notifications[index].nickNameFrom = friendNick } } onNotificationsReady( notifications: notifications ) }) } class func removeNotificationsById(notificationIds:[String], onNotificationsReady:()->Void) { KuasarsEntity.deleteEntitiesOfType("requests", withIds: notificationIds) { (response:KuasarsResponse!, error:KuasarsError!) in if( error != nil ) { print("Kuasars error:\(error.description)") } else { print("Removed") } onNotificationsReady() } } class func sendNotifications(notifications:[Notification],onNotificationsReady:(error:Bool)->Void) { let serverTimeRequest:KuasarsRequest = KuasarsServices.getCurrentTime() KuasarsCore.executeRequest(serverTimeRequest) { (response:KuasarsResponse!, error:KuasarsError!) in if( error != nil ) { print("Error get server time: \(error.description)") } else { let expire:Double = 10*60*1000 //Ten minutes! //Get time from server. let content:NSDictionary = response.contentObjects[0] as! NSDictionary let serverTime:Double = content["timeInMillisFrom1970"] as! Double let batch = KuasarsBatch() for notification in notifications { let type:String = getNameByType( notification.getType() ) if( type.isEmpty ){ continue } let friendId:String = notification.getTo() let userId:String = notification.getFrom() let roomId:String = notification.getRoomId() //create friend request. let entity = ["type":type,"to":friendId,"from":"pub_\(userId)","roomId":roomId,"expireAt":(serverTime + expire)] let requestsEntity = KuasarsEntity(type: "requests", customData: entity as [NSObject : AnyObject], expirationDate:(serverTime + expire), occEnabled: false) let acl = KuasarsPermissions() acl.setReadPermissions( KuasarsReadPermissionALL, usersList: nil, groupList: nil ) requestsEntity.setPermissions( acl ) let request:KuasarsRequest = KuasarsServices.saveNewEntity(requestsEntity) batch.addRequest( request ) } batch.performRequests({ (response:KuasarsResponse!, error:KuasarsError!) in onNotificationsReady(error:error != nil) }) } } } class func sendFriendshipRequest(userId:String, friendSecrectCode:String, friendNick:String,onFriendshipReady:(error:Bool)->Void) { //Check secrect code remote user & get time from server. let criteria:[String:AnyObject] = ["code":friendSecrectCode, "nick":friendNick] let query = KuasarsQuery( criteria, retrievingFields: nil ) as KuasarsQuery let userQueryRequest:KuasarsRequest = KuasarsServices.queryEntities( query, type: "users", occEnabled: false) let serverTimeRequest:KuasarsRequest = KuasarsServices.getCurrentTime() let batch = KuasarsBatch() batch.addRequest( userQueryRequest ) batch.addRequest( serverTimeRequest ) batch.performRequests { (response:KuasarsResponse!, error:KuasarsError!) in if( error != nil ) { print( "Error from kuasars: \(error.description)" ) onFriendshipReady( error:true ) } else { //User exist? let responses = response.contentObjects as! [NSDictionary] let resp1 = responses[0] as NSDictionary let userExists = ( resp1["code"] as! Int == 200 ) if( userExists ) { let body1 = resp1["body"] as! NSArray let friendID = body1[0]["id"] as! String print("friend ID:\(friendID)") //Server time. let expire:Double = 24*60*60*1000 let resp2 = responses[1] as NSDictionary let body2 = resp2["body"] as! NSDictionary let serverTime:Double = body2["timeInMillisFrom1970"] as! Double print("Server time:\(serverTime) - Add:\(expire)") //create friend request. let entity = ["type":"friendship","to":friendID,"from":"pub_\(userId)","expireAt":(serverTime + expire)] let requestsEntity = KuasarsEntity(type: "requests", customData: entity as [NSObject : AnyObject], expirationDate:(serverTime + expire), occEnabled: false) let acl = KuasarsPermissions() acl.setReadPermissions( KuasarsReadPermissionALL, usersList: nil, groupList: nil ) requestsEntity.setPermissions( acl ) requestsEntity.save { ( response:KuasarsResponse!, error:KuasarsError! ) -> Void in if( error != nil ) { print( "Error from kuasars: \(error.description)" ) onFriendshipReady( error:true ) } else { print("Request was sent!") onFriendshipReady( error:false ) } } } else { onFriendshipReady( error:true ) } } } } class func getNotificationsSentByMe(userId:String, onNotificationsReady:(notifications:[NotificationType:[Notification]])->Void) { var notificationsByType:[NotificationType:[Notification]] = [NotificationType:[Notification]]() let criteria:[String:AnyObject] = ["from":"pub_\(userId)"] let query = KuasarsQuery( criteria, retrievingFields: nil ) as KuasarsQuery KuasarsEntity.query( query, entityType: "requests", occEnabled: false, completion:{ (response:KuasarsResponse!, error:KuasarsError!) -> Void in if( error != nil ) { print( "Error from kuasars: \(error.description)" ) } else { let entities = response.contentObjects as! [KuasarsEntity] for entity:KuasarsEntity in entities { let id:String = entity.ID let type:String = (entity.customData![TypeField])! as! String let from:String = (entity.customData![FromField])! as! String let to:String = (entity.customData![ToField])! as! String var roomId:String = "" if( type == ReadingRoom || type == PlayingRoom ) { roomId = (entity.customData![RoomIdField])! as! String } let typed = getTypeByName(type) let notification = Notification( id:id, type:typed, from:from, to:to, roomId:roomId ) if var _ = notificationsByType[typed] { notificationsByType[typed]?.append( notification ) } else { notificationsByType[typed] = [notification] } } } onNotificationsReady( notifications:notificationsByType ) }) } /*=============================================================*/ /* Private Section */ /*=============================================================*/ private class func getTypeByName( typeName:String ) -> NotificationType { let notificationType:NotificationType switch( typeName ) { case ReadingRoom: notificationType = .ReadingRoom break case PlayingRoom: notificationType = .PlayingRoom break case FriendShip: notificationType = .FriendShip break default: notificationType = .Undefined break } return notificationType } private class func getNameByType( type:NotificationType ) -> String { let name:String switch( type ) { case .ReadingRoom: name = ReadingRoom break case .PlayingRoom: name = PlayingRoom break case .FriendShip: name = FriendShip break default: name = "" } return name } //Fields. private static let TypeField:String = "type" private static let FromField:String = "from" private static let ToField:String = "to" private static let RoomIdField:String = "roomId" //Types. private static let ReadingRoom:String = "readingroom" private static let PlayingRoom:String = "playingroom" private static let FriendShip:String = "friendship" }
f79ab8557ba4014134a50a19309270fe
39.626016
175
0.515744
false
false
false
false
objecthub/swift-lispkit
refs/heads/master
Sources/LispKit/Data/Expr.swift
apache-2.0
1
// // Expr.swift // LispKit // // Created by Matthias Zenger on 08/11/2015. // Copyright © 2016-2022 ObjectHub. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // import Foundation import NumberKit /// /// `Expr` represents LispKit expressions in form of an enumeration with associated values. /// public enum Expr: Hashable { case undef case void case eof case null case `true` case `false` case uninit(Symbol) case symbol(Symbol) case fixnum(Int64) case bignum(BigInt) indirect case rational(Expr, Expr) case flonum(Double) case complex(DoubleComplex) case char(UniChar) case string(NSMutableString) case bytes(ByteVector) indirect case pair(Expr, Expr) case box(Cell) case mpair(Tuple) case array(Collection) case vector(Collection) case record(Collection) case table(HashTable) case promise(Promise) indirect case values(Expr) case procedure(Procedure) case special(SpecialForm) case env(Environment) case port(Port) case object(NativeObject) indirect case tagged(Expr, Expr) case error(RuntimeError) indirect case syntax(SourcePosition, Expr) /// Returns the type of this expression. public var type: Type { switch self { case .undef, .uninit(_): return .undefinedType case .void: return .voidType case .eof: return .eofType case .null: return .nullType case .true: return .booleanType case .false: return .booleanType case .symbol(_): return .symbolType case .fixnum(_): return .fixnumType case .bignum(_): return .bignumType case .rational(_, _): return .rationalType case .flonum(let num): return Foundation.trunc(num) == num ? .integerType : .floatType case .complex(_): return .complexType case .char(_): return .charType case .string(_): return .strType case .bytes(_): return .byteVectorType case .pair(_, _): return .pairType case .box(_): return .boxType case .mpair(_): return .mpairType case .array(_): return .arrayType case .vector(let vec): return vec.isGrowableVector ? .gvectorType : .vectorType case .record(_): return .recordType case .table(_): return .tableType case .promise(let future): return future.isStream ? .streamType : .promiseType case .values(_): return .valuesType case .procedure(_): return .procedureType case .special(_): return .specialType case .env(_): return .envType case .port(_): return .portType case .object(let obj): return obj.type case .tagged(_, _): return .taggedType case .error(_): return .errorType case .syntax(_, _): return .syntaxType } } /// Returns the position of this expression. public var pos: SourcePosition { switch self { case .syntax(let sourcePos, _): return sourcePos default: return SourcePosition.unknown } } // Predicate methods /// Returns true if this expression is undefined. public var isUndef: Bool { switch self { case .undef, .uninit(_): return true default: return false } } /// Returns true if this expression is null. public var isNull: Bool { switch self { case .null: return true default: return false } } /// Returns true if this is not the `#f` value. public var isTrue: Bool { switch self { case .false: return false default: return true } } /// Returns true if this is the `#f` value. public var isFalse: Bool { switch self { case .false: return true default: return false } } /// Returns true if this is an exact number. public var isExactNumber: Bool { switch self { case .fixnum(_), .bignum(_), .rational(_, _): return true default: return false } } /// Returns true if this is an inexact number. public var isInexactNumber: Bool { switch self { case .flonum(_), .complex(_): return true default: return false } } /// Normalizes the representation (relevant for numeric datatypes) public var normalized: Expr { switch self { case .bignum(let num): if let fn = num.intValue { return .fixnum(fn) } return self case .rational(let n, let d): switch d { case .fixnum(let fd): return fd == 1 ? n : self case .bignum(let bd): return bd == 1 ? n.normalized : self default: return self } case .complex(let num): return num.value.isReal ? .flonum(num.value.re) : self default: return self } } /// Returns the source position associated with this expression, or `outer` in case there is /// no syntax annotation. public func pos(_ outer: SourcePosition = SourcePosition.unknown) -> SourcePosition { switch self { case .syntax(let p, _): return p case .pair(.syntax(let p, _), _): return p default: return outer } } /// Returns the given expression with all symbols getting interned and syntax nodes removed. public var datum: Expr { switch self { case .symbol(let sym): return .symbol(sym.root) case .pair(let car, let cdr): return .pair(car.datum, cdr.datum) case .syntax(_, let expr): return expr.datum default: return self } } /// Returns the given expression with all syntax nodes removed up to `depth` nested expression /// nodes. public func removeSyntax(depth: Int = 4) -> Expr { guard depth > 0 else { return self } switch self { case .pair(let car, let cdr): return .pair(car.removeSyntax(depth: depth - 1), cdr.removeSyntax(depth: depth - 1)) case .syntax(_, let expr): return expr.removeSyntax(depth: depth) default: return self } } /// Inject the given position into the expression. public func at(pos: SourcePosition) -> Expr { switch self { case .pair(let car, let cdr): return .syntax(pos, .pair(car.at(pos: pos), cdr.at(pos: pos))) case .syntax(_, _): return self default: return .syntax(pos, self) } } /// Maps a list into an array of expressions and a tail (= null for proper lists) public func toExprs() -> (Exprs, Expr) { var exprs = Exprs() var expr = self while case .pair(let car, let cdr) = expr { exprs.append(car) expr = cdr } return (exprs, expr) } /// The length of this expression (all non-pair expressions have length 1). var length: Int { var expr = self var len = 0 while case .pair(_, let cdr) = expr { len += 1 expr = cdr } return len } /// Returns true if the expression isn't referring to other expressions directly or /// indirectly. public var isAtom: Bool { switch self { case .undef, .void, .eof, .null, .true, .false, .uninit(_), .symbol(_), .fixnum(_), .bignum(_), .rational(_, _), .flonum(_), .complex(_), .char(_), .string(_), .bytes(_), .env(_), .port(_), .object(_): return true case .pair(let car0, .pair(let car1, .pair(let car2, let cdr))): return car0.isSimpleAtom && car1.isSimpleAtom && car2.isSimpleAtom && cdr.isSimpleAtom case .pair(let car0, .pair(let car1, let cdr)): return car0.isSimpleAtom && car1.isSimpleAtom && cdr.isSimpleAtom case .pair(let car, let cdr): return car.isSimpleAtom && cdr.isSimpleAtom case .tagged(let tag, let expr): return tag.isSimpleAtom && expr.isAtom case .values(let expr): return expr.isAtom default: return false } } public var isSimpleAtom: Bool { switch self { case .undef, .void, .eof, .null, .true, .false, .uninit(_), .symbol(_), .fixnum(_), .bignum(_), .rational(_, _), .flonum(_), .complex(_), .char(_), .string(_), .bytes(_), .env(_), .port(_), .object(_): return true default: return false } } public func hash(into hasher: inout Hasher) { equalHash(self, into: &hasher) } } /// Extension adding static factory methods to `Expr`. /// extension Expr { public static func makeBoolean(_ val: Bool) -> Expr { return val ? .true : .false } public static func makeNumber(_ num: Int) -> Expr { return .fixnum(Int64(num)) } public static func makeNumber(_ num: Int64) -> Expr { return .fixnum(num) } public static func makeNumber(_ num: UInt64) -> Expr { return Expr.bignum(BigInt(num)).normalized } public static func makeNumber(_ num: BigInt) -> Expr { return Expr.bignum(num).normalized } public static func makeNumber(_ num: Rational<Int64>) -> Expr { return Expr.rational(.fixnum(num.numerator), .fixnum(num.denominator)).normalized } public static func makeNumber(_ num: Rational<BigInt>) -> Expr { return Expr.rational(.bignum(num.numerator), .bignum(num.denominator)).normalized } public static func makeNumber(_ num: Double) -> Expr { return .flonum(num) } public static func makeNumber(_ num: Complex<Double>) -> Expr { return Expr.complex(ImmutableBox(num)).normalized } public static func makeList(_ expr: Expr...) -> Expr { return Expr.makeList(fromStack: expr.reversed(), append: Expr.null) } public static func makeList(_ exprs: Exprs, append: Expr = Expr.null) -> Expr { return Expr.makeList(fromStack: exprs.reversed(), append: append) } public static func makeList(_ exprs: Arguments, append: Expr = Expr.null) -> Expr { return Expr.makeList(fromStack: exprs.reversed(), append: append) } public static func makeList(fromStack exprs: [Expr], append: Expr = Expr.null) -> Expr { var res = append for expr in exprs { res = pair(expr, res) } return res } public static func makeString(_ str: String) -> Expr { return .string(NSMutableString(string: str)) } } /// This extension adds projections to `Expr`. /// extension Expr { @inline(__always) public func assertType(at pos: SourcePosition = SourcePosition.unknown, _ types: Type...) throws { for type in types { for subtype in type.included { if self.type == subtype { return } } } throw RuntimeError.type(self, expected: Set(types)).at(pos) } @inline(__always) public func asInt64(at pos: SourcePosition = SourcePosition.unknown) throws -> Int64 { guard case .fixnum(let res) = self else { throw RuntimeError.type(self, expected: [.fixnumType]).at(pos) } return res } @inline(__always) public func asInt(above: Int = 0, below: Int = Int.max) throws -> Int { guard case .fixnum(let res) = self else { throw RuntimeError.type(self, expected: [.fixnumType]) } guard res >= Int64(above) && res < Int64(below) else { throw RuntimeError.range(self, min: Int64(above), max: below == Int.max ? Int64.max : Int64(below - 1)) } return Int(res) } @inline(__always) public func asUInt8() throws -> UInt8 { guard case .fixnum(let number) = self , number >= 0 && number <= 255 else { throw RuntimeError.type(self, expected: [.byteType]) } return UInt8(number) } public func asDouble(coerce: Bool = false) throws -> Double { if !coerce { if case .flonum(let num) = self { return num } throw RuntimeError.type(self, expected: [.floatType]) } switch self.normalized { case .fixnum(let num): return Double(num) case .bignum(let num): return num.doubleValue case .rational(.fixnum(let n), .fixnum(let d)): return Double(n) / Double(d) case .rational(.bignum(let n), .bignum(let d)): return n.doubleValue / d.doubleValue case .flonum(let num): return num default: throw RuntimeError.type(self, expected: [.realType]) } } public func asComplex(coerce: Bool = false) throws -> Complex<Double> { if !coerce { switch self { case .flonum(let num): return Complex(num, 0.0) case .complex(let complex): return complex.value default: throw RuntimeError.type(self, expected: [.complexType]) } } switch self.normalized { case .fixnum(let num): return Complex(Double(num), 0.0) case .bignum(let num): return Complex(num.doubleValue, 0.0) case .rational(.fixnum(let n), .fixnum(let d)): return Complex(Double(n) / Double(d), 0.0) case .rational(.bignum(let n), .bignum(let d)): return Complex(n.doubleValue / d.doubleValue, 0.0) case .flonum(let num): return Complex(num, 0.0) case .complex(let num): return num.value default: throw RuntimeError.type(self, expected: [.complexType]) } } @inline(__always) public func asSymbol() throws -> Symbol { switch self { case .symbol(let sym): return sym default: throw RuntimeError.type(self, expected: [.symbolType]) } } @inline(__always) public func toSymbol() -> Symbol? { switch self { case .symbol(let sym): return sym default: return nil } } @inline(__always) public func asUniChar() throws -> UniChar { guard case .char(let res) = self else { throw RuntimeError.type(self, expected: [.charType]) } return res } @inline(__always) public func charAsString() throws -> String { guard case .char(let res) = self else { throw RuntimeError.type(self, expected: [.charType]) } return String(unicodeScalar(res)) } @inline(__always) public func charOrString() throws -> String { switch self { case .char(let res): return String(unicodeScalar(res)) case .string(let res): return res as String default: throw RuntimeError.type(self, expected: [.strType]) } } @inline(__always) public func asString() throws -> String { guard case .string(let res) = self else { throw RuntimeError.type(self, expected: [.strType]) } return res as String } @inline(__always) public func asMutableStr() throws -> NSMutableString { guard case .string(let res) = self else { throw RuntimeError.type(self, expected: [.strType]) } return res } @inline(__always) public func asPath() throws -> String { guard case .string(let res) = self else { throw RuntimeError.type(self, expected: [.strType]) } return res.expandingTildeInPath } @inline(__always) public func asURL() throws -> URL { guard case .string(let res) = self else { throw RuntimeError.type(self, expected: [.strType]) } guard let url = URL(string: res as String) else { throw RuntimeError.eval(.invalidUrl, self) } return url } @inline(__always) public func asByteVector() throws -> ByteVector { guard case .bytes(let bvector) = self else { throw RuntimeError.type(self, expected: [.byteVectorType]) } return bvector } @inline(__always) public func arrayAsCollection() throws -> Collection { guard case .array(let res) = self else { throw RuntimeError.type(self, expected: [.arrayType]) } return res } @inline(__always) public func vectorAsCollection(growable: Bool? = nil) throws -> Collection { guard case .vector(let vec) = self else { let exp: Set<Type> = growable == nil ? [.vectorType, .gvectorType] : growable! ? [.gvectorType] : [.vectorType] throw RuntimeError.type(self, expected: exp) } if let growable = growable, growable != vec.isGrowableVector { throw RuntimeError.type(self, expected: growable ? [.gvectorType] : [.vectorType]) } return vec } @inline(__always) public func recordAsCollection() throws -> Collection { guard case .record(let res) = self else { throw RuntimeError.type(self, expected: [.recordType]) } return res } @inline(__always) public func asHashTable() throws -> HashTable { guard case .table(let map) = self else { throw RuntimeError.type(self, expected: [.tableType]) } return map } @inline(__always) public func asProcedure() throws -> Procedure { guard case .procedure(let proc) = self else { throw RuntimeError.type(self, expected: [.procedureType]) } return proc } @inline(__always) public func asEnvironment() throws -> Environment { guard case .env(let environment) = self else { throw RuntimeError.type(self, expected: [.envType]) } return environment } @inline(__always) public func asPort() throws -> Port { guard case .port(let port) = self else { throw RuntimeError.type(self, expected: [.portType]) } return port } @inline(__always) public func asObject(of type: Type) throws -> NativeObject { guard case .object(let obj) = self, obj.type == type else { throw RuntimeError.type(self, expected: [type]) } return obj } } /// This extension makes `Expr` implement the `CustomStringConvertible`. /// extension Expr: CustomStringConvertible { public var description: String { return self.toString() } public var unescapedDescription: String { return self.toString(escape: false) } public func toString(escape: Bool = true) -> String { var enclObjs = Set<Reference>() var objId = [Reference: Int]() func objIdString(_ ref: Reference) -> String? { if let id = objId[ref] { return "#\(id)#" } else if enclObjs.contains(ref) { objId[ref] = objId.count return "#\(objId.count - 1)#" } else { return nil } } func fixString(_ ref: Reference, _ str: String) -> String { if let id = objId[ref] { return "#\(id)=\(str)" } else { return str } } func doubleString(_ val: Double) -> String { if val.isInfinite { return (val.sign == .minus) ? "-inf.0" : "+inf.0" } else if val.isNaN { return (val.sign == .minus) ? "-nan.0" : "+nan.0" } else { return String(val) } } func stringReprOf(_ expr: Expr) -> String { switch expr { case .undef: return "#<undef>" case .void: return "#<void>" case .eof: return "#<eof>" case .null: return "()" case .true: return "#t" case .false: return "#f" case .uninit(let sym): guard escape else { return "#<uninit \(sym.rawIdentifier)>" } return "#<uninit \(sym.description)>" case .symbol(let sym): guard escape else { return sym.rawIdentifier } return sym.description case .fixnum(let val): return String(val) case .bignum(let val): return val.description case .rational(let n, let d): return stringReprOf(n) + "/" + stringReprOf(d) case .flonum(let val): return doubleString(val) case .complex(let val): var res = doubleString(val.value.re) if val.value.im.isNaN || val.value.im.isInfinite || val.value.im < 0.0 { res += doubleString(val.value.im) } else { res += "+" + doubleString(val.value.im) } return res + "i" case .char(let ch): guard escape else { return String(unicodeScalar(ch)) } switch ch { case 7: return "#\\alarm" case 8: return "#\\backspace" case 127: return "#\\delete" case 27: return "#\\escape" case 10: return "#\\newline" case 0: return "#\\null" case 12: return "#\\page" case 13: return "#\\return" case 32: return "#\\space" case 9: return "#\\tab" case 11: return "#\\vtab" default : if WHITESPACES_NL.contains(unicodeScalar(ch)) || CONTROL_CHARS.contains(unicodeScalar(ch)) || ILLEGAL_CHARS.contains(unicodeScalar(ch)) || MODIFIER_CHARS.contains(unicodeScalar(ch)) || ch > 0xd7ff { return "#\\x\(String(ch, radix:16))" } else if let scalar = UnicodeScalar(ch) { return "#\\\(Character(scalar))" } else { return "#\\x\(String(ch, radix:16))" } } case .string(let str): guard escape else { return str as String } return "\"\(Expr.escapeStr(str as String))\"" case .bytes(let boxedVec): var builder = StringBuilder(prefix: "#u8(", postfix: ")", separator: " ") for byte in boxedVec.value { builder.append(String(byte)) } return builder.description case .pair(let head, let tail): var builder = StringBuilder(prefix: "(", separator: " ") builder.append(stringReprOf(head)) var expr = tail while case .pair(let car, let cdr) = expr { builder.append(stringReprOf(car)) expr = cdr } return builder.description + (expr.isNull ? ")" : " . \(stringReprOf(expr)))") case .box(let cell): if let res = objIdString(cell) { return res } else { enclObjs.insert(cell) let res = "#<box \(stringReprOf(cell.value))>" enclObjs.remove(cell) return fixString(cell, res) } case .mpair(let tuple): if let res = objIdString(tuple) { return res } else { enclObjs.insert(tuple) let res = "#<pair \(stringReprOf(tuple.fst)) \(stringReprOf(tuple.snd))>" enclObjs.remove(tuple) return fixString(tuple, res) } case .array(let array): if let res = objIdString(array) { return res } else if array.exprs.count == 0 { return "#<array>" } else { enclObjs.insert(array) var builder = StringBuilder(prefix: "#<array ", postfix: ">", separator: " ") for expr in array.exprs { builder.append(stringReprOf(expr)) } enclObjs.remove(array) return fixString(array, builder.description) } case .vector(let vector): if let res = objIdString(vector) { return res } else if vector.exprs.count == 0 { return vector.isGrowableVector ? "#g()" : "#()" } else { enclObjs.insert(vector) var builder = StringBuilder(prefix: vector.isGrowableVector ? "#g(" : "#(", postfix: ")", separator: " ") for expr in vector.exprs { builder.append(stringReprOf(expr)) } enclObjs.remove(vector) return fixString(vector, builder.description) } case .record(let record): guard case .record(let type) = record.kind else { guard record.exprs.count > 0 else { preconditionFailure("incorrect internal record type state: \(record.kind) | " + "\(record.description)") } guard case .symbol(let sym) = record.exprs[0] else { preconditionFailure("incorrect encoding of record type") } return "#<record-type \(sym.description)>" } if let res = objIdString(record) { return res } else { guard case .symbol(let sym) = type.exprs[0] else { preconditionFailure("incorrect encoding of record type") } enclObjs.insert(record) var builder = StringBuilder(prefix: "#<record \(sym.description)", postfix: ">", separator: ", ", initial: ": ") var fields = type.exprs[2] for expr in record.exprs { guard case .pair(let sym, let nextFields) = fields else { preconditionFailure("incorrect encoding of record \(type.exprs[0].description)") } builder.append(sym.description, "=", stringReprOf(expr)) fields = nextFields } enclObjs.remove(record) return fixString(record, builder.description) } case .table(let map): if let res = objIdString(map) { return res } else { enclObjs.insert(map) let prefix = Context.simplifiedDescriptions ? "#<hashtable" : "#<hashtable \(map.identityString)" var builder = StringBuilder(prefix: prefix, postfix: ">", separator: ", ", initial: ": ") for (key, value) in map.mappings { builder.append(stringReprOf(key), " -> ", stringReprOf(value)) } enclObjs.remove(map) return fixString(map, builder.description) } case .promise(let promise): return "#<\(promise.kind) \(promise.identityString)>" case .values(let list): var builder = StringBuilder(prefix: "#<values", postfix: ">", separator: " ", initial: ": ") var expr = list while case .pair(let car, let cdr) = expr { builder.append(stringReprOf(car)) expr = cdr } return builder.description case .procedure(let proc): switch proc.kind { case .parameter(let tuple): if let res = objIdString(proc) { return res } else { enclObjs.insert(proc) let res = "#<parameter \(proc.name): \(stringReprOf(tuple.snd))>" enclObjs.remove(proc) return fixString(proc, res) } case .rawContinuation(_): return "#<raw-continuation \(proc.embeddedName)>" case .closure(.continuation, _, _, _): return "#<continuation \(proc.embeddedName)>" default: return "#<procedure \(proc.embeddedName)>" } case .special(let special): return "#<special \(special.name)>" case .env(let environment): var type: String = "" switch environment.kind { case .library(let name): type = " " + name.description case .program(let filename): type = " " + filename case .repl: type = " interaction" case .custom: type = "" } var builder = StringBuilder(prefix: "#<env", postfix: ">", separator: ", ", initial: type + ": ") for sym in environment.boundSymbols { builder.append(sym.description) } return builder.description case .port(let port): return "#<\(port.typeDescription) \(port.identDescription)>" case .object(let obj): return obj.string case .tagged(.pair(let fst, _), let expr): var res = "#<" switch fst { case .pair(let head, let tail): var builder = StringBuilder(prefix: "", separator: " ") builder.append(stringReprOf(head)) var expr = tail while case .pair(let car, let cdr) = expr { builder.append(stringReprOf(car)) expr = cdr } if expr.isNull { res += builder.description + ": " } else { res += builder.description + " . \(stringReprOf(expr)): " } case .object(let obj): res += obj.tagString + " " default: res += stringReprOf(fst) + " " } switch expr { case .object(let obj): res += obj.tagString.truncated(limit: 100) case .pair(let head, let tail): var builder = StringBuilder(prefix: "", separator: " ") builder.append(stringReprOf(head)) var expr = tail while case .pair(let car, let cdr) = expr { builder.append(stringReprOf(car)) expr = cdr } res += (builder.description + (expr.isNull ? "" : " . \(stringReprOf(expr))")) .truncated(limit: 100) default: res += stringReprOf(expr).truncated(limit: 100) } return res + ">" case .tagged(let tag, let expr): if case .object(let objTag) = tag { if case .object(let objExpr) = expr { return "#<\(objTag.tagString): \(objExpr.tagString)>" } else { return "#<\(objTag.tagString): \(stringReprOf(expr))>" } } else if case .object(let objExpr) = expr { return "#<tag \(stringReprOf(tag)): \(objExpr.tagString)>" } else { return "#<tag \(stringReprOf(tag)): \(stringReprOf(expr))>" } case .error(let error): return "#<\(error.inlineDescription)>" case .syntax(_, let expr): return stringReprOf(expr) } } return stringReprOf(self) } internal static func escapeStr(_ str: String) -> String { var res = "" for c in str { switch c { case "\u{7}": res += "\\a" case "\u{8}": res += "\\b" case "\t": res += "\\t" case "\n": res += "\\n" case "\u{11}": res += "\\v" case "\u{12}": res += "\\f" case "\r": res += "\\r" case "\"": res += "\\\"" case "\\": res += "\\\\" default: res.append(c) } } return res } public static func ==(lhs: Expr, rhs: Expr) -> Bool { return equalExpr(rhs, lhs) } } public typealias ByteVector = MutableBox<[UInt8]> public typealias DoubleComplex = ImmutableBox<Complex<Double>>
348e4f9f3c944f1cb4cf70a40617984a
30.094634
100
0.548695
false
false
false
false
rwbutler/TypographyKit
refs/heads/master
Example/TypographyKit/MenuViewController.swift
mit
1
// // MenuViewController.swift // TypographyKit // // Created by Ross Butler on 22/02/2020. // Copyright © 2020 Ross Butler. All rights reserved. // import Foundation import UIKit import TypographyKit class MenuViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() title = "TypographyKit" } @IBAction func presentTypographyColors(_ sender: UIButton) { if #available(iOS 9.0, *), let navController = navigationController { let navSettings = ViewControllerNavigationSettings(animated: true, closeButtonAlignment: .noCloseButtonExportButtonRight) TypographyKit.pushTypographyColors(navigationController: navController, navigationSettings: navSettings) } } @IBAction func presentTypographyStyles(_ sender: UIButton) { if let navController = navigationController { let navSettings = ViewControllerNavigationSettings(animated: true, closeButtonAlignment: .noCloseButtonExportButtonRight) TypographyKit.pushTypographyStyles(navigationController: navController, navigationSettings: navSettings) } } }
cf9363d98eb881b10ad8b7a5bfaed9bd
34.555556
117
0.657031
false
false
false
false
DylanSecreast/uoregon-cis-portfolio
refs/heads/master
uoregon-cis-399/examples/LendingLibrary/LendingLibrary/Source/Controller/CategoryDetailViewController.swift
gpl-3.0
1
// // CategoryDetailViewController.swift // LendingLibrary // // Created by Charles Augustine. // // import UIKit class CategoryDetailViewController: UITableViewController, UITextFieldDelegate { // MARK: IBAction @IBAction private func cancel(_ sender: AnyObject) { delegate.categoryDetailViewControllerDidFinish(self) } @IBAction private func save(_ sender: AnyObject) { let orderIndex = delegate.numberOfCategoriesForCategoryDetailViewController(self) do { try LendingLibraryService.shared.addCategory(withName: name, andOrderIndex: orderIndex) delegate.categoryDetailViewControllerDidFinish(self) } catch _ { let alertController = UIAlertController(title: "Save failed", message: "Failed to save the new lent item", preferredStyle: .alert) alertController.addAction(UIAlertAction(title: "OK", style: .default, handler: nil)) present(alertController, animated: true, completion: nil) } } // MARK: UITableViewDelegate override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { nameTextField.becomeFirstResponder() } // MARK: UITextFieldDelegate func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool { name = ((textField.text ?? "") as NSString).replacingCharacters(in: range, with: string) return true } func textFieldShouldClear(_ textField: UITextField) -> Bool { return true } func textFieldShouldReturn(_ textField: UITextField) -> Bool { nameTextField.resignFirstResponder() return false } // MARK: View Management override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) if selectedCategory != nil { navigationItem.title = "Edit Category" navigationItem.leftBarButtonItem = nil navigationItem.rightBarButtonItem = nil } else { navigationItem.title = "Add Category" navigationItem.leftBarButtonItem = UIBarButtonItem(barButtonSystemItem: .cancel, target: self, action: #selector(CategoryDetailViewController.cancel(_:))) navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .save, target: self, action: #selector(CategoryDetailViewController.save(_:))) } nameTextField.text = name } override func viewWillDisappear(_ animated: Bool) { if let someCategory = selectedCategory { do { try LendingLibraryService.shared.renameCategory(someCategory, withNewName: name) } catch _ { let alertController = UIAlertController(title: "Save failed", message: "Failed to save the new lent item", preferredStyle: .alert) alertController.addAction(UIAlertAction(title: "OK", style: .default, handler: nil)) present(alertController, animated: true, completion: nil) } } super.viewWillDisappear(animated) } // MARK: Properties var selectedCategory: Category? { didSet { if let someCategory = selectedCategory { name = someCategory.name! } else { name = CategoryDetailViewController.defaultName } } } var delegate: CategoryDetailViewControllerDelegate! // MARK: Properties (Private) private var name = CategoryDetailViewController.defaultName // MARK: Properties (IBOutlet) @IBOutlet private weak var nameTextField: UITextField! // MARK: Properties (Private Static Constant) private static let defaultName = "New Category" }
ad4f5038562cb6dd19d5a33893dbb685
29.59633
157
0.753823
false
false
false
false
maurovc/MyMarvel
refs/heads/master
MyMarvel/NoDataCollectionViewCell.swift
mit
1
// // NoDataCollectionViewCell.swift // MyMarvel // // Created by Mauro Vime Castillo on 27/10/16. // Copyright © 2016 Mauro Vime Castillo. All rights reserved. // import UIKit /** SadCharacters is an enumeration used represent the different "no data cell" options. This class uses famous Marvel charcters to represent the data. - Deadpool - Cyclops - Wolverine - Daredevil */ enum SadCharacters: Int { case Deadpool = 0 case Cyclops = 1 case Wolverine = 2 case Daredevil = 3 func imageName() -> String { switch self { case .Deadpool: return "sadDeadpool" case .Cyclops: return "sadCyclops" case .Wolverine: return "sadWolverine" case .Daredevil: return "sadDaredevil" } } func description() -> String { switch self { case .Deadpool: return NSLocalizedString("I'm sorry! This character doesn't appear in any comic", comment: "") case .Cyclops: return NSLocalizedString("I'm sorry! This character doesn't have any serie", comment: "") case .Wolverine: return NSLocalizedString("I'm sorry! This character doesn't have any event", comment: "") case .Daredevil: return NSLocalizedString("I'm sorry! This character doesn't have any story", comment: "") } } } /// Class that represents a cell used to display that a CollectionView doesn't have data. class NoDataCollectionViewCell: UICollectionViewCell { static let identifier = "noDataCell" @IBOutlet weak var descriptionLabel: UILabel! @IBOutlet weak var logoImageView: UIImageView! var type: SadCharacters? { didSet { descriptionLabel.text = type?.description() logoImageView.image = UIImage(named: type?.imageName() ?? "") } } }
3b91f946bac2d3c94d4b93c8e828e8e3
29.779661
148
0.654736
false
false
false
false
andrucuna/ios
refs/heads/master
Swiftris/Swiftris/Shape.swift
gpl-2.0
1
// // Shape.swift // Swiftris // // Created by Andrés Ruiz on 9/25/14. // Copyright (c) 2014 Andrés Ruiz. All rights reserved. // import Foundation import SpriteKit let NumOrientations: UInt32 = 4 enum Orientation: Int, Printable { case Zero = 0, Ninety, OneEighty, TwoSeventy var description: String { switch self { case .Zero: return "0" case .Ninety: return "90" case .OneEighty: return "180" case .TwoSeventy: return "270" } } static func random() -> Orientation { return Orientation.fromRaw(Int(arc4random_uniform(NumOrientations)))! } // We provided a method capable of returning the next orientation when traveling either clockwise or // counterclockwise. static func rotate(orientation:Orientation, clockwise: Bool) -> Orientation { var rotated = orientation.toRaw() + (clockwise ? 1 : -1) if rotated > Orientation.TwoSeventy.toRaw() { rotated = Orientation.Zero.toRaw() } else if rotated < 0 { rotated = Orientation.TwoSeventy.toRaw() } return Orientation.fromRaw(rotated)! } } // The number of total shape varieties let NumShapeTypes: UInt32 = 7 // Shape indexes let FirstBlockIdx: Int = 0 let SecondBlockIdx: Int = 1 let ThirdBlockIdx: Int = 2 let FourthBlockIdx: Int = 3 class Shape: Hashable, Printable { // The color of the shape let color:BlockColor // The blocks comprising the shape var blocks = Array<Block>() // The current orientation of the shape var orientation: Orientation // The column and row representing the shape's anchor point var column, row:Int // Required Overrides // Defines a computed Dictionary. A dictionary is defined with square braces – […] – and maps one type // of object to another. // Subclasses must override this property var blockRowColumnPositions: [Orientation: Array<(columnDiff: Int, rowDiff: Int)>] { return [:] } // #2 // Subclasses must override this property var bottomBlocksForOrientations: [Orientation: Array<Block>] { return [:] } // We wrote a complete computed property which is designed to return the bottom blocks of the shape at // its current orientation. This will be useful later when our blocks get physical and start contacting // walls and each other. var bottomBlocks:Array<Block> { if let bottomBlocks = bottomBlocksForOrientations[orientation] { return bottomBlocks } return [] } // Hashable var hashValue:Int { // We use the reduce<S : Sequence, U>(sequence: S, initial: U, combine: (U, S.GeneratorType.Element) // -> U) -> U method to iterate through our entire blocks array. We exclusively-or each block's // hashValue together to create a single hashValue for the Shape they comprise. return reduce(blocks, 0) { $0.hashValue ^ $1.hashValue } } // Printable var description: String { return "\(color) block facing \(orientation): \(blocks[FirstBlockIdx]), \(blocks[SecondBlockIdx]), \(blocks[ThirdBlockIdx]), \(blocks[FourthBlockIdx])" } init( column:Int, row:Int, color: BlockColor, orientation:Orientation ) { self.color = color self.column = column self.row = row self.orientation = orientation initializeBlocks() } // We introduce a special type of initializer. A convenience initializer must call down to a standard // initializer or otherwise your class will fail to compile. We've placed this one here in order to // simplify the initialization process for users of the Shape class. It assigns the given row and column // values while generating a random color and a random orientation. convenience init(column:Int, row:Int) { self.init(column:column, row:row, color:BlockColor.random(), orientation:Orientation.random()) } // We defined a final function which means it cannot be overridden by subclasses. This implementation of // initializeBlocks() is the only one allowed by Shape and its subclasses. final func initializeBlocks() { // We introduced conditional assignments. This if conditional first attempts to assign an array into // blockRowColumnTranslations after extracting it from the computed dictionary property. If one is // not found, the if block is not executed. if let blockRowColumnTranslations = blockRowColumnPositions[orientation] { for i in 0..<blockRowColumnTranslations.count { let blockRow = row + blockRowColumnTranslations[i].rowDiff let blockColumn = column + blockRowColumnTranslations[i].columnDiff let newBlock = Block(column: blockColumn, row: blockRow, color: color) blocks.append(newBlock) } } } final func rotateBlocks(orientation: Orientation) { if let blockRowColumnTranslation:Array<(columnDiff: Int, rowDiff: Int)> = blockRowColumnPositions[orientation] { // We introduce the enumerate operator. This allows us to iterate through an array object by // defining an index variable for (idx, (columnDiff:Int, rowDiff:Int)) in enumerate(blockRowColumnTranslation) { blocks[idx].column = column + columnDiff blocks[idx].row = row + rowDiff } } } // We created a couple methods for quickly rotating a shape one turn clockwise or counterclockwise, this // will come in handy when testing a potential rotation and reverting it if it breaks the rules. Below //that we've added convenience functions which allow us to move our shapes incrementally in any direction. final func rotateClockwise() { let newOrientation = Orientation.rotate(orientation, clockwise: true) rotateBlocks(newOrientation) orientation = newOrientation } final func rotateCounterClockwise() { let newOrientation = Orientation.rotate(orientation, clockwise: false) rotateBlocks(newOrientation) orientation = newOrientation } final func lowerShapeByOneRow() { shiftBy(0, rows:1) } final func raiseShapeByOneRow() { shiftBy(0, rows:-1) } final func shiftRightByOneColumn() { shiftBy(1, rows:0) } final func shiftLeftByOneColumn() { shiftBy(-1, rows:0) } // We've included a simple shiftBy(columns: Int, rows: Int) method which will adjust each row and column // by rows and columns, respectively. final func shiftBy(columns: Int, rows: Int) { self.column += columns self.row += rows for block in blocks { block.column += columns block.row += rows } } // We provide an absolute approach to position modification by setting the column and row properties // before rotating the blocks to their current orientation which causes an accurate realignment of all // blocks relative to the new row and column properties. final func moveTo(column: Int, row:Int) { self.column = column self.row = row rotateBlocks(orientation) } final class func random(startingColumn:Int, startingRow:Int) -> Shape { switch Int(arc4random_uniform(NumShapeTypes)) { // We've created a method to generate a random Tetromino shape and you can see that subclasses // naturally inherit initializers from their parent class. case 0: return SquareShape(column:startingColumn, row:startingRow) case 1: return LineShape(column:startingColumn, row:startingRow) case 2: return TShape(column:startingColumn, row:startingRow) case 3: return LShape(column:startingColumn, row:startingRow) case 4: return JShape(column:startingColumn, row:startingRow) case 5: return SShape(column:startingColumn, row:startingRow) default: return ZShape(column:startingColumn, row:startingRow) } } } func ==(lhs: Shape, rhs: Shape) -> Bool { return lhs.row == rhs.row && lhs.column == rhs.column }
2b30a4f5841b96d15b08b51e244dffad
33.255906
159
0.630732
false
false
false
false
Harley-xk/Chrysan
refs/heads/master
Example/AppDelegate.swift
mit
1
// // AppDelegate.swift // Example // // Created by Harley-xk on 2020/6/1. // Copyright © 2020 Harley. All rights reserved. // import UIKit import Chrysan @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. let options = HUDResponder.global.viewOptions options.mainColor = .systemRed var maskColor = UIColor.black.withAlphaComponent(0.2) if #available(iOS 13.0, *) { maskColor = UIColor.label.withAlphaComponent(0.2) } options.maskColor = maskColor options.hudVisualEffect = UIBlurEffect(style: .prominent) options.hudCornerRadius = 10 HUDResponder.global.register(.circleDots, for: .loading) return true } }
297601884de1042b0dc54d325ef5ea05
26.75
145
0.677678
false
false
false
false
caiobzen/Pomodoro
refs/heads/master
Pomodoro/CCCoreDataStack.swift
mit
1
// // CCCoreDataStack.swift // Pomodoro // // Created by Carlos Corrêa on 8/25/15. // Copyright © 2015 Carlos Corrêa. All rights reserved. // import Foundation import CoreData public class CCCoreDataStack { public class var sharedInstance:CCCoreDataStack { struct Singleton { static let instance = CCCoreDataStack() } return Singleton.instance } // MARK: - CRUD methods /** This method will add a new TaskModel object into core data. :param: name The given name of the TaskModel object. :returns: A brand new TaskModel object. */ public func createTask(name:String) -> TaskModel? { let newTask = NSEntityDescription.insertNewObjectForEntityForName("TaskModel", inManagedObjectContext: self.managedObjectContext!) as! TaskModel; newTask.name = name newTask.creationTime = NSDate() return newTask } /** This method will delete a TaskModel object from core data. :param: task The given TaskModel object to be deleted. */ public func deleteTask(task:TaskModel) { self.managedObjectContext?.deleteObject(task) self.saveContext() } /** This method will fetch all the TaskModel objects from core data. :returns: An Array of TaskModel objects. */ public func allTasks() -> [TaskModel]? { let request = NSFetchRequest(entityName: "TaskModel") request.sortDescriptors = [ NSSortDescriptor(key: "creationTime", ascending: false) ] do { let tasks = try self.managedObjectContext?.executeFetchRequest(request) as! [TaskModel]? return tasks } catch let error as NSError { print(error) return [] } } // MARK: - lazy vars //Why lazy vars? For delaying the creation of an object or some other expensive process until it’s needed. And we can also add logic to our lazy initialization. That is cool, huh? lazy var applicationDocumentsDirectory: NSURL = { let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask) return urls[urls.count-1] as NSURL }() // The managed object model for the application. lazy var managedObjectModel: NSManagedObjectModel = { return NSManagedObjectModel.mergedModelFromBundles(nil)! }() // The persistent store coordinator for the application. lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator? = { var coordinator: NSPersistentStoreCoordinator? = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel) var containerPath = self.applicationDocumentsDirectory.URLByAppendingPathComponent("Pomodoro.sqlite") var error: NSError? = nil do { try coordinator!.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: containerPath, options: nil) } catch { return nil } return coordinator }() lazy var managedObjectContext: NSManagedObjectContext? = { let coordinator = self.persistentStoreCoordinator if coordinator == nil { return nil } var managedObjectContext = NSManagedObjectContext(concurrencyType: NSManagedObjectContextConcurrencyType.MainQueueConcurrencyType) managedObjectContext.persistentStoreCoordinator = coordinator return managedObjectContext }() // MARK: - Core Data Saving support public func saveContext () { if let context = self.managedObjectContext { if (context.hasChanges) { do{ try context.save() } catch let error as NSError { print(error) } } } } }
413deb1143f982211c9ef9f36422a0fa
32.842105
183
0.65232
false
false
false
false
RickiG/dynamicCellHeight
refs/heads/master
AutolayoutCellPoC/TextCell.swift
mit
1
// // BasicCell.swift // AutolayoutCellPoC // // Created by Ricki Gregersen on 05/12/14. // Copyright (c) 2014 youandthegang.com. All rights reserved. // import UIKit class TextCell: SizeableTableViewCell, SizeableCell, UpdateableCell { @IBOutlet weak var titleLabel: UILabel! @IBOutlet weak var subTitleLabel: UILabel! override func awakeFromNib() { super.awakeFromNib() // Initialization code } override func layoutSubviews() { super.layoutSubviews() self.contentView.layoutIfNeeded() updatePreferredLayoutSizes() } /* Method : updatePreferredLayoutSizes() The preferredMaxLayoutWidth must be reset on each layout for the dynamic sizing to work */ func updatePreferredLayoutSizes() { titleLabel.preferredMaxLayoutWidth = CGRectGetWidth(titleLabel.frame) subTitleLabel.preferredMaxLayoutWidth = CGRectGetWidth(subTitleLabel.frame) } func update(data: AnyObject) { if let d = data as? CellTextData { titleLabel.text = d.title subTitleLabel.text = d.subTitle } } }
e88835e2efa8470f596647bff1583ef8
26.095238
83
0.672232
false
false
false
false
snewolnivekios/HideNavTabBarsDemo
refs/heads/master
HideNavTabBarsDemo/BarsSettingsViewController.swift
gpl-3.0
1
// // BarsSettingsViewController.swift // HideNavTabBarsDemo // // Copyright © 2016 Kevin L. Owens. All rights reserved. // // HideNavTabBarsDemo 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. // // HideNavTabBarsDemo 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 HideNavTabBarsDemo. If not, see <http://www.gnu.org/licenses/>. // import UIKit /// Presents the table view controller-based settings view for navigation and tab bar animations. class BarsSettingsViewController: UITableViewController { /// The data containing switch-configurable navigation and tab bar animation settings. var barsSettingsModel = BarsSettingsModel(id: "\(#file)") /// Configures cell heights to adjust to autosizing subviews (where Lines is set to 0). override func viewDidLoad() { tableView.rowHeight = UITableViewAutomaticDimension tableView.estimatedRowHeight = 42 } /// Shows the navigation bar. override func viewWillAppear(_ animated: Bool) { navigationController?.setNavigationBarHidden(false, animated: true) } /// Returns the number of settings groups. override func numberOfSections(in tableView: UITableView) -> Int { return barsSettingsModel.numberOfSections } /// Returns the number of configuration items in the given `section`. override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return barsSettingsModel.numberOfRows(inSection: section) } /// Returns a cell populated with `barsSettings`-provided data corresponding to the given `indexPath`. override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "LabelDetailSwitch") as! LabelDetailSwitchCell if let content = barsSettingsModel.content(for: indexPath) { cell.label.text = content.label cell.label.sizeToFit() cell.detail.text = content.detail cell.switch.isOn = content.isOn cell.switch.tag = indexPath.section * 100 + indexPath.row cell.switch.addTarget(self, action: #selector(BarsSettingsViewController.switchValueChanged(sender:)), for: .valueChanged) } return cell } /// Updates the `barsSettings` with the setting corresponding do the given `sender` switch. func switchValueChanged(sender: UISwitch) { let section = sender.tag / 100 let row = sender.tag - section barsSettingsModel.set(isOn: sender.isOn, for: IndexPath(row: row, section: section)) } }
366835d5e6581f3dc1b00731557030df
38.105263
128
0.74428
false
false
false
false
adevelopers/prosvet
refs/heads/master
Prosvet/Common/Controllers/MainVC.swift
mit
1
// // ViewController.swift // Prosvet // // Created by adeveloper on 17.04.17. // Copyright © 2017 adeveloper. All rights reserved. // import UIKit class MainVC: UIViewController { @IBOutlet weak var uiTable: UITableView! var posts:[Post] = [Post]() override func viewDidLoad() { super.viewDidLoad() loadFeedFromServer() } func loadFeedFromServer(){ let model = NetModel() model.npGetList({ posts in DispatchQueue.main.async { self.posts = posts self.uiTable.reloadData() } }) } } // MARK: - Constants extension MainVC { fileprivate struct Constants { static let postCellIdentifier = "PostCell" static let postSegueIdentifier = "segueShowPost" } } //MARK: DataSource extension MainVC: UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return posts.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = Bundle.main.loadNibNamed("MainCell", owner: self, options: nil)?.first as! MainCell let title = posts[indexPath.row].title cell.uiTitle.text = title return cell } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 80.0 } } // MARK: - UITableViewDelegate extension MainVC: UITableViewDelegate { func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: true) performSegue(withIdentifier: Constants.postSegueIdentifier, sender: posts[indexPath.row]) } } // MARK: - Segue extension MainVC { override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == Constants.postSegueIdentifier { let controller = segue.destination as! PostDetail let post = sender as! Post controller.post = post } } }
8af4d3d871078f82f57f533a90dc722f
22.695652
110
0.618349
false
false
false
false
cuba/NetworkKit
refs/heads/master
Source/Request/MultiPartRequest.swift
mit
1
// // MultiPartRequest.swift // NetworkKit iOS // // Created by Jacob Sikorski on 2019-03-27. // Copyright © 2019 Jacob Sikorski. All rights reserved. // import Foundation /// A convenience Request object for submitting a multi-part request. public struct MultiPartRequest: Request { public var method: HTTPMethod public var path: String public var queryItems: [URLQueryItem] public var headers: [String: String] public var httpBody: Data? /// Initialize this upload request. /// /// - Parameters: /// - method: The HTTP method to use /// - path: The path that will be appended to the baseURL on the `ServerProvider`. public init(method: HTTPMethod, path: String) { self.method = method self.path = path self.queryItems = [] self.headers = [:] } /// Set the HTTP body using multi-part form data /// /// - Parameters: /// - file: The file to attach. This file will be attached as-is /// - fileName: The file name that will be used. /// - mimeType: The mime type or otherwise known as Content-Type /// - parameters: Any additional mult-part parameters to include mutating public func setHTTPBody(file: Data, fileFieldName: String = "file", fileName: String, mimeType: String, parameters: [String: String] = [:]) { let boundary = UUID().uuidString let contentType = "multipart/form-data; boundary=\(boundary)" let endBoundaryPart = String(format: "--%@--\r\n", boundary) var body = makeBody(file: file, fileFieldName: fileFieldName, fileName: fileName, mimeType: mimeType, parameters: parameters, boundary: boundary) body.append(endBoundaryPart.data(using: String.Encoding.utf8)!) headers["Content-Length"] = "\(body.count)" headers["Content-Type"] = contentType self.httpBody = body } /// Set the HTTP body using multi-part form data /// /// - Parameters: /// - parameters: Any mult-part parameters to include mutating public func setHTTPBody(parameters: [String: String]) { let boundary = UUID().uuidString let contentType = "multipart/form-data; boundary=\(boundary)" let endBoundaryPart = String(format: "--%@--\r\n", boundary) var body = makeBody(parameters: parameters, boundary: boundary) body.append(endBoundaryPart.data(using: String.Encoding.utf8)!) headers["Content-Length"] = "\(body.count)" headers["Content-Type"] = contentType self.httpBody = body } private func makeBody(file: Data, fileFieldName: String, fileName: String, mimeType: String, parameters: [String: String], boundary: String) -> Data { var body = makeBody(parameters: parameters, boundary: boundary) // Add image data let boundaryPart = String(format: "--%@\r\n", boundary) let keyPart = String(format: "Content-Disposition:form-data; name=\"%@\"; filename=\"%@\"\r\n", fileFieldName, fileName) let valuePart = String(format: "Content-Type: %@\r\n\r\n", mimeType) let spacePart = String(format: "\r\n") body.append(boundaryPart.data(using: String.Encoding.utf8)!) body.append(keyPart.data(using: String.Encoding.utf8)!) body.append(valuePart.data(using: String.Encoding.utf8)!) body.append(file) body.append(spacePart.data(using: String.Encoding.utf8)!) return body } private func makeBody(parameters: [String: String], boundary: String) -> Data { var body = Data() // Add params (all params are strings) for (key, value) in parameters { let boundaryPart = String(format: "--%@\r\n", boundary) let keyPart = String(format: "Content-Disposition:form-data; name=\"%@\"\r\n\r\n", key) let valuePart = String(format: "%@\r\n", value) body.append(boundaryPart.data(using: String.Encoding.utf8)!) body.append(keyPart.data(using: String.Encoding.utf8)!) body.append(valuePart.data(using: String.Encoding.utf8)!) } return body } }
984f2528079de6647f5e677f8dc11ca9
41.13
154
0.626157
false
false
false
false
lkzhao/MCollectionView
refs/heads/master
Carthage/Checkouts/YetAnotherAnimationLibrary/Sources/Solvers/CurveSolver.swift
mit
2
// The MIT License (MIT) // // Copyright (c) 2016 Luke Zhao <[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 Foundation public struct CurveSolver<Value: VectorConvertible>: Solver { public let current: AnimationProperty<Value> public let target: AnimationProperty<Value> public let velocity: AnimationProperty<Value> public let curve: Curve public let duration: TimeInterval public var start: Value.Vector public var time: TimeInterval = 0 init(duration: TimeInterval, curve: Curve, current: AnimationProperty<Value>, target: AnimationProperty<Value>, velocity: AnimationProperty<Value>) { self.current = current self.target = target self.velocity = velocity self.duration = duration self.curve = curve self.start = current.vector } public mutating func solve(dt: TimeInterval) -> Bool { time += dt if time > duration { current.vector = target.vector velocity.vector = .zero return true } let t = curve.solve(time / duration) let oldCurrent = current.vector current.vector = (target.vector - start) * t + start velocity.vector = (current.vector - oldCurrent) / dt return false } }
519a325364f8598882156d93b6ae671e
38.233333
80
0.695837
false
false
false
false
latera1n/Learning-Swift
refs/heads/master
TipCalc/TipCalc/ViewController.swift
mit
1
// // ViewController.swift // TipCalc // // Created by DengYuchi on 2/19/16. // Copyright © 2016 LateRain. All rights reserved. // import UIKit class ViewController: UIViewController { @IBOutlet weak var textFieldAmount: UITextField! @IBOutlet weak var slider: UISlider! @IBOutlet weak var labelPercentage: UILabel! { didSet { labelPercentage.font = labelPercentage.font.monospacedDigitFont } } @IBOutlet weak var labelTip: UILabel! { didSet { labelTip.font = labelTip.font.monospacedDigitFont } } @IBOutlet weak var labelTotal: UILabel! { didSet { labelTotal.font = labelTotal.font.monospacedDigitFont } } var amountString = "" override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. slider.minimumTrackTintColor = UIColor(red: 0, green: 200/255, blue: 83/255, alpha: 1) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func sliderTouchedDown(sender: AnyObject) { let textFieldAmountString = textFieldAmount.text! if textFieldAmountString != "" && (textFieldAmountString as NSString).substringToIndex(1) != "$" && textFieldAmountString != "." { dismissKeyboard(sender) } } @IBAction func sliderValueChanged(sender: AnyObject) { updateDisplay() } func updateDisplay() { let sliderValue = slider.value let tipPercentage = Int(sliderValue) labelPercentage.text = String(tipPercentage) + "%" if amountString != "" { let numberFormatter = NSNumberFormatter() numberFormatter.numberStyle = .CurrencyStyle let tip = Double(amountString)! * Double(tipPercentage) / 100 labelTip.text = numberFormatter.stringFromNumber(tip) labelTotal.text = numberFormatter.stringFromNumber(Double(amountString)! + tip) } } @IBAction func dismissKeyboard(sender: AnyObject) { view.endEditing(true) let textFieldAmountString = textFieldAmount.text! if textFieldAmountString != "" && (textFieldAmountString as NSString).substringToIndex(1) != "$" && textFieldAmountString != "." { amountString = textFieldAmount.text! let numberFormatter = NSNumberFormatter() numberFormatter.numberStyle = .CurrencyStyle textFieldAmount.text = numberFormatter.stringFromNumber(Double(amountString)!) if textFieldAmount.text != "$0.00" { updateDisplay() } else { labelTip.text = "$0.00" labelTotal.text = "$0.00" amountString = "" textFieldAmount.text = "" } } else if textFieldAmountString == "" { labelTip.text = "$0.00" labelTotal.text = "$0.00" amountString = "" } else if textFieldAmountString == "." { labelTip.text = "$0.00" labelTotal.text = "$0.00" amountString = "" textFieldAmount.text = "" } } }
718a6aeb15dccd6cb7a2c191a274d87a
33.736842
138
0.603636
false
false
false
false
lenssss/whereAmI
refs/heads/master
Whereami/Controller/Game/GameChallengeBenameViewController.swift
mit
1
// // GameChallengeBenameViewController.swift // Whereami // // Created by A on 16/3/25. // Copyright © 2016年 WuQifei. All rights reserved. // import UIKit import SVProgressHUD class GameChallengeBenameViewController: UIViewController { var challengeLogoView:UIImageView? = nil var tipLabel:UILabel? = nil var nameTextField:UITextField? = nil var gameRange:CountryModel? = nil //地区 var isRandom:Bool? = nil //是否挑战 var matchUsers:[FriendsModel]? = nil //匹配对手 override func viewDidLoad() { super.viewDidLoad() self.setConfig() self.title = NSLocalizedString("challengeFriend",tableName:"Localizable", comment: "") self.matchUsers = GameParameterManager.sharedInstance.matchUser if self.matchUsers == nil { GameParameterManager.sharedInstance.matchUser = [FriendsModel]() } self.getGameModel() self.setUI() // Do any additional setup after loading the view. } func getGameModel(){ let gameMode = GameParameterManager.sharedInstance.gameMode let gameModel = gameMode!["competitor"] as! Int if gameModel == Competitor.Friend.rawValue { self.isRandom = false } else{ self.isRandom = true } } func setUI(){ self.view.backgroundColor = UIColor.getGameColor() self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: NSLocalizedString("next",tableName:"Localizable", comment: ""), style: .Done, target: self, action: #selector(GameChallengeBenameViewController.pushToNextVC)) self.challengeLogoView = UIImageView() self.challengeLogoView?.image = UIImage(named: "ChallengeLogo") self.challengeLogoView?.contentMode = .ScaleAspectFit self.challengeLogoView?.layer.masksToBounds = true self.challengeLogoView?.layer.cornerRadius = 50 self.view.addSubview(self.challengeLogoView!) self.tipLabel = UILabel() self.tipLabel?.text = NSLocalizedString("namingChallenge",tableName:"Localizable", comment: "") self.tipLabel?.textAlignment = .Center self.view.addSubview(self.tipLabel!) self.nameTextField = UITextField() self.nameTextField?.rac_signalForControlEvents(.EditingDidEndOnExit).subscribeNext({ (textField) in textField.resignFirstResponder() }) self.nameTextField?.borderStyle = .RoundedRect self.nameTextField?.backgroundColor = UIColor.whiteColor() self.view.addSubview(self.nameTextField!) self.challengeLogoView?.autoPinEdgeToSuperviewEdge(.Top, withInset: 60) self.challengeLogoView?.autoSetDimensionsToSize(CGSize(width: 100,height: 100)) self.challengeLogoView?.autoAlignAxisToSuperviewAxis(.Vertical) self.challengeLogoView?.autoPinEdge(.Bottom, toEdge: .Top, ofView: self.tipLabel!, withOffset: -50) self.tipLabel?.autoSetDimensionsToSize(CGSize(width: 200,height: 50)) self.tipLabel?.autoAlignAxisToSuperviewAxis(.Vertical) self.tipLabel?.autoPinEdge(.Bottom, toEdge: .Top, ofView: self.nameTextField!, withOffset: -10) self.nameTextField?.autoPinEdgeToSuperviewEdge(.Left, withInset: 50) self.nameTextField?.autoPinEdgeToSuperviewEdge(.Right, withInset: 50) } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) self.navigationItem.rightBarButtonItem?.enabled = true } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func pushToNextVC(){ self.navigationItem.rightBarButtonItem?.enabled = false let backBtn = TheBackBarButton.initWithAction({ let viewControllers = self.navigationController?.viewControllers let index = (viewControllers?.count)! - 2 let viewController = viewControllers![index] self.navigationController?.popToViewController(viewController, animated: true) }) self.navigationItem.leftBarButtonItem = UIBarButtonItem(customView: backBtn) if isRandom == false { let selectFriendVC = GameChallengeSelectFriendViewController() GameParameterManager.sharedInstance.roomTitle = self.nameTextField?.text self.navigationController?.pushViewController(selectFriendVC, animated: true) } else{ var dict = [String: AnyObject]() dict["countryCode"] = GameParameterManager.sharedInstance.gameRange?.countryCode dict["accountId"] = UserModel.getCurrentUser()?.id dict["title"] = GameParameterManager.sharedInstance.roomTitle dict["friendId"] = self.getFriendIdArray() SocketManager.sharedInstance.sendMsg("startChangellengeFriendBattle", data: dict, onProto: "startChangellengeFriendBattleed") { (code, objs) in if code == statusCode.Normal.rawValue{ // CoreDataManager.sharedInstance.consumeLifeItem() print("=====================\(objs)") self.pushVC(objs) self.navigationItem.rightBarButtonItem?.enabled = true } else if code == statusCode.Error.rawValue { self.runInMainQueue({ SVProgressHUD.showErrorWithStatus("error") self.performSelector(#selector(self.SVProgressDismiss), withObject: nil, afterDelay: 1) }) } } } } func pushVC(objs:[AnyObject]){ let matchDetailModel = MatchDetailModel.getModelFromDictionary(objs[0] as! [String : AnyObject]) GameParameterManager.sharedInstance.matchDetailModel = matchDetailModel self.runInMainQueue({ let battleDetailsVC = GameChallengeBattleDetailsViewController() self.navigationController?.pushViewController(battleDetailsVC, animated: true) }) } func getFriendIdArray() -> [AnyObject] { var array = [AnyObject]() for item in self.matchUsers! { var dic = [String: AnyObject]() dic["id"] = item.friendId array.append(dic) } return array } func SVProgressDismiss(){ SVProgressHUD.dismiss() self.backAction() } func backAction(){ let viewControllers = self.navigationController?.viewControllers if viewControllers?.count != 1{ let index = (viewControllers?.count)! - 2 let viewController = viewControllers![index] self.navigationController?.popToViewController(viewController, animated: true) } self.dismissViewControllerAnimated(true, completion: nil) } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
16bb4d4de7c1e7ea57602af14df6fe94
40.106145
230
0.64773
false
false
false
false
qutheory/vapor
refs/heads/master
Sources/Vapor/Middleware/FileMiddleware.swift
mit
1
/// Serves static files from a public directory. /// /// `FileMiddleware` will default to `DirectoryConfig`'s working directory with `"/Public"` appended. public final class FileMiddleware: Middleware { /// The public directory. /// - note: Must end with a slash. private let publicDirectory: String /// Creates a new `FileMiddleware`. public init(publicDirectory: String) { self.publicDirectory = publicDirectory.hasSuffix("/") ? publicDirectory : publicDirectory + "/" } /// See `Middleware`. public func respond(to request: Request, chainingTo next: Responder) -> EventLoopFuture<Response> { // make a copy of the path var path = request.url.path // path must be relative. while path.hasPrefix("/") { path = String(path.dropFirst()) } // protect against relative paths guard !path.contains("../") else { return request.eventLoop.makeFailedFuture(Abort(.forbidden)) } // create absolute file path let filePath = self.publicDirectory + (path.removingPercentEncoding ?? path) // check if file exists and is not a directory var isDir: ObjCBool = false guard FileManager.default.fileExists(atPath: filePath, isDirectory: &isDir), !isDir.boolValue else { return next.respond(to: request) } // stream the file let res = request.fileio.streamFile(at: filePath) return request.eventLoop.makeSucceededFuture(res) } }
990f294084db457f9f9f27589cfe89db
35.5
108
0.642531
false
false
false
false
justin/Aspen
refs/heads/master
Aspen/FileLogger.swift
mit
1
// The MIT License (MIT) // // Copyright (c) 2015 Justin Williams // // 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 final class FileLogger: NSObject, LogInterface { public var fileURL: URL? private var fileHandle: FileHandle? public override init() { super.init() let locale = Locale(identifier: "en_US_POSIX") let timeFormatter = DateFormatter() timeFormatter.locale = locale timeFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZZZZZ" let dateString = timeFormatter.string(from: Date()) let fm = FileManager.default let urls = fm.urls(for: .libraryDirectory, in: .userDomainMask) guard let url = urls.last else { return } let path = URL.init(fileURLWithPath: "\(url.path)/Logs/\(dateString).log") fileURL = path openFile() } deinit { closeFile() } public func log(message: String) { if let handle = fileHandle { handle.seekToEndOfFile() let messageWithNewLine = "\(message)\n" if let data = messageWithNewLine.data(using: String.Encoding.utf8, allowLossyConversion: false) { let exception = tryBlock { handle.write(data) } if exception != nil { print("Error writing to log file \(String(describing: exception))") } } } } private func openFile() { let fm = FileManager.default if let URL = fileURL { let filePath = URL.path if fm.fileExists(atPath: filePath) == false { do { try fm.createDirectory(at: URL.deletingLastPathComponent(), withIntermediateDirectories: true, attributes: nil) } catch _ { } fm.createFile(atPath: filePath, contents: nil, attributes: nil) } do { fileHandle = try FileHandle(forWritingTo: URL) } catch { print("Error opening log file \(error)") fileHandle = nil } } } private func closeFile() { if let handle = fileHandle { handle.closeFile() } fileHandle = nil } }
971aa17fa8be82c5e56b1e67bd82bbf1
35.531915
131
0.59901
false
false
false
false
theodinspire/FingerBlade
refs/heads/development
FingerBlade/TutorialViewController.swift
gpl-3.0
1
// // TutorialViewController.swift // FingerBlade // // Created by Cormack on 3/3/17. // Copyright © 2017 the Odin Spire. All rights reserved. // import UIKit class TutorialViewController: UIViewController { @IBOutlet weak var contButton: UIButton! @IBOutlet weak var messageLabel: UILabel! @IBOutlet weak var messageView: UIView! let lefty = UserDefaults.standard.string(forKey: "Hand") == "Left" var cut: CutLine! var pathGenerator: CutPathGenerator! var aniGen: AnimationGenerator! var shapeLayer: CAShapeLayer? var wordPath: UIBezierPath? var wordPause: UIBezierPath? var word: UILabel? var dotView: UIView! var tap: UITapGestureRecognizer! var swipe: UITapSwipeGestureRecognizer! var tapSwipe: UITapSwipeGestureRecognizer! let cutStore = SampleStore() override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. cut = cutStore.first messageView.alpha = 0 messageView.layer.zPosition = 1 contButton.layer.zPosition = 2 tap = UITapGestureRecognizer(target: self, action: #selector(tapped)) tap.numberOfTapsRequired = 1 tap.numberOfTouchesRequired = 1 swipe = UITapSwipeGestureRecognizer(target: self, action: #selector(swiped)) swipe.numberOfTapsRequired = 0 swipe.numberOfTapTouchesRequired = 1 swipe.numberOfSwipeTouchesRequired = 1 tapSwipe = UITapSwipeGestureRecognizer(target: self, action: #selector(tapSwiped)) tapSwipe.numberOfTapsRequired = 1 tapSwipe.numberOfTapTouchesRequired = 1 tapSwipe.numberOfSwipeTouchesRequired = 1 contButton.isHidden = true } override func viewWillAppear(_ animated: Bool) { // Path generation pathGenerator = CutPathGenerator(ofSize: view!.bounds.size) // Animation set up //Touch aniGen = AnimationGenerator(withPathGenerator: pathGenerator) let dotDiameter = aniGen.dotSize shapeLayer = aniGen.tapAnimation(forCut: cut) //Words word = UILabel() word?.text = "Tap" word?.sizeToFit() word?.center = aniGen.swipeWordStartPoint(forCut: cut) // Set up view for the touch area let diaHalf = dotDiameter / 2 let start = pathGenerator.start(for: cut) dotView = UIView(frame: CGRect(x: start.x - diaHalf, y: start.y - diaHalf, width: dotDiameter, height: dotDiameter)) dotView.backgroundColor = UIColor.clear dotView.addGestureRecognizer(tap) // Add to view view.layer.addSublayer(shapeLayer!) view.addSubview(dotView) view.addSubview(word!) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. if let nextView = segue.destination as? CutViewController { nextView.cutStore = cutStore nextView.counter = 1 } } // Tutorial Methods /// Handles single tap gesture /// /// - Parameter sender: Tap Recognizer func tapped(_ sender: UITapGestureRecognizer?) { CATransaction.begin() // Remove all previous animations dotView.removeGestureRecognizer(tap) dotView.removeFromSuperview() word?.layer.removeAllAnimations() word?.removeFromSuperview() shapeLayer?.removeAllAnimations() shapeLayer?.removeFromSuperlayer() // Establish new animations word = UILabel() word?.text = "Swipe" word?.sizeToFit() word?.center = aniGen.swipeWordRestPoint(forCut: cut) word?.layer.add(aniGen.wordSwipeAnimation(forCut: cut), forKey: "position") shapeLayer = aniGen.swipeAnimation(forCut: cut) view.layer.addSublayer(shapeLayer!) view.addSubview(word!) view.addGestureRecognizer(swipe) CATransaction.commit() } /// Handles the solitary swipe gesture /// /// - Parameter sender: Swipe recognizer func swiped(_ sender: UITapSwipeGestureRecognizer) { CATransaction.begin() // Remove all previous animations view.removeGestureRecognizer(swipe) word?.layer.removeAllAnimations() word?.removeFromSuperview() shapeLayer?.removeAllAnimations() shapeLayer?.removeFromSuperlayer() // Establish new animations word = UILabel() word?.numberOfLines = 0 word?.textAlignment = .center word?.text = "Tap and\nSwipe" word?.sizeToFit() word?.center = aniGen.swipeWordRestPoint(forCut: cut) word?.layer.add(aniGen.wordSwipeAnimation(forCut: cut, long: true), forKey: "position") shapeLayer = aniGen.tapSwipeAnimation(forCut: cut) view.layer.addSublayer(shapeLayer!) view.addSubview(word!) view.addGestureRecognizer(tapSwipe) CATransaction.commit() } /// Handles the Tap and Swipe recognizer /// /// - Parameter sender: TapSwipe recognizer func tapSwiped(_ sender: UITapSwipeGestureRecognizer) { view.removeGestureRecognizer(tapSwipe) CATransaction.begin() shapeLayer?.removeAllAnimations() shapeLayer?.removeFromSuperlayer() word?.layer.removeAllAnimations() word?.removeFromSuperview() CATransaction.commit() // Message animations contButton.alpha = 0 contButton.isHidden = false messageLabel.text = "You got it!" let animateIn = { self.messageView.alpha = 1; self.contButton.alpha = 1 } let options: UIViewAnimationOptions = [.curveEaseInOut, .beginFromCurrentState] UIView.animate(withDuration: 0.5, delay: 0, options: options, animations: animateIn, completion: nil) // Prepare cutStore.put(trail: sender.trail, into: cut) } }
4c7132e7e44a35d3de372df487acfac2
31.79602
124
0.630309
false
false
false
false
blackspotbear/MMDViewer
refs/heads/master
MMDViewer/DataReader.swift
mit
1
import Foundation class DataReader { var defaultEncoding = String.Encoding.utf16LittleEndian var data: Data var pointer: UnsafeRawPointer init(data: Data) { self.data = data pointer = (data as NSData).bytes } func read<T>() -> T { let t = pointer.assumingMemoryBound(to: T.self) pointer = UnsafeRawPointer(t.successor()) return t.pointee } func readIntN(_ n: Int) -> Int { if n == 1 { return Int(read() as UInt8) } else if n == 2 { return Int(read() as UInt16) } else if n == 4 { return Int(read() as UInt32) } else if n == 8 { return read() } return 0 } func readString(_ encoding: UInt? = nil) -> String? { let length = Int(read() as UInt32) return readStringN(length, encoding: encoding) } func readStringN(_ nbytes: Int, encoding: UInt? = nil) -> String? { if nbytes == 0 { return "" } let r = NSString(bytes: pointer, length: nbytes, encoding: encoding ?? defaultEncoding.rawValue) as String? pointer = pointer.advanced(by: nbytes) return r } func readCStringN(_ nbytes: Int, encoding: UInt? = nil) -> String? { if nbytes == 0 { return "" } var length = 0 var p = pointer while true { let ch = p.assumingMemoryBound(to: UInt8.self).pointee if ch == 0 { break } p = p.advanced(by: 1) length += 1 } let r = readStringN(length, encoding: encoding) pointer = pointer.advanced(by: nbytes - length) return r } func skip(_ nbytes: Int) { pointer = pointer.advanced(by: nbytes) } }
4046d0b99b07af7ff94991e6b4b11de1
23.77027
115
0.520458
false
false
false
false
belatrix/BelatrixEventsIOS
refs/heads/master
Hackatrix/Controller/SettingsVC.swift
apache-2.0
1
// // SettingsVC.swift // Hackatrix // // Created by Erik Fernando Flores Quispe on 9/05/17. // Copyright © 2017 Belatrix. All rights reserved. // import UIKit import Alamofire import SwiftyJSON class SettingsVC: UIViewController { //MARK: - Properties @IBOutlet weak var tableViewSettings: UITableView! var cities:[City] = [] //MARK: - LifeCycle override func viewDidLoad() { super.viewDidLoad() self.customStyleTableView() } //MARK: - Navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == K.segue.citySetting { let locations = segue.destination as! LocationVC locations.cities = self.cities } } //MARK: - Functions func customStyleTableView() { self.tableViewSettings.tableFooterView = UIView() } func getCities(completitionHandler: @escaping () -> Void) { Alamofire.request(api.url.event.city).responseJSON { response in if let responseServer = response.result.value { let json = JSON(responseServer) for (_,subJson):(String, JSON) in json { self.cities.append(City(data: subJson)) } completitionHandler() } } } } //MARK: - UITableViewDataSource extension SettingsVC:UITableViewDataSource { func numberOfSections(in tableView: UITableView) -> Int { return 1 } func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { return "Localización" } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 1 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: K.cell.setting) as! SettingsCell return cell } } //MARK: - UITableViewDelegate extension SettingsVC:UITableViewDelegate { func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { self.cities = [] self.getCities { self.performSegue(withIdentifier: K.segue.citySetting, sender: nil) } } }
8e88c6fb68c9cadf1b5251702d6b2610
24.9
100
0.62248
false
false
false
false
NathanE73/Blackboard
refs/heads/main
Sources/BlackboardFramework/Availability/Version.swift
mit
1
// // Copyright (c) 2022 Nathan E. Walczak // // MIT License // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import Foundation struct Version { var major: Int var minor: Int? var patch: Int? } extension Version { init(_ major: Int, _ minor: Int? = nil, _ patch: Int? = nil) { self.init(major: major, minor: minor, patch: patch) } init?(_ text: String) { let elements = text.split(separator: ".", omittingEmptySubsequences: false) guard elements.count <= 3, let first = elements.first, let major = Int(first) else { return nil } guard let second = elements.second else { self.init(major) return } guard let minor = Int(second) else { return nil } guard let third = elements.third else { self.init(major, minor) return } guard let patch = Int(third) else { return nil } self.init(major, minor, patch) } } extension Version: Comparable { static func < (lhs: Self, rhs: Self) -> Bool { let lhs = [lhs.major, lhs.minor ?? 0, lhs.patch ?? 0] let rhs = [rhs.major, rhs.minor ?? 0, rhs.patch ?? 0] return lhs.lexicographicallyPrecedes(rhs) } } extension Version: CustomStringConvertible { var description: String { [major, minor, patch] .compactMap { $0?.description } .joined(separator: ".") } } extension Version: Decodable { init(from decoder: Decoder) throws { let container = try decoder.singleValueContainer() let text = try container.decode(String.self) guard let version = Version(text) else { throw DecodingError.dataCorruptedError( in: container, debugDescription: "Cannot initialize Version") } self = version } }
1206b3cb23b55b6602eb83dc056dff89
31.666667
80
0.617512
false
false
false
false
hironytic/FormulaCalc
refs/heads/master
FormulaCalc/View/UIViewController+Transition.swift
mit
1
// // UIViewController+Transition.swift // FormulaCalc // // Copyright (c) 2016, 2017 Hironori Ichimiya <[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 RxSwift public extension UIViewController { public func transitioner(_ observable: Observable<Message>) -> Disposable { return observable .subscribe(onNext: { [unowned self] message in switch message { case let message as TransitionMessage: let viewController = createViewController(for: message.viewModel) switch message.type { case .present: viewController.modalTransitionStyle = message.modalTransitionStyle self.present(viewController, animated: message.animated, completion: nil) case .push: var vc = viewController if let navvc = vc as? UINavigationController { vc = navvc.viewControllers[0] } self.navigationController?.pushViewController(vc, animated: message.animated) } case let message as DismissingMessage: switch message.type { case .dismiss: self.dismiss(animated: message.animated, completion: nil) case .pop: _ = self.navigationController?.popViewController(animated: message.animated) } default: break } }) } }
141bdac82fea2eeeb376dd1b700c3951
43.786885
101
0.614934
false
false
false
false
mkihmouda/ChatRoom
refs/heads/master
ChatRoom/ChatMessagesVC.swift
mit
1
// // ViewController.swift // IChat // // Created by Mac on 12/23/16. // Copyright © 2016 Mac. All rights reserved. // import UIKit import SocketIO class ChatMessagesVC: UIViewController,roomMessagesAPIDelegate , getMessageAPIDelegate, SocketData { // IBOutlet variables @IBOutlet var scrollView: UIScrollView! // scrollView @IBOutlet var mainView: MainView! // mainView @IBOutlet var actiivityIndicator: UIActivityIndicatorView! // variables var chatRoomId : String? // room_id var messageText : String? // message Text var socket : SocketIOClient! // Socket IO var roomMessageArray : [ChatMessage]? // messages array var roomMessagesAPI : RoomMessagesAPI? // Get Messages API var createMessageAPI : CreateMessageAPI? //Post Messages API var listScrollModel : ListScrollModel! // scrollView model to handle all scrolling functionalities // MARK: override UIViewController methods override func viewDidLoad() { super.viewDidLoad() getPreviousMessagesAPI() // call get previous messages API listScrollModel = ListScrollModel.init(scrollView: self.scrollView) // list scroll model handle all scrolling functionalities socketConnection() // connect to socket } override func viewWillAppear(_ animated: Bool) { // load subviews loadSubViews() } // MARK: load subViews func loadSubViews(){ mainView.loadViews(parent: self) } // call get previous messages func getPreviousMessagesAPI(){ roomMessagesAPI = RoomMessagesAPI() roomMessagesAPI?.delegate = self self.scrollView.isHidden = true // hide scoll view until finish loading all messages showActivityIndicator() roomMessagesAPI?.callAPI { self.loadMessages() // load messages } } // MARK: socket connection func socketConnection(){ socket = SocketIOClient.init(socketURL: URL.init(string: SOCKET_URL)!) // init socket socket.connect() // socket connect handleSocket() // handle listen operations } // handle socket listen operations func handleSocket(){ self.socket.onAny { print("Got event: \($0.event), with items: \($0.items)") // for logging operations } // listen for socket at channel - chatRoomId self.socket.on("\(chatRoomId!)", callback: {data, ack in if let dictionary = data[0] as? Dictionary <String,AnyObject> { // get message and user_image if let message = dictionary["message"] as? String, let user_image = dictionary["user_image"] as? String { // post message self.mainView.chatView?.postMessage(text: message, automatic: false, senderURL: user_image) } } }) } // MARK :roomMessagesAPIDelegate methods func setChatMessagesArray(chatMessagesArray: [ChatMessage]) { self.roomMessageArray = chatMessagesArray } func getRoomId() -> String { return self.chatRoomId! } // load previous message after finish API call func loadMessages(){ for object in self.roomMessageArray!{ self.mainView.chatView?.addMessagesAutomatically(text: object.text!, image: object.user_image!) // add message } // scrolling methods self.listScrollModel.automaticUpdateScrollWithHiddenKeyboard() self.listScrollModel.scrollView.contentOffset = CGPoint(x: 0, y: self.listScrollModel.scrollView.contentSize.height - self.listScrollModel.scrollView.bounds.size.height) self.listScrollModel.automaticUpdateScrollWithHiddenKeyboard() Timer.scheduledTimer(withTimeInterval: TimeInterval(1.0), repeats: false) { timer in self.hideActivityIndicator() // hide activity indicator self.scrollView.isHidden = false // show scroll view } } // MARK :call post message API func postAPI(text: String){ messageText = text createMessageAPI = CreateMessageAPI() createMessageAPI?.delegate = self createMessageAPI?.callAPI { self.emitSocket(text: text) // socket emit message } } // emit socket message func emitSocket(text : String){ let messageData = ["message": text, // text "room_id": "\(chatRoomId!)", // channel - room id "user_image" : UserDefaults.standard.value(forKey: "user_image") as! String] // user image self.socket.emit("Message", messageData) // socket emit message } // MARK :getMessageAPIDelegate methods func getMessageText() -> String { return messageText! } func getMessageRoomId() -> String { return chatRoomId! } // MARK: activityIndicator methods func showActivityIndicator(){ actiivityIndicator.isHidden = false actiivityIndicator.startAnimating() } func hideActivityIndicator(){ actiivityIndicator.stopAnimating() actiivityIndicator.isHidden = true } // MARK: Button Actions @IBAction func leaveGroup(_ sender: Any) { socket.disconnect() // disconnect socket self.navigationController?.popViewController(animated: true) // return back } }
c228ccb7c6a3891d6f8b4eb6cd962eb3
22.782101
177
0.569535
false
false
false
false
huangboju/Moots
refs/heads/master
Examples/UIScrollViewDemo/UIScrollViewDemo/Account/Views/Cells/TextFiledCell.swift
mit
1
// // TextFiledCell.swift // UIScrollViewDemo // // Created by 黄伯驹 on 2017/11/3. // Copyright © 2017年 伯驹 黄. All rights reserved. // import UIKit class TextFiledCell: UITableViewCell, Updatable { typealias FileItem = (placeholder: String?, iconName: String) final var inputText: String? { return textField.text } final func setField(with item: FileItem) { var attri: NSAttributedString? if let placeholder = item.placeholder { attri = NSAttributedString(string: placeholder, attributes: [ .font: UIFontMake(15) ]) } textField.attributedPlaceholder = attri imageView?.image = UIImage(named: item.iconName) } final func setRightView(with rightView: UIView?) { guard let rightView = rightView else { textField.rightView = nil textField.rightViewMode = .never return } textField.rightView = rightView textField.rightViewMode = .always } let textField = UITextField() private let bottomLine = UIView() override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) selectionStyle = .none contentView.addSubview(textField) textField.snp.makeConstraints { (make) in make.leading.equalTo(45) make.trailing.equalTo(-16) make.top.bottom.equalTo(self) } textField.addTarget(self, action: #selector(editingDidBeginAction), for: .editingDidBegin) textField.addTarget(self, action: #selector(editingDidEndAction), for: .editingDidEnd) contentView.addSubview(bottomLine) bottomLine.snp.makeConstraints { (make) in make.height.equalTo(1) make.leading.equalTo(16) make.trailing.equalTo(-16) make.bottom.equalToSuperview() } bottomLine.backgroundColor = UIColor(hex: 0xCCCCCC) didInitialzed() } open func didInitialzed() {} @objc private func editingDidBeginAction() { bottomLine.backgroundColor = UIColor(hex: 0xA356AB) } @objc private func editingDidEndAction() { bottomLine.backgroundColor = UIColor(hex: 0xCCCCCC) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func update(viewData: NoneItem) {} }
811d83b0b19dbdc2ec9ec20471cf9a08
27.340909
98
0.630714
false
false
false
false
kinetic-fit/sensors-swift
refs/heads/master
Sources/SwiftySensors/CyclingPowerSerializer.swift
mit
1
// // CyclingPowerSerializer.swift // SwiftySensors // // https://github.com/kinetic-fit/sensors-swift // // Copyright © 2017 Kinetic. All rights reserved. // import Foundation /// :nodoc: open class CyclingPowerSerializer { public struct Features: OptionSet { public let rawValue: UInt32 public static let PedalPowerBalanceSupported = Features(rawValue: 1 << 0) public static let AccumulatedTorqueSupported = Features(rawValue: 1 << 1) public static let WheelRevolutionDataSupported = Features(rawValue: 1 << 2) public static let CrankRevolutionDataSupported = Features(rawValue: 1 << 3) public static let ExtremeMagnitudesSupported = Features(rawValue: 1 << 4) public static let ExtremeAnglesSupported = Features(rawValue: 1 << 5) public static let TopAndBottomDeadSpotAnglesSupported = Features(rawValue: 1 << 6) public static let AccumulatedEnergySupported = Features(rawValue: 1 << 7) public static let OffsetCompensationIndicatorSupported = Features(rawValue: 1 << 8) public static let OffsetCompensationSupported = Features(rawValue: 1 << 9) public static let ContentMaskingSupported = Features(rawValue: 1 << 10) public static let MultipleSensorLocationsSupported = Features(rawValue: 1 << 11) public static let CrankLengthAdjustmentSupported = Features(rawValue: 1 << 12) public static let ChainLengthAdjustmentSupported = Features(rawValue: 1 << 13) public static let ChainWeightAdjustmentSupported = Features(rawValue: 1 << 14) public static let SpanLengthAdjustmentSupported = Features(rawValue: 1 << 15) public static let SensorMeasurementContext = Features(rawValue: 1 << 16) public static let InstantaneousMeasurementDirectionSupported = Features(rawValue: 1 << 17) public static let FactoryCalibrationDateSupported = Features(rawValue: 1 << 18) public init(rawValue: UInt32) { self.rawValue = rawValue } } public static func readFeatures(_ data: Data) -> Features { let bytes = data.map { $0 } var rawFeatures: UInt32 = 0 if bytes.count > 0 { rawFeatures |= UInt32(bytes[0]) } if bytes.count > 1 { rawFeatures |= UInt32(bytes[1]) << 8 } if bytes.count > 2 { rawFeatures |= UInt32(bytes[2]) << 16 } if bytes.count > 3 { rawFeatures |= UInt32(bytes[3]) << 24 } return Features(rawValue: rawFeatures) } struct MeasurementFlags: OptionSet { let rawValue: UInt16 static let PedalPowerBalancePresent = MeasurementFlags(rawValue: 1 << 0) static let AccumulatedTorquePresent = MeasurementFlags(rawValue: 1 << 2) static let WheelRevolutionDataPresent = MeasurementFlags(rawValue: 1 << 4) static let CrankRevolutionDataPresent = MeasurementFlags(rawValue: 1 << 5) static let ExtremeForceMagnitudesPresent = MeasurementFlags(rawValue: 1 << 6) static let ExtremeTorqueMagnitudesPresent = MeasurementFlags(rawValue: 1 << 7) static let ExtremeAnglesPresent = MeasurementFlags(rawValue: 1 << 8) static let TopDeadSpotAnglePresent = MeasurementFlags(rawValue: 1 << 9) static let BottomDeadSpotAnglePresent = MeasurementFlags(rawValue: 1 << 10) static let AccumulatedEnergyPresent = MeasurementFlags(rawValue: 1 << 11) static let OffsetCompensationIndicator = MeasurementFlags(rawValue: 1 << 12) } public struct MeasurementData: CyclingMeasurementData { public var timestamp: Double = 0 public var instantaneousPower: Int16 = 0 public var pedalPowerBalance: UInt8? public var pedalPowerBalanceReference: Bool? public var accumulatedTorque: UInt16? public var cumulativeWheelRevolutions: UInt32? public var lastWheelEventTime: UInt16? public var cumulativeCrankRevolutions: UInt16? public var lastCrankEventTime: UInt16? public var maximumForceMagnitude: Int16? public var minimumForceMagnitude: Int16? public var maximumTorqueMagnitude: Int16? public var minimumTorqueMagnitude: Int16? public var maximumAngle: UInt16? public var minimumAngle: UInt16? public var topDeadSpotAngle: UInt16? public var bottomDeadSpotAngle: UInt16? public var accumulatedEnergy: UInt16? } public static func readMeasurement(_ data: Data) -> MeasurementData { var measurement = MeasurementData() let bytes = data.map { $0 } var index: Int = 0 if bytes.count >= 2 { let rawFlags: UInt16 = UInt16(bytes[index++=]) | UInt16(bytes[index++=]) << 8 let flags = MeasurementFlags(rawValue: rawFlags) if bytes.count >= 4 { measurement.instantaneousPower = Int16(bytes[index++=]) | Int16(bytes[index++=]) << 8 if flags.contains(.PedalPowerBalancePresent) && bytes.count >= index { measurement.pedalPowerBalance = bytes[index++=] measurement.pedalPowerBalanceReference = rawFlags & 0x2 == 0x2 } if flags.contains(.AccumulatedTorquePresent) && bytes.count >= index + 1 { measurement.accumulatedTorque = UInt16(bytes[index++=]) | UInt16(bytes[index++=]) << 8 } if flags.contains(.WheelRevolutionDataPresent) && bytes.count >= index + 6 { var cumulativeWheelRevolutions = UInt32(bytes[index++=]) cumulativeWheelRevolutions |= UInt32(bytes[index++=]) << 8 cumulativeWheelRevolutions |= UInt32(bytes[index++=]) << 16 cumulativeWheelRevolutions |= UInt32(bytes[index++=]) << 24 measurement.cumulativeWheelRevolutions = cumulativeWheelRevolutions measurement.lastWheelEventTime = UInt16(bytes[index++=]) | UInt16(bytes[index++=]) << 8 } if flags.contains(.CrankRevolutionDataPresent) && bytes.count >= index + 4 { measurement.cumulativeCrankRevolutions = UInt16(bytes[index++=]) | UInt16(bytes[index++=]) << 8 measurement.lastCrankEventTime = UInt16(bytes[index++=]) | UInt16(bytes[index++=]) << 8 } if flags.contains(.ExtremeForceMagnitudesPresent) && bytes.count >= index + 4 { measurement.maximumForceMagnitude = Int16(bytes[index++=]) | Int16(bytes[index++=]) << 8 measurement.minimumForceMagnitude = Int16(bytes[index++=]) | Int16(bytes[index++=]) << 8 } if flags.contains(.ExtremeTorqueMagnitudesPresent) && bytes.count >= index + 4 { measurement.maximumTorqueMagnitude = Int16(bytes[index++=]) | Int16(bytes[index++=]) << 8 measurement.minimumTorqueMagnitude = Int16(bytes[index++=]) | Int16(bytes[index++=]) << 8 } if flags.contains(.ExtremeAnglesPresent) && bytes.count >= index + 3 { // TODO: this bit shifting is not correct. measurement.minimumAngle = UInt16(bytes[index++=]) | UInt16(bytes[index] & 0xF0) << 4 measurement.maximumAngle = UInt16(bytes[index++=]) | UInt16(bytes[index++=]) << 4 } if flags.contains(.TopDeadSpotAnglePresent) && bytes.count >= index + 2 { measurement.topDeadSpotAngle = UInt16(bytes[index++=]) | UInt16(bytes[index++=]) << 8 } if flags.contains(.BottomDeadSpotAnglePresent) && bytes.count >= index + 2 { measurement.bottomDeadSpotAngle = UInt16(bytes[index++=]) | UInt16(bytes[index++=]) << 8 } if flags.contains(.AccumulatedEnergyPresent) && bytes.count >= index + 2 { measurement.accumulatedEnergy = UInt16(bytes[index++=]) | UInt16(bytes[index++=]) << 8 } } } measurement.timestamp = Date.timeIntervalSinceReferenceDate return measurement } struct VectorFlags: OptionSet { let rawValue: UInt8 static let CrankRevolutionDataPresent = VectorFlags(rawValue: 1 << 0) static let FirstCrankAnglePresent = VectorFlags(rawValue: 1 << 1) static let InstantaneousForcesPresent = VectorFlags(rawValue: 1 << 2) static let InstantaneousTorquesPresent = VectorFlags(rawValue: 1 << 3) } public struct VectorData { public enum MeasurementDirection { case unknown case tangentialComponent case radialComponent case lateralComponent } public var instantaneousMeasurementDirection: MeasurementDirection = .unknown public var cumulativeCrankRevolutions: UInt16? public var lastCrankEventTime: UInt16? public var firstCrankAngle: UInt16? public var instantaneousForce: [Int16]? public var instantaneousTorque: [Double]? } public static func readVector(_ data: Data) -> VectorData { var vector = VectorData() let bytes = data.map { $0 } let flags = VectorFlags(rawValue: bytes[0]) let measurementDirection = (bytes[0] & 0x30) >> 4 switch measurementDirection { case 0: vector.instantaneousMeasurementDirection = .unknown case 1: vector.instantaneousMeasurementDirection = .tangentialComponent case 2: vector.instantaneousMeasurementDirection = .radialComponent case 3: vector.instantaneousMeasurementDirection = .lateralComponent default: vector.instantaneousMeasurementDirection = .unknown } var index: Int = 1 if flags.contains(.CrankRevolutionDataPresent) { vector.cumulativeCrankRevolutions = UInt16(bytes[index++=]) | UInt16(bytes[index++=]) << 8 vector.lastCrankEventTime = UInt16(bytes[index++=]) | UInt16(bytes[index++=]) << 8 } if flags.contains(.FirstCrankAnglePresent) { vector.firstCrankAngle = UInt16(bytes[index++=]) | UInt16(bytes[index++=]) << 8 } // These two arrays are mutually exclusive if flags.contains(.InstantaneousForcesPresent) { } else if flags.contains(.InstantaneousTorquesPresent) { let torqueRaw = Int16(bytes[index++=]) | Int16(bytes[index++=]) << 8 let torque = Double(torqueRaw) / 32.0 print(torque) } return vector } }
3a93547e272ea67c7b68e981f4d24483
47.798283
115
0.591733
false
false
false
false
flibbertigibbet/CycleSaver
refs/heads/develop
CycleSaver/Controllers/TripListController.swift
apache-2.0
1
// // TripListController.swift // CycleSaver // // Created by Kathryn Killebrew on 12/5/15. // Copyright © 2015 Kathryn Killebrew. All rights reserved. // import Foundation import UIKit import CoreData private let tripCellIdentifier = "tripCellReuseIdentifier" class TripListController: UIViewController { @IBOutlet weak var tripTableView: UITableView! var fetchedResultsController : NSFetchedResultsController! lazy var coreDataStack = (UIApplication.sharedApplication().delegate as! AppDelegate).coreDataStack let formatter = NSDateFormatter() override func viewDidLoad() { super.viewDidLoad() formatter.dateStyle = .ShortStyle formatter.timeStyle = .ShortStyle let fetchRequest = NSFetchRequest(entityName: "Trip") let startSort = NSSortDescriptor(key: "start", ascending: true) let stopSort = NSSortDescriptor(key: "stop", ascending: true) fetchRequest.sortDescriptors = [startSort, stopSort] fetchedResultsController = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: coreDataStack.context, sectionNameKeyPath: nil, cacheName: nil) fetchedResultsController.delegate = self tripTableView.delegate = self do { try fetchedResultsController.performFetch() tripTableView.reloadData() } catch let error as NSError { print("Error: \(error.localizedDescription)") } } func configureCell(cell: TripCell, indexPath: NSIndexPath) { let trip = fetchedResultsController.objectAtIndexPath(indexPath) as! Trip if let tripStart = trip.start { cell.startLabel.text = formatter.stringFromDate(tripStart) } if let tripStop = trip.stop { cell.stopLabel.text = formatter.stringFromDate(tripStop) } cell.coordsCount.text = "???" // TODO: how to get related obj } } extension TripListController: UITableViewDataSource { func numberOfSectionsInTableView (tableView: UITableView) -> Int { return fetchedResultsController.sections!.count } func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? { let sectionInfo = fetchedResultsController.sections![section] return sectionInfo.name } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { let sectionInfo = fetchedResultsController.sections![section] return sectionInfo.numberOfObjects } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier(tripCellIdentifier, forIndexPath: indexPath) as! TripCell configureCell(cell, indexPath: indexPath) return cell } } extension TripListController: UITableViewDelegate { func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { let trip = fetchedResultsController.objectAtIndexPath(indexPath) as! Trip print("Selected trip that started at \(trip.start).") self.performSegueWithIdentifier("ShowTripMap", sender: trip) } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if (segue.identifier == "ShowTripMap") { if let tripMapController = segue.destinationViewController as? TripDetailController { tripMapController.trip = sender as? Trip tripMapController.coreDataStack = coreDataStack } } } func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool { return true } func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { switch editingStyle { case .Delete: // delete from data source here; this will then trigger deletion on the NSFetchedResultsControllerDelegate, which updates the view let trip = fetchedResultsController.objectAtIndexPath(indexPath) as! Trip coreDataStack.context.deleteObject(trip) coreDataStack.saveContext() default: break } } } extension TripListController: NSFetchedResultsControllerDelegate { func controllerWillChangeContent(controller: NSFetchedResultsController) { tripTableView.beginUpdates() } func controller(controller: NSFetchedResultsController, didChangeObject anObject: AnyObject, atIndexPath indexPath: NSIndexPath?, forChangeType type: NSFetchedResultsChangeType, newIndexPath: NSIndexPath?) { switch type { case .Insert: tripTableView.insertRowsAtIndexPaths([newIndexPath!], withRowAnimation: .Automatic) case .Delete: tripTableView.deleteRowsAtIndexPaths([indexPath!], withRowAnimation: .Automatic) case .Update: let cell = tripTableView.cellForRowAtIndexPath(indexPath!) as! TripCell configureCell(cell, indexPath: indexPath!) case .Move: tripTableView.deleteRowsAtIndexPaths([indexPath!], withRowAnimation: .Automatic) tripTableView.insertRowsAtIndexPaths([newIndexPath!], withRowAnimation: .Automatic) } } func controllerDidChangeContent(controller: NSFetchedResultsController) { tripTableView.endUpdates() } func controller(controller: NSFetchedResultsController, didChangeSection sectionInfo: NSFetchedResultsSectionInfo, atIndex sectionIndex: Int,forChangeType type: NSFetchedResultsChangeType) { let indexSet = NSIndexSet(index: sectionIndex) switch type { case .Insert: tripTableView.insertSections(indexSet, withRowAnimation: .Automatic) case .Delete: tripTableView.deleteSections(indexSet, withRowAnimation: .Automatic) default : break } } }
20518aa2d227ee7d6c16a24eef701b65
35.757396
211
0.682711
false
false
false
false
fredfoc/OpenWit
refs/heads/master
Example/OpenWit/Examples/Manager/OpenWitConversationManager.swift
mit
1
// // OpenWitConversationManager.swift // OpenWit // // Created by fauquette fred on 7/01/17. // Copyright © 2017 CocoaPods. All rights reserved. // import Foundation import OpenWit import ObjectMapper /// Your logic to analyse Wit answers could go there class OpenWitConversationManager { typealias ConversationCompletion = ((String) -> ())? private var converseSessionId = "1234" private var nextConverseType = OpenWitConverseType.unknwon func startConversation(_ message: String? = nil, context: Mappable? = nil, completion: ConversationCompletion = nil) { converseSessionId = String.randomString(length: 10) if let message = message { converse(message, context: context, completion: completion) } } /// this will analyse the conversation (returns of Wit Api) /// /// - Parameter context: an optional context func converse(_ message: String, context: Mappable? = nil, completion: ConversationCompletion = nil) { OpenWit .sharedInstance .conversationMessage(message, sessionId: converseSessionId, context: context) {[unowned self] result in switch result { case .success(let converse): /// Your logic should start here... :-) var message: String? self.nextConverseType = converse.type switch converse.type { case .action: if let action = converse.action { switch action { case "addShopItem": self.addShopItem(converse: converse, context: context, completion: completion) case "createList": self.createList(converse: converse, context: context, completion: completion) default: break } } case .msg: message = converse.msg! case .merge: message = "some merge" case .stop: message = "Merci (Fin de la conversation)" case .unknwon: message = "Oupss..." } if let message = message { completion?(message) } case .failure(let error): print(error) } } } /// In case we get a createList action from Wit /// /// - Parameters: /// - converse: the return from Wit /// - context: an optional context private func createList(converse: OpenWitConverseModel, context: Mappable? = nil, completion: ConversationCompletion){ let createListAnswerModel: CreateListAnswerModel if let shopList = converse.shopList { createListAnswerModel = CreateListAnswerModel(listName: shopList.value, missingListName: nil) } else { createListAnswerModel = CreateListAnswerModel(listName: nil, missingListName: "something is missing here") } OpenWit.sharedInstance.conversationAction(createListAnswerModel, sessionId: converseSessionId, context: context) {[unowned self] result in switch result { case .success(let converse): /// Your logic should start here... :-) var message: String? self.nextConverseType = converse.type switch converse.type { case .action: print(converse) case .msg: message = converse.msg! case .merge: message = "some merge" case .stop: message = "Merci (Fin de la conversation)" case .unknwon: message = "Oupss..." } if let message = message { completion?(message) } case .failure(let error): print(error) } } } /// In case we get a addShopItem form Wit action from Wit /// /// - Parameters: /// - converse: the return from Wit /// - context: an optional context private func addShopItem(converse: OpenWitConverseModel, context: Mappable? = nil, completion: ConversationCompletion){ let addShopItemAnswerModel: AddShopItemAnswerModel if let shopItem = converse.shopItem, let shopList = converse.shopList { addShopItemAnswerModel = AddShopItemAnswerModel(allOk: (shopItem.value ?? "strange product") + " ajouté à " + (shopList.value ?? "strange list"), shopListAlone: nil, shopItemAlone: nil, missingAll: nil) } else if let shopItem = converse.shopItem { addShopItemAnswerModel = AddShopItemAnswerModel(allOk: nil, shopListAlone: nil, shopItemAlone: shopItem.value, missingAll: nil) } else if let shopList = converse.shopList { addShopItemAnswerModel = AddShopItemAnswerModel(allOk: nil, shopListAlone: shopList.value, shopItemAlone: nil, missingAll: nil) } else { addShopItemAnswerModel = AddShopItemAnswerModel(allOk: nil, shopListAlone: nil, shopItemAlone: nil, missingAll: true) } OpenWit.sharedInstance.conversationAction(addShopItemAnswerModel, sessionId: converseSessionId, context: context) {[unowned self] result in switch result { case .success(let converse): /// Your logic should start here... :-) var message: String? self.nextConverseType = converse.type switch converse.type { case .action: self.addShopItem(converse: converse, context: context, completion: completion) case .msg: message = converse.msg! case .merge: message = "some merge" case .stop: message = "Merci (Fin de la conversation)" case .unknwon: message = "Oupss..." } if let message = message { completion?(message) } case .failure(let error): print(error) } } } }
e0c9d7ddac4d980ef75742598489a9c5
56.662857
158
0.351105
false
false
false
false
Alienson/Bc
refs/heads/master
source-code/GameScene-zalohaOld.swift
apache-2.0
1
// // GameScene.swift // Parketovanie // // Created by Adam Turna on 4.1.2016. // Copyright (c) 2016 Adam Turna. All rights reserved. // import SpriteKit import Foundation private let movableString = "movable" class GameScene: SKScene { var listOfParquets: [Parquet] = [] var selectedNode = SKSpriteNode() let background = SKSpriteNode(imageNamed: "hracia_plocha_lvl1") var surfaceBackground = SKSpriteNode() var surf = Surface() let panRec = UIPanGestureRecognizer() override init(size: CGSize) { super.init(size: size) anchorPoint = CGPoint(x: 0.0, y: 0.0) self.background.name = "background" self.background.position = CGPoint(x: 0, y: 0) self.background.anchorPoint = CGPoint(x: 0, y: 0) addChild(self.background) leftBarlvl1() makeSurface() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func didMoveToView(view: SKView) { let gestureRecognizer = UIPanGestureRecognizer(target: self, action: Selector("handlePanFrom:")) self.view!.addGestureRecognizer(gestureRecognizer) let doubleTap = UITapGestureRecognizer(target: self, action: "doubleTapped") doubleTap.numberOfTapsRequired = 2 view.addGestureRecognizer(doubleTap) // panRec.addTarget(self, action: "panned:") // panRec.maximumNumberOfTouches = 1 // self.view!.addGestureRecognizer(panRec) } func panned(sender: UIPanGestureRecognizer){ var touchLocation: CGPoint = sender.locationInView(self.view!) touchLocation = self.convertPointFromView(touchLocation) } func doubleTapped() { if selectedNode.name == "parquet" { print(selectedNode.name) //selectedNode.anchorPoint = CGPoint(x: 0.5, y: 0.5) selectedNode.runAction(SKAction.rotateByAngle(degToRad(90.0), duration: 0.1)) //selectedNode.anchorPoint = CGPoint(x: 0, y: 0) } } func handlePanFrom(recognizer : UIPanGestureRecognizer) { if recognizer.state == .Began { var touchLocation = recognizer.locationInView(recognizer.view) touchLocation = self.convertPointFromView(touchLocation) self.selectNodeForTouch(touchLocation) print("began \(touchLocation)") } else if recognizer.state == .Changed { var translation = recognizer.translationInView(recognizer.view!) translation = CGPoint(x: translation.x, y: -translation.y) self.panForTranslation(translation) recognizer.setTranslation(CGPointZero, inView: recognizer.view) print("changed") } else if recognizer.state == .Ended { print("ended") if selectedNode.name != "parquet" { print("tu") // let scrollDuration = 0.2 // let velocity = recognizer.velocityInView(recognizer.view) // let pos = selectedNode.position // // // This just multiplies your velocity with the scroll duration. // let p = CGPoint(x: velocity.x * CGFloat(scrollDuration), y: velocity.y * CGFloat(scrollDuration)) // // var newPos = CGPoint(x: pos.x + p.x, y: pos.y + p.y) // newPos = self.boundLayerPos(newPos) // selectedNode.removeAllActions() // // let moveTo = SKAction.moveTo(newPos, duration: scrollDuration) // moveTo.timingMode = .EaseOut // selectedNode.runAction(moveTo) } } } func degToRad(degree: Double) -> CGFloat { return CGFloat(degree / 180.0 * M_PI) } func selectNodeForTouch(touchLocation : CGPoint) { // 1 let touchedNode = self.nodeAtPoint(touchLocation) if touchedNode.name == "parquet" { // 2 if !selectedNode.isEqual(touchedNode) { selectedNode.removeAllActions() selectedNode = touchedNode as! SKSpriteNode } else { selectedNode = SKSpriteNode() } } } func deSelectNodeForTouch(touchLocation : CGPoint) { selectedNode = SKSpriteNode() } func panForTranslation(translation : CGPoint) { let position = selectedNode.position if selectedNode.isMemberOfClass(Parquet){ print(selectedNode.name) selectedNode.position = CGPoint(x: position.x + translation.x, y: position.y + translation.y) } } func boundLayerPos(aNewPosition : CGPoint) -> CGPoint { let winSize = self.size var retval = aNewPosition retval.x = CGFloat(min(retval.x, 0)) retval.x = CGFloat(max(retval.x, -(background.size.width) + winSize.width)) retval.y = self.position.y return retval } func makeSurface() { surfaceBackground = SKSpriteNode(texture: nil, color: UIColor.purpleColor(), size: CGSize(width: 743, height: 550)) surfaceBackground.anchorPoint = CGPoint(x: 0.0, y: 0.0) surfaceBackground.name = "surfaceBackground" surfaceBackground.position = CGPoint(x: 280, y: 176) surfaceBackground.alpha = CGFloat(0.5) addChild(surfaceBackground) self.surf = Surface(rows: 3, collumns: 4, parent: surfaceBackground) } func leftBarlvl1() { // let leftBar = SKSpriteNode(imageNamed: "lava_lista") // leftBar.position = CGPoint(x:0, y: 0) // leftBar.anchorPoint = CGPoint(x: 0, y: 0) // leftBar.name = "lava_lista" // background.addChild(leftBar) // let offset = CGFloat(12.5) let offsetY = CGFloat(100) let width = CGFloat(280) let firstLineParquets = CGFloat(250) let secondLineParquets = CGFloat(150) // _ = leftBar.size.height // let width = leftBar.size.width let mono = Parquet(imageNamed: "1-mono") mono.position = CGPointMake(width / 4 - offset, offsetY+firstLineParquets) mono.anchorPoint = CGPoint(x: 0.5, y: 0.5) let duo = Parquet(imageNamed: "2-duo") duo.position = CGPointMake(width / 2, offsetY+firstLineParquets+25) duo.anchorPoint = CGPoint(x: 0.5, y: 0.5) let trio = Parquet(imageNamed: "3-3I") trio.position = CGPointMake(3 * width / 4 + offset, offsetY+firstLineParquets+50) trio.anchorPoint = CGPoint(x: 0.5, y: 0.5) let roztek = Parquet(imageNamed: "4-roztek") roztek.position = CGPointMake(width / 3 - offset, offsetY+secondLineParquets) roztek.anchorPoint = CGPoint(x: 0.5, y: 0.5) let stvorka = Parquet(imageNamed: "5-stvorka") stvorka.position = CGPointMake(2 * width / 3 + offset, offsetY+secondLineParquets) stvorka.anchorPoint = CGPoint(x: 0.5, y: 0.5) let elko = Parquet(imageNamed: "6-elko") elko.position = CGPointMake(width / 3 - offset, offsetY) elko.anchorPoint = CGPoint(x: 0.5, y: 0.5) let elko_obratene = Parquet(imageNamed: "7-elko-obratene") elko_obratene.position = CGPointMake(2 * width / 3 + offset, offsetY) elko_obratene.anchorPoint = CGPoint(x: 0.5, y: 0.5) listOfParquets.append(mono) listOfParquets.append(duo) listOfParquets.append(trio) listOfParquets.append(roztek) listOfParquets.append(stvorka) listOfParquets.append(elko) listOfParquets.append(elko_obratene) for par in listOfParquets { par.movable = true par.zPosition = 0 background.addChild(par) } } override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) { /* Called when a touch begins */ for touch in touches { let location = touch.locationInNode(self) let touchedNode = nodeAtPoint(location) touchedNode.zPosition = 15 //let liftUp = SKAction.scaleTo(1.2, duration: 0.2) //touchedNode.runAction(liftUp, withKey: "pickup") selectNodeForTouch(location) } } override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) { /* Called when a touch begins */ for touch in touches { let location = touch.locationInNode(self) let touchedNode = nodeAtPoint(location) touchedNode.zPosition = 0 //let dropDown = SKAction.scaleTo(1.0, duration: 0.2) touchedNode.position.x = touchedNode.position.x - touchedNode.position.x % 10 //point.x - point.x % 10 touchedNode.position.y = touchedNode.position.y - touchedNode.position.y % 10 //touchedNode.runAction(dropDown, withKey: "drop") //print(touchedNode.position) deSelectNodeForTouch(location) } } override func touchesMoved(touches: Set<UITouch>, withEvent event: UIEvent?) { for touch in touches { let location = touch.locationInNode(self) deSelectNodeForTouch(location) //selectedNode = SKSpriteNode() } } override func update(currentTime: CFTimeInterval) { /* Called before each frame is rendered */ } } extension UIColor { public convenience init?(hexString: String) { let r, g, b, a: CGFloat if hexString.hasPrefix("#") { let start = hexString.startIndex.advancedBy(1) let hexColor = hexString.substringFromIndex(start) if hexColor.characters.count == 8 { let scanner = NSScanner(string: hexColor) var hexNumber: UInt64 = 0 if scanner.scanHexLongLong(&hexNumber) { r = CGFloat((hexNumber & 0xff000000) >> 24) / 255 g = CGFloat((hexNumber & 0x00ff0000) >> 16) / 255 b = CGFloat((hexNumber & 0x0000ff00) >> 8) / 255 a = CGFloat(hexNumber & 0x000000ff) / 255 self.init(red: r, green: g, blue: b, alpha: a) return } } } return nil } }
fe11f294a305b85a4fdecd5884e7963f
34.754967
123
0.572566
false
false
false
false
xu6148152/binea_project_for_ios
refs/heads/master
ToDoListDemo/ToDoListDemo/ViewController.swift
mit
1
// // ViewController.swift // ToDoListDemo // // Created by Binea Xu on 15/2/24. // Copyright (c) 2015年 Binea Xu. All rights reserved. // import UIKit var todos: [ToDoBean] = [] var filterTodos: [ToDoBean] = [] func dateFromString(dateStr: String)->NSDate?{ let dateFormatter = NSDateFormatter() dateFormatter.dateFormat = "yyyy-MM-dd" let date = dateFormatter.dateFromString(dateStr) return date } class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, UISearchDisplayDelegate { @IBOutlet weak var tableView: UITableView! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. todos = [ToDoBean(id: "1", image: "child-selected", title: "1. 去游乐场", date: dateFromString("2014-10-20")!), ToDoBean(id: "2", image: "shopping-cart-selected", title: "2. 购物", date: dateFromString("2014-10-28")!), ToDoBean(id: "3", image: "phone-selected", title: "3. 打电话", date: dateFromString("2014-10-30")!), ToDoBean(id: "4", image: "travel-selected", title: "4. Travel to Europe", date: dateFromString("2014-10-31")!)] tableView.dataSource = self navigationItem.leftBarButtonItem = editButtonItem() // hide the search bar var contentOffset = tableView.contentOffset contentOffset.y += searchDisplayController!.searchBar.frame.size.height tableView.contentOffset = contentOffset } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int{ if tableView == searchDisplayController?.searchResultsTableView{ return filterTodos.count } return todos.count } // Row display. Implementers should *always* try to reuse cells by setting each cell's reuseIdentifier and querying for available reusable cells with dequeueReusableCellWithIdentifier: // Cell gets various attributes set automatically based on table (separators) and data source (accessory views, editing controls) func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell{ let cell = self.tableView.dequeueReusableCellWithIdentifier("todoCell") as UITableViewCell var todo : ToDoBean if tableView == searchDisplayController?.searchResultsTableView{ todo = filterTodos[indexPath.row] as ToDoBean }else{ todo = todos[indexPath.row] as ToDoBean } var image = cell.viewWithTag(101) as UIImageView var title = cell.viewWithTag(102) as UILabel var date = cell.viewWithTag(103) as UILabel image.image = UIImage(named: todo.image) title.text = todo.title let locale = NSLocale.currentLocale() let dateFormat = NSDateFormatter.dateFormatFromTemplate("yyyy-MM-dd ", options: 0, locale: locale) let dateFormatter = NSDateFormatter() dateFormatter.dateFormat = dateFormat date.text = dateFormatter.stringFromDate(todo.date) return cell } func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { if editingStyle == UITableViewCellEditingStyle.Delete{ todos.removeAtIndex(indexPath.row) self.tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Automatic) } } //edit override func setEditing(editing: Bool, animated: Bool) { super.setEditing(editing, animated: animated) tableView.setEditing(editing, animated: true) } @IBAction func close(segue: UIStoryboardSegue){ tableView.reloadData() } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if segue.identifier == "EditTodo" { var vc = segue.destinationViewController as DetailViewController // var indexPath = tableView.indexPathForCell(sender as UITableViewCell) var indexPath = tableView.indexPathForSelectedRow() if let index = indexPath { vc.todo = todos[index.row] } } } // Move the cell func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool { return self.editing } func tableView(tableView: UITableView, moveRowAtIndexPath sourceIndexPath: NSIndexPath, toIndexPath destinationIndexPath: NSIndexPath) { let todo = todos.removeAtIndex(sourceIndexPath.row) todos.insert(todo, atIndex: destinationIndexPath.row) } func searchDisplayController(controller: UISearchDisplayController, shouldReloadTableForSearchString searchString: String!) -> Bool { filterTodos = todos.filter(){$0.title.rangeOfString(searchString) != nil} return true } func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { return 80 } }
431df747678c17b8644e19147e8a3aa7
38.266667
188
0.676476
false
false
false
false
davidbutz/ChristmasFamDuels
refs/heads/master
iOS/Boat Aware/selectwifiTableViewController.swift
mit
1
// // selectwifiTableViewController.swift // ThriveIOSPrototype // // Created by Dave Butz on 1/11/16. // Copyright © 2016 Dave Butz. All rights reserved. // import UIKit class selectwifiTableViewController: UITableViewController { @IBOutlet weak var tblView: UITableView! typealias JSONArray = Array<AnyObject> typealias JSONDictionary = Dictionary<String, AnyObject> var wifiList : JSONArray = [] let appvar = ApplicationVariables.applicationvariables; 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() // Do any additional setup after loading the view. // get wifi data... let JSONObject: [String : AnyObject] = [ "userid" : appvar.userid ] let api = APICalls(); api.apicallout("/api/setupwifi/scanwifi" , iptype: "thriveIPAddress", method: "POST", JSONObject: JSONObject, callback: { (response) -> () in //handle the response. i should get status : fail/success and message: various let status = (response as! NSDictionary)["status"] as! Bool; if(status){ let networks = (response as! NSDictionary)["networks"] as! Array<Dictionary<String, AnyObject>>; self.wifiList = networks; self.tblView.reloadData(); } }); } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Table view data source override func numberOfSectionsInTableView(tableView: UITableView) -> Int { // #warning Incomplete implementation, return the number of sections return 1;//wifiList.count ?? 0 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // #warning Incomplete implementation, return the number of rows return wifiList.count ?? 0 } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("wificell", forIndexPath: indexPath) // Configure the cell... var wifi = wifiList[indexPath.row] as! JSONDictionary let wifiname = wifi["ssid"] as! String; let security = wifi["security"] as! String; cell.textLabel!.text = wifiname; cell.detailTextLabel!.text = security; return cell; } override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { // Process an Selection } /* // Override to support conditional editing of the table view. override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return false if you do not want the specified item to be editable. return true } */ /* // Override to support editing the table view. override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { if editingStyle == .Delete { // Delete the row from the data source tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade) } else if editingStyle == .Insert { // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view } } */ /* // Override to support rearranging the table view. override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) { } */ /* // Override to support conditional rearranging of the table view. override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return false if you do not want the item to be re-orderable. return true } */ /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
c3599333bf0282ba059d8cf770f49f89
35.914063
157
0.665397
false
false
false
false
panjinqiang11/Swift-WeiBo
refs/heads/master
WeiBo/WeiBo/Class/ModelView/PJUserAccountViewModel.swift
mit
1
// // PJUserAccountViewModel.swift // WeiBo // // Created by 潘金强 on 16/7/12. // Copyright © 2016年 潘金强. All rights reserved. // import UIKit class PJUserAccountViewModel: NSObject { //创建单例 static let shareUserAccount :PJUserAccountViewModel = PJUserAccountViewModel() var userAccount:PJUserAount? { return PJUserAount.loadUserAccount() } //私有化 private override init(){ super.init() } //判断accessToken是否为nil var isLogin :Bool{ return accessToken != nil } var accessToken: String? { guard let token = userAccount?.access_token else{ return nil } let result = userAccount?.expiresDate?.compare(NSDate()) if result == NSComparisonResult.OrderedDescending { return token }else{ return nil } } //通过授权码获得accesstoken func requestAccesstoken(code: String ,callBack: (isSuccess :Bool) -> ()) { //调用PJNetworkTools中的requestAccessToken方法 PJNetworkTools.shareTools.requestAccessToken(code) { (response, error) -> () in if error != nil{ callBack(isSuccess: false) return//请求失败 }else { //回调数据 guard let dic = response as? [String :AnyObject] else{ print("不是正确json格式") return } //通过令牌获得用户信息 let user = PJUserAount(dic: dic) self.requestUserInfo(user,callBack: callBack) } } } // MARK: - 请求用户信息 private func requestUserInfo(userAccount: PJUserAount,callBack: (isSuccess :Bool) -> ()){ PJNetworkTools.shareTools.requestUserInfo(userAccount) { (response, error) -> () in if error != nil { callBack(isSuccess: false) return } guard let dic = response as? [String :AnyObject] else{ callBack(isSuccess: false) return } let name = dic["name"] let avatar_large = dic["avatar_large"] // 设置用户名和头像 userAccount.name = name as? String userAccount.avatar_large = avatar_large as? String print(avatar_large) // 保存用户对象 let result = userAccount.saveUserAccount() if result { callBack(isSuccess: true) }else { callBack(isSuccess: false) } } } }
5688eed4bdc1dccf4ab79bf8c42f186d
22.464
93
0.463007
false
false
false
false
jakubknejzlik/ChipmunkSwiftWrapper
refs/heads/master
Pod/Classes/ChipmunkShape.swift
mit
1
// // ChipmunkShape.swift // Pods // // Created by Jakub Knejzlik on 15/11/15. // // import Foundation public class ChipmunkShape: ChipmunkSpaceObject { weak var body: ChipmunkBody? let shape: UnsafeMutablePointer<cpShape> override var space: ChipmunkSpace? { willSet { if let space = self.space { cpSpaceRemoveShape(space.space, self.shape) } } didSet { if let space = self.space { if let body = self.body where body.isStatic { cpSpaceAddStaticShape(space.space, self.shape) } else { cpSpaceAddShape(space.space, self.shape) } } } } /** A boolean value if this shape is a sensor or not. Sensors only call collision callbacks, and never generate real collisions.*/ public var sensor: Bool { get { return Bool(cpShapeGetSensor(shape)) } set(value) { cpShapeSetSensor(shape, value.cpBool()) } } /** Elasticity of the shape. A value of 0.0 gives no bounce, while a value of 1.0 will give a “perfect” bounce. However due to inaccuracies in the simulation using 1.0 or greater is not recommended however. The elasticity for a collision is found by multiplying the elasticity of the individual shapes together. */ public var elasticity: Double { get { return Double(cpShapeGetElasticity(shape)) } set(value) { cpShapeSetElasticity(shape, cpFloat(value)) } } /** Friction coefficient. Chipmunk uses the Coulomb friction model, a value of 0.0 is frictionless. The friction for a collision is found by multiplying the friction of the individual shapes together. */ public var friction: Double { get { return Double(cpShapeGetFriction(shape)) } set(value) { cpShapeSetFriction(shape, cpFloat(value)) } } /** The surface velocity of the object. Useful for creating conveyor belts or players that move around. This value is only used when calculating friction, not resolving the collision. */ public var surfaceVelocity: CGPoint { get { return cpShapeGetSurfaceVelocity(shape) } set(value) { cpShapeSetSurfaceVelocity(shape, value) } } /** You can assign types to Chipmunk collision shapes that trigger callbacks when objects of certain types touch.*/ public var collisionType: AnyObject { get { return UnsafeMutablePointer<AnyObject>(bitPattern: cpShapeGetCollisionType(shape)).memory } set(value) { let pointer = unsafeAddressOf(value) cpShapeSetCollisionType(shape, pointer.getUIntValue()) } } /** Shapes in the same non-zero group do not generate collisions. Useful when creating an object out of many shapes that you don’t want to self collide. Defaults to CP_NO_GROUP. */ public var group: AnyObject { get { return UnsafeMutablePointer<AnyObject>(bitPattern: cpShapeGetGroup(shape)).memory } set(value) { let pointer = unsafeAddressOf(value) cpShapeSetGroup(shape, pointer.getUIntValue()) } } /** Shapes only collide if they are in the same bit-planes. i.e. (a->layers & b->layers) != 0 By default, a shape occupies all bit-planes. */ public var layers: UInt { get { return UInt(cpShapeGetLayers(shape)) } set(value) { cpShapeSetLayers(shape, UInt32(value)) } } init(body: ChipmunkBody, shape: UnsafeMutablePointer<cpShape>) { self.body = body self.shape = shape super.init() cpShapeSetUserData(shape, UnsafeMutablePointer<ChipmunkShape>(unsafeAddressOf(self))) body.addShape(self) } public convenience init(body: ChipmunkBody, radius: Double, offset: CGPoint) { self.init(body: body, shape: cpCircleShapeNew(body.body, cpFloat(radius), offset)) } public convenience init(body: ChipmunkBody, size: CGSize) { self.init(body: body, shape: cpBoxShapeNew(body.body, cpFloat(size.width), cpFloat(size.height))) } }
52e47ac3e6a55e3d09cffd1fb77c4d35
35.141667
318
0.620849
false
false
false
false
OneBusAway/onebusaway-iphone
refs/heads/develop
Carthage/Checkouts/SwiftEntryKit/Source/MessageViews/EKRatingMessageView.swift
apache-2.0
3
// // EKRatingMessageView.swift // SwiftEntryKit // // Created by Daniel Huri on 6/1/18. // Copyright (c) 2018 [email protected]. All rights reserved. // import UIKit import QuickLayout public class EKRatingMessageView: UIView, EntryAppearanceDescriptor { // MARK: Properties private var message: EKRatingMessage // MARK: EntryAppearenceDescriptor var bottomCornerRadius: CGFloat = 0 { didSet { buttonBarView.bottomCornerRadius = bottomCornerRadius } } private var selectedIndex: Int! { didSet { message.selectedIndex = selectedIndex let item = message.ratingItems[selectedIndex] set(title: item.title, description: item.description) } } private let messageContentView = EKMessageContentView() private let symbolsView = EKRatingSymbolsContainerView() private var buttonBarView: EKButtonBarView! public init(with message: EKRatingMessage) { self.message = message super.init(frame: UIScreen.main.bounds) setupMessageContentView() setupSymbolsView() setupButtonBarView() set(title: message.initialTitle, description: message.initialDescription) } required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } private func set(title: EKProperty.LabelContent, description: EKProperty.LabelContent) { self.messageContentView.titleContent = title self.messageContentView.subtitleContent = description UIView.animate(withDuration: 0.4, delay: 0, usingSpringWithDamping: 1, initialSpringVelocity: 0, options: [.transitionCrossDissolve], animations: { SwiftEntryKit.layoutIfNeeded() }, completion: nil) } private func setupMessageContentView() { addSubview(messageContentView) messageContentView.verticalMargins = 20 messageContentView.horizontalMargins = 30 messageContentView.layoutToSuperview(axis: .horizontally, priority: .must) messageContentView.layoutToSuperview(.top, offset: 10) } private func setupSymbolsView() { addSubview(symbolsView) symbolsView.setup(with: message) { [unowned self] (index: Int) in self.message.selectedIndex = index self.message.selection?(index) self.selectedIndex = index self.animateIn() } symbolsView.layoutToSuperview(.centerX) symbolsView.layout(.top, to: .bottom, of: messageContentView, offset: 10, priority: .must) } private func setupButtonBarView() { buttonBarView = EKButtonBarView(with: message.buttonBarContent) buttonBarView.clipsToBounds = true buttonBarView.alpha = 0 addSubview(buttonBarView) buttonBarView.layout(.top, to: .bottom, of: symbolsView, offset: 30) buttonBarView.layoutToSuperview(.bottom) buttonBarView.layoutToSuperview(axis: .horizontally) } // MARK: Internal Animation private func animateIn() { layoutIfNeeded() buttonBarView.expand() } }
80474934b02118f928a687482a596bfd
32.744681
155
0.672762
false
false
false
false
DianQK/RxExample
refs/heads/master
RxZhihuDaily/Extension/UINavgationExtension.swift
mit
1
// // UINavgationExtension.swift // RxExample // // Created by 宋宋 on 16/2/15. // Copyright © 2016年 DianQK. All rights reserved. // import UIKit private var key: Void? ///https://github.com/ltebean/LTNavigationBar/blob/master/LTNavigationBar/UINavigationBar%2BAwesome.m extension UINavigationBar { var overlay: UIView? { get { return objc_getAssociatedObject(self, &key) as? UIView } set { objc_setAssociatedObject(self, &key, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } } var lt_backgroundColor: UIColor? { get { if self.overlay == nil { self.setBackgroundImage(UIImage(), forBarMetrics: .Default) self.overlay = UIView(frame: CGRect(x: 0, y: -20, width: UIScreen.mainScreen().bounds.size.width, height: CGRectGetHeight(self.bounds) + 20)) self.overlay?.userInteractionEnabled = false self.overlay?.autoresizingMask = [.FlexibleWidth, .FlexibleHeight] self.insertSubview(self.overlay!, atIndex: 0) } return self.overlay?.backgroundColor } set { if self.overlay == nil { self.setBackgroundImage(UIImage(), forBarMetrics: .Default) self.overlay = UIView(frame: CGRect(x: 0, y: -20, width: UIScreen.mainScreen().bounds.size.width, height: CGRectGetHeight(self.bounds) + 20)) self.overlay?.userInteractionEnabled = false self.overlay?.autoresizingMask = [.FlexibleWidth, .FlexibleHeight] self.insertSubview(self.overlay!, atIndex: 0) } self.overlay?.backgroundColor = newValue } } }
db7d2244f092a291a4fc27c22f17e742
37.533333
157
0.607843
false
false
false
false
micchyboy1023/Today
refs/heads/dev
Today iOS App/Today Extension/TodayExtensionViewController.swift
mit
1
// // TodayViewController.swift // TodayExtension // // Created by UetaMasamichi on 2016/01/20. // Copyright © 2016年 Masamichi Ueta. All rights reserved. // import UIKit import TodayKit import NotificationCenter final class TodayExtensionViewController: UIViewController, NCWidgetProviding { @IBOutlet weak var tableView: UITableView! fileprivate let tableViewRowHeight: CGFloat = 44.0 fileprivate let rowNum = 4 override func viewDidLoad() { super.viewDidLoad() setupTableView() self.extensionContext?.widgetLargestAvailableDisplayMode = .expanded } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } func widgetPerformUpdate(completionHandler: @escaping (NCUpdateResult) -> Void) { completionHandler(NCUpdateResult.newData) } func widgetActiveDisplayModeDidChange(_ activeDisplayMode: NCWidgetDisplayMode, withMaximumSize maxSize: CGSize) { if activeDisplayMode == .compact { self.preferredContentSize = maxSize } else { self.preferredContentSize = CGSize(width: tableView.frame.width, height: tableViewRowHeight * 4) } } private func setupTableView() { tableView.rowHeight = UITableViewAutomaticDimension tableView.estimatedRowHeight = tableViewRowHeight } } extension TodayExtensionViewController: UITableViewDelegate, UITableViewDataSource { func numberOfSections(in tableView: UITableView) -> Int { return 1 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return rowNum } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let sharedData = AppGroupSharedData.shared switch (indexPath as NSIndexPath).row { case 0: guard let cell = tableView.dequeueReusableCell(withIdentifier: "TodayExtensionCell", for: indexPath) as? TodayExtensionTodayTableViewCell else { fatalError("Wrong cell type") } cell.configureForObject(sharedData.todayScore) //For tap bug cell.backgroundView = UILabel() return cell case 1: let cell = tableView.dequeueReusableCell(withIdentifier: "TodayExtensionKeyValueExtensionCell", for: indexPath) cell.textLabel?.text = localize("Total") cell.detailTextLabel?.text = "\(sharedData.total) " + localize("days") //For tap bug cell.backgroundView = UILabel() return cell case 2: let cell = tableView.dequeueReusableCell(withIdentifier: "TodayExtensionKeyValueExtensionCell", for: indexPath) cell.textLabel?.text = localize("Longest streak") cell.detailTextLabel?.text = "\(sharedData.longestStreak) " + localize("days") //For tap bug cell.backgroundView = UILabel() return cell case 3: let cell = tableView.dequeueReusableCell(withIdentifier: "TodayExtensionKeyValueExtensionCell", for: indexPath) cell.textLabel?.text = localize("Current streak") cell.detailTextLabel?.text = "\(sharedData.currentStreak) " + localize("days") //For tap bug cell.backgroundView = UILabel() return cell default: fatalError("Wront cell number") } //dummy let cell = UITableViewCell(style: .default, reuseIdentifier: "cell") return cell } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { guard let url = URL(string: appGroupURLScheme + "://") else { return } extensionContext?.open(url, completionHandler: nil) } }
610836811ce45548ee5e5fbd5c0ed018
34.261261
156
0.644354
false
false
false
false
wangchong321/tucao
refs/heads/master
WCWeiBo/WCWeiBo/Classes/Module/User.swift
mit
1
// // User.swift // WCWeiBo // // Created by 王充 on 15/5/18. // Copyright (c) 2015年 wangchong. All rights reserved. // import UIKit class User: NSObject { /// 用户UID var id : Int = 0 /// 友好显示名称 var name : String? /// 用户头像地址(中图),50×50像素 var profile_image_url :String? { didSet{ iconUrl = NSURL(string: profile_image_url!) } } // 头像url var iconUrl : NSURL? /// 是否是微博认证用户,即加V用户,true:是,false:否 var verified: Bool = false /// 认证类型 -1:没有认证,0,认证用户,2,3,5: 企业认证,220: 草根明星 var verified_type : Int = -1 /// 属性数组 // 1~6 一共6级会员 var mbrank: Int = 0 private static let proparties = ["id","name","profile_image_url","verified","verified_type","mbrank"] init(dic : [String : AnyObject]){ super.init() for key in User.proparties { if dic[key] != nil { setValue(dic[key], forKey: key) } } } }
107a1ed8948292a6b583915e3e4ed72f
21.181818
105
0.522541
false
false
false
false
avhurst/week3
refs/heads/master
InstaClone/InstaClone/Filters.swift
mit
1
// // Filters.swift // InstaClone // // Created by Allen Hurst on 2/16/16. // Copyright © 2016 Allen Hurst. All rights reserved. // import UIKit typealias FiltersCompletion = (theImage: UIImage?) -> () class Filters { static let shared = Filters() var gpuContext: CIContext private init() { let options = [kCIContextWorkingColorSpace: NSNull()] let EAGContext = EAGLContext(API: .OpenGLES2) gpuContext = CIContext(EAGLContext: EAGContext, options: options) } private func filter(name: String, image: UIImage, completion: FiltersCompletion) { NSOperationQueue().addOperationWithBlock{ () -> Void in guard let filter = CIFilter(name: name) else { fatalError("Check filter spelling") } filter.setValue(CIImage(image: image), forKey: kCIInputImageKey) //GPU Context //get the final image guard let outputImage = filter.outputImage else { fatalError("Why no image?") } let CGImage = self.gpuContext.createCGImage(outputImage, fromRect: outputImage.extent) NSOperationQueue.mainQueue().addOperationWithBlock({ () -> Void in completion(theImage: UIImage(CGImage: CGImage)) }) } } func bw(image: UIImage, completion: FiltersCompletion) { self.filter("CIPhotoEffectMono", image: image, completion: completion) } func px(image: UIImage, completion: FiltersCompletion) { self.filter("CIPixellate", image: image, completion: completion) } func invert(image: UIImage, completion: FiltersCompletion) { self.filter("CIColorInvert", image: image, completion: completion) } func sepia(image: UIImage, completion: FiltersCompletion) { self.filter("CISepiaTone", image: image, completion: completion) } func line(image: UIImage, completion: FiltersCompletion) { self.filter("CILineScreen", image: image, completion: completion) } }
2705cd012e2551948478b070e038a444
26.329114
98
0.608434
false
false
false
false
skedgo/tripkit-ios
refs/heads/main
Sources/TripKitUI/cards/TKUINearbyMapManager.swift
apache-2.0
1
// // TKUINearbyMapManager.swift // TripKitUI // // Created by Adrian Schoenig on 19/5/17. // Copyright © 2017 SkedGo Pty Ltd. All rights reserved. // import Foundation import MapKit import RxSwift import RxCocoa import TripKit public class TKUINearbyMapManager: TKUIMapManager { public weak var viewModel: TKUINearbyViewModel? public override init() { super.init() self.preferredZoomLevel = .road self.showOverlayPolygon = true } private var mapTrackingPublisher = PublishSubject<MKUserTrackingMode>() private var mapRectPublisher = PublishSubject<MKMapRect>() public var mapCenter: Driver<CLLocationCoordinate2D?> { mapRect.map { MKMapRectEqualToRect($0, .null) ? nil : MKCoordinateRegion($0).center } } public var mapRect: Driver<MKMapRect> { mapRectPublisher.asDriver(onErrorJustReturn: .null) } private var tapRecognizer = UITapGestureRecognizer() private var mapSelectionPublisher = PublishSubject<TKUIIdentifiableAnnotation?>() public var mapSelection: Signal<TKUIIdentifiableAnnotation?> { return mapSelectionPublisher.asSignal(onErrorJustReturn: nil) } public var searchResult: MKAnnotation? { didSet { updateSearchResult(searchResult, previous: oldValue) } } private var disposeBag = DisposeBag() override public func takeCharge(of mapView: MKMapView, animated: Bool) { super.takeCharge(of: mapView, animated: animated) if viewModel == nil { viewModel = TKUINearbyViewModel.homeInstance } guard let viewModel = viewModel else { assertionFailure(); return } // Default content on taking charge mapView.showsScale = true let showCurrentLocation = TKLocationManager.shared.authorizationStatus == .authorized mapView.showsUserLocation = showCurrentLocation if let searchResult = self.searchResult { mapView.setUserTrackingMode(.none, animated: animated) mapView.addAnnotation(searchResult) zoom(to: [searchResult], animated: animated) } else if let start = viewModel.fixedLocation { mapView.setUserTrackingMode(.none, animated: animated) zoom(to: [start], animated: animated) } else if showCurrentLocation { mapView.setUserTrackingMode(.follow, animated: animated) } // Dynamic content viewModel.mapAnnotations .drive(onNext: { [weak self] annotations in guard let self = self else { return } self.animatedAnnotations = annotations }) .disposed(by: disposeBag) viewModel.mapAnnotationToSelect .emit(onNext: { [weak self] annotation in guard let mapView = self?.mapView else { return } guard let onMap = mapView.annotations.first(where: { ($0 as? TKUIIdentifiableAnnotation)?.identity == annotation.identity }) else { assertionFailure("We were asked to select annotation with identity \(annotation.identity ?? "nil"), but that hasn't been added to the map. Available: \(mapView.annotations.compactMap { ($0 as? TKUIIdentifiableAnnotation)?.identity }.joined(separator: ", "))") return } let alreadySelected = mapView.selectedAnnotations.contains(where: { $0.coordinate.latitude == onMap.coordinate.latitude && $0.coordinate.longitude == onMap.coordinate.longitude }) if alreadySelected { // We deselect the annotation, so mapView(_:didSelect:) can fire if the same // one is selected. This closes https://redmine.buzzhives.com/issues/10190. mapView.deselectAnnotation(onMap, animated: false) // We chose not to animate so the annotation appear fixed in place when we // deselect and then select. mapView.selectAnnotation(onMap, animated: false) } else { mapView.selectAnnotation(onMap, animated: true) } }) .disposed(by: disposeBag) viewModel.mapOverlays .drive(onNext: { [weak self] overlays in guard let self = self else { return } self.overlays = overlays }) .disposed(by: disposeBag) viewModel.searchResultToShow .drive(rx.searchResult) .disposed(by: disposeBag) // Action on MKOverlay mapView.addGestureRecognizer(tapRecognizer) tapRecognizer.rx.event .filter { $0.state == .ended } .compactMap { [weak self] in self?.closestAnnotation(to: $0) } .bind(to: mapSelectionPublisher) .disposed(by: disposeBag) } override public func cleanUp(_ mapView: MKMapView, animated: Bool) { disposeBag = DisposeBag() if let searchResult = self.searchResult { mapView.removeAnnotation(searchResult) } super.cleanUp(mapView, animated: animated) } private func closestLine(to coordinate: CLLocationCoordinate2D) -> TKRoutePolyline? { guard let mapView = self.mapView else { return nil } let routes = mapView.overlays.compactMap { $0 as? TKRoutePolyline } let mapPoint = MKMapPoint(coordinate) return routes.filter { $0.distance(to: mapPoint) < 44 }.min { $0.distance(to: mapPoint) < $1.distance(to: mapPoint) } } private func closestAnnotation(to tap: UITapGestureRecognizer) -> TKUIIdentifiableAnnotation? { guard let mapView = self.mapView else { assertionFailure(); return nil } let point = tap.location(in: mapView) let coordinate = mapView.convert(point, toCoordinateFrom: mapView) guard let line = closestLine(to: coordinate) else { return nil } return line.route as? TKUIIdentifiableAnnotation } } extension TKRoutePolyline { fileprivate func distance(to mapPoint: MKMapPoint) -> CLLocationDistance { return closestPoint(to: mapPoint).distance } } extension TKUINearbyMapManager { public func mapView(_ mapView: MKMapView, didChange mode: MKUserTrackingMode, animated: Bool) { mapTrackingPublisher.onNext(mode) } public override func mapView(_ mapView: MKMapView, regionDidChangeAnimated animated: Bool) { super.mapView(mapView, regionDidChangeAnimated: animated) mapRectPublisher.onNext(mapView.visibleMapRect) } public override func mapView(_ mapView: MKMapView, didSelect view: MKAnnotationView) { super.mapView(mapView, didSelect: view) guard let identifiable = view.annotation as? TKUIIdentifiableAnnotation else { return } mapSelectionPublisher.onNext(identifiable) } } // MARK: Search result extension Reactive where Base: TKUINearbyMapManager { @MainActor var searchResult: Binder<MKAnnotation?> { return Binder(self.base) { mapManager, annotation in mapManager.searchResult = annotation } } } extension TKUINearbyMapManager { func updateSearchResult(_ annotation: MKAnnotation?, previous: MKAnnotation?) { guard let mapView = mapView else { return } if let old = previous { mapView.removeAnnotation(old) } if let new = annotation { mapView.addAnnotation(new) zoom(to: [new], animated: true) } } }
f44db6d0cd1a3df1d0d79ea25fd9b80b
31.228311
269
0.692689
false
false
false
false
creatubbles/ctb-api-swift
refs/heads/develop
CreatubblesAPIClient/Sources/Utils/Logger.swift
mit
1
// // Logger.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 UIKit import XCGLogger public enum LogLevel { case verbose case debug case info case warning case error case severe case none } public protocol LogListener: class { func log(logLevel: LogLevel, message: String?, fileName: String, lineNumber: Int, date: Date) } class Logger { private static var loggerIdentifier = "com.creatubbles.CreatubblesAPIClient.logger" private static var logger = XCGLogger(identifier: loggerIdentifier, includeDefaultDestinations: true) private static var listeners: Array<LogListener> = Array<LogListener>() class func log(_ level: LogLevel, _ message: String?, fileName: StaticString = #file, lineNumber: Int = #line) { listeners.forEach({ $0.log(logLevel: level, message: message, fileName: String(describing: fileName).lastPathComponent, lineNumber: lineNumber, date: Date()) }) switch level { case .verbose: logger.verbose(message, fileName: fileName, lineNumber: lineNumber) case .debug: logger.debug(message, fileName: fileName, lineNumber: lineNumber) case .info: logger.info(message, fileName: fileName, lineNumber: lineNumber) case .warning: logger.warning(message, fileName: fileName, lineNumber: lineNumber) case .error: logger.error(message, fileName: fileName, lineNumber: lineNumber) case .severe: logger.severe(message, fileName: fileName, lineNumber: lineNumber) case .none: return } } class func setup(logLevel: LogLevel = .info) { logger.setup(level: Logger.logLevelToXCGLevel(level: logLevel), showLogIdentifier: true, showFunctionName: false, showThreadName: true, showLevel: true, showFileNames: true, showLineNumbers: true, showDate: true, writeToFile: nil, fileLevel: nil) } private class func logLevelToXCGLevel(level: LogLevel) -> XCGLogger.Level { switch level { case .verbose: return .verbose case .debug: return .debug case .info: return .info case .warning: return .warning case .error: return .error case .severe: return .severe case .none: return .none } } class func addListener(listener: LogListener) { if !listeners.contains(where: { $0 === listener }) { listeners.append(listener) } } }
0b93a176e847b598c9430cd266f96599
42.421687
254
0.690067
false
false
false
false
fgengine/quickly
refs/heads/master
Quickly/Views/Switch/QSwitch.swift
mit
1
// // Quickly // open class QSwitchStyleSheet : IQStyleSheet { public var tintColor: UIColor? public var onTintColor: UIColor? public var thumbTintColor: UIColor? public var onImage: UIImage? public var offImage: UIImage? public init( tintColor: UIColor? = nil, onTintColor: UIColor? = nil, thumbTintColor: UIColor? = nil, onImage: UIImage? = nil, offImage: UIImage? = nil ) { self.tintColor = tintColor self.onTintColor = onTintColor self.thumbTintColor = thumbTintColor self.onImage = onImage self.offImage = offImage } public init(_ styleSheet: QSwitchStyleSheet) { self.tintColor = styleSheet.tintColor self.onTintColor = styleSheet.onTintColor self.thumbTintColor = styleSheet.thumbTintColor self.onImage = styleSheet.onImage self.offImage = styleSheet.offImage } } open class QSwitch : UISwitch, IQView { public typealias ChangedClosure = (_ `switch`: QSwitch, _ isOn: Bool) -> Void public var onChanged: ChangedClosure? = nil public required init() { super.init(frame: CGRect.zero) self.setup() } public override init(frame: CGRect) { super.init(frame: frame) self.setup() } public required init?(coder: NSCoder) { super.init(coder: coder) self.setup() } open func setup() { self.addTarget(self, action: #selector(self._handleChanged(_:)), for: .valueChanged) } deinit { self.removeTarget(self, action: #selector(self._handleChanged(_:)), for: .valueChanged) } public func apply(_ styleSheet: QSwitchStyleSheet) { self.tintColor = styleSheet.tintColor self.onTintColor = styleSheet.onTintColor self.thumbTintColor = styleSheet.thumbTintColor self.onImage = styleSheet.onImage self.offImage = styleSheet.offImage } @objc private func _handleChanged(_ sender: Any) { guard let onChanged = self.onChanged else { return } onChanged(self, self.isOn) } }
54c0bb1a7cde051c6c1092aee7d11ac1
26.2125
95
0.618741
false
false
false
false
149393437/Templates
refs/heads/master
Templates/Project Templates/Mac/Application/Game.xctemplate/SpriteKit_AppDelegate.swift
mit
1
// // ___FILENAME___ // ___PACKAGENAME___ // // Created by ___FULLUSERNAME___ on ___DATE___. // Copyright (c) ___YEAR___ ___ORGANIZATIONNAME___. All rights reserved. // import Cocoa import SpriteKit extension SKNode { class func unarchiveFromFile(file : NSString) -> SKNode? { if let path = NSBundle.mainBundle().pathForResource(file, ofType: "sks") { var sceneData = NSData(contentsOfFile: path, options: .DataReadingMappedIfSafe, error: nil)! var archiver = NSKeyedUnarchiver(forReadingWithData: sceneData) archiver.setClass(self.classForKeyedUnarchiver(), forClassName: "SKScene") let scene = archiver.decodeObjectForKey(NSKeyedArchiveRootObjectKey) as GameScene archiver.finishDecoding() return scene } else { return nil } } } @NSApplicationMain class ___FILEBASENAME___: NSObject, NSApplicationDelegate { @IBOutlet weak var window: NSWindow! @IBOutlet weak var skView: SKView! func applicationDidFinishLaunching(aNotification: NSNotification) { /* Pick a size for the scene */ if let scene = GameScene.unarchiveFromFile("GameScene") as? GameScene { /* Set the scale mode to scale to fit the window */ scene.scaleMode = .AspectFill self.skView!.presentScene(scene) /* Sprite Kit applies additional optimizations to improve rendering performance */ self.skView!.ignoresSiblingOrder = true self.skView!.showsFPS = true self.skView!.showsNodeCount = true } } func applicationShouldTerminateAfterLastWindowClosed(sender: NSApplication) -> Bool { return true } }
e3645c58b908ccebc2c7ca8ad9b802e0
32.203704
104
0.624094
false
false
false
false
toggl/superday
refs/heads/develop
teferi/UI/Common/Views/CategoryButton.swift
bsd-3-clause
1
import UIKit protocol CategoryButtonDelegate:class { func categorySelected(category:Category) } class CategoryButton : UIView { private let animationDuration = TimeInterval(0.225) var category : Category? { didSet { guard let category = category else { return } label.text = category.description label.sizeToFit() label.center = CGPoint.zero label.textColor = category.color button.backgroundColor = category.color button.setImage(category.icon.image, for: .normal) } } var angle : CGFloat = -CGFloat.pi / 2 //The default value is so the label appears at the bottom in EditView { didSet { positionLabel() } } weak var delegate:CategoryButtonDelegate? private let button : UIButton private let labelHolder : UIView private let label : UILabel required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } required override init(frame: CGRect) { button = UIButton(frame: frame) labelHolder = UIView() label = UILabel() super.init(frame: frame) backgroundColor = UIColor.clear clipsToBounds = false button.layer.cornerRadius = min(frame.width, frame.height) / 2 button.adjustsImageWhenHighlighted = false addSubview(button) label.font = UIFont.boldSystemFont(ofSize: 9) label.textAlignment = .center labelHolder.center = button.center addSubview(labelHolder) labelHolder.addSubview(label) positionLabel() button.addTarget(self, action: #selector(CategoryButton.buttonTap), for: .touchUpInside) } func show() { let scaleTransform = CGAffineTransform(scaleX: 0.01, y: 0.01) self.transform = scaleTransform self.isHidden = false let changesToAnimate = { self.layer.removeAllAnimations() self.transform = .identity } self.label.alpha = 0 self.label.transform = CGAffineTransform(scaleX: 0, y: 0) let showLabelAnimation = { self.label.alpha = 1 self.label.transform = CGAffineTransform.identity } UIView.animate(changesToAnimate, duration: animationDuration, withControlPoints: 0.23, 1, 0.32, 1) { UIView.animate( withDuration: 0.3, delay: 0.08, usingSpringWithDamping: 0.5, initialSpringVelocity: 0.2, options: UIViewAnimationOptions.curveEaseOut, animations: showLabelAnimation) } } func hide() { let scaleTransform = CGAffineTransform(scaleX: 0.01, y: 0.01) self.transform = .identity self.isHidden = false let changesToAnimate = { self.layer.removeAllAnimations() self.transform = scaleTransform } UIView.animate(changesToAnimate, duration: animationDuration, withControlPoints: 0.175, 0.885, 0.32, 1) } private func positionLabel() { let radius = frame.width / 2 + 12 let x = button.center.x + radius * cos(angle - CGFloat.pi) let y = button.center.y + radius * sin(angle - CGFloat.pi) labelHolder.center = CGPoint(x: x, y: y) let labelOffset = -cos(angle) label.center = CGPoint(x: labelOffset * (label.frame.width / 2 - label.frame.height / 2), y: 0) } @objc private func buttonTap() { guard let category = category, let delegate = delegate else { return } delegate.categorySelected(category: category) } }
08bf4935be4fc6e6908fc8f7a452519a
27.12766
111
0.572113
false
false
false
false
kNeerajPro/CGFLoatingUIKit
refs/heads/master
CGFloatLabelUITextKit/CGFloatLabelUITextKit/ViewController.swift
mit
1
// // ViewController.swift // CGFloatLabelUITextKit // // Created by Neeraj Kumar on 07/12/14. // Copyright (c) 2014 Neeraj Kumar. All rights reserved. // import UIKit class ViewController: UIViewController { @IBOutlet weak var firstNameTextField: CGFloatTextField! @IBOutlet weak var middleNameTextField: CGFloatTextField! @IBOutlet weak var lastNameTextField: CGFloatTextField! @IBOutlet weak var floatTextView: CGFloatTextView! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. self.firstNameTextField.floatingLabelText = "First Name" self.firstNameTextField.floatingLabelFontColor = UIColor.blue self.firstNameTextField.floatingLabelFont = UIFont.systemFont(ofSize: 15) self.middleNameTextField.floatingLabelText = "Middle Name" self.middleNameTextField.floatingLabelFontColor = UIColor.green self.middleNameTextField.animationTime = 1.0 self.middleNameTextField.floatingLabelOffset = 20.0 self.lastNameTextField.floatingLabelText = "Last Name" self.lastNameTextField.animationTime = 0.5 self.floatTextView.placeholderText = "Enter text here" self.floatTextView.floatingLabelText = "Enter text here" } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
110af8dd5bbfb51ffd23a696fb124c36
28.584906
81
0.684311
false
false
false
false
eliasbloemendaal/KITEGURU
refs/heads/master
KITEGURU/MailViewController.swift
mit
1
// // MailViewController.swift // KITEGURU // // Created by Elias Houttuijn Bloemendaal on 26-01-16. // Copyright © 2016 Elias Houttuijn Bloemendaal. All rights reserved. // import UIKit import MessageUI class MailViewController: UIViewController, MFMailComposeViewControllerDelegate { @IBOutlet weak var subjectTextfield: UITextField! @IBOutlet weak var bodyTextview: UITextView! // Segue for the mail from personalRatingViewController var city: String? var temp: Double? var desc: String? var icon: String? var speed: Double? var deg: Double? var kiteguruFinalAdvise: Int? var firstName: String? // Variable for the mail var tempString: String? var speedString: String? var degString: String? var functions = Functions() override func viewDidLoad() { super.viewDidLoad() // Als er geen plaats is opgezocht geef dan een waarden in plaat van nil en voorkom een error if temp == nil || speed == nil || deg == nil || icon == nil || city == nil || kiteguruFinalAdvise == nil || desc == nil{ temp = 0 speed = 0 deg = 0 icon = "02n" city = " city " kiteguruFinalAdvise = 0 desc = "weather mood" } // Rounding the numbers for in the mail tempString = String(format: "%.2f", temp!) + " Celsius" speedString = String(format: "%.2f", speed!) + " Knots" degString = String(format: "%.2f", deg!) + " Direction" // http://stackoverflow.com/questions/26614395/swift-background-image-does-not-fit-showing-small-part-of-the-all-image let backgroundImage = UIImageView(frame: UIScreen.mainScreen().bounds) backgroundImage.image = UIImage(named: "kiteBackFour") backgroundImage.contentMode = UIViewContentMode.ScaleAspectFill self.view.insertSubview(backgroundImage, atIndex: 0) // Het opgestelde mailtje met the weather predictions, het kiteguru advies plus cijfer. let messageBody = bodyTextview messageBody.text = "YO Dude, KITEGURU gave me an advise! \nThese are the weather conditions in \(city!), Temperature: \(tempString!), Weather mood: \(desc!), Windspeed: \(speedString!), Wind direction \(degString!) \nThis is the grade I got: \(kiteguruFinalAdvise!). This is my personal KITEGURU advice: \(functions.advise(kiteguruFinalAdvise!)). \nlet me know if you want to go! \nHANGLOOSEEE BROTHA!" // http://stackoverflow.com/questions/17403483/set-title-of-back-bar-button-item-in-ios // NavigationBar titles self.navigationItem.title = firstName! let btn = UIBarButtonItem(title: "Advice", style: .Plain, target: self, action: "backBtnClicked") self.navigationController?.navigationBar.topItem?.backBarButtonItem = btn } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } // De mail button zal een mailtje opstellen plus onderwerp plus een toegevoegde foto van KITEGURU @IBAction func sendMailButton(sender: AnyObject) { let messageBody = bodyTextview var SubjectText = "KITGURU - " let Recipients = ["[email protected]"] let mc: MFMailComposeViewController = MFMailComposeViewController() SubjectText += subjectTextfield.text! mc.mailComposeDelegate = self mc.setSubject(SubjectText) mc.setMessageBody(messageBody.text, isHTML: false) mc.setToRecipients(Recipients) mc.addAttachmentData(UIImageJPEGRepresentation(UIImage(named: "kiteGuru.png")!, CGFloat(1.0))!, mimeType: "image/jpeg", fileName: "test.jpeg") self.presentViewController(mc, animated: true, completion: nil) } // Geef een alert als de mail niet verzonden kan worden func showSendMailErrorAlert(){ let alertview = UIAlertController(title: "Could Not Send Email", message: "Your device could not send e-mail. Please check e-mail configuration and try again.", preferredStyle: .Alert) alertview.addAction(UIAlertAction(title: "OK", style: .Default, handler: { (alertAction) -> Void in self.dismissViewControllerAnimated(true, completion: nil) })) alertview.addAction(UIAlertAction(title: "Cancel", style: .Cancel, handler: nil)) self.presentViewController(alertview, animated: true, completion: nil) } // De mail zal verdwijnen nadat de mail is verstuurd of gecanceled func mailComposeController(controller: MFMailComposeViewController, didFinishWithResult result: MFMailComposeResult, error: NSError?) { controller.dismissViewControllerAnimated(true, completion: nil) } // De on screen keyboard zal verdwijnen wanner je buiten het keyboard klikt override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) { self.view.endEditing(true) } }
9b1e34e2f2afddc91173a2cd9d5bc431
44.272727
410
0.675904
false
false
false
false
enabledhq/Selfie-Bot
refs/heads/master
Selfie-Bot/SelfieBotAnalysisViewController.swift
mit
1
// // SelfieBotCardViewController.swift // Selfie-Bot // // Created by John Smith on 24/2/17. // Copyright © 2017 Enabled. All rights reserved. // import Foundation import UIKit class SelfieBotAnalysisViewController: ViewController { private let viewModel: SelfieBotAnalysisViewModel private let analysisView: AnalysisView init(viewModel: SelfieBotAnalysisViewModel) { self.viewModel = viewModel analysisView = AnalysisView(options: viewModel.options) super.init(nibName: nil, bundle: nil) } override func viewDidLoad() { let imageView = UIImageView(image: viewModel.image) let selfieBotSaysLabel = UILabel() let qouteLabel = UILabel() let textColor = UIColor(colorLiteralRed: 140 / 255, green: 140 / 255, blue: 140 / 255, alpha: 1) //Drop Shadow imageView.layer.shadowOffset = CGSize(width: -1.0, height: -1.0) imageView.layer.shadowOpacity = 0.5 imageView.contentMode = .scaleAspectFit selfieBotSaysLabel.textAlignment = .center selfieBotSaysLabel.text = "Selfie bot says" selfieBotSaysLabel.textColor = textColor qouteLabel.textAlignment = .center qouteLabel.text = viewModel.qoute qouteLabel.numberOfLines = 0 qouteLabel.font = UIFont.init(name: "ChalkboardSE-Light", size: 17) qouteLabel.textColor = textColor view.backgroundColor = UIColor.white view.addSubview(imageView) view.addSubview(selfieBotSaysLabel) view.addSubview(qouteLabel) view.addSubview(analysisView) imageView.snp.makeConstraints { make in make.height.equalTo(200) make.top.equalTo(view).inset(50) make.centerX.equalTo(view) } selfieBotSaysLabel.snp.makeConstraints { make in make.left.right.equalTo(view).inset(50) make.top.equalTo(imageView.snp.bottom).offset(20) } qouteLabel.snp.makeConstraints { make in make.left.right.equalTo(view).inset(70) make.top.equalTo(selfieBotSaysLabel.snp.bottom).offset(10) } analysisView.snp.makeConstraints { make in make.top.equalTo(qouteLabel.snp.bottom).offset(20) make.left.right.equalTo(view).inset(50) } } override func viewDidAppear(_ animated: Bool) { analysisView.animateConfidenceBars() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
ef7b21b02607ed7313ebfd7405753013
29.340659
104
0.607026
false
false
false
false
TTVS/NightOut
refs/heads/master
Clubber/WelcomeViewController.swift
apache-2.0
1
// // WelcomeViewController.swift // Clubber // // Created by Terra on 6/1/15. // Copyright (c) 2015 Dino Media Asia. All rights reserved. // import UIKit class WelcomeViewController: UIViewController { @IBOutlet var welcomeView: UIView! @IBOutlet var welcomeWebViewBG: UIWebView! @IBOutlet var welcomeLabel: UILabel! @IBOutlet var signUpButton: UIButton! @IBOutlet var loginButton: UIButton! var colorX : UIColor = UIColor(red: (10/255.0), green: (237/255.0), blue: (213/255.0), alpha: 1.0) var colorY : UIColor = UIColor(red: (255/255.0), green: (0/255.0), blue: (70/255.0), alpha: 1.0) override func viewDidLoad() { super.viewDidLoad() // Create File Path and Read From It let filePath = NSBundle.mainBundle().pathForResource("faceBook", ofType: "gif") let gif = NSData(contentsOfFile: filePath!) // UIWebView to Load gif welcomeWebViewBG.loadData(gif!, MIMEType: "image/gif", textEncodingName: "utf-8", baseURL: NSURL(string: "http://localhost/")!) welcomeWebViewBG.userInteractionEnabled = false self.view.addSubview(welcomeWebViewBG) // backgroundFilter let filter = UIView() filter.frame = self.view.frame filter.backgroundColor = UIColor.blackColor() filter.alpha = 0.35 self.view.addSubview(filter) welcomeLabel.text = "Welcome Fellow Clubber" welcomeLabel.textColor = UIColor.whiteColor() welcomeLabel.font = UIFont(name: "Avenir Next", size: 17) self.view.addSubview(welcomeLabel) loginButton.setBackgroundImage(UIImage(named: "cyanOutfill"), forState: UIControlState.Normal) // loginButton.layer.borderColor = UIColor.whiteColor().CGColor // loginButton.layer.borderWidth = 1 // loginButton.layer.cornerRadius = 5 loginButton.titleLabel!.font = UIFont(name: "Avenir Next", size: 16) loginButton.tintColor = colorX loginButton.backgroundColor = UIColor.clearColor() loginButton.setTitle("Login", forState: UIControlState.Normal) loginButton.center = CGPointMake(welcomeView.frame.size.width / 2, welcomeView.frame.size.height / 2) self.view.addSubview(loginButton) signUpButton.setBackgroundImage(UIImage(named: "coralRedOutfill"), forState: UIControlState.Normal) // signUpButton.layer.borderColor = UIColor.whiteColor().CGColor // signUpButton.layer.borderWidth = 1 // signUpButton.layer.cornerRadius = 5 signUpButton.titleLabel!.font = UIFont(name: "Avenir Next", size: 16) signUpButton.tintColor = colorY signUpButton.backgroundColor = UIColor.clearColor() signUpButton.setTitle("Sign Up", forState: UIControlState.Normal) self.view.addSubview(signUpButton) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
ee1a789e3a5d267b0bc1e9bc010edca5
39.654321
139
0.616155
false
false
false
false
yrchen/edx-app-ios
refs/heads/master
Source/IrregularBorderView.swift
apache-2.0
1
// // IrregularBorderStyle.swift // edX // // Created by Ehmad Zubair Chughtai on 26/10/2015. // Copyright © 2015 edX. All rights reserved. // import UIKit struct CellPosition : OptionSetType { let rawValue : UInt static let Top = CellPosition(rawValue: 1 << 0) static let Bottom = CellPosition(rawValue: 1 << 1) var roundedCorners : UIRectCorner { var result = UIRectCorner() if self.contains(CellPosition.Top) { result = result.union([.TopLeft, .TopRight]) } if self.contains(CellPosition.Bottom) { result = result.union([.BottomLeft, .BottomRight]) } return result } } struct IrregularBorderStyle { let corners : UIRectCorner let base : BorderStyle init(corners : UIRectCorner, base : BorderStyle) { self.corners = corners self.base = base } init(position : CellPosition, base : BorderStyle) { self.init(corners: position.roundedCorners, base: base) } } class IrregularBorderView : UIImageView { let cornerMaskView = UIImageView() init() { super.init(frame : CGRectZero) self.addSubview(cornerMaskView) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } var style : IrregularBorderStyle? { didSet { if let style = style { let radius = style.base.cornerRadius.value(self) self.cornerMaskView.image = renderMaskWithCorners(style.corners, cornerRadii: CGSizeMake(radius, radius)) self.maskView = cornerMaskView self.image = renderBorderWithEdges(style.corners, style : style.base) } else { self.maskView = nil self.image = nil } } } private func renderMaskWithCorners(corners : UIRectCorner, cornerRadii : CGSize) -> UIImage { let size = CGSizeMake(cornerRadii.width * 2 + 1, cornerRadii.height * 2 + 1) UIGraphicsBeginImageContextWithOptions(size, false, 0) UIColor.blackColor().setFill() let path = UIBezierPath(roundedRect: CGRect(origin: CGPointZero, size: size), byRoundingCorners: corners, cornerRadii: cornerRadii) path.fill() let result = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return result.resizableImageWithCapInsets(UIEdgeInsets(top: cornerRadii.height, left: cornerRadii.width, bottom: cornerRadii.height, right: cornerRadii.width)) } private func renderBorderWithEdges(corners : UIRectCorner, style : BorderStyle) -> UIImage? { let radius = style.cornerRadius.value(self) let size = CGSizeMake(radius * 2 + 1, radius * 2 + 1) guard let color = style.color else { return nil } UIGraphicsBeginImageContextWithOptions(size, false, 0) color.setStroke() let path = UIBezierPath(roundedRect: CGRect(origin: CGPointZero, size: size), byRoundingCorners: corners, cornerRadii: CGSizeMake(radius, radius)) path.lineWidth = style.width.value path.stroke() let result = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return result.resizableImageWithCapInsets(UIEdgeInsets(top: radius, left: radius, bottom: radius, right: radius)) } override func layoutSubviews() { super.layoutSubviews() self.maskView?.frame = self.bounds } }
3f75e819d9eba4c8edc3bd5f7effb701
32.333333
167
0.633611
false
false
false
false
chicio/Exploring-SceneKit
refs/heads/master
ExploringSceneKit/Model/Scenes/BlinnPhong/DynamicSphere.swift
mit
1
// // DynamicSphere.swift // ExploringSceneKit // // Created by Fabrizio Duroni on 26.08.17. // import SceneKit class DynamicSphere: Object { let sphereGeometry: SCNSphere init(material: BlinnPhongMaterial, physicsBodyFeature: PhysicsBodyFeatures, radius: CGFloat, position: SCNVector3, rotation: SCNVector4) { sphereGeometry = SCNSphere(radius: radius) super.init(geometry: sphereGeometry, position: position, rotation: rotation) node.geometry?.firstMaterial = material.material node.physicsBody = SCNPhysicsBody.dynamic() node.physicsBody?.mass = physicsBodyFeature.mass node.physicsBody?.rollingFriction = physicsBodyFeature.rollingFriction } }
9412af3a8bfbe3446b381630575ffeac
33.190476
142
0.731198
false
false
false
false
SwifterSwift/SwifterSwift
refs/heads/master
Tests/SceneKitTests/SCNBoxExtensionsTests.swift
mit
1
// SCNBoxExtensionsTests.swift - Copyright 2020 SwifterSwift @testable import SwifterSwift import XCTest #if canImport(SceneKit) import SceneKit final class SCNBoxExtensionsTests: XCTestCase { func testInitWithoutChamferRadius() { let box = SCNBox(width: 1, height: 2, length: 3) XCTAssertEqual(box.boundingSize, SCNVector3(1, 2, 3)) } func testInitWithMaterial() { let material = SCNMaterial(color: .red) let box = SCNBox(width: 1, height: 2, length: 3, chamferRadius: 0, material: material) XCTAssertEqual(box.materials, [material]) } func testInitWithColor() { let color = SFColor.red let box = SCNBox(width: 1, height: 2, length: 3, chamferRadius: 0, color: color) XCTAssertEqual(box.materials[0].diffuse.contents as? SFColor, color) } func testInitWithSideLength() { let box = SCNBox(sideLength: 1) XCTAssertEqual(box.boundingSize, SCNVector3(1, 1, 1)) } func testInitWithSideLengthAndMaterial() { let material = SCNMaterial(color: .red) let box = SCNBox(sideLength: 1, chamferRadius: 0, material: material) XCTAssertEqual(box.boundingSize, SCNVector3(1, 1, 1)) XCTAssertEqual(box.materials, [material]) } func testInitWithSideLengthAndColor() { let color = SFColor.red let box = SCNBox(sideLength: 1, chamferRadius: 0, color: color) XCTAssertEqual(box.boundingSize, SCNVector3(1, 1, 1)) XCTAssertEqual(box.materials[0].diffuse.contents as? SFColor, color) } } #endif
4e1d79ddeb0422d30d2e065c9325c507
32.489362
94
0.672808
false
true
false
false
brightify/torch
refs/heads/fix/xcode11
Tests/GCDSafetyTest.swift
mit
1
// // GCDSafetyTest.swift // Torch // // Created by Tadeas Kriz on 7/5/17. // Copyright © 2017 Brightify. All rights reserved. // import XCTest import RealmSwift import Torch //class SyncThread: Thread { // private let lockQueue = DispatchQueue(label: "lockQueue") // private let dispatchGroup = DispatchGroup() // private var work: () -> Any = { Void() } // private var result: Any = Void() // // private let queue = OperationQueue() // // override func main() { // self.result = work() // work = { Void() } // print(result) // dispatchGroup.leave() // } // // func sync<RESULT>(work: () -> RESULT) -> RESULT { // return lockQueue.sync { // return withoutActuallyEscaping(work) { work in // self.work = work // dispatchGroup.enter() // start() // dispatchGroup.wait() // return result as! RESULT // } // } // } //} class GCDSafetyTest: XCTestCase { func testSyncDifferentThread() { let queue = DispatchQueue(label: "test") let otherQueue = DispatchQueue(label: "other") let check = queue.sync { Thread.current } let e = expectation(description: "Threads") otherQueue.async { queue.sync { XCTAssertNotEqual(check, Thread.current) e.fulfill() } } waitForExpectations(timeout: 5) } func testSyncSafety() { let queue = DispatchQueue(label: "test") let otherQueue = DispatchQueue(label: "other") let other2Queue = DispatchQueue(label: "other2") let (database, check) = queue.sync { (TestUtils.initDatabase(), Thread.current) } let e = expectation(description: "Create") var entity = OtherData(id: nil, text: "Test") otherQueue.async { print("async 1") queue.sync { print("sync 1a") TestUtils.initDatabase(keepData: true).create(&entity) print("sync 1b") XCTAssertNotEqual(check, Thread.current) print("sync 1c") e.fulfill() print("sync 1d") } } let e2 = expectation(description: "Load") other2Queue.async { sleep(1) print("async 2") queue.sync { print("sync 2a") print(TestUtils.initDatabase(keepData: true).load(OtherData.self)) print("sync 2b") XCTAssertNotEqual(check, Thread.current) print("sync 2c") e2.fulfill() print("sync 2d") } } waitForExpectations(timeout: 60) } // func testThreadSafety() { // let otherQueue = DispatchQueue(label: "other") // let thread = SyncThread() // // let check = thread.sync { // Thread.current // } // // // let e = expectation(description: "Threads") // // otherQueue.async { // thread.sync { // XCTAssertEqual(check, Thread.current) // e.fulfill() // } // } // // waitForExpectations(timeout: 5) // } }
b2c545fad4b4963e0964c0096c8bca5b
25.357143
82
0.509786
false
true
false
false
ksco/swift-algorithm-club-cn
refs/heads/master
Fixed Size Array/FixedSizeArray.swift
mit
2
/* An unordered array with a maximum size. Performance is always O(1). */ struct FixedSizeArray<T> { private var maxSize: Int private var defaultValue: T private var array: [T] private (set) var count = 0 init(maxSize: Int, defaultValue: T) { self.maxSize = maxSize self.defaultValue = defaultValue self.array = [T](count: maxSize, repeatedValue: defaultValue) } subscript(index: Int) -> T { assert(index >= 0) assert(index < count) return array[index] } mutating func append(newElement: T) { assert(count < maxSize) array[count] = newElement count += 1 } mutating func removeAtIndex(index: Int) -> T { assert(index >= 0) assert(index < count) count -= 1 let result = array[index] array[index] = array[count] array[count] = defaultValue return result } mutating func removeAll() { for i in 0..<count { array[i] = defaultValue } count = 0 } }
9beed84c7ee6e2a65dcd0eb4dfede457
19.913043
65
0.628898
false
false
false
false
neotron/SwiftBot-Discord
refs/heads/master
DiscordAPI/Source/API/WebSockets/API/GatewayUrlRequest.swift
gpl-3.0
1
// // Created by David Hedbor on 2/12/16. // Copyright (c) 2016 NeoTron. All rights reserved. // import Foundation import Alamofire import AlamofireObjectMapper class GatewayUrlRequest { internal func execute(_ callback: ((Bool)->Void)?) { guard let token = Registry.instance.token else { LOG_ERROR("Cannot retrieve endpoint, login first.") callback?(false) return } // public func request( // _ url: URLConvertible, // method: HTTPMethod = .get, // parameters: Parameters? = nil, // encoding: ParameterEncoding = URLEncoding.default, // headers: HTTPHeaders? = nil) // -> DataRequest let headers: HTTPHeaders = [ "Content-Type": "application/json", "User-Agent": Registry.userAgent, "Authorization": token, ] Alamofire.request(Endpoints.Simple(.Gateway), headers: headers).responseObject { (response: DataResponse<GatewayUrlResponseModel>) in var success = false if let url = response.result.value?.url { Registry.instance.websocketEndpoint = url LOG_INFO("Retrieved websocket endpoint: \(url)") success = true } else { LOG_ERROR("Failed to retrieve websocket endpoint: \(response.result.error)"); } callback?(success) } } }
a32941075d5d218344f41cd08250c653
32.613636
93
0.565923
false
false
false
false
jacobwhite/firefox-ios
refs/heads/master
Extensions/ShareTo/UXConstants.swift
mpl-2.0
1
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import UIKit struct UX { static let doneDialogAnimationDuration: TimeInterval = 0.2 static let durationToShowDoneDialog: TimeInterval = UX.doneDialogAnimationDuration + 0.8 static let alphaForFullscreenOverlay: CGFloat = 0.3 static let dialogCornerRadius: CGFloat = 8 static let topViewHeight = 320 static let topViewWidth = 345 static let viewHeightForDoneState = 170 static let pageInfoRowHeight = 64 static let actionRowHeight = 44 static let actionRowSpacingBetweenIconAndTitle: CGFloat = 16 static let actionRowIconSize = 24 static let rowInset: CGFloat = 16 static let pageInfoRowLeftInset = UX.rowInset + 6 static let pageInfoLineSpacing: CGFloat = 2 static let doneLabelBackgroundColor = UIColor(red: 76 / 255.0, green: 158 / 255.0, blue: 1.0, alpha: 1.0) static let doneLabelFont = UIFont.boldSystemFont(ofSize: 17) static let separatorColor = UIColor(white: CGFloat(205.0/255.0), alpha: 1.0) static let baseFont = UIFont.systemFont(ofSize: 15) static let actionRowTextAndIconColor = UIColor.Photon.Grey80 }
71673022ac1eaf17c0f6335c35773ee5
47.148148
109
0.740769
false
false
false
false
Ivacker/swift
refs/heads/master
validation-test/compiler_crashers_fixed/00875-getselftypeforcontainer.swift
apache-2.0
13
// RUN: not %target-swift-frontend %s -parse // Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing protocol c { class A { if true { func f: NSObject { enum A { } if c = c(v: NSObject { } f = b: e == T) { func compose<T: C { } typealias e = c() -> V { func a(f: A: A { } var d where T>) -> { let d<T : P { } let c: P { } protocol c = e, V>: Array) { } self] { print() -> { } protocol P { } } var b = { protocol P { } } enum S<T) { return g<T>: A() { } deinit { } } } } } } extension NSSet { } } } var e: e!.e == c: String = compose(false) protocol P { } typealias e : e == ni
2b7044d1518d547566f2c62df1540bae
11.563636
87
0.580318
false
false
false
false
ocrickard/Theodolite
refs/heads/master
Theodolite/UI/Text/TextKitLayer.swift
mit
1
// // TextKitLayer.swift // Theodolite // // Created by Oliver Rickard on 10/31/17. // Copyright © 2017 Oliver Rickard. All rights reserved. // import UIKit private class TextKitDrawParameters: NSObject { let attributes: TextKitAttributes init(attributes: TextKitAttributes) { self.attributes = attributes } } public final class TextKitLayer: TheodoliteAsyncLayer { var attributes: TextKitAttributes? = nil { didSet { if attributes != oldValue { self.setNeedsDisplay() } } } public override init() { super.init() #if DEBUG if let _ = NSClassFromString("XCTest") { // While tests are running, we need to ensure we display synchronously self.displayMode = .alwaysSync } else { self.displayMode = .alwaysAsync } #else self.displayMode = .alwaysAsync #endif } public override var needsDisplayOnBoundsChange: Bool { get { return true } set { // Don't allow this property to be disabled. Unfortunately, UIView will turn this off when setting the // backgroundColor, for reasons that cannot be understood. Even worse, it doesn't ever set it back, so it will // subsequently stay off. Just make sure that it never gets overridden, because the text will not be drawn in the // correct way (or even at all) if this is set to NO. } } public required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } public override init(layer: Any) { super.init(layer: layer) } public override class func defaultValue(forKey key: String) -> Any? { switch key { case "contentsScale": return NSNumber(value: Double(TextKitLayer.gScreenScale)) default: return super.defaultValue(forKey: key) } } public override func drawParameters() -> NSObject! { guard let attributes = self.attributes else { return NSObject() } return TextKitDrawParameters(attributes: attributes) } public override func draw(in ctx: CGContext) { if self.isOpaque, let bgColor = self.backgroundColor { ctx.saveGState() let boundsRect = ctx.boundingBoxOfClipPath ctx.setFillColor(bgColor) ctx.fill(boundsRect) ctx.restoreGState() } super.draw(in: ctx) } public override class func draw(in ctx: CGContext, parameters: NSObject) { guard let params = parameters as? TextKitDrawParameters else { return } let rect = ctx.boundingBoxOfClipPath let renderer = TextKitRenderer.renderer(attributes: params.attributes, constrainedSize: rect.size) renderer.drawInContext(graphicsContext: ctx, bounds: rect) } public override func didDisplayAsynchronously(_ newContents: Any?, withDrawParameters drawParameters: NSObjectProtocol) { guard newContents != nil else { return } let image = newContents as! CGImage let bytes = image.bytesPerRow * image.height TextKitLayer .gTextKitRenderArtifactCache .setObject(image, forKey: TextKitRendererKey( attributes: self.attributes!, constrainedSize: self.bounds.size), cost: bytes) } public override func willDisplayAsynchronously(withDrawParameters drawParameters: NSObjectProtocol) -> Any? { let cached = TextKitLayer .gTextKitRenderArtifactCache .object(forKey: TextKitRendererKey( attributes: self.attributes!, constrainedSize: self.bounds.size)) return cached } static var gTextKitRenderArtifactCache: TextCache<TextKitRendererKey, AnyObject> = { let cache = TextCache<TextKitRendererKey, AnyObject>() cache.totalCostLimit = 6 * 1024 * 1024 return cache }() static var gScreenScale: CGFloat = UIScreen.main.scale }
1a093fbfee5e3a6a75cffd2393b3f93f
28.484848
123
0.668294
false
false
false
false
wireapp/wire-ios-sync-engine
refs/heads/develop
Source/Synchronization/Strategies/UserImageAssetUpdateStrategy.swift
gpl-3.0
1
// // Wire // Copyright (C) 2017 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 WireRequestStrategy internal enum AssetTransportError: Error { case invalidLength case assetTooLarge case other(Error?) init(response: ZMTransportResponse) { switch (response.httpStatus, response.payloadLabel()) { case (400, .some("invalid-length")): self = .invalidLength case (413, .some("client-error")): self = .assetTooLarge default: self = .other(response.transportSessionError) } } } public final class UserImageAssetUpdateStrategy: AbstractRequestStrategy, ZMContextChangeTrackerSource, ZMSingleRequestTranscoder, ZMDownstreamTranscoder { internal let requestFactory = AssetRequestFactory() internal var upstreamRequestSyncs = [ProfileImageSize: ZMSingleRequestSync]() internal var deleteRequestSync: ZMSingleRequestSync? internal var downstreamRequestSyncs = [ProfileImageSize: ZMDownstreamObjectSyncWithWhitelist]() internal let moc: NSManagedObjectContext internal weak var imageUploadStatus: UserProfileImageUploadStatusProtocol? fileprivate var observers: [Any] = [] @objc public convenience init(managedObjectContext: NSManagedObjectContext, applicationStatusDirectory: ApplicationStatusDirectory, userProfileImageUpdateStatus: UserProfileImageUpdateStatus) { self.init(managedObjectContext: managedObjectContext, applicationStatus: applicationStatusDirectory, imageUploadStatus: userProfileImageUpdateStatus) } internal init(managedObjectContext: NSManagedObjectContext, applicationStatus: ApplicationStatus, imageUploadStatus: UserProfileImageUploadStatusProtocol) { self.moc = managedObjectContext self.imageUploadStatus = imageUploadStatus super.init(withManagedObjectContext: managedObjectContext, applicationStatus: applicationStatus) downstreamRequestSyncs[.preview] = whitelistUserImageSync(for: .preview) downstreamRequestSyncs[.complete] = whitelistUserImageSync(for: .complete) downstreamRequestSyncs.forEach { (_, sync) in sync.whiteListObject(ZMUser.selfUser(in: managedObjectContext)) } upstreamRequestSyncs[.preview] = ZMSingleRequestSync(singleRequestTranscoder: self, groupQueue: moc) upstreamRequestSyncs[.complete] = ZMSingleRequestSync(singleRequestTranscoder: self, groupQueue: moc) deleteRequestSync = ZMSingleRequestSync(singleRequestTranscoder: self, groupQueue: moc) observers.append(NotificationInContext.addObserver( name: .userDidRequestCompleteAsset, context: managedObjectContext.notificationContext, using: { [weak self] in self?.requestAssetForNotification(note: $0) }) ) observers.append(NotificationInContext.addObserver( name: .userDidRequestPreviewAsset, context: managedObjectContext.notificationContext, using: { [weak self] in self?.requestAssetForNotification(note: $0) }) ) } fileprivate func whitelistUserImageSync(for size: ProfileImageSize) -> ZMDownstreamObjectSyncWithWhitelist { let predicate: NSPredicate switch size { case .preview: predicate = ZMUser.previewImageDownloadFilter case .complete: predicate = ZMUser.completeImageDownloadFilter } return ZMDownstreamObjectSyncWithWhitelist(transcoder: self, entityName: ZMUser.entityName(), predicateForObjectsToDownload: predicate, managedObjectContext: moc) } internal func size(for requestSync: ZMDownstreamObjectSyncWithWhitelist) -> ProfileImageSize? { for (size, sync) in downstreamRequestSyncs where sync === requestSync { return size } return nil } internal func size(for requestSync: ZMSingleRequestSync) -> ProfileImageSize? { for (size, sync) in upstreamRequestSyncs where sync === requestSync { return size } return nil } func requestAssetForNotification(note: NotificationInContext) { moc.performGroupedBlock { guard let objectID = note.object as? NSManagedObjectID, let object = self.moc.object(with: objectID) as? ZMManagedObject else { return } switch note.name { case .userDidRequestPreviewAsset: self.downstreamRequestSyncs[.preview]?.whiteListObject(object) case .userDidRequestCompleteAsset: self.downstreamRequestSyncs[.complete]?.whiteListObject(object) default: break } RequestAvailableNotification.notifyNewRequestsAvailable(nil) } } public override func nextRequestIfAllowed(for apiVersion: APIVersion) -> ZMTransportRequest? { for size in ProfileImageSize.allSizes { let requestSync = downstreamRequestSyncs[size] if let request = requestSync?.nextRequest(for: apiVersion) { return request } } guard let updateStatus = imageUploadStatus else { return nil } // There are assets added for deletion if updateStatus.hasAssetToDelete() { deleteRequestSync?.readyForNextRequestIfNotBusy() return deleteRequestSync?.nextRequest(for: apiVersion) } let sync = ProfileImageSize.allSizes.filter(updateStatus.hasImageToUpload).compactMap { upstreamRequestSyncs[$0] }.first sync?.readyForNextRequestIfNotBusy() return sync?.nextRequest(for: apiVersion) } // MARK: - ZMContextChangeTrackerSource public var contextChangeTrackers: [ZMContextChangeTracker] { return Array(downstreamRequestSyncs.values) } // MARK: - ZMDownstreamTranscoder public func request(forFetching object: ZMManagedObject!, downstreamSync: ZMObjectSync!, apiVersion: APIVersion) -> ZMTransportRequest! { guard let whitelistSync = downstreamSync as? ZMDownstreamObjectSyncWithWhitelist else { return nil } guard let user = object as? ZMUser else { return nil } guard let size = size(for: whitelistSync) else { return nil } let remoteId: String? switch size { case .preview: remoteId = user.previewProfileAssetIdentifier case .complete: remoteId = user.completeProfileAssetIdentifier } guard let assetId = remoteId else { return nil } let path: String switch apiVersion { case .v0: path = "/assets/v3/\(assetId)" case .v1: guard let domain = user.domain.nonEmptyValue ?? BackendInfo.domain else { return nil } path = "/assets/v4/\(domain)/\(assetId)" case .v2: guard let domain = user.domain.nonEmptyValue ?? BackendInfo.domain else { return nil } path = "/assets/\(domain)/\(assetId)" } return ZMTransportRequest.imageGet(fromPath: path, apiVersion: apiVersion.rawValue) } public func delete(_ object: ZMManagedObject!, with response: ZMTransportResponse!, downstreamSync: ZMObjectSync!) { guard let whitelistSync = downstreamSync as? ZMDownstreamObjectSyncWithWhitelist else { return } guard let user = object as? ZMUser else { return } switch size(for: whitelistSync) { case .preview?: user.previewProfileAssetIdentifier = nil case .complete?: user.completeProfileAssetIdentifier = nil default: break } } public func update(_ object: ZMManagedObject!, with response: ZMTransportResponse!, downstreamSync: ZMObjectSync!) { guard let whitelistSync = downstreamSync as? ZMDownstreamObjectSyncWithWhitelist else { return } guard let user = object as? ZMUser else { return } guard let size = size(for: whitelistSync) else { return } user.setImage(data: response.rawData, size: size) } // MARK: - ZMSingleRequestTranscoder public func request(for sync: ZMSingleRequestSync, apiVersion: APIVersion) -> ZMTransportRequest? { if let size = size(for: sync), let image = imageUploadStatus?.consumeImage(for: size) { let request = requestFactory.upstreamRequestForAsset(withData: image, shareable: true, retention: .eternal, apiVersion: apiVersion) request?.addContentDebugInformation("Uploading to /assets/V3: [\(size)] [\(image)] ") return request } else if sync === deleteRequestSync { if let assetId = imageUploadStatus?.consumeAssetToDelete() { let path = "/assets/v3/\(assetId)" return ZMTransportRequest(path: path, method: .methodDELETE, payload: nil, apiVersion: apiVersion.rawValue) } } return nil } public func didReceive(_ response: ZMTransportResponse, forSingleRequest sync: ZMSingleRequestSync) { guard let size = size(for: sync) else { return } guard response.result == .success else { let error = AssetTransportError(response: response) imageUploadStatus?.uploadingFailed(imageSize: size, error: error) return } guard let payload = response.payload?.asDictionary(), let assetId = payload["key"] as? String else { fatal("No asset ID present in payload") } imageUploadStatus?.uploadingDone(imageSize: size, assetId: assetId) } }
adeb27a966cf1127de28e7ad985c2332
42.195833
160
0.673483
false
false
false
false
fizx/jane
refs/heads/master
ruby/lib/vendor/grpc-swift/Examples/Google/Datastore/Sources/main.swift
mit
3
/* * Copyright 2017, gRPC Authors All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import Commander import Dispatch import Foundation import SwiftGRPC import OAuth2 // Convert Encodable objects to dictionaries of property-value pairs. class PropertiesEncoder { static func encode<T: Encodable>(_ value: T) throws -> [String: Any]? { #if os(OSX) let plist = try PropertyListEncoder().encode(value) let properties = try PropertyListSerialization.propertyList(from: plist, options: [], format: nil) #else let data = try JSONEncoder().encode(value) let properties = try JSONSerialization.jsonObject(with: data, options: []) #endif return properties as? [String: Any] } } // Create Decodable objects from dictionaries of property-value pairs. class PropertiesDecoder { static func decode<T: Decodable>(_ type: T.Type, from: [String: Any]) throws -> T { #if os(OSX) let plist = try PropertyListSerialization.data(fromPropertyList: from, format: .binary, options: 0) return try PropertyListDecoder().decode(type, from: plist) #else let data = try JSONSerialization.data(withJSONObject: from, options: []) return try JSONDecoder().decode(type, from: data) #endif } } // a Swift interface to the Google Cloud Datastore API class Datastore { var projectID: String var service: Google_Datastore_V1_DatastoreServiceClient! let scopes = ["https://www.googleapis.com/auth/datastore"] init(projectID: String) { self.projectID = projectID } func authenticate() throws { var authToken: String! if let provider = DefaultTokenProvider(scopes: scopes) { let sem = DispatchSemaphore(value: 0) try provider.withToken { (token, _) -> Void in if let token = token { authToken = token.AccessToken } sem.signal() } sem.wait() } if authToken == nil { print("ERROR: No OAuth token is available. Did you set GOOGLE_APPLICATION_CREDENTIALS?") exit(-1) } // Initialize gRPC service gRPC.initialize() service = Google_Datastore_V1_DatastoreServiceClient(address: "datastore.googleapis.com") service.metadata = Metadata(["authorization": "Bearer " + authToken]) } func performList<T: Codable>(type: T.Type) throws -> [Int64: T] { var request = Google_Datastore_V1_RunQueryRequest() request.projectID = projectID var query = Google_Datastore_V1_GqlQuery() query.queryString = "select * from " + String(describing: type) request.gqlQuery = query let result = try service.runquery(request) var entities: [Int64: T] = [:] for entityResult in result.batch.entityResults { var properties: [String: Any] = [:] for property in entityResult.entity.properties { let key = property.key switch property.value.valueType! { case .integerValue(let v): properties[key] = v case .stringValue(let v): properties[key] = v default: print("?") } } let entity = try PropertiesDecoder.decode(type, from: properties) entities[entityResult.entity.key.path[0].id] = entity } return entities } func performInsert<T: Codable>(thing: T) throws { var request = Google_Datastore_V1_CommitRequest() request.projectID = projectID request.mode = .nonTransactional var pathElement = Google_Datastore_V1_Key.PathElement() pathElement.kind = String(describing: type(of: thing)) var key = Google_Datastore_V1_Key() key.path = [pathElement] var entity = Google_Datastore_V1_Entity() entity.key = key let properties = try PropertiesEncoder.encode(thing)! for (k, v) in properties { var value = Google_Datastore_V1_Value() switch v { case let v as String: value.stringValue = v case let v as Int: value.integerValue = Int64(v) default: break } entity.properties[k] = value } var mutation = Google_Datastore_V1_Mutation() mutation.insert = entity request.mutations.append(mutation) let result = try service.commit(request) for mutationResult in result.mutationResults { print("\(mutationResult)") } } func performDelete(kind: String, id: Int64) throws { var request = Google_Datastore_V1_CommitRequest() request.projectID = projectID request.mode = .nonTransactional var pathElement = Google_Datastore_V1_Key.PathElement() pathElement.kind = kind pathElement.id = id var key = Google_Datastore_V1_Key() key.path = [pathElement] var mutation = Google_Datastore_V1_Mutation() mutation.delete = key request.mutations.append(mutation) let result = try service.commit(request) for mutationResult in result.mutationResults { print("\(mutationResult)") } } } let projectID = "your-project-identifier" struct Thing: Codable { var name: String var number: Int } Group { $0.command("insert") { (number: Int) in let datastore = Datastore(projectID: projectID) try datastore.authenticate() let thing = Thing(name: "Thing", number: number) try datastore.performInsert(thing: thing) } $0.command("delete") { (id: Int) in let datastore = Datastore(projectID: projectID) try datastore.authenticate() try datastore.performDelete(kind: "Thing", id: Int64(id)) } $0.command("list") { let datastore = Datastore(projectID: projectID) try datastore.authenticate() let entities = try datastore.performList(type: Thing.self) print("\(entities)") } }.run()
a008e4b1bdfc95eb4a5123fee31fa835
31.603175
105
0.673483
false
false
false
false
zhouxj6112/ARKit
refs/heads/master
ARHome/ARHome/Focus Square/Plane.swift
apache-2.0
1
// // Plane.swift // ARCube // // Created by 张嘉夫 on 2017/7/10. // Copyright © 2017年 张嘉夫. All rights reserved. // import UIKit import SceneKit import ARKit class Plane: SCNNode { var anchor: ARPlaneAnchor! var planeGeometry: SCNPlane! init(withAnchor anchor: ARPlaneAnchor) { super.init() self.anchor = anchor planeGeometry = SCNPlane(width: CGFloat(anchor.extent.x), height: CGFloat(anchor.extent.z)) // 相比把网格视觉化为灰色平面,我更喜欢用科幻风的颜色来渲染 let material = SCNMaterial() let img = UIImage(named: "fabric") material.diffuse.contents = img material.lightingModel = .physicallyBased planeGeometry.materials = [material] let planeNode = SCNNode(geometry: planeGeometry) planeNode.position = SCNVector3Make(anchor.center.x, 0, anchor.center.z) // SceneKit 里的平面默认是垂直的,所以需要旋转90度来匹配 ARKit 中的平面 planeNode.transform = SCNMatrix4MakeRotation(Float(-.pi / 2.0), 1.0, 0.0, 0.0) setTextureScale() addChildNode(planeNode) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func update(anchor: ARPlaneAnchor) { // 随着用户移动,平面 plane 的 范围 extend 和 位置 location 可能会更新。 // 需要更新 3D 几何体来匹配 plane 的新参数。 planeGeometry.width = CGFloat(anchor.extent.x); planeGeometry.height = CGFloat(anchor.extent.z); // plane 刚创建时中心点 center 为 0,0,0,node transform 包含了变换参数。 // plane 更新后变换没变但 center 更新了,所以需要更新 3D 几何体的位置 position = SCNVector3Make(anchor.center.x, 0, anchor.center.z) setTextureScale() } func setTextureScale() { let width = planeGeometry.width let height = planeGeometry.height // 平面的宽度/高度 width/height 更新时,我希望 tron grid material 覆盖整个平面,不断重复纹理。 // 但如果网格小于 1 个单位,我不希望纹理挤在一起,所以这种情况下通过缩放更新纹理坐标并裁剪纹理 let material = planeGeometry.materials.first material?.diffuse.contentsTransform = SCNMatrix4MakeScale(Float(width), Float(height), 1) material?.diffuse.wrapS = .repeat material?.diffuse.wrapT = .repeat } }
1eeea9c6b9890c51b003545ceac777a6
31.397059
99
0.636859
false
false
false
false
fuzzymeme/TutorApp
refs/heads/master
Tutor/QandAView.swift
mit
1
// // QandAView.swift // Tutor // // Created by Fuzzymeme on 28/05/2017. // Copyright © 2017 Fuzzymeme. All rights reserved. // import UIKit class QandAView: UIView { @IBOutlet weak var optionZeroButton: UIButton! @IBOutlet weak var optionOneButton: UIButton! @IBOutlet weak var optionTwoButton: UIButton! @IBOutlet weak var optionThreeButton: UIButton! @IBOutlet weak var skipNextButton: UIButton! @IBOutlet weak var questionLabel: UILabel! @IBOutlet weak var successLabel: UILabel! lazy private var buttonToIndexMap: [UIButton: Int] = self.initializeButtonMap() private var buttons = [UIButton]() private var viewListener: ViewController? @IBAction func optionButtonTouched(_ sender: UIButton) { viewListener?.handleButtonTouchedEvent(buttonIndex: buttonToIndexMap[sender]!) } @IBAction func skipNextButtonTouched(_ sender: UIButton) { viewListener?.handleSkipButtonTouchedEvent() } func initializeButtonMap() -> [UIButton: Int] { return [optionZeroButton: 0, optionOneButton: 1, optionTwoButton: 2, optionThreeButton: 3] } func setDelegate(_ viewListener: ViewController) { self.viewListener = viewListener } func setButtonStyleRounded() { for button in buttonToIndexMap.keys { button.layer.cornerRadius = 6 button.layer.borderWidth = 0 } } func setBackground(color newBackgroundColor: UIColor) { self.backgroundColor = newBackgroundColor } func setButtonsBackground(color newBackgroundColor: UIColor) { for button in buttonToIndexMap.keys { button.backgroundColor = newBackgroundColor } } func setSkipNextButtonBackground(color newBackgroundColor: UIColor) { skipNextButton.backgroundColor = newBackgroundColor } func setSkipButtonStyleRounded() { skipNextButton.layer.cornerRadius = 6 skipNextButton.layer.borderWidth = 0 } func setSkipNextButtonText(newText: String) { skipNextButton.setTitle(newText, for: .normal) } func setOption(atIndex optionNumber: Int, setTo newValue: String) { let selectedButton = buttonWithIndex(optionNumber) selectedButton?.setTitle(newValue, for: .normal) } func setAnswers(_ answers: [String]) { var index = 0 for answer in answers { setOption(atIndex: index, setTo: answer) index += 1 } } var question: String { get { return questionLabel.text ?? ""} set { questionLabel.text = newValue} } var displaySuccess: Bool { get{ return false} set { if newValue { successLabel!.text = "Correct" successLabel!.backgroundColor = UIColor.green } else { successLabel!.text = "Wrong" successLabel!.backgroundColor = UIColor.red } } } private func buttonWithIndex(_ index: Int) -> UIButton? { return buttonToIndexMap.keys.first(where: {[weak self] in self?.buttonToIndexMap[$0] == index}) } } protocol QandAViewListener { func handleButtonTouchedEvent(buttonIndex: Int) }
8168868186244c4453b05021cdf31abf
28.936364
103
0.64379
false
false
false
false
marselan/brooch
refs/heads/master
brooch/brooch/HttpClient.swift
gpl-3.0
1
// // HttpClient.swift // brooch // // Created by Mariano Arselan on 2/19/18. // Copyright © 2018 Mariano Arselan. All rights reserved. // import Foundation class HttpClient { func hit(url: String, callback: @escaping (Data?, URLResponse?, Error?) -> Void) { let requestURL = URL(string: url) let request = URLRequest(url: requestURL!) let config = URLSessionConfiguration.default let session = URLSession(configuration: config) let task = session.dataTask(with: request, completionHandler: callback) task.resume() } } extension URLResponse { func getStatus() -> Int? { if let httpResponse = self as? HTTPURLResponse, let status = httpResponse.statusCode as? Int { return status } return nil } func getHeader(_ key: String) -> String? { if let httpResponse = self as? HTTPURLResponse, let field = httpResponse.allHeaderFields[key] as? String { return field } return nil } }
226da00451cc3ae4e7c350b590a2a2ed
24.585366
114
0.618684
false
true
false
false
LeeMZC/MZCWB
refs/heads/master
MZCWB/MZCWB/Classes/login- 登录相关/Controller/MZCWelcomeViewController.swift
artistic-2.0
1
// // MZCWelcomeViewController.swift // MZCWB // // Created by 马纵驰 on 16/7/27. // Copyright © 2016年 马纵驰. All rights reserved. // import UIKit import YYKit import QorumLogs class MZCWelcomeViewController: UIViewController { @IBOutlet weak var userIcon_imgView: UIImageView! @IBOutlet weak var welcome_label: UILabel! @IBOutlet weak var iconButtom_layout: NSLayoutConstraint! // 圆角数值 let userIconRadius = 10 as CGFloat override func viewDidLoad() { QL1("") super.viewDidLoad() setupUI() } func setupUI(){ guard let accountTokenMode = MZCAccountTokenMode.accountToKen() else { return } let iconUrlString = accountTokenMode.user?.avatar_large let iconUrl = NSURL(string: iconUrlString!) userIcon_imgView.setImageWithURL(iconUrl!, placeholderImage: UIImage.init(named: "avatar_default_big")) //设置圆角 userIcon_imgView.layer.cornerRadius = userIconRadius userIcon_imgView.clipsToBounds = true welcome_label.alpha = 0 let iconOffset = view.bounds.size.height - iconButtom_layout.constant UIView.animateWithDuration(MZCWelcomeAniTimer, animations: { //开始动画 self.iconButtom_layout.constant = iconOffset self.view.layoutIfNeeded() }) { (true) in UIView.animateWithDuration(MZCWelcomeAniTimer, animations: { self.welcome_label.alpha = 1 }, completion: { (_) in //通知更换UIWindow NSNotificationCenter.defaultCenter().postNotificationName(MZCMainViewControllerWillChange, object: nil) }) } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
cf51db3a52ac8e861c44c07b5ad65c34
27.939394
123
0.623037
false
false
false
false
mourodrigo/a-simple-reddit-client
refs/heads/master
a-simple-reddit-client/a-simple-reddit-client/Extensions/String+Extension.swift
mit
1
// // Notification+Extension.swift // a-simple-reddit-client // // Created by Rodrigo Bueno Tomiosso on 07/02/17. // Copyright © 2017 mourodrigo. All rights reserved. // import Foundation import UIKit extension String { var componentsFromQueryString: [String : String] { var components = [String: String]() for qs in self.components(separatedBy: "&") { let key = qs.components(separatedBy: "=")[0] var value = qs.components(separatedBy: "=")[1] value = value.replacingOccurrences(of: "+", with: " ") value = value.removingPercentEncoding! components[key] = value } return components } var isURL: Bool { // create NSURL instance if let url = NSURL(string: self) { // check if your application can open the NSURL instance return UIApplication.shared.canOpenURL(url as URL) } return false } }
dd725c2d6aade31698f67c272e190df5
24.44186
70
0.52925
false
false
false
false
michael-lehew/swift-corelibs-foundation
refs/heads/master
Foundation/NSCoder.swift
apache-2.0
1
// 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 // extension NSCoder { /*! Describes the action an NSCoder should take when it encounters decode failures (e.g. corrupt data) for non-TopLevel decodes. Darwin platfrom supports exceptions here, and there may be other approaches supported in the future, so its included for completeness. */ public enum DecodingFailurePolicy : Int { case setErrorAndReturn } } public protocol NSCoding { func encode(with aCoder: NSCoder) init?(coder aDecoder: NSCoder) } public protocol NSSecureCoding : NSCoding { static var supportsSecureCoding: Bool { get } } open class NSCoder : NSObject { internal var _pendingBuffers = Array<(UnsafeMutableRawPointer, Int)>() deinit { for buffer in _pendingBuffers { // Cannot deinitialize a pointer to unknown type. buffer.0.deallocate(bytes: buffer.1, alignedTo: MemoryLayout<Int>.alignment) } } open func encodeValue(ofObjCType type: UnsafePointer<Int8>, at addr: UnsafeRawPointer) { NSRequiresConcreteImplementation() } open func encode(_ data: Data) { NSRequiresConcreteImplementation() } open func decodeValue(ofObjCType type: UnsafePointer<Int8>, at data: UnsafeMutableRawPointer) { NSRequiresConcreteImplementation() } open func decodeData() -> Data? { NSRequiresConcreteImplementation() } open func version(forClassName className: String) -> Int { NSRequiresConcreteImplementation() } open func decodeObject<DecodedObjectType: NSCoding>(of cls: DecodedObjectType.Type, forKey key: String) -> DecodedObjectType? where DecodedObjectType: NSObject { NSUnimplemented() } /*! @method decodeObjectOfClasses:forKey: @abstract Decodes an object for the key, restricted to the specified classes. @param classes An array of the expected classes. @param key The code key. @return The decoded object. @discussion This function signature differs from Foundation OS X in that classes is an array of Classes, not a NSSet. This is because AnyClass cannot be casted to NSObject, nor is it Hashable. */ open func decodeObject(of classes: [AnyClass]?, forKey key: String) -> Any? { NSUnimplemented() } open func decodeTopLevelObject() throws -> Any? { NSUnimplemented() } open func decodeTopLevelObject(forKey key: String) throws -> Any? { NSUnimplemented() } open func decodeTopLevelObject<DecodedObjectType: NSCoding>(of cls: DecodedObjectType.Type, forKey key: String) throws -> DecodedObjectType? where DecodedObjectType: NSObject { NSUnimplemented() } /*! @method decodeTopLevelObjectOfClasses: @abstract Decodes an top-level object for the key, restricted to the specified classes. @param classes An array of the expected classes. @param key The code key. @return The decoded object. @discussion This function signature differs from Foundation OS X in that classes is an array of Classes, not a NSSet. This is because AnyClass cannot be casted to NSObject, nor is it Hashable. */ open func decodeTopLevelObject(of classes: [AnyClass], forKey key: String) throws -> Any? { NSUnimplemented() } open func encode(_ object: Any?) { var object = object withUnsafePointer(to: &object) { (ptr: UnsafePointer<Any?>) -> Void in encodeValue(ofObjCType: "@", at: unsafeBitCast(ptr, to: UnsafeRawPointer.self)) } } open func encodeRootObject(_ rootObject: Any) { encode(rootObject) } open func encodeBycopyObject(_ anObject: Any?) { encode(anObject) } open func encodeByrefObject(_ anObject: Any?) { encode(anObject) } open func encodeConditionalObject(_ object: Any?) { encode(object) } open func encodeArray(ofObjCType type: UnsafePointer<Int8>, count: Int, at array: UnsafeRawPointer) { encodeValue(ofObjCType: "[\(count)\(String(cString: type))]", at: array) } open func encodeBytes(_ byteaddr: UnsafeRawPointer?, length: Int) { var newLength = UInt32(length) withUnsafePointer(to: &newLength) { (ptr: UnsafePointer<UInt32>) -> Void in encodeValue(ofObjCType: "I", at: ptr) } var empty: [Int8] = [] withUnsafePointer(to: &empty) { encodeArray(ofObjCType: "c", count: length, at: byteaddr ?? UnsafeRawPointer($0)) } } open func decodeObject() -> Any? { if self.error != nil { return nil } var obj: Any? = nil withUnsafeMutablePointer(to: &obj) { (ptr: UnsafeMutablePointer<Any?>) -> Void in decodeValue(ofObjCType: "@", at: unsafeBitCast(ptr, to: UnsafeMutableRawPointer.self)) } return obj } open func decodeArray(ofObjCType itemType: UnsafePointer<Int8>, count: Int, at array: UnsafeMutableRawPointer) { decodeValue(ofObjCType: "[\(count)\(String(cString: itemType))]", at: array) } /* // TODO: This is disabled, as functions which return unsafe interior pointers are inherently unsafe when we have no autorelease pool. open func decodeBytes(withReturnedLength lengthp: UnsafeMutablePointer<Int>) -> UnsafeMutableRawPointer? { var length: UInt32 = 0 withUnsafeMutablePointer(to: &length) { (ptr: UnsafeMutablePointer<UInt32>) -> Void in decodeValue(ofObjCType: "I", at: unsafeBitCast(ptr, to: UnsafeMutableRawPointer.self)) } // we cannot autorelease here so instead the pending buffers will manage the lifespan of the returned data... this is wasteful but good enough... let result = UnsafeMutableRawPointer.allocate(bytes: Int(length), alignedTo: MemoryLayout<Int>.alignment) decodeValue(ofObjCType: "c", at: result) lengthp.pointee = Int(length) _pendingBuffers.append((result, Int(length))) return result } */ open func encodePropertyList(_ aPropertyList: Any) { NSUnimplemented() } open func decodePropertyList() -> Any? { NSUnimplemented() } open var systemVersion: UInt32 { return 1000 } open var allowsKeyedCoding: Bool { return false } open func encode(_ objv: Any?, forKey key: String) { NSRequiresConcreteImplementation() } open func encodeConditionalObject(_ objv: Any?, forKey key: String) { NSRequiresConcreteImplementation() } open func encode(_ boolv: Bool, forKey key: String) { NSRequiresConcreteImplementation() } open func encode(_ intv: Int32, forKey key: String) { NSRequiresConcreteImplementation() } open func encode(_ intv: Int64, forKey key: String) { NSRequiresConcreteImplementation() } open func encode(_ realv: Float, forKey key: String) { NSRequiresConcreteImplementation() } open func encode(_ realv: Double, forKey key: String) { NSRequiresConcreteImplementation() } open func encodeBytes(_ bytesp: UnsafePointer<UInt8>?, length lenv: Int, forKey key: String) { NSRequiresConcreteImplementation() } open func containsValue(forKey key: String) -> Bool { NSRequiresConcreteImplementation() } open func decodeObject(forKey key: String) -> Any? { NSRequiresConcreteImplementation() } open func decodeBool(forKey key: String) -> Bool { NSRequiresConcreteImplementation() } // NOTE: this equivalent to the decodeIntForKey: in Objective-C implementation open func decodeCInt(forKey key: String) -> Int32 { NSRequiresConcreteImplementation() } open func decodeInt32(forKey key: String) -> Int32 { NSRequiresConcreteImplementation() } open func decodeInt64(forKey key: String) -> Int64 { NSRequiresConcreteImplementation() } open func decodeFloat(forKey key: String) -> Float { NSRequiresConcreteImplementation() } open func decodeDouble(forKey key: String) -> Double { NSRequiresConcreteImplementation() } // TODO: This is disabled, as functions which return unsafe interior pointers are inherently unsafe when we have no autorelease pool. /* open func decodeBytes(forKey key: String, returnedLength lengthp: UnsafeMutablePointer<Int>?) -> UnsafePointer<UInt8>? { // returned bytes immutable! NSRequiresConcreteImplementation() } */ /// - experimental: This method does not exist in the Darwin Foundation. open func withDecodedUnsafeBufferPointer<ResultType>(forKey key: String, body: (UnsafeBufferPointer<UInt8>?) throws -> ResultType) rethrows -> ResultType { NSRequiresConcreteImplementation() } open func encode(_ intv: Int, forKey key: String) { NSRequiresConcreteImplementation() } open func decodeInteger(forKey key: String) -> Int { NSRequiresConcreteImplementation() } open var requiresSecureCoding: Bool { return false } open func decodePropertyListForKey(_ key: String) -> Any? { NSUnimplemented() } /*! @property allowedClasses @abstract The set of coded classes allowed for secure coding. (read-only) @discussion This property type differs from Foundation OS X in that classes is an array of Classes, not a Set. This is because AnyClass is not hashable. */ /// - Experiment: This is a draft API currently under consideration for official import into Foundation open var allowedClasses: [AnyClass]? { NSUnimplemented() } open func failWithError(_ error: Error) { NSUnimplemented() // NOTE: disabled for now due to bridging uncertainty // if let debugDescription = error.userInfo["NSDebugDescription"] { // NSLog("*** NSKeyedUnarchiver.init: \(debugDescription)") // } else { // NSLog("*** NSKeyedUnarchiver.init: decoding error") // } } open var decodingFailurePolicy: NSCoder.DecodingFailurePolicy { return .setErrorAndReturn } open var error: Error? { NSRequiresConcreteImplementation() } internal func _decodeArrayOfObjectsForKey(_ key: String) -> [Any] { NSRequiresConcreteImplementation() } internal func _decodePropertyListForKey(_ key: String) -> Any { NSRequiresConcreteImplementation() } }
0d18a653727455ae514fd18d86d7f767
33.86478
264
0.655001
false
false
false
false
CodaFi/swift
refs/heads/master
test/IDE/complete_subscript.swift
apache-2.0
7
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=METATYPE_UNRESOLVED | %FileCheck %s -check-prefix=METATYPE_UNRESOLVED // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=METATYPE_UNRESOLVED_BRACKET | %FileCheck %s -check-prefix=METATYPE_UNRESOLVED_BRACKET // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=METATYPE_INT | %FileCheck %s -check-prefix=METATYPE_INT // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=METATYPE_INT_BRACKET | %FileCheck %s -check-prefix=METATYPE_INT_BRACKET // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=INSTANCE_INT | %FileCheck %s -check-prefix=INSTANCE_INT // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=INSTANCE_INT_BRACKET | %FileCheck %s -check-prefix=INSTANCE_INT_BRACKET // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=METATYPE_ARCHETYPE | %FileCheck %s -check-prefix=METATYPE_ARCHETYPE // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=METATYPE_ARCHETYPE_BRACKET | %FileCheck %s -check-prefix=METATYPE_ARCHETYPE_BRACKET // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=INSTANCE_ARCHETYPE | %FileCheck %s -check-prefix=INSTANCE_ARCHETYPE // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=INSTANCE_ARCHETYPE_BRACKET | %FileCheck %s -check-prefix=INSTANCE_ARCHETYPE_BRACKET // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=METATYPE_LABEL | %FileCheck %s -check-prefix=METATYPE_LABEL // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=INSTANCE_LABEL | %FileCheck %s -check-prefix=INSTANCE_LABEL // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=SELF_IN_INSTANCEMETHOD | %FileCheck %s -check-prefix=SELF_IN_INSTANCEMETHOD // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=SUPER_IN_INSTANCEMETHOD | %FileCheck %s -check-prefix=SUPER_IN_INSTANCEMETHOD // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=SELF_IN_STATICMETHOD | %FileCheck %s -check-prefix=SELF_IN_STATICMETHOD // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=SUPER_IN_STATICMETHOD | %FileCheck %s -check-prefix=SUPER_IN_STATICMETHOD // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=LABELED_SUBSCRIPT | %FileCheck %s -check-prefix=LABELED_SUBSCRIPT // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=TUPLE | %FileCheck %s -check-prefix=TUPLE struct MyStruct<T> { static subscript(x: Int, static defValue: T) -> MyStruct<T> { fatalError() } subscript(x: Int, instance defValue: T) -> Int { fatalError() } } func test1() { let _ = MyStruct #^METATYPE_UNRESOLVED^# // METATYPE_UNRESOLVED: Begin completions, 4 items // METATYPE_UNRESOLVED-DAG: Decl[Subscript]/CurrNominal: [{#(x): Int#}, {#static: _#}][#MyStruct<_>#]; // METATYPE_UNRESOLVED-DAG: Decl[Constructor]/CurrNominal: ()[#MyStruct<_>#]; // METATYPE_UNRESOLVED-DAG: Keyword[self]/CurrNominal: .self[#MyStruct<_>.Type#]; // METATYPE_UNRESOLVED-DAG: Keyword/CurrNominal: .Type[#MyStruct<_>.Type#]; // METATYPE_UNRESOLVED: End completions let _ = MyStruct[#^METATYPE_UNRESOLVED_BRACKET^# // METATYPE_UNRESOLVED_BRACKET: Begin completions // METATYPE_UNRESOLVED_BRACKET-DAG: Decl[Subscript]/CurrNominal: ['[']{#(x): Int#}, {#static: _#}[']'][#MyStruct<_>#]; // METATYPE_UNRESOLVED_BRACKET: End completions let _ = MyStruct<Int> #^METATYPE_INT^# // METATYPE_INT: Begin completions, 4 items // METATYPE_INT-DAG: Decl[Subscript]/CurrNominal: [{#(x): Int#}, {#static: Int#}][#MyStruct<Int>#]; // METATYPE_INT-DAG: Decl[Constructor]/CurrNominal: ()[#MyStruct<Int>#]; // METATYPE_INT-DAG: Keyword[self]/CurrNominal: .self[#MyStruct<Int>.Type#]; // METATYPE_INT-DAG: Keyword/CurrNominal: .Type[#MyStruct<Int>.Type#]; // METATYPE_INT: End completions let _ = MyStruct<Int>[#^METATYPE_INT_BRACKET^# // METATYPE_INT_BRACKET: Begin completions // METATYPE_INT_BRACKET-DAG: Decl[Subscript]/CurrNominal: ['[']{#(x): Int#}, {#static: Int#}[']'][#MyStruct<Int>#]; // METATYPE_INT_BRACKET: End completions let _ = MyStruct<Int>()#^INSTANCE_INT^# // INSTANCE_INT: Begin completions, 2 items // INSTANCE_INT-DAG: Decl[Subscript]/CurrNominal: [{#(x): Int#}, {#instance: Int#}][#Int#]; // INSTANCE_INT-DAG: Keyword[self]/CurrNominal: .self[#MyStruct<Int>#]; // INSTANCE_INT: End completions let _ = MyStruct<Int>()[#^INSTANCE_INT_BRACKET^# // INSTANCE_INT_BRACKET: Begin completions // INSTANCE_INT_BRACKET-DAG: Decl[Subscript]/CurrNominal: ['[']{#(x): Int#}, {#instance: Int#}[']'][#Int#]; // INSTANCE_INT_BRACKET-DAG: Pattern/CurrModule: ['[']{#keyPath: KeyPath<MyStruct<Int>, Value>#}[']'][#Value#]; // INSTANCE_INT_BRACKET: End completions } func test2<U>(value: MyStruct<U>) { let _ = MyStruct<U>#^METATYPE_ARCHETYPE^# // METATYPE_ARCHETYPE: Begin completions, 4 items // METATYPE_ARCHETYPE-DAG: Decl[Subscript]/CurrNominal: [{#(x): Int#}, {#static: U#}][#MyStruct<U>#]; // METATYPE_ARCHETYPE-DAG: Decl[Constructor]/CurrNominal: ()[#MyStruct<U>#]; // METATYPE_ARCHETYPE-DAG: Keyword[self]/CurrNominal: .self[#MyStruct<U>.Type#]; // METATYPE_ARCHETYPE-DAG: Keyword/CurrNominal: .Type[#MyStruct<U>.Type#]; // METATYPE_ARCHETYPE: End completions let _ = MyStruct<U>[#^METATYPE_ARCHETYPE_BRACKET^# // METATYPE_ARCHETYPE_BRACKET: Begin completions // METATYPE_ARCHETYPE_BRACKET-DAG: Decl[Subscript]/CurrNominal: ['[']{#(x): Int#}, {#static: U#}[']'][#MyStruct<U>#]; // METATYPE_ARCHETYPE_BRACKET: End completions let _ = value #^INSTANCE_ARCHETYPE^# // INSTANCE_ARCHETYPE: Begin completions, 2 items // INSTANCE_ARCHETYPE-DAG: Decl[Subscript]/CurrNominal: [{#(x): Int#}, {#instance: U#}][#Int#]; // INSTANCE_ARCHETYPE-DAG: Keyword[self]/CurrNominal: .self[#MyStruct<U>#]; // INSTANCE_ARCHETYPE: End completions let _ = value[#^INSTANCE_ARCHETYPE_BRACKET^# // INSTANCE_ARCHETYPE_BRACKET: Begin completions // INSTANCE_ARCHETYPE_BRACKET-DAG: Decl[Subscript]/CurrNominal: ['[']{#(x): Int#}, {#instance: U#}[']'][#Int#]; // INSTANCE_ARCHETYPE_BRACKET-DAG: Pattern/CurrModule: ['[']{#keyPath: KeyPath<MyStruct<U>, Value>#}[']'][#Value#]; // INSTANCE_ARCHETYPE_BRACKET: End completions let _ = MyStruct<U>[42, #^METATYPE_LABEL^# // METATYPE_LABEL: Begin completions, 1 items // METATYPE_LABEL-DAG: Pattern/ExprSpecific: {#static: U#}[#U#]; // METATYPE_LABEL: End completions let _ = value[42, #^INSTANCE_LABEL^# // INSTANCE_LABEL: Begin completions, 1 items // INSTANCE_LABEL-DAG: Pattern/ExprSpecific: {#instance: U#}[#U#]; // INSTANCE_LABEL: End completions } class Base { static subscript(static x: Int) -> Int { return 1 } subscript(instance x: Int) -> Int { return 1 } } class Derived: Base { static subscript(derivedStatic x: Int) -> Int { return 1 } subscript(derivedInstance x: Int) -> Int { return 1 } func testInstance() { let _ = self[#^SELF_IN_INSTANCEMETHOD^#] // SELF_IN_INSTANCEMETHOD: Begin completions, 3 items // SELF_IN_INSTANCEMETHOD-DAG: Decl[Subscript]/CurrNominal: ['[']{#derivedInstance: Int#}[']'][#Int#]; // SELF_IN_INSTANCEMETHOD-DAG: Decl[Subscript]/Super: ['[']{#instance: Int#}[']'][#Int#]; // SELF_IN_INSTANCEMETHOD-DAG: Pattern/CurrModule: ['[']{#keyPath: KeyPath<Derived, Value>#}[']'][#Value#]; // SELF_IN_INSTANCEMETHOD: End completions let _ = super[#^SUPER_IN_INSTANCEMETHOD^#] // SUPER_IN_INSTANCEMETHOD: Begin completions, 2 items // SUPER_IN_INSTANCEMETHOD-DAG: Decl[Subscript]/CurrNominal: ['[']{#instance: Int#}[']'][#Int#]; // SUPER_IN_INSTANCEMETHOD-DAG: Pattern/CurrModule: ['[']{#keyPath: KeyPath<Base, Value>#}[']'][#Value#]; // SUPER_IN_INSTANCEMETHOD: End completions } static func testStatic() { let _ = self[#^SELF_IN_STATICMETHOD^#] // SELF_IN_STATICMETHOD: Begin completions, 2 items // SELF_IN_STATICMETHOD-DAG: Decl[Subscript]/CurrNominal: ['[']{#derivedStatic: Int#}[']'][#Int#]; // SELF_IN_STATICMETHOD-DAG: Decl[Subscript]/Super: ['[']{#static: Int#}[']'][#Int#]; // SELF_IN_STATICMETHOD: End completions let _ = super[#^SUPER_IN_STATICMETHOD^#] // SUPER_IN_STATICMETHOD: Begin completions, 1 items // SUPER_IN_STATICMETHOD-DAG: Decl[Subscript]/CurrNominal: ['[']{#static: Int#}[']'][#Int#]; // SUPER_IN_STATICMETHOD: End completions } } struct MyStruct1<X: Comparable> { subscript(idx1 _: Int, idx2 _: X) -> Int! { return 1 } } func testSubscriptCallSig<T>(val: MyStruct1<T>) { val[#^LABELED_SUBSCRIPT^# // LABELED_SUBSCRIPT: Begin completions, 2 items // LABELED_SUBSCRIPT-DAG: Decl[Subscript]/CurrNominal: ['[']{#idx1: Int#}, {#idx2: Comparable#}[']'][#Int!#]; // LABELED_SUBSCRIPT-DAG: Pattern/CurrModule: ['[']{#keyPath: KeyPath<MyStruct1<T>, Value>#}[']'][#Value#]; // LABELED_SUBSCRIPT: End completions } func testSubcscriptTuple(val: (x: Int, String)) { val[#^TUPLE^#] // TUPLE: Begin completions, 1 items // TUPLE-DAG: Pattern/CurrModule: ['[']{#keyPath: KeyPath<(x: Int, String), Value>#}[']'][#Value#]; // TUPLE: End completions }
bcc0f869ae13364c6f174bb353f595d8
59.628931
176
0.686307
false
true
false
false
Eonil/Editor
refs/heads/develop
Editor4/TemporalLazyCollection.swift
mit
1
// // TemporalLazyCollection.swift // Editor4 // // Created by Hoon H. on 2016/05/26. // Copyright © 2016 Eonil. All rights reserved. // /// A collection that is valid only at specific time range. For optimization. /// /// This GUARANTEES the content of the collection is immutable and won't be /// changed later. Anyway, you can access elements only while /// `version == accessibleVersion`. /// struct TemporalLazyCollection<Element>: CollectionType { typealias Index = AnyRandomAccessIndex // typealias SubSequence = private(set) var version: Version private var controller: TemporalLazyCollectionController<Element>? var accessibleVersion: Version { get { return controller?.version ?? version } } /// Initializes an empty sequence. init() { self.version = emptySequenceVersion self.controller = nil } init<C: CollectionType where C.Generator.Element == Element, C.Index: RandomAccessIndexType>(_ elements: C) { let c = TemporalLazyCollectionController<Element>() c.source = AnyRandomAccessCollection<Element>(elements) self.init(controller: c) } private init(controller: TemporalLazyCollectionController<Element>) { self.version = controller.version self.controller = controller } var isEmpty: Bool { get { return getSource().isEmpty } } func generate() -> AnyGenerator<Element> { return getSource().generate() } var startIndex: AnyRandomAccessIndex { get { return getSource().startIndex } } var endIndex: AnyRandomAccessIndex { get { return getSource().endIndex ?? AnyRandomAccessIndex(0) } } subscript(position: AnyRandomAccessIndex) -> Element { get { return getSource()[position] } } private func getSource() -> AnyRandomAccessCollection<Element> { // Shouldn't be broken even the controller is missing. assert(controller != nil, InvalidationErrorMessage) assert(version == accessibleVersion, InvalidationErrorMessage) return controller?.source ?? AnyRandomAccessCollection([]) } } private let InvalidationErrorMessage = "This sequence has been invalidated. You cannot access this now." extension TemporalLazyCollection: ArrayLiteralConvertible { init(arrayLiteral elements: Element...) { self.init(elements) } } /// Performs all mutations here. /// For each time you mutate, you'll get *conceptually* new sequence. /// And old sequence gets invalidated, and shouldn't be accessed anymore. final class TemporalLazyCollectionController<T> { private(set) var sequence = TemporalLazyCollection<T>() var version = Version() /// Setting a new source will invalidate any existing copies. var source: AnyRandomAccessCollection<T> = AnyRandomAccessCollection<T>([]) { didSet { version.revise() sequence = TemporalLazyCollection(controller: self) } } } private let emptySequenceVersion = Version()
ef67536661e4354db58becffa26535b7
28.784314
113
0.686965
false
false
false
false
1457792186/JWSwift
refs/heads/master
SwiftWX/LGWeChatKit/LGChatKit/conversion/imagePick/LGAssetGridViewController.swift
apache-2.0
1
// // LGAssetGridViewController.swift // LGChatViewController // // Created by jamy on 10/22/15. // Copyright © 2015 jamy. All rights reserved. // import UIKit import Photos private let reuseIdentifier = "girdCell" private let itemMargin: CGFloat = 5 private let durationTime = 0.3 private let itemSize: CGFloat = 80 class LGAssetGridViewController: UICollectionViewController, UIViewControllerTransitioningDelegate { let presentController = LGPresentAnimationController() let dismissController = LGDismissAnimationController() var assetsFetchResults: PHFetchResult<AnyObject>! { willSet { for i in 0...newValue.count - 1 { let asset = newValue[i] as! PHAsset let assetModel = LGAssetModel(asset: asset, select: false) self.assetModels.append(assetModel) } } } var toolBar: LGAssetToolView! var assetViewCtrl: LGAssetViewController! var assetModels = [LGAssetModel]() var selectedInfo: NSMutableArray? var previousPreRect: CGRect! lazy var imageManager: PHCachingImageManager = { return PHCachingImageManager() }() init() { let layout = UICollectionViewFlowLayout() layout.itemSize = CGSize(width: itemSize, height: itemSize) layout.minimumInteritemSpacing = itemMargin layout.minimumLineSpacing = itemMargin layout.sectionInset = UIEdgeInsetsMake(itemMargin, itemMargin, itemMargin, itemMargin) super.init(collectionViewLayout: layout) self.collectionView?.collectionViewLayout = layout collectionView?.contentInset = UIEdgeInsetsMake(0, 0, 50, 0) } override init(collectionViewLayout layout: UICollectionViewLayout) { super.init(nibName: nil, bundle: nil) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() collectionView!.backgroundColor = UIColor.white // Register cell classes self.collectionView!.register(LGAssertGridViewCell.self, forCellWithReuseIdentifier: reuseIdentifier) previousPreRect = CGRect.zero toolBar = LGAssetToolView(leftTitle: "预览", leftSelector: #selector(LGAssetGridViewController.preView), rightSelector: #selector(LGAssetGridViewController.send), parent: self) toolBar.frame = CGRect(x: 0, y: view.bounds.height - 50, width: view.bounds.width, height: 50) view.addSubview(toolBar) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) toolBar.selectCount = 0 for assetModel in assetModels { if assetModel.select { toolBar.addSelectCount = 1 } } collectionView?.reloadData() } func preView() { let assetCtrl = LGAssetViewController() assetCtrl.assetModels = assetModels self.navigationController?.pushViewController(assetCtrl, animated: true) } func send() { navigationController?.viewControllers[0].dismiss(animated: true, completion: nil) } // MARK: - UIViewControllerTransitioningDelegate func animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? { self.selectedIndexPath = assetViewCtrl.currentIndex return dismissController } func animationController(forPresented presented: UIViewController, presenting: UIViewController, source: UIViewController) -> UIViewControllerAnimatedTransitioning? { return presentController } } extension LGAssetGridViewController { // MARK: UICollectionViewDataSource override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { // #warning Incomplete implementation, return the number of items return assetModels.count } override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath) as! LGAssertGridViewCell let asset = assetModels[indexPath.row].asset cell.assetModel = assetModels[indexPath.row] cell.assetIdentifier = asset.localIdentifier cell.selectIndicator.tag = indexPath.row if assetModels[indexPath.row].select { cell.buttonSelect = true } else { cell.buttonSelect = false } cell.selectIndicator.addTarget(self, action: #selector(LGAssetGridViewController.selectButton(_:)), for: .touchUpInside) let scale = UIScreen.main.scale imageManager.requestImage(for: asset, targetSize: CGSize(width: itemSize * scale, height: itemSize * scale), contentMode: .aspectFill, options: nil) { (image, _:[AnyHashable: Any]?) -> Void in if cell.assetIdentifier == asset.localIdentifier { cell.imageView.image = image } } return cell } override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { let assetCtrl = LGAssetViewController() self.selectedIndexPath = indexPath assetCtrl.assetModels = assetModels assetCtrl.selectedInfo = selectedInfo assetCtrl.selectIndex = indexPath.row self.assetViewCtrl = assetCtrl let nav = UINavigationController(rootViewController: assetCtrl) nav.transitioningDelegate = self self.present(nav, animated: true, completion: nil) } // MARK: cell button selector func selectButton(_ button: UIButton) { let assetModel = assetModels[button.tag] let cell = collectionView?.cellForItem(at: IndexPath(row: button.tag, section: 0)) as! LGAssertGridViewCell if button.isSelected == false { assetModel.setSelect(true) toolBar.addSelectCount = 1 button.isSelected = true button.addAnimation(durationTime) selectedInfo?.add(cell.imageView.image!) button.setImage(UIImage(named: "CellBlueSelected"), for: UIControlState()) } else { button.isSelected = false assetModel.setSelect(false) toolBar.addSelectCount = -1 selectedInfo?.remove(cell.imageView.image!) button.setImage(UIImage(named: "CellGreySelected"), for: UIControlState()) } } // MARK: update chache asset override func scrollViewDidScroll(_ scrollView: UIScrollView) { updateAssetChache() } func updateAssetChache() { let isViewVisible = self.isViewLoaded && self.view.window != nil if !isViewVisible { return } var preRect = (self.collectionView?.bounds)! preRect = preRect.insetBy(dx: 0, dy: -0.5 * preRect.height) let delta = abs(preRect.midY - previousPreRect.midY) if delta > (collectionView?.bounds.height)! / 3 { var addIndexPaths = [IndexPath]() var remoeIndexPaths = [IndexPath]() differentBetweenRect(previousPreRect, newRect: preRect, removeHandler: { (removeRect) -> Void in remoeIndexPaths.append(contentsOf: self.indexPathInRect(removeRect)) }, addHandler: { (addRect) -> Void in addIndexPaths.append(contentsOf: self.indexPathInRect(addRect)) }) imageManager.startCachingImages(for: assetAtIndexPath(addIndexPaths), targetSize: CGSize(width: itemSize, height: itemSize), contentMode: .aspectFill, options: nil) imageManager.stopCachingImages(for: assetAtIndexPath(remoeIndexPaths), targetSize: CGSize(width: itemSize, height: itemSize), contentMode: .aspectFill, options: nil) } } func assetAtIndexPath(_ indexPaths: [IndexPath]) -> [PHAsset] { if indexPaths.count == 0 { return [] } var assets = [PHAsset]() for indexPath in indexPaths { assets.append(assetsFetchResults[indexPath.row] as! PHAsset) } return assets } func indexPathInRect(_ rect: CGRect) -> [IndexPath]{ let allAttributes = collectionView?.collectionViewLayout.layoutAttributesForElements(in: rect) if allAttributes?.count == 0 { return [] } var indexPaths = [IndexPath]() for layoutAttribute in allAttributes! { indexPaths.append(layoutAttribute.indexPath) } return indexPaths } func differentBetweenRect(_ oldRect: CGRect, newRect: CGRect, removeHandler: (CGRect)->Void, addHandler:(CGRect)->Void) { if newRect.intersects(oldRect) { let oldMaxY = oldRect.maxY let oldMinY = oldRect.minY let newMaxY = newRect.maxY let newMinY = newRect.minY if newMaxY > oldMaxY { let rectToAdd = CGRect(x: newRect.x, y: oldMaxY, width: newRect.width, height: newMaxY - oldMaxY) addHandler(rectToAdd) } if oldMinY > newMinY { let rectToAdd = CGRect(x: newRect.x, y: newMinY, width: newRect.width, height: oldMinY - newMinY) addHandler(rectToAdd) } if newMaxY < oldMaxY { let rectToMove = CGRect(x: newRect.x, y: newMaxY, width: newRect.width, height: oldMaxY - newMaxY) removeHandler(rectToMove) } if oldMinY < newMinY { let rectToMove = CGRect(x: newRect.x, y: oldMinY, width: newRect.width, height: newMinY - oldMinY) removeHandler(rectToMove) } } else { addHandler(newRect) removeHandler(oldRect) } } }
d842e00e9ff1ec3704465127673e0c90
37.406716
200
0.639075
false
false
false
false
OpsLabJPL/MarsImagesIOS
refs/heads/main
MarsImagesIOS/Curiosity.swift
apache-2.0
1
// // Curiosity.swift // MarsImagesIOS // // Created by Mark Powell on 7/28/17. // Copyright © 2017 Mark Powell. All rights reserved. // import Foundation class Curiosity: Mission { let SOL = "Sol" let LTST = "LTST" let RMC = "RMC" enum TitleState { case START, SOL_NUMBER, IMAGESET_ID, INSTRUMENT_NAME, MARS_LOCAL_TIME, DISTANCE, YAW, PITCH, ROLL, TILT, ROVER_MOTION_COUNTER } override init() { super.init() var comps = DateComponents() comps.day=6 comps.month=8 comps.year=2012 comps.hour=6 comps.minute=30 comps.second=00 comps.timeZone = TimeZone(abbreviation: "UTC") self.epoch = Calendar.current.date(from: comps) self.eyeIndex = 1 self.instrumentIndex = 0 self.sampleTypeIndex = 17 self.cameraFOVs["NL"] = 0.785398163 self.cameraFOVs["NR"] = 0.785398163 self.cameraFOVs["ML"] = 0.261799388 self.cameraFOVs["MR"] = 0.087266463 } override func urlPrefix() -> String { return "https://s3-us-west-1.amazonaws.com/msl-raws" } override func rowTitle(_ title: String) -> String { return tokenize(title).instrumentName } override func tokenize(_ title: String) -> Title { let msl = Title() let tokens = title.components(separatedBy: " ") var state = TitleState.START for word in tokens { if word == SOL { state = TitleState.SOL_NUMBER continue } else if word == LTST { state = TitleState.MARS_LOCAL_TIME continue } else if word == RMC { state = TitleState.ROVER_MOTION_COUNTER continue } var indices:[Int] = [] switch (state) { case .START: break case .SOL_NUMBER: msl.sol = Int(word)! state = TitleState.IMAGESET_ID break case .IMAGESET_ID: msl.imageSetID = word state = TitleState.INSTRUMENT_NAME break case .INSTRUMENT_NAME: if msl.instrumentName.isEmpty { msl.instrumentName = String(word) } else { msl.instrumentName.append(" \(word)") } break case .MARS_LOCAL_TIME: msl.marsLocalTime = word break case .ROVER_MOTION_COUNTER: indices = word.components(separatedBy: "-").map { Int($0)! } msl.siteIndex = indices[0] msl.driveIndex = indices[1] break default: print("Unexpected state in parsing image title: \(state)") break } } return msl } override func imageName(imageId: String) -> String { let instrument = getInstrument(imageId: imageId) if instrument == "N" || instrument == "F" || instrument == "R" { let eye = getEye(imageId: imageId) if eye == "L" { return "Left" } else { return "Right" } } return "" } func isStereo(instrument:String) -> Bool { return instrument == "F" || instrument == "R" || instrument == "N" } override func getCameraId(imageId: String) -> String { let c:Character = imageId[0] if c >= "0" && c <= "9" { return imageId[4..<5] } else { return imageId[0..<1] } } override func stereoImageIndices(imageIDs: [String]) -> (Int,Int)? { let imageid = imageIDs[0] let instrument = getInstrument(imageId: imageid) if !isStereo(instrument: instrument) { return nil } var leftImageIndex = -1; var rightImageIndex = -1; var index = 0; for imageId in imageIDs { let eye = getEye(imageId: imageId) if leftImageIndex == -1 && eye=="L" { leftImageIndex = index; } if rightImageIndex == -1 && eye=="R" { rightImageIndex = index; } index += 1; } if (leftImageIndex >= 0 && rightImageIndex >= 0) { return (Int(leftImageIndex), Int(rightImageIndex)) } return nil } override func mastPosition() -> [Double] { return [0.80436, 0.55942, -1.90608] } }
a21810b2b90d7c9e5ef8d15fddaaed2f
27.309524
76
0.485913
false
false
false
false
alexfish/tissue
refs/heads/master
tissue/Modules/Issues/IssueViewController.swift
mit
1
// // IssueViewController.swift // tissue // // Created by Alex Fish on 07/06/2014. // Copyright (c) 2014 alexefish. All rights reserved. // import UIKit class IssueViewController: TableViewController { override func setupTitle() { self.title = repo.id } override func getData(completionHandler: () -> Void) { let client: Client = Client(repo: self.repo) client.getObjects(Issue.self, { issues in self.data = issues completionHandler() }) } } extension IssueViewController : UITableViewDataSource { override func numberOfSectionsInTableView(tableView: UITableView?) -> Int { return 1 } override func tableView(tableView: UITableView?, numberOfRowsInSection section: Int) -> Int { return self.data.count } override func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath?) -> UITableViewCell? { let cell : UITableViewCell = tableView.dequeueReusableCellWithIdentifier("reuseIdentifier", forIndexPath: indexPath) as UITableViewCell if indexPath!.row < self.data.count { let issue: Issue = self.data[indexPath!.row] as Issue cell.text = "#\(issue.id) - \(issue.title)" } return cell } }
689437e51732f359facdaa44ba230bcd
26.595745
143
0.657672
false
false
false
false
rnystrom/GitHawk
refs/heads/master
Pods/StyledTextKit/Source/StyledTextView.swift
mit
1
// // StyledTextKitView.swift // StyledTextKit // // Created by Ryan Nystrom on 12/14/17. // Copyright © 2017 Ryan Nystrom. All rights reserved. // import UIKit public protocol StyledTextViewDelegate: class { func didTap(view: StyledTextView, attributes: [NSAttributedStringKey: Any], point: CGPoint) func didLongPress(view: StyledTextView, attributes: [NSAttributedStringKey: Any], point: CGPoint) } open class StyledTextView: UIView { open weak var delegate: StyledTextViewDelegate? open var gesturableAttributes = Set<NSAttributedStringKey>() open var drawsAsync = false private var renderer: StyledTextRenderer? private var tapGesture: UITapGestureRecognizer? private var longPressGesture: UILongPressGestureRecognizer? private var highlightLayer = CAShapeLayer() override public init(frame: CGRect) { super.init(frame: frame) commonInit() } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) commonInit() } private func commonInit() { translatesAutoresizingMaskIntoConstraints = false layer.contentsGravity = kCAGravityTopLeft let tap = UITapGestureRecognizer(target: self, action: #selector(onTap(recognizer:))) tap.cancelsTouchesInView = false addGestureRecognizer(tap) self.tapGesture = tap let long = UILongPressGestureRecognizer(target: self, action: #selector(onLong(recognizer:))) addGestureRecognizer(long) self.longPressGesture = long self.highlightColor = UIColor.black.withAlphaComponent(0.1) layer.addSublayer(highlightLayer) } public var highlightColor: UIColor? { get { guard let color = highlightLayer.fillColor else { return nil } return UIColor(cgColor: color) } set { highlightLayer.fillColor = newValue?.cgColor } } // MARK: Overrides open override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { super.touchesBegan(touches, with: event) guard let touch = touches.first else { return } highlight(at: touch.location(in: self)) } open override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) { super.touchesEnded(touches, with: event) clearHighlight() } open override func touchesCancelled(_ touches: Set<UITouch>, with event: UIEvent?) { super.touchesCancelled(touches, with: event) clearHighlight() } // MARK: UIGestureRecognizerDelegate override open func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool { guard (gestureRecognizer === tapGesture || gestureRecognizer === longPressGesture), let attributes = renderer?.attributes(at: gestureRecognizer.location(in: self)) else { return super.gestureRecognizerShouldBegin(gestureRecognizer) } for attribute in attributes.attributes { if gesturableAttributes.contains(attribute.key) { return true } } return false } // MARK: Private API @objc func onTap(recognizer: UITapGestureRecognizer) { let point = recognizer.location(in: self) guard let attributes = renderer?.attributes(at: point) else { return } delegate?.didTap(view: self, attributes: attributes.attributes, point: point) } @objc func onLong(recognizer: UILongPressGestureRecognizer) { let point = recognizer.location(in: self) guard recognizer.state == .began, let attributes = renderer?.attributes(at: point) else { return } delegate?.didLongPress(view: self, attributes: attributes.attributes, point: point) } private func highlight(at point: CGPoint) { guard let renderer = renderer, let attributes = renderer.attributes(at: point), attributes.attributes[.highlight] != nil else { return } let storage = renderer.storage let maxLen = storage.length var min = attributes.index var max = attributes.index storage.enumerateAttributes( in: NSRange(location: 0, length: attributes.index), options: .reverse ) { (attrs, range, stop) in if attrs[.highlight] != nil && min > 0 { min = range.location } else { stop.pointee = true } } storage.enumerateAttributes( in: NSRange(location: attributes.index, length: maxLen - attributes.index), options: [] ){ (attrs, range, stop) in if attrs[.highlight] != nil && max < maxLen { max = range.location + range.length } else { stop.pointee = true } } let range = NSRange(location: min, length: max - min) var firstRect: CGRect = CGRect.null var bodyRect: CGRect = CGRect.null var lastRect: CGRect = CGRect.null let path = UIBezierPath() renderer.layoutManager.enumerateEnclosingRects( forGlyphRange: range, withinSelectedGlyphRange: NSRange(location: NSNotFound, length: 0), in: renderer.textContainer ) { (rect, stop) in if firstRect.isNull { firstRect = rect } else if lastRect.isNull { lastRect = rect } else { // We have a lastRect that was previously filled, now it needs to be dumped into the body bodyRect = lastRect.intersection(bodyRect) // and save the current rect as the new "lastRect" lastRect = rect } } if !firstRect.isNull { path.append(UIBezierPath(roundedRect: firstRect.insetBy(dx: -2, dy: -2), cornerRadius: 3)) } if !bodyRect.isNull { path.append(UIBezierPath(roundedRect: bodyRect.insetBy(dx: -2, dy: -2), cornerRadius: 3)) } if !lastRect.isNull { path.append(UIBezierPath(roundedRect: lastRect.insetBy(dx: -2, dy: -2), cornerRadius: 3)) } highlightLayer.frame = bounds highlightLayer.path = path.cgPath } private func clearHighlight() { highlightLayer.path = nil } private func setRenderResults(renderer: StyledTextRenderer, result: (CGImage?, CGSize)) { layer.contents = result.0 frame = CGRect(origin: CGPoint(x: renderer.inset.left, y: renderer.inset.top), size: result.1) } static var renderQueue = DispatchQueue( label: "com.whoisryannystrom.StyledText.renderQueue", qos: .default, attributes: DispatchQueue.Attributes(rawValue: 0), autoreleaseFrequency: .workItem, target: nil ) // MARK: Public API open func configure(with renderer: StyledTextRenderer, width: CGFloat) { self.renderer = renderer layer.contentsScale = renderer.scale reposition(for: width) accessibilityLabel = renderer.string.allText } open func reposition(for width: CGFloat) { guard let capturedRenderer = self.renderer else { return } // First, we check if we can immediately apply a previously cached render result. let cachedResult = capturedRenderer.cachedRender(for: width) if let cachedImage = cachedResult.image, let cachedSize = cachedResult.size { setRenderResults(renderer: capturedRenderer, result: (cachedImage, cachedSize)) return } // We have to do a full render, so if we are drawing async it's time to dispatch: if drawsAsync { StyledTextView.renderQueue.async { // Compute the render result (sizing and rendering to an image) on a bg thread let result = capturedRenderer.render(for: width) DispatchQueue.main.async { // If the renderer changed, then our computed result is now invalid, so we have to throw it out. if capturedRenderer !== self.renderer { return } // If the renderer hasn't changed, we're OK to actually apply the result of our computation. self.setRenderResults(renderer: capturedRenderer, result: result) } } } else { // We're in fully-synchronous mode. Immediately compute the result and set it. let result = capturedRenderer.render(for: width) setRenderResults(renderer: capturedRenderer, result: result) } } }
7849765475c3816eabed5f1d3d4cacf1
35.578059
116
0.627639
false
false
false
false
towlebooth/watchos-countdown-tutorial
refs/heads/master
CountdownTutorial/DisplayViewController.swift
mit
1
// // DisplayViewController.swift // CountdownTutorial // // Created by Chad Towle on 12/23/15. // Copyright © 2015 Intertech. All rights reserved. // import UIKit import WatchConnectivity class DisplayViewController: UIViewController, WCSessionDelegate { @IBOutlet weak var startDateLabel: UILabel! var savedDate: NSDate = NSDate() let userCalendar = NSCalendar.currentCalendar() var session : WCSession! override func viewDidLoad() { super.viewDidLoad() if (WCSession.isSupported()) { session = WCSession.defaultSession() session.delegate = self; session.activateSession() } // get values from user defaults let defaults = NSUserDefaults.standardUserDefaults() if let dateString = defaults.stringForKey("dateKey") { startDateLabel.text = dateString } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func saveSegue(segue:UIStoryboardSegue) { let dateFormat = NSDateFormatter() dateFormat.calendar = userCalendar dateFormat.dateFormat = "yyyy-MM-dd" let savedDateString = dateFormat.stringFromDate(savedDate) startDateLabel.text = savedDateString // save to user defaults for use here in phone app let defaults = NSUserDefaults.standardUserDefaults() defaults.setObject(savedDateString, forKey: "dateKey") // save values to session to be shared with watch let applicationDict = ["dateKey":savedDateString] do { try session.updateApplicationContext(applicationDict) } catch { print("Error updating application context.") } // update complication if session.watchAppInstalled { session.transferCurrentComplicationUserInfo(applicationDict) } } }
9a1d1ab53e082154177a4f17f42da7d0
29.878788
72
0.640824
false
true
false
false
ProfileCreator/ProfileCreator
refs/heads/master
ProfileCreator/ProfileCreator/Profile Editor TableView CellViews/PayloadCellViewHostPort.swift
mit
1
// // PayloadCellViewHostPort.swift // ProfileCreator // // Created by Erik Berglund. // Copyright © 2018 Erik Berglund. All rights reserved. // import Cocoa import ProfilePayloads class PayloadCellViewHostPort: PayloadCellView, ProfileCreatorCellView, NSTextFieldDelegate { // MARK: - // MARK: Instance Variables var textFieldHost: PayloadTextField? var textFieldPort: PayloadTextField? var constraintPortTrailing: NSLayoutConstraint? @objc var valuePort: NSNumber? var isEditingHost: Bool = false var isEditingPort: Bool = false var valueBeginEditingHost: String? var valueBeginEditingPort: String? // MARK: - // MARK: Initialization required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } required init(subkey: PayloadSubkey, payloadIndex: Int, enabled: Bool, required: Bool, editor: ProfileEditor) { super.init(subkey: subkey, payloadIndex: payloadIndex, enabled: enabled, required: required, editor: editor) // --------------------------------------------------------------------- // Setup Custom View Content // --------------------------------------------------------------------- self.textFieldHost = EditorTextField.input(defaultString: "", placeholderString: "Host", cellView: self) self.setupTextField(host: self.textFieldHost!) self.textFieldPort = EditorTextField.input(defaultString: "", placeholderString: "Port", cellView: self) self.setupTextField(port: self.textFieldPort!) _ = EditorTextField.label(string: ":", fontWeight: .regular, leadingItem: self.textFieldHost!, leadingConstant: nil, trailingItem: self.textFieldPort!, constraints: &self.cellViewConstraints, cellView: self) // --------------------------------------------------------------------- // Setup KeyView Loop Items // --------------------------------------------------------------------- self.leadingKeyView = self.textFieldHost self.trailingKeyView = self.textFieldPort // --------------------------------------------------------------------- // Activate Layout Constraints // --------------------------------------------------------------------- NSLayoutConstraint.activate(self.cellViewConstraints) } // MARK: - // MARK: PayloadCellView Functions override func enable(_ enable: Bool) { self.isEnabled = enable self.textFieldHost?.isEnabled = enable self.textFieldHost?.isSelectable = enable self.textFieldPort?.isEnabled = enable self.textFieldPort?.isSelectable = enable } } // MARK: - // MARK: NSControl Functions extension PayloadCellViewHostPort { internal func controlTextDidBeginEditing(_ obj: Notification) { guard let textField = obj.object as? NSTextField, let userInfo = obj.userInfo, let fieldEditor = userInfo["NSFieldEditor"] as? NSTextView, let originalString = fieldEditor.textStorage?.string else { return } if textField == self.textFieldHost { self.isEditingHost = true self.valueBeginEditingHost = originalString } else if textField == self.textFieldPort { self.isEditingPort = true self.valueBeginEditingPort = originalString } } internal func controlTextDidEndEditing(_ obj: Notification) { if !isEditingHost && !isEditingPort { return } guard let textField = obj.object as? NSTextField, let userInfo = obj.userInfo, let fieldEditor = userInfo["NSFieldEditor"] as? NSTextView, let newString = fieldEditor.textStorage?.string else { if isEditingHost { self.isEditingHost = false } else if isEditingPort { self.isEditingPort = false } return } if textField == self.textFieldHost, newString != self.valueBeginEditingHost { // self.profile.settings.updatePayloadSettings(value: newString, subkey: self.subkey, payloadIndex: self.payloadIndex) self.profile.settings.setValue(newString, forSubkey: self.subkey, payloadIndex: self.payloadIndex) self.isEditingHost = false } else if textField == self.textFieldPort, newString != self.valueBeginEditingPort { // self.profile.settings.updatePayloadSettings(value: newString, subkey: self.subkey, payloadIndex: self.payloadIndex) self.profile.settings.setValue(newString, forSubkey: self.subkey, payloadIndex: self.payloadIndex) self.isEditingPort = false } } } // MARK: - // MARK: Setup NSLayoutConstraints extension PayloadCellViewHostPort { private func setupTextField(host: NSTextField) { // --------------------------------------------------------------------- // Add TextField to TableCellView // --------------------------------------------------------------------- self.addSubview(host) // --------------------------------------------------------------------- // Add constraints // --------------------------------------------------------------------- // Below self.addConstraints(forViewBelow: host) // Leading self.addConstraints(forViewLeading: host) } private func setupTextField(port: NSTextField) { // --------------------------------------------------------------------- // Add Number Formatter to TextField // --------------------------------------------------------------------- let numberFormatter = NumberFormatter() numberFormatter.numberStyle = .none numberFormatter.minimum = 1 numberFormatter.maximum = 65_535 port.formatter = numberFormatter port.bind(.value, to: self, withKeyPath: "valuePort", options: [NSBindingOption.nullPlaceholder: "Port", NSBindingOption.continuouslyUpdatesValue: true]) // --------------------------------------------------------------------- // Add TextField to TableCellView // --------------------------------------------------------------------- self.addSubview(port) // --------------------------------------------------------------------- // Add constraints // --------------------------------------------------------------------- // Width (fixed size to fit 5 characters: 49.0) self.cellViewConstraints.append(NSLayoutConstraint(item: port, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1.0, constant: 49.0)) // Trailing self.constraintPortTrailing = NSLayoutConstraint(item: self, attribute: .trailing, relatedBy: .equal, toItem: port, attribute: .trailing, multiplier: 1.0, constant: 8.0) self.cellViewConstraints.append(self.constraintPortTrailing!) } }
014302572e9dce35bb25fa86a37c998a
40.747312
215
0.498261
false
false
false
false
PureSwift/Bluetooth
refs/heads/master
Sources/BluetoothHCI/HCILESetScanParameters.swift
mit
1
// // HCILESetScanParameters.swift // Bluetooth // // Created by Alsey Coleman Miller on 6/14/18. // Copyright © 2018 PureSwift. All rights reserved. // import Foundation /// LE Set Scan Parameters Command /// /// Used to set the scan parameters. /// /// - Note: The Host shall not issue this command when scanning is enabled in the Controller; /// if it is the Command Disallowed error code shall be used. public struct HCILESetScanParameters: HCICommandParameter { // HCI_LE_Set_Scan_Parameters public static let command = HCILowEnergyCommand.setScanParameters // 0x000B public static let length = 1 + 2 + 2 + 1 + 1 public typealias TimeInterval = LowEnergyScanTimeInterval /// Controls the type of scan to perform public let type: ScanType // LE_Scan_Type /// This is defined as the time interval from when the Controller /// started its last LE scan until it begins the subsequent LE scan. public let interval: TimeInterval // LE_Scan_Interval /// The duration of the LE scan. /// Should be less than or equal to `interval`. public let window: TimeInterval // LE_Scan_Window /// Determines the address used (Public or Random Device Address) when performing active scan. public let addressType: LowEnergyAddressType // Own_Address_Type /// Scanning filter policy. public let filterPolicy: FilterPolicy public init(type: ScanType = .passive, interval: TimeInterval = TimeInterval(rawValue: 0x01E0)!, window: TimeInterval = TimeInterval(rawValue: 0x0030)!, addressType: LowEnergyAddressType = .public, filterPolicy: FilterPolicy = .accept) { precondition(window <= interval, "LE_Scan_Window shall be less than or equal to LE_Scan_Interval") self.type = type self.interval = interval self.window = window self.addressType = addressType self.filterPolicy = filterPolicy } public var data: Data { let scanType = type.rawValue let scanInterval = interval.rawValue.littleEndian.bytes let scanWindow = window.rawValue.littleEndian.bytes let ownAddressType = addressType.rawValue let filter = filterPolicy.rawValue return Data([scanType, scanInterval.0, scanInterval.1, scanWindow.0, scanWindow.1, ownAddressType, filter]) } } // MARK: - Supporting Types public extension HCILESetScanParameters { /// Controls the type of scan to perform enum ScanType: UInt8 { /// Passive scanning. /// /// No scanning PDUs shall be sent. case passive = 0x0 /// Active scanning. /// /// Scanning PDUs may be sent. case active = 0x1 /// Initialize with default value (Passive scanning). public init() { self = .passive } } enum FilterPolicy: UInt8 { // Scanning_Filter_Policy /// Accept all advertisement packets. /// /// Directed advertising packets which are not addressed for this device shall be ignored. case accept = 0x0 /// Ignore advertisement packets from devices not in the White List Only. /// /// Directed advertising packets which are not addressed for this device shall be ignored. case ignore = 0x1 /// Accept all advertising packets except: /// • advertising packets where the advertiser's identity address is not in the White List; and /// • directed advertising packets where the initiator's identity address does not address this device /// /// - Note: Directed advertising packets where the initiator's address is a resolvable private address that cannot be resolved are also accepted. case directed = 0x02 /// Initialize with default value (Accept all advertisement packets). public init() { self = .accept } } }
343187db3352e6afee31010560d37ff5
34.452174
153
0.639195
false
false
false
false
DiUS/pact-consumer-swift
refs/heads/master
Tests/PactConsumerSwiftTests/AnimalServiceClient.swift
mit
1
import Foundation public struct Animal: Decodable { public let name: String public let type: String public let dob: String? public let legs: Int? enum CodingKeys: String, CodingKey { case name case type case dob = "dateOfBirth" case legs } } open class AnimalServiceClient: NSObject, URLSessionDelegate { fileprivate let baseUrl: String public init(baseUrl : String) { self.baseUrl = baseUrl } // MARK: - open func getAlligators(_ success: @escaping (Array<Animal>) -> Void, failure: @escaping (NSError?) -> Void) { self.performRequest("\(baseUrl)/alligators", decoder: decodeAnimals) { animals, nsError in if let animals = animals { success(animals) } else { if let error = nsError { failure(error) } else { failure(NSError(domain: "", code: 42, userInfo: nil)) } } } } open func getSecureAlligators(authToken: String, success: @escaping (Array<Animal>) -> Void, failure: @escaping (NSError?) -> Void) { self.performRequest("\(baseUrl)/alligators", headers: ["Authorization": authToken], decoder: decodeAnimals) { animals, nsError in if let animals = animals { success(animals) } else { if let error = nsError { failure(error) } else { failure(NSError(domain: "", code: 42, userInfo: nil)) } } } } open func getAlligator(_ id: Int, success: @escaping (Animal) -> Void, failure: @escaping (NSError?) -> Void) { self.performRequest("\(baseUrl)/alligators/\(id)", decoder: decodeAnimal) { animal, nsError in if let animal = animal { success(animal) } else { if let error = nsError { failure(error) } else { failure(NSError(domain: "", code: 42, userInfo: nil)) } } } } open func findAnimals(live: String, response: @escaping ([Animal]) -> Void) { let liveEncoded = live.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)! self.performRequest("\(baseUrl)/animals?live=\(liveEncoded)", decoder: decodeAnimals) { animals, nsError in if let animals = animals { response(animals) } } } open func eat(animal: String, success: @escaping () -> Void, error: @escaping (Int) -> Void) { self.performRequest("\(baseUrl)/alligator/eat", method: "patch", parameters: ["type": animal], decoder: decodeString) { string, nsError in if let localErr = nsError { error(localErr.code) } else { success() } } } open func wontEat(animal: String, success: @escaping () -> Void, error: @escaping (Int) -> Void) { self.performRequest("\(baseUrl)/alligator/eat", method: "delete", parameters: ["type": animal], decoder: decodeAnimals) { animals, nsError in if let localErr = nsError { error(localErr.code) } else { success() } } } open func eats(_ success: @escaping ([Animal]) -> Void) { self.performRequest("\(baseUrl)/alligator/eat", decoder: decodeAnimals) { animals, nsError in if let animals = animals { success(animals) } } } // MARK: - URLSessionDelegate public func urlSession( _ session: URLSession, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void ) { guard challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust, challenge.protectionSpace.host.contains("localhost"), let serverTrust = challenge.protectionSpace.serverTrust else { completionHandler(.performDefaultHandling, nil) return } let credential = URLCredential(trust: serverTrust) completionHandler(.useCredential, credential) } // MARK: - Networking and Decoding private lazy var session = { URLSession(configuration: .ephemeral, delegate: self, delegateQueue: .main) }() private func performRequest<T: Decodable>(_ urlString: String, headers: [String: String]? = nil, method: String = "get", parameters: [String: String]? = nil, decoder: @escaping (_ data: Data) throws -> T, completionHandler: @escaping (_ response: T?, _ error: NSError?) -> Void ) { var request = URLRequest(url: URL(string: urlString)!) request.httpMethod = method if let headers = headers { request.allHTTPHeaderFields = headers } if let parameters = parameters, let data = try? JSONSerialization.data(withJSONObject: parameters, options: []) { request.addValue("application/json", forHTTPHeaderField: "Content-Type") request.httpBody = data } let task = self.session.dataTask(with: request) { data, response, error in if let error = error { completionHandler(nil, error as NSError) return } if let data = data, let response = response as? HTTPURLResponse, (200..<300).contains(response.statusCode) { do { let result = try decoder(data) completionHandler(result, nil) } catch { completionHandler(nil, error as NSError) } } else { completionHandler(nil, NSError(domain: "", code: 41, userInfo: nil)) } } task.resume() } private func decodeAnimal(_ data: Data) throws -> Animal { let decoder = JSONDecoder() return try decoder.decode(Animal.self, from: data) } private func decodeAnimals(_ data: Data) throws -> [Animal] { let decoder = JSONDecoder() return try decoder.decode([Animal].self, from: data) } private func decodeString(_ data: Data) throws -> String { guard let result = String(data: data, encoding: .utf8) else { throw NSError(domain: "", code: 63, userInfo: nil) } return result } }
09535c458aa4ef0f6fc0a8884cb58f9d
30.888298
145
0.618182
false
false
false
false
Fidetro/SwiftFFDB
refs/heads/master
Sources/Select.swift
apache-2.0
1
// // Select.swift // Swift-FFDB // // Created by Fidetro on 2018/5/25. // Copyright © 2018年 Fidetro. All rights reserved. // import Foundation public struct Select:STMT { public let stmt : String public init( _ columns: [String]) { var columnString = "" for (index,column) in columns.enumerated() { if index == 0 { columnString += column }else{ columnString = columnString + "," + column } } self.init(columnString) } public init(_ stmt : String) { self.stmt = "select" + " " + stmt + " " } } // MARK: - From extension Select { public func from(_ from:String) -> From { return From(stmt, format: from) } public func from(_ table:FFObject.Type) -> From { return From(stmt, table: table) } }
804d6a18aa90054d6c6999b2df753e0b
19.340426
58
0.48431
false
false
false
false
ls1intum/sReto
refs/heads/master
Source/sReto/Core/Utils/MappingSequence.swift
mit
1
// // StateSequence.swift // sReto // // Created by Julian Asamer on 21/08/14. // Copyright (c) 2014 - 2016 Chair for Applied Software Engineering // // Licensed under the MIT License // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. // // The software is provided "as is", without warranty of any kind, express or implied, including but not limited to the warranties of merchantability, fitness // for a particular purpose and noninfringement. in no event shall the authors or copyright holders be liable for any claim, damages or other liability, // whether in an action of contract, tort or otherwise, arising from, out of or in connection with the software or the use or other dealings in the software. // import Foundation /** * The iterateMapping function creates a sequence by applying a mapping to a state an arbitrary number of times. * For example, iterateMapping(initialState: 0, { $0 + 1 }) constructs an infinite list of the numbers 0, 1, 2, ... */ func iterateMapping<E>(initialState: E, mapping: @escaping (E) -> E?) -> MappingSequence<E> { return MappingSequence(initialState: initialState, mapping: mapping) } struct MappingGenerator<E>: IteratorProtocol { typealias Element = E var state: E? let mapping: (E) -> E? init(initialState: E, mapping: @escaping (E) -> E?) { self.state = initialState self.mapping = mapping } mutating func next() -> Element? { let result = self.state if let state = self.state { self.state = self.mapping(state) } return result } } struct MappingSequence<E>: Sequence { let initialState: E let mapping: (E) -> E? func makeIterator() -> MappingGenerator<E> { return MappingGenerator(initialState: self.initialState, mapping: self.mapping) } }
1ae0aa3a6ebb6a4473f47b7e847c2d4e
42.407407
159
0.712884
false
false
false
false
DuckDeck/GrandStore
refs/heads/master
GrandStoreDemo/TempSaveTestViewController.swift
mit
1
// // TempSaveTestViewController.swift // GrandStoreDemo // // Created by HuStan on 3/3/16. // Copyright © 2016 Qfq. All rights reserved. // import UIKit class TempSaveTestViewController: UIViewController { var demoTemp = GrandStore(name: "demoTemp", defaultValue: "temp", timeout: 0) var txtString:UITextField? var btnSet:UIButton? var btnGet:UIButton? var lblString:UILabel? override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = UIColor.white txtString = UITextField(frame: CGRect(x: 20, y: 167, width: UIScreen.main.bounds.width - 40, height: 40)) txtString?.layer.borderColor = UIColor.blue.cgColor txtString?.layer.borderWidth = 0.5 view.addSubview(txtString!) btnSet = UIButton(frame: CGRect(x: 20, y: txtString!.frame.maxY, width: UIScreen.main.bounds.width - 40, height: 40)) btnSet?.setTitle("设值", for: UIControl.State()) btnSet?.setTitleColor(UIColor.black, for: UIControl.State()) btnSet?.addTarget(self, action: #selector(TempSaveTestViewController.setString(_:)), for: UIControl.Event.touchUpInside) view.addSubview(btnSet!) btnGet = UIButton(frame: CGRect(x: 20, y: btnSet!.frame.maxY, width: UIScreen.main.bounds.width - 40, height: 40)) btnGet?.setTitle("取值", for: UIControl.State()) btnGet?.setTitleColor(UIColor.black, for: UIControl.State()) btnGet?.addTarget(self, action: #selector(TempSaveTestViewController.getString(_:)), for: UIControl.Event.touchUpInside) view.addSubview(btnGet!) lblString = UILabel(frame: CGRect(x: 20, y:btnGet!.frame.maxY, width: UIScreen.main.bounds.width - 40, height: 40)) lblString?.textColor = UIColor.black view.addSubview(lblString!) } @objc func setString(_ sender:UIButton) { if let txt = txtString?.text{ demoTemp.Value = txt } } @objc func getString(_ sender:UIButton) { lblString?.text = demoTemp.Value } }
9ec6aa92802688dca5674d2c940cd353
35.017241
128
0.649114
false
true
false
false
adelang/DoomKit
refs/heads/master
Sources/Graphic.swift
mit
1
// // Graphic.swift // DoomKit // // Created by Arjan de Lang on 03-01-15. // Copyright (c) 2015 Blue Depths Media. All rights reserved. // import Cocoa var __graphicsCache = [String: Graphic]() open class Graphic { open var width: Int16 = 0 open var height: Int16 = 0 open var xOffset: Int16 = 0 open var yOffset: Int16 = 0 var _pixelData: [UInt8?] = [] var _cachedImage: NSImage? open class func graphicWithLumpName(_ lumpName: String, inWad wad: Wad) -> Graphic? { if lumpName == "-" { return nil } if let graphic = __graphicsCache[lumpName] { return graphic } for lump in wad.lumps { if lump.name == lumpName { if let data = lump.data { var dataPointer = 0 var width: Int16 = 0 (data as NSData).getBytes(&width, range: NSMakeRange(dataPointer, MemoryLayout<Int16>.size)) dataPointer += MemoryLayout<Int16>.size var height: Int16 = 0 (data as NSData).getBytes(&height, range: NSMakeRange(dataPointer, MemoryLayout<Int16>.size)) dataPointer += MemoryLayout<Int16>.size var xOffset: Int16 = 0 (data as NSData).getBytes(&xOffset, range: NSMakeRange(dataPointer, MemoryLayout<Int16>.size)) dataPointer += MemoryLayout<Int16>.size var yOffset: Int16 = 0 (data as NSData).getBytes(&yOffset, range: NSMakeRange(dataPointer, MemoryLayout<Int16>.size)) dataPointer += MemoryLayout<Int16>.size var pixelData = [UInt8?](repeating: nil, count: (Int(width) * Int(height))) var columnPointers: [UInt32] = [] for _ in (0 ..< width) { var columnPointer: UInt32 = 0 (data as NSData).getBytes(&columnPointer, range: NSMakeRange(dataPointer, MemoryLayout<UInt32>.size)) columnPointers.append(columnPointer) dataPointer += MemoryLayout<UInt32>.size } var x: Int16 = 0 for _ in columnPointers { readPoles: while(true) { var y: UInt8 = 0 (data as NSData).getBytes(&y, range: NSMakeRange(dataPointer, MemoryLayout<UInt8>.size)) dataPointer += MemoryLayout<UInt8>.size if y == 255 { break readPoles } var numberOfPixels: UInt8 = 0 (data as NSData).getBytes(&numberOfPixels, range: NSMakeRange(dataPointer, MemoryLayout<UInt8>.size)) dataPointer += MemoryLayout<UInt8>.size // Ignore first byte dataPointer += MemoryLayout<UInt8>.size var pixelIndex = Int(y) + Int(x * height) for _ in (0 ..< numberOfPixels) { var paletteIndex: UInt8 = 0 (data as NSData).getBytes(&paletteIndex, range: NSMakeRange(dataPointer, MemoryLayout<UInt8>.size)) pixelData[pixelIndex] = paletteIndex pixelIndex += 1 dataPointer += MemoryLayout<UInt8>.size } // Also ignore last byte dataPointer += MemoryLayout<UInt8>.size } x += 1 } let graphic = Graphic(width: width, height: height, xOffset: xOffset, yOffset: yOffset, pixelData: pixelData) __graphicsCache[lumpName] = graphic return graphic } } } print("Unable to find graphic with name '\(lumpName)'") return nil } open class func flatWithLumpName(_ lumpName: String, inWad wad: Wad) -> Graphic? { if lumpName == "-" { return nil } if let graphic = __graphicsCache[lumpName] { return graphic } for lump in wad.lumps { if lump.name == lumpName { if let data = lump.data { let width: Int16 = 64 let height: Int16 = 64 let xOffset: Int16 = 0 let yOffset: Int16 = 0 var pixelData = [UInt8](repeating: 0, count: (Int(width) * Int(height))) (data as NSData).getBytes(&pixelData, range: NSMakeRange(0, MemoryLayout<UInt8>.size * Int(width) * Int(height))) let graphic = Graphic(width: width, height: height, xOffset: xOffset, yOffset: yOffset, pixelData: pixelData) __graphicsCache[lumpName] = graphic return graphic } } } print("Unable to find graphic with name '\(lumpName)'") return nil } public init(width: Int16, height: Int16, xOffset: Int16, yOffset: Int16, pixelData: [UInt8?]) { self.width = width self.height = height self.xOffset = xOffset self.yOffset = yOffset self._pixelData = pixelData } open func imageWithPalette(_ palette: Palette) -> NSImage { if let image = _cachedImage { return image } let bitmap = NSBitmapImageRep(bitmapDataPlanes: nil, pixelsWide: Int(width), pixelsHigh: Int(height), bitsPerSample: 8, samplesPerPixel: 4, hasAlpha: true, isPlanar: false, colorSpaceName: NSCalibratedRGBColorSpace, bytesPerRow: Int(4 * width), bitsPerPixel: 32) let image = NSImage() image.addRepresentation(bitmap!) var pixelIndex = 0 for x in 0 ..< Int(width) { for y in 0 ..< Int(height) { let paletteIndex = _pixelData[pixelIndex] pixelIndex += 1 let color: NSColor if let paletteIndex = paletteIndex { color = palette.colors[Int(paletteIndex)] } else { color = NSColor.clear } bitmap?.setColor(color, atX: x, y: y) } } _cachedImage = image return image } }
5ea55f9b8f3334adf850a5f93e3a36dc
28.011429
264
0.647627
false
false
false
false
oskarpearson/rileylink_ios
refs/heads/dev
MinimedKit/PumpEvents/ChangeSensorSetup2PumpEvent.swift
mit
2
// // ChangeSensorSetup2PumpEvent.swift // RileyLink // // Created by Pete Schwamb on 3/8/16. // Copyright © 2016 Pete Schwamb. All rights reserved. // import Foundation public struct ChangeSensorSetup2PumpEvent: TimestampedPumpEvent { public let length: Int public let rawData: Data public let timestamp: DateComponents public init?(availableData: Data, pumpModel: PumpModel) { if pumpModel.hasLowSuspend { length = 41 } else { length = 37 } guard length <= availableData.count else { return nil } rawData = availableData.subdata(in: 0..<length) timestamp = DateComponents(pumpEventData: availableData, offset: 2) } public var dictionaryRepresentation: [String: Any] { return [ "_type": "ChangeSensorSetup2", ] } }
0b2201575ec1a31301d066756bf198fb
23.081081
75
0.612795
false
false
false
false
tedgoddard/Augra
refs/heads/master
Augra/ModelLoader.swift
mit
1
// // ModelLoader.swift // Augra // // Created by Ted Goddard on 2016-09-08. // import Foundation import SceneKit import SceneKit.ModelIO class ModelLoader { let environmentScene: SCNScene? var fanRadius = Double(4) var modelClamp = Float(2) init(environmentScene: SCNScene?) { self.environmentScene = environmentScene } func addAssortedMesh() { let daeURLs = Bundle.main.urls(forResourcesWithExtension: "dae", subdirectory: "ARassets.scnassets") let objURLs = Bundle.main.urls(forResourcesWithExtension: "obj", subdirectory: "ARassets.scnassets") var modelURLs: [URL] = [] modelURLs += daeURLs ?? [] modelURLs += objURLs ?? [] if let documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first { let userURLs = (try? FileManager.default.contentsOfDirectory(at: documentsURL, includingPropertiesForKeys: nil, options: [])) modelURLs += userURLs ?? [] } for (index, modelURL) in modelURLs.enumerated() { //partition arc equally and count endpoints to balance it let theta = Double(index + 1) / Double(modelURLs.count + 2) * (Double.pi * 2.0) let fanPosition = SCNVector3(x: -1 * Float(fanRadius * sin(theta)), y: 1.0, z: Float(fanRadius * cos(theta))) let importedModel = clampAndPlaceModel(url: modelURL, atPosition: fanPosition) // debugBubble(modelNode: importedModel) } } func clampAndPlaceModel(url: URL, atPosition: SCNVector3) -> SCNNode? { let modelScene = try? SCNScene(url: url, options: nil) guard let sceneRoot = modelScene?.rootNode else { print("import FAIL \(url)") return nil } guard let modelNode = sceneRoot.childNodes.first else { return nil } modelNode.name = url.lastPathComponent let (modelCenter, modelRadius) = modelNode.boundingSphere if (modelRadius > modelClamp) { modelNode.scale = scale(SCNVector3(x: 1, y: 1, z: 1), modelClamp / modelRadius) } modelNode.position = atPosition print("added model \(modelNode.name) \(atPosition)") environmentScene?.rootNode.addChildNode(modelNode) return modelNode } func debugBubble(modelNode: SCNNode?, color: UIColor = .green) { guard let modelNode = modelNode else { return } let sphere = SCNNode() sphere.geometry = SCNSphere(radius: CGFloat(modelNode.boundingSphere.radius)) sphere.position = modelNode.boundingSphere.center sphere.geometry?.firstMaterial?.diffuse.contents = color.withAlphaComponent(0.5) modelNode.addChildNode(sphere) } func debugBox(modelNode: SCNNode?, color: UIColor = .green) { guard let modelNode = modelNode else { return } let boxNode = SCNNode() let boundingBoxEnds = modelNode.boundingBox let boundingBox = SCNBox() let boundingDelta = sum(boundingBoxEnds.max, scale(boundingBoxEnds.min, -1)) boundingBox.width = CGFloat(boundingDelta.x) boundingBox.height = CGFloat(boundingDelta.y) boundingBox.length = CGFloat(boundingDelta.z) boxNode.geometry = boundingBox boxNode.position = sum(boundingBoxEnds.min, scale(boundingDelta, 0.5)) boxNode.geometry?.firstMaterial?.diffuse.contents = color.withAlphaComponent(0.5) modelNode.addChildNode(boxNode) } }
42a38044885a3018f204bd865d0c3ab9
39.045977
137
0.65729
false
false
false
false
bugcoding/macOSCalendar
refs/heads/master
MacCalendar/CalendarUtils.swift
gpl-2.0
1
/*==================== FileName : CalendarUtils Desc : Utils Function For Calendar 天体运算部分移植自<算法的乐趣 -- 王晓华> 书中示例代码 Author : bugcode Email : [email protected] CreateDate : 2016-5-8 ====================*/ import Foundation import Darwin open class CalendarUtils{ // 单例 class var sharedInstance : CalendarUtils{ struct Static{ static let ins:CalendarUtils = CalendarUtils() } return Static.ins } fileprivate init(){ } // 每天的时间结构 struct WZDayTime{ // 年月日时分秒 var year:Int = 0 var month:Int = 0 var day:Int = 0 var hour:Int = 0 var minute:Int = 0 var second:Double = 0 init(_ y: Int, _ m: Int, _ d: Int) { year = y month = m day = d } public var description : String { return "\(year)-" + "\(month)-" + "\(day)" } } // 根据当前日期获取下一个节日 func getNextHolidayBy(wzTime: WZDayTime) -> (String, Int) { let res = wzTime.month * 100 + wzTime.day var holidayName = "" var days = 0 for key in CalendarConstant.generalHolidaysArray { if res < key { let (name, month, day) = CalendarConstant.generalHolidaysDict[key]! holidayName = name days = CalendarUtils.sharedInstance.calcDaysBetweenDate(wzTime.year, monthStart: wzTime.month, dayStart: wzTime.day, yearEnd: wzTime.year, monthEnd: month, dayEnd: day) break } } return (holidayName, days) } // 根据农历月与农历日获取农历节日名称,没有返回空字符串 func getLunarFestivalNameBy(month: Int, day: Int) -> String { let combineStr = String(month) + "-" + String(day) if let festivalName = CalendarConstant.lunarHolidaysDict[combineStr] { return festivalName } else { return "" } } // 获取公历假日名称,如果不是假日返回空字符串 func getHolidayNameBy(month: Int, day: Int) -> String { let combineStr = String(month) + "-" + String(day) if let holidayName = CalendarConstant.georiHolidaysDict[combineStr] { //print("name = \(holidayName)") return holidayName } else { return "" } } // 蔡勒公式算公历某天的星期 func getWeekDayBy(_ year:Int, month m:Int, day d:Int) -> Int { var year = year var m = m if m < 3 { year -= 1 m += 12 } // 年份的最后二位. 2003 -> 03 | 1997 -> 97 let y:Int = year % 100 // 年份的前二位. 2003 -> 20 | 1997 -> 19 let c:Int = Int(year / 100) var week:Int = Int(c / 4) - 2 * c + y + Int(y / 4) + (26 * (m + 1) / 10) + d - 1 week = (week % 7 + 7) % 7 return week } // 根据当前年月日获取下个节气的序号 func getNextJieqiNumBy(calendar: LunarCalendarUtils, month: Int, day: Int) -> Int { var next = 0 var count = 0 var year = calendar.getCurrentYear() var dayCount = day var monthCount = month // 循环到找到下一个节气为止 while true { // 节气一般相差十五天左右,30天为容错,足够找到下一个节气了 count += 1 if count > 30 { break } // 当前的农历日期 let mi = calendar.getMonthInfo(month: monthCount) let dayInfo = mi.getDayInfo(day: dayCount) // 当前日期就是节气 if dayInfo.st != -1 { next = dayInfo.st break } // 此月份天数 let days = getDaysBy(year: year, month: monthCount) dayCount += 1 if dayCount > days { dayCount = 1 monthCount += 1 if monthCount > 12 { year += 1 monthCount = 1 } } } //print("getNextJieqiNum = next = \(next) termName = \(CalendarConstant.nameOfJieQi[next])") return next } // 根据当前日期获取当前所属于的节令月 func getLunarJieqiMonthNameBy(calendar: LunarCalendarUtils, month: Int, day: Int) -> Int { var jieqiMonthName = 0 let nextJieqi = getNextJieqiNumBy(calendar: calendar, month: month, day: day) switch nextJieqi { case 22 ... 23: jieqiMonthName = 1 case 0 ... 1: jieqiMonthName = 2 case 2 ... 3: jieqiMonthName = 3 case 4 ... 5: jieqiMonthName = 4 case 6 ... 7: jieqiMonthName = 5 case 8 ... 9: jieqiMonthName = 6 case 10 ... 11: jieqiMonthName = 7 case 12 ... 13: jieqiMonthName = 8 case 14 ... 15: jieqiMonthName = 9 case 16 ... 17: jieqiMonthName = 10 case 18 ... 19: jieqiMonthName = 11 case 20 ... 21: jieqiMonthName = 12 default: jieqiMonthName = 0 } //print("getLunarJieqiMonthNameBy = \(jieqiMonthName)") return jieqiMonthName } // 通过2000年有基准获取某一农历年的干支 func getLunarYearNameBy(_ year:Int) -> (heaven:String, earthy:String, zodiac:String){ let baseMinus:Int = year - 2000 var heavenly = (7 + baseMinus) % 10 var earth = (5 + baseMinus) % 12 if heavenly <= 0 { heavenly += 10 } if earth <= 0 { earth += 12 } return (CalendarConstant.HEAVENLY_STEMS_NAME[heavenly - 1], CalendarConstant.EARTHY_BRANCHES_NAME[earth - 1], CalendarConstant.CHINESE_ZODIC_NAME[earth - 1]) } // 根据年,月,获取月干支 func getLunarMonthNameBy(calendar: LunarCalendarUtils, month: Int, day: Int) -> (heaven: String, earthy: String) { var sbMonth:Int = 0, sbDay:Int = 0 var year = calendar.getCurrentYear() // 算出农历年干支,以立春为界 calendar.getSpringBeginDay(month: &sbMonth, day: &sbDay) year = (month >= sbMonth) ? year : year - 1 let baseMinus:Int = year - 2000 var heavenly = (7 + baseMinus) % 10 let curJieqiMonth = CalendarUtils.sharedInstance.getLunarJieqiMonthNameBy(calendar: calendar, month: month, day: day) if heavenly <= 0 { heavenly += 10 } var monthHeavenly = ((heavenly * 2) + curJieqiMonth) % 10 if monthHeavenly <= 0 { monthHeavenly = 10 } return (CalendarConstant.HEAVENLY_STEMS_NAME[monthHeavenly - 1], CalendarConstant.EARTHY_MONTH_NAME[curJieqiMonth - 1]) } // 获取日干支 func getLunarDayNameBy(year: Int, month: Int, day: Int) -> (heaven:String, earthy:String) { var year = year var month = month if month == 1 || month == 2 { month += 12 year -= 1 } let x = Int(year / 100) let y = year % 100 // 日 干 计算 let res = (5 * (x + y) + Int(x / 4) + Int(y / 4) + (month + 1) * 3 / 5 + day - 3 - x) var dayHeavenly = res % 10 if dayHeavenly == 0 { dayHeavenly = 10 } // 日 支 计算 let i = (month % 2 != 0) ? 0 : 6 var dayEarthy = (res + 4 * x + 10 + i) % 12 if dayEarthy == 0 { dayEarthy = 12 } return (CalendarConstant.HEAVENLY_STEMS_NAME[dayHeavenly - 1], CalendarConstant.EARTHY_BRANCHES_NAME[dayEarthy - 1]) } // 平,闫年判定 func getIsLeapBy(_ year:Int) -> Bool { return (year % 4 == 0 && year % 100 != 0) || year % 400 == 0 } // 指定月份的天数 func getDaysBy(year:Int, month: Int) -> Int { var days = 0 if getIsLeapBy(year) { days = CalendarConstant.DAYS_OF_MONTH_LEAP_YEAR[month] } else{ days = CalendarConstant.DAYS_OF_MONTH_NORMAL_YEAR[month] } return days } // 今天的日期 func getDateStringOfToday() -> String { let nowDate = Date() let formatter = DateFormatter() formatter.dateFormat = "yyyy-MM-dd" let dateString = formatter.string(from: nowDate) return dateString } // 根据日期字符串 yyyy-mm-dd形式获取(year,month,day)的元组 func getYMDTuppleBy(_ dateString:String) -> (year:Int, month:Int, day:Int) { let formatter = DateFormatter() formatter.dateFormat = "yyyy-MM-dd" let date = formatter.date(from: dateString) formatter.dateFormat = "yyyy" let y = formatter.string(from: date!) formatter.dateFormat = "MM" let m = formatter.string(from: date!) formatter.dateFormat = "dd" let d = formatter.string(from: date!) return (Int(y)!, Int(m)!, Int(d)!) } // 手动切分日期字符串 func manualSplitDate(_ dateString: String) -> (year:Int, month:Int, day:Int) { let strArr = dateString.components(separatedBy: "-") let year = strArr[0] let month = strArr[1] let day = strArr[2] return (Int(year)!, Int(month)!, Int(day)!) } // 根据传入日期字符串获取下月 func getMonthDateStringBy(year: Int, month: Int, step:Int) -> (year: Int, month: Int) { var year = year var curMonth = month curMonth = curMonth + step if curMonth > 12 && step > 0 { curMonth = 1 year = year + 1 } else if curMonth < 1 && step < 0{ curMonth = 12 year = year - 1 } return (year, curMonth) } // 月份增减的时候保证天数不超出当月的最大天数 func fixMonthDays(year: Int, month: Int, day: Int) -> Int { var retDay = day let days = getDaysOfMonthBy(year, month: month) if day > days { retDay = days } return retDay } // 获取某月某天是周几 func getWeekBy(year: Int, month: Int, andFirstDay:Int) -> Int { let weekDay = getWeekDayBy(year, month: month, day: andFirstDay) return weekDay } // 获取一个月有几天 func getDaysOfMonthBy(_ year:Int, month:Int) -> Int { if month < 1 || month > 12 { return 0 } if getIsLeapBy(year) { return CalendarConstant.DAYS_OF_MONTH_LEAP_YEAR[month] } return CalendarConstant.DAYS_OF_MONTH_NORMAL_YEAR[month] } // 计算一年中过去的天数,含指定的这天 func calcYearPassDays(_ year:Int, month:Int, day:Int) -> Int { var passedDays = 0 for i in 0 ..< month - 1 { if getIsLeapBy(year) { passedDays += CalendarConstant.DAYS_OF_MONTH_LEAP_YEAR[i] }else{ passedDays += CalendarConstant.DAYS_OF_MONTH_NORMAL_YEAR[i] } } passedDays += day return passedDays } // 计算一年剩下的天数,不含指定的这天 func calcYearRestDays(_ year:Int, month:Int, day:Int) -> Int{ var leftDays = 0 if getIsLeapBy(year) { leftDays = CalendarConstant.DAYS_OF_MONTH_LEAP_YEAR[month] - day }else{ leftDays = CalendarConstant.DAYS_OF_MONTH_NORMAL_YEAR[month] - day } for i in month ..< CalendarConstant.MONTHES_FOR_YEAR { if getIsLeapBy(year) { leftDays += CalendarConstant.DAYS_OF_MONTH_LEAP_YEAR[i] }else{ leftDays += CalendarConstant.DAYS_OF_MONTH_NORMAL_YEAR[i] } } return leftDays } // 计算二个年份之间的天数 前面包含元旦,后面不包含 func calcYearsDays(_ yearStart:Int, yearEnd:Int) -> Int { var days = 0 for i in yearStart ..< yearEnd { if getIsLeapBy(i) { days += CalendarConstant.DAYS_OF_LEAP_YEAR }else{ days += CalendarConstant.DAYS_OF_NORMAL_YEAR } } return days } // 计算二个指定日期之间的天数 func calcDaysBetweenDate(_ yearStart:Int, monthStart:Int, dayStart:Int, yearEnd:Int, monthEnd:Int, dayEnd:Int) -> Int { var days = calcYearRestDays(yearStart, month: monthStart, day: dayStart) if yearStart != yearEnd { if yearEnd - yearStart >= 2 { days += calcYearsDays(yearStart + 1, yearEnd: yearEnd) } days += calcYearPassDays(yearEnd, month: monthEnd, day: dayEnd) }else{ days -= calcYearRestDays(yearEnd, month: monthEnd, day: dayEnd) } return days } // 判定日期是否使用了格里历 func isGregorianDays(_ year:Int, month:Int, day:Int) -> Bool { if year < CalendarConstant.GREGORIAN_CALENDAR_OPEN_YEAR { return false } if year == CalendarConstant.GREGORIAN_CALENDAR_OPEN_YEAR { if (month < CalendarConstant.GREGORIAN_CALENDAR_OPEN_MONTH) || (month == CalendarConstant.GREGORIAN_CALENDAR_OPEN_MONTH && day < CalendarConstant.GREGORIAN_CALENDAR_OPEN_DAY){ return false } } return true } // 计算儒略日 func calcJulianDay(_ year:Int, month:Int, day:Int, hour:Int, min:Int, second:Double) -> Double { var year = year var month = month if month <= 2 { month += 12 year -= 1 } var B = -2 if isGregorianDays(year, month: month, day: day) { B = year / 400 - year / 100 } let a = 365.25 * Double(year) let b = 30.6001 * Double(month + 1) let sec:Double = Double(hour) / 24.0 + Double(min) / 1440.0 + Double(second) / 86400.0 let param:Double = Double(Int(a)) + Double(Int(b)) + Double(B) + Double(day) let res = param + sec + 1720996.5 return res } // 儒略日获得日期 func getDayTimeFromJulianDay(_ jd:Double, dt:inout WZDayTime){ var cna:Int, cnd:Int var cnf:Double let jdf:Double = jd + 0.5 cna = Int(jdf) cnf = jdf - Double(cna) if cna > 2299161 { cnd = Int((Double(cna) - 1867216.25) / 36524.25) cna = cna + 1 + cnd - Int(cnd / 4) } cna = cna + 1524 var year = Int((Double(cna) - 122.1) / 365.25) cnd = cna - Int(Double(year) * 365.25) var month = Int(Double(cnd) / 30.6001) let day = cnd - Int(Double(month) * 30.6001) year -= 4716 month = month - 1 if month > 12 { month -= 12 } if month <= 2 { year += 1 } if year < 1 { year -= 1 } cnf = cnf * 24.0 dt.hour = Int(cnf) cnf = cnf - Double(dt.hour) cnf *= 60.0 dt.minute = Int(cnf) cnf = cnf - Double(dt.minute) dt.second = cnf * 60.0 dt.year = year dt.month = month dt.day = day } // 360度转换 func mod360Degree(_ degrees:Double) -> Double { var dbValue:Double = degrees while dbValue < 0.0{ dbValue += 360.0 } while dbValue > 360.0{ dbValue -= 360.0 } return dbValue } // 角度转弧度 func degree2Radian(_ degree:Double) -> Double { return degree * CalendarConstant.PI / 180.0 } // 弧度转角度 func radian2Degree(_ radian:Double) -> Double { return radian * 180.0 / CalendarConstant.PI } func getEarthNutationParameter(dt:Double, D:inout Double, M:inout Double, Mp:inout Double, F:inout Double, Omega:inout Double) { // T是从J2000起算的儒略世纪数 let T = dt * 10 let T2 = T * T let T3 = T2 * T // 平距角(如月对地心的角距离) D = 297.85036 + 445267.111480 * T - 0.0019142 * T2 + T3 / 189474.0 // 太阳(地球)平近点角 M = 357.52772 + 35999.050340 * T - 0.0001603 * T2 - T3 / 300000.0 // 月亮平近点角 Mp = 134.96298 + 477198.867398 * T + 0.0086972 * T2 + T3 / 56250.0 // 月亮纬度参数 F = 93.27191 + 483202.017538 * T - 0.0036825 * T2 + T3 / 327270.0 // 黄道与月亮平轨道升交点黄经 Omega = 125.04452 - 1934.136261 * T + 0.0020708 * T2 + T3 / 450000.0 } // 计算某时刻的黄经章动干扰量,dt是儒略千年数,返回值单位是度 func calcEarthLongitudeNutation(dt:Double) -> Double { let T = dt * 10 var D:Double = 0.0, M:Double = 0.0, Mp:Double = 0.0, F:Double = 0.0, Omega:Double = 0.0 getEarthNutationParameter(dt: dt, D: &D, M: &M, Mp: &Mp, F: &F, Omega: &Omega) var resulte = 0.0 for i in 0 ..< CalendarConstant.nutation.count { var sita = CalendarConstant.nutation[i].D * D + CalendarConstant.nutation[i].M * M + CalendarConstant.nutation[i].Mp * Mp + CalendarConstant.nutation[i].F * F + CalendarConstant.nutation[i].omega * Omega sita = degree2Radian(sita) resulte += (CalendarConstant.nutation[i].sine1 + CalendarConstant.nutation[i].sine2 * T ) * sin(sita) } /*先乘以章动表的系数 0.0001,然后换算成度的单位*/ return resulte * 0.0001 / 3600.0 } /*计算某时刻的黄赤交角章动干扰量,dt是儒略千年数,返回值单位是度*/ func calcEarthObliquityNutation(dt:Double) -> Double { // T是从J2000起算的儒略世纪数 let T = dt * 10 var D = 0.0, M = 0.0, Mp = 0.0, F = 0.0, Omega = 0.0 getEarthNutationParameter(dt:dt, D: &D, M: &M, Mp: &Mp, F: &F, Omega: &Omega) var resulte = 0.0 for i in 0 ..< CalendarConstant.nutation.count { var sita = CalendarConstant.nutation[i].D * D + CalendarConstant.nutation[i].M * M + CalendarConstant.nutation[i].Mp * Mp + CalendarConstant.nutation[i].F * F + CalendarConstant.nutation[i].omega * Omega sita = degree2Radian(sita) resulte += (CalendarConstant.nutation[i].cosine1 + CalendarConstant.nutation[i].cosine2 * T ) * cos(sita) } // 先乘以章动表的系数 0.001,然后换算成度的单位 return resulte * 0.0001 / 3600.0 } // 利用已知节气推算其它节气的函数,st的值以小寒节气为0,大寒为1,其它节气类推 func calculateSolarTermsByExp(year:Int, st:Int) -> Double { if st < 0 || st > 24 { return 0.0 } let stJd = 365.24219878 * Double(year - 1900) + CalendarConstant.stAccInfo[st] / 86400.0 return CalendarConstant.base1900SlightColdJD + stJd } /* moved from <算法的乐趣 - 王晓华> 示例代码 计算节气和朔日的经验公式 当天到1900年1月0日(星期日)的差称为积日,那么第y年(1900算0年)第x个节气的积日是: F = 365.242 * y + 6.2 + 15.22 *x - 1.9 * sin(0.262 * x) 从1900年开始的第m个朔日的公式是: M = 1.6 + 29.5306 * m + 0.4 * sin(1 - 0.45058 * m) */ func calculateSolarTermsByFm(year:Int, st:Int) -> Double { let baseJD = calcJulianDay(1900, month: 1, day: 1, hour: 0, min: 0, second: 0.0) - 1 let y = year - 1900 let tmp = 15.22 * Double(st) - 1.0 * sin(0.262 * Double(st)) let accDay = 365.2422 * Double(y) + 6.2 + tmp return baseJD + accDay } func calculateNewMoonByFm(m:Int) -> Double { let baseJD = calcJulianDay(1900, month: 1, day: 1, hour: 0, min: 0, second: 0.0) - 1 let accDay = 1.6 + 29.5306 * Double(m) + 0.4 * sin(1 - 0.45058 * Double(m)) return baseJD + accDay } func calcPeriodicTerm(coff:[PlanetData.VSOP87_COEFFICIENT], count:Int, dt:Double) -> Double { var val = 0.0 for i in 0 ..< count { val += (coff[i].A * cos((coff[i].B + coff[i].C * dt))) } return val } // 计算太阳的地心黄经(度),dt是儒略千年数 func calcSunEclipticLongitudeEC(dt:Double) -> Double { let L0 = calcPeriodicTerm(coff: PlanetData.Earth_L0, count: PlanetData.Earth_L0.count, dt: dt) let L1 = calcPeriodicTerm(coff: PlanetData.Earth_L1, count: PlanetData.Earth_L1.count, dt: dt) let L2 = calcPeriodicTerm(coff: PlanetData.Earth_L2, count: PlanetData.Earth_L2.count, dt: dt) let L3 = calcPeriodicTerm(coff: PlanetData.Earth_L3, count: PlanetData.Earth_L3.count, dt: dt) let L4 = calcPeriodicTerm(coff: PlanetData.Earth_L4, count: PlanetData.Earth_L4.count, dt: dt) let L5 = calcPeriodicTerm(coff: PlanetData.Earth_L5, count: PlanetData.Earth_L5.count, dt: dt) let L = (((((L5 * dt + L4) * dt + L3) * dt + L2) * dt + L1) * dt + L0) / 100000000.0 // 地心黄经 = 日心黄经 + 180度 return (mod360Degree(mod360Degree(L / CalendarConstant.RADIAN_PER_ANGLE) + 180.0)) } func calcSunEclipticLatitudeEC(dt:Double) -> Double { let B0 = calcPeriodicTerm(coff: PlanetData.Earth_B0, count: PlanetData.Earth_B0.count, dt: dt) let B1 = calcPeriodicTerm(coff: PlanetData.Earth_B1, count: PlanetData.Earth_B1.count, dt: dt) let B2 = calcPeriodicTerm(coff: PlanetData.Earth_B2, count: PlanetData.Earth_B2.count, dt: dt) let B3 = calcPeriodicTerm(coff: PlanetData.Earth_B3, count: PlanetData.Earth_B3.count, dt: dt) let B4 = calcPeriodicTerm(coff: PlanetData.Earth_B4, count: PlanetData.Earth_B4.count, dt: dt) let B = (((((B4 * dt) + B3) * dt + B2) * dt + B1) * dt + B0) / 100000000.0 // 地心黄纬 = -日心黄纬 return -(B / CalendarConstant.RADIAN_PER_ANGLE) } /*修正太阳的地心黄经,longitude, latitude 是修正前的太阳地心黄经和地心黄纬(度),dt是儒略千年数,返回值单位度*/ func adjustSunEclipticLongitudeEC(dt:Double, longitude:Double, latitude:Double) -> Double { //T是儒略世纪数 let T = dt * 10 var dbLdash = longitude - 1.397 * T - 0.00031 * T * T // 转换为弧度 dbLdash *= Double(CalendarConstant.RADIAN_PER_ANGLE) return (-0.09033 + 0.03916 * (cos(dbLdash) + sin(dbLdash)) * tan(latitude * CalendarConstant.RADIAN_PER_ANGLE)) / 3600.0 } /*修正太阳的地心黄纬,longitude是修正前的太阳地心黄经(度),dt是儒略千年数,返回值单位度*/ func adjustSunEclipticLatitudeEC(dt:Double, longitude:Double) -> Double { //T是儒略世纪数 let T = dt * 10 var dLdash = longitude - 1.397 * T - 0.00031 * T * T // 转换为弧度 dLdash *= CalendarConstant.RADIAN_PER_ANGLE return (0.03916 * (cos(dLdash) - sin(dLdash))) / 3600.0 } func calcSunEarthRadius(dt:Double) -> Double { let R0 = calcPeriodicTerm(coff: PlanetData.Earth_R0, count: PlanetData.Earth_R0.count, dt: dt) let R1 = calcPeriodicTerm(coff: PlanetData.Earth_R1, count: PlanetData.Earth_R1.count, dt: dt) let R2 = calcPeriodicTerm(coff: PlanetData.Earth_R2, count: PlanetData.Earth_R2.count, dt: dt) let R3 = calcPeriodicTerm(coff: PlanetData.Earth_R3, count: PlanetData.Earth_R3.count, dt: dt) let R4 = calcPeriodicTerm(coff: PlanetData.Earth_R4, count: PlanetData.Earth_R4.count, dt: dt) let R = (((((R4 * dt) + R3) * dt + R2) * dt + R1) * dt + R0) / 100000000.0 return R } // 得到某个儒略日的太阳地心黄经(视黄经),单位度 func getSunEclipticLongitudeEC(jde:Double) -> Double { // 儒略千年数 let dt = (jde - CalendarConstant.JD2000) / 365250.0 // 计算太阳的地心黄经 var longitude = calcSunEclipticLongitudeEC(dt: dt) // 计算太阳的地心黄纬 let latitude = calcSunEclipticLatitudeEC(dt: dt) * 3600.0 // 修正精度 longitude += adjustSunEclipticLongitudeEC(dt: dt, longitude: longitude, latitude: latitude) // 修正天体章动 longitude += calcEarthLongitudeNutation(dt: dt) // 修正光行差 /*太阳地心黄经光行差修正项是: -20".4898/R*/ longitude -= (20.4898 / calcSunEarthRadius(dt: dt)) / 3600.0 return longitude } // 得到某个儒略日的太阳地心黄纬(视黄纬),单位度 func getSunEclipticLatitudeEC(jde:Double) -> Double { // 儒略千年数 let dt = (jde - CalendarConstant.JD2000) / 365250.0 // 计算太阳的地心黄经 let longitude = calcSunEclipticLongitudeEC(dt: dt) // 计算太阳的地心黄纬 var latitude = calcSunEclipticLatitudeEC(dt: dt) * 3600.0 // 修正精度 let delta = adjustSunEclipticLatitudeEC(dt: dt, longitude: longitude) latitude += delta * 3600.0 return latitude } func getMoonEclipticParameter(dt:Double, Lp:inout Double, D: inout Double, M: inout Double, Mp:inout Double, F: inout Double, E: inout Double) { // T是从J2000起算的儒略世纪数 let T = dt let T2 = T * T let T3 = T2 * T let T4 = T3 * T // 月球平黄经 Lp = 218.3164591 + 481267.88134236 * T - 0.0013268 * T2 + T3/538841.0 - T4 / 65194000.0 Lp = mod360Degree(Lp) // 月日距角 D = 297.8502042 + 445267.1115168 * T - 0.0016300 * T2 + T3 / 545868.0 - T4 / 113065000.0 D = mod360Degree(D) // 太阳平近点角 M = 357.5291092 + 35999.0502909 * T - 0.0001536 * T2 + T3 / 24490000.0 M = mod360Degree(M) // 月亮平近点角 Mp = 134.9634114 + 477198.8676313 * T + 0.0089970 * T2 + T3 / 69699.0 - T4 / 14712000.0 Mp = mod360Degree(Mp) // 月球经度参数(到升交点的平角距离) F = 93.2720993 + 483202.0175273 * T - 0.0034029 * T2 - T3 / 3526000.0 + T4 / 863310000.0 F = mod360Degree(F) E = 1 - 0.002516 * T - 0.0000074 * T2 } // 计算月球地心黄经周期项的和 func calcMoonECLongitudePeriodic(D: Double, M: Double, Mp: Double, F: Double, E: Double) -> Double { var EI = 0.0 for i in 0 ..< PlanetData.Moon_longitude.count { var sita = PlanetData.Moon_longitude[i].D * D + PlanetData.Moon_longitude[i].M * M + PlanetData.Moon_longitude[i].Mp * Mp + PlanetData.Moon_longitude[i].F * F sita = degree2Radian(sita) EI += (PlanetData.Moon_longitude[i].eiA * sin(sita) * pow(E, fabs(PlanetData.Moon_longitude[i].M))) } return EI } // 计算月球地心黄纬周期项的和 func calcMoonECLatitudePeriodicTbl(D: Double, M: Double, Mp: Double, F: Double, E: Double) -> Double { var EB = 0.0 for i in 0 ..< PlanetData.moon_Latitude.count { var sita = PlanetData.moon_Latitude[i].D * D + PlanetData.moon_Latitude[i].M * M + PlanetData.moon_Latitude[i].Mp * Mp + PlanetData.moon_Latitude[i].F * F sita = degree2Radian(sita) EB += (PlanetData.moon_Latitude[i].eiA * sin(sita) * pow(E, fabs(PlanetData.Moon_longitude[i].M))) } return EB } // 计算月球地心距离周期项的和 func calcMoonECDistancePeriodicTbl(D: Double, M: Double, Mp: Double, F: Double, E: Double) -> Double { var ER = 0.0 for i in 0 ..< PlanetData.Moon_longitude.count { var sita = PlanetData.Moon_longitude[i].D * D + PlanetData.Moon_longitude[i].M * M + PlanetData.Moon_longitude[i].Mp * Mp + PlanetData.Moon_longitude[i].F * F sita = degree2Radian(sita) ER += (PlanetData.Moon_longitude[i].erA * cos(sita) * pow(E, fabs(PlanetData.Moon_longitude[i].M))) } return ER } // 计算金星摄动,木星摄动以及地球扁率摄动对月球地心黄经的影响,dt 是儒略世纪数,Lp和F单位是度 func calcMoonLongitudePerturbation(dt: Double, Lp: Double, F: Double) -> Double { // T是从J2000起算的儒略世纪数 let T = dt var A1 = 119.75 + 131.849 * T var A2 = 53.09 + 479264.290 * T A1 = mod360Degree(A1) A2 = mod360Degree(A2) var result = 3958.0 * sin(degree2Radian(A1)) result += (1962.0 * sin(degree2Radian(Lp - F))) result += (318.0 * sin(degree2Radian(A2))) return result } // 计算金星摄动,木星摄动以及地球扁率摄动对月球地心黄纬的影响,dt 是儒略世纪数,Lp、Mp和F单位是度 func calcMoonLatitudePerturbation(dt: Double, Lp: Double, F: Double, Mp: Double) -> Double { // T是从J2000起算的儒略世纪数 let T = dt var A1 = 119.75 + 131.849 * T var A3 = 313.45 + 481266.484 * T A1 = mod360Degree(A1) A3 = mod360Degree(A3) var result = -2235.0 * sin(degree2Radian(Lp)) result += (382.0 * sin(degree2Radian(A3))) result += (175.0 * sin(degree2Radian(A1 - F))) result += (175.0 * sin(degree2Radian(A1 + F))) result += (127.0 * sin(degree2Radian(Lp - Mp))) result += (115.0 * sin(degree2Radian(Lp + Mp))) return result } func getMoonEclipticLongitudeEC(dbJD: Double) -> Double { var Lp:Double = 0.0, D:Double = 0.0, M:Double = 0.0, Mp:Double = 0.0, F:Double = 0.0, E:Double = 0.0 // 儒略世纪数 let dt = (dbJD - CalendarConstant.JD2000) / 36525.0 getMoonEclipticParameter(dt: dt, Lp: &Lp, D: &D, M: &M, Mp: &Mp, F: &F, E: &E) // 计算月球地心黄经周期项 var EI = calcMoonECLongitudePeriodic(D: D, M: M, Mp: Mp, F: F, E: E) // 修正金星,木星以及地球扁率摄动 EI += calcMoonLongitudePerturbation(dt: dt, Lp: Lp, F: F) // 计算月球地心黄经 var longitude = Lp + EI / 1000000.0 // 计算天体章动干扰 longitude += calcEarthLongitudeNutation(dt: dt / 10.0) // 映射到0-360范围内 longitude = mod360Degree(longitude) return longitude } func getMoonEclipticLatitudeEC(dbJD: Double) -> Double { // 儒略世纪数 let dt = (dbJD - CalendarConstant.JD2000) / 36525.0 var Lp = 0.0, D = 0.0, M = 0.0, Mp = 0.0, F = 0.0, E = 0.0 getMoonEclipticParameter(dt: dt, Lp: &Lp, D: &D, M: &M, Mp: &Mp, F: &F, E: &E) // 计算月球地心黄纬周期项 var EB = calcMoonECLatitudePeriodicTbl(D: D, M: M, Mp: Mp, F: F, E: E) // 修正金星,木星以及地球扁率摄动 EB += calcMoonLatitudePerturbation(dt: dt, Lp: Lp, F: F, Mp: Mp) // 计算月球地心黄纬*/ let latitude = EB / 1000000.0 return latitude } func getMoonEarthDistance(dbJD: Double) -> Double { // 儒略世纪数 let dt = (dbJD - CalendarConstant.JD2000) / 36525.0 var Lp = 0.0, D = 0.0, M = 0.0, Mp = 0.0, F = 0.0, E = 0.0 getMoonEclipticParameter(dt: dt, Lp: &Lp, D: &D, M: &M, Mp: &Mp, F: &F, E: &E) // 计算月球地心距离周期项 let ER = calcMoonECDistancePeriodicTbl(D: D, M: M, Mp: Mp, F: F, E: E) // 计算月球地心黄纬 let distance = 385000.56 + ER / 1000.0 return distance } func getInitialEstimateSolarTerms(year: Int, angle: Int) -> Double { var STMonth = Int(ceil(Double((Double(angle) + 90.0) / 30.0))) STMonth = STMonth > 12 ? STMonth - 12 : STMonth // 每月第一个节气发生日期基本都4-9日之间,第二个节气的发生日期都在16-24日之间 if (angle % 15 == 0) && (angle % 30 != 0) { return calcJulianDay(year, month: STMonth, day: 6, hour: 12, min: 0, second: 0.0) }else{ return calcJulianDay(year, month: STMonth, day: 20, hour: 12, min: 0, second: 0.0) } } // 计算指定年份的任意节气,angle是节气在黄道上的读数 // 返回指定节气的儒略日时间(力学时) func calculateSolarTerms(year: Int, angle: Int) -> Double { var JD0:Double, JD1:Double, stDegree:Double, stDegreep:Double JD1 = getInitialEstimateSolarTerms(year: year, angle: angle) repeat { JD0 = JD1 stDegree = getSunEclipticLongitudeEC(jde: JD0) /* 对黄经0度迭代逼近时,由于角度360度圆周性,估算黄经值可能在(345,360]和[0,15)两个区间, 如果值落入前一个区间,需要进行修正 */ stDegree = ((angle == 0) && (stDegree > 345.0)) ? stDegree - 360.0 : stDegree stDegreep = (getSunEclipticLongitudeEC(jde: Double(JD0) + 0.000005) - getSunEclipticLongitudeEC(jde: Double(JD0) - 0.000005)) / 0.00001 JD1 = JD0 - (stDegree - Double(angle)) / stDegreep //print("getInitialEstimateSolarTerms JD1-JD0 = \(JD1 - JD0)") }while((fabs(JD1 - JD0) > 0.0000001)) return JD1 } /* 得到给定的时间后面第一个日月合朔的时间,平均误差小于3秒 输入参数是指定时间的力学时儒略日数 返回值是日月合朔的力学时儒略日数 */ func calculateMoonShuoJD(tdJD: Double) -> Double { var JD0:Double, JD1:Double, stDegree:Double, stDegreep:Double var count = 0 JD1 = tdJD repeat { JD0 = JD1 var moonLongitude = getMoonEclipticLongitudeEC(dbJD: JD0) var sunLongitude = getSunEclipticLongitudeEC(jde: JD0) if (moonLongitude > 330.0) && (sunLongitude < 30.0) { sunLongitude = 360.0 + sunLongitude } if (sunLongitude > 330.0) && (moonLongitude < 30.0) { moonLongitude = 60.0 + moonLongitude } stDegree = moonLongitude - sunLongitude if(stDegree >= 360.0){ stDegree -= 360.0 } if(stDegree < -360.0) { stDegree += 360.0 } stDegreep = (getMoonEclipticLongitudeEC(dbJD: JD0 + 0.000005) - getSunEclipticLongitudeEC(jde: JD0 + 0.000005) - getMoonEclipticLongitudeEC(dbJD: JD0 - 0.000005) + getSunEclipticLongitudeEC(jde: JD0 - 0.000005)) / 0.00001 JD1 = JD0 - stDegree / stDegreep count += 1 if count > 500 { break } }while((fabs(JD1 - JD0) > 0.00000001)) return JD1 } // 根据年份计算农历干支与生肖 func calculateStemsBranches(year: Int, stems: inout Int, branches: inout Int) { let sc = year - 2000 stems = (7 + sc) % 10 branches = (5 + sc) % 12 if stems < 0 { stems += 10 } if branches <= 0 { branches += 12 } } // TD - UT1 误差校验结构 private struct TD_UTC_DELTA{ var year: Int var d1:Double, d2: Double, d3: Double, d4: Double init(_ year: Int, _ d1: Double, _ d2: Double, _ d3: Double, _ d4: Double) { self.year = year self.d1 = d1 self.d2 = d2 self.d3 = d3 self.d4 = d4 } } // TD - UT1 误差计算表 private static let deltaTbl:[TD_UTC_DELTA] = [ TD_UTC_DELTA( -4000, 108371.7,-13036.80,392.000, 0.0000 ), TD_UTC_DELTA( -500, 17201.0, -627.82, 16.170,-0.3413 ), TD_UTC_DELTA( -150, 12200.6, -346.41, 5.403,-0.1593 ), TD_UTC_DELTA( 150, 9113.8, -328.13, -1.647, 0.0377 ), TD_UTC_DELTA( 500, 5707.5, -391.41, 0.915, 0.3145 ), TD_UTC_DELTA( 900, 2203.4, -283.45, 13.034,-0.1778 ), TD_UTC_DELTA( 1300, 490.1, -57.35, 2.085,-0.0072 ), TD_UTC_DELTA( 1600, 120.0, -9.81, -1.532, 0.1403 ), TD_UTC_DELTA( 1700, 10.2, -0.91, 0.510,-0.0370 ), TD_UTC_DELTA( 1800, 13.4, -0.72, 0.202,-0.0193 ), TD_UTC_DELTA( 1830, 7.8, -1.81, 0.416,-0.0247 ), TD_UTC_DELTA( 1860, 8.3, -0.13, -0.406, 0.0292 ), TD_UTC_DELTA( 1880, -5.4, 0.32, -0.183, 0.0173 ), TD_UTC_DELTA( 1900, -2.3, 2.06, 0.169,-0.0135 ), TD_UTC_DELTA( 1920, 21.2, 1.69, -0.304, 0.0167 ), TD_UTC_DELTA( 1940, 24.2, 1.22, -0.064, 0.0031 ), TD_UTC_DELTA( 1960, 33.2, 0.51, 0.231,-0.0109 ), TD_UTC_DELTA( 1980, 51.0, 1.29, -0.026, 0.0032 ), TD_UTC_DELTA( 2000, 63.87, 0.1, 0.0, 0.0 ), TD_UTC_DELTA( 2005, 0.0, 0.0, 0.0, 0.0 ) ] func deltaExt(y: Double, jsd: Int) -> Double { let dy = (y - 1820.0) / 100.0 return -20.0 + Double(jsd) * dy * dy } func tdUtcDeltaT(y: Double) -> Double { if y >= 2005 { let y1: Int = 2014 let sd = 0.4 let jsd: Int = 31 if y <= Double(y1) { return 64.7 + (y - 2005) * sd } var v = deltaExt(y: y, jsd: jsd) let dv = deltaExt(y: Double(y1), jsd: jsd) - (64.7 + Double(y1 - 2005) * sd) if y < Double(y1) + 100 { v -= dv * (Double(y1) + 100 - y) / 100 } return v } else { var i = 0 for flag in 0 ..< CalendarUtils.deltaTbl.count { i = flag if y < Double(CalendarUtils.deltaTbl[i + 1].year) { break } } let t1 = Double(y - Double(CalendarUtils.deltaTbl[i].year)) / Double(CalendarUtils.deltaTbl[i + 1].year - CalendarUtils.deltaTbl[i].year) * 10.0 let t2 = t1 * t1 let t3 = t2 * t1 return CalendarUtils.deltaTbl[i].d1 + CalendarUtils.deltaTbl[i].d2 * t1 + CalendarUtils.deltaTbl[i].d3 * t2 + CalendarUtils.deltaTbl[i].d4 * t3 } } func tdUtcDeltaT2(jd2k: Double) -> Double { return tdUtcDeltaT(y: jd2k / 365.2425 + 2000) / 86400.0 } // 本地时间转utc func jdLocalTimetoUTC(localJD: Double) -> Double { let tz = NSTimeZone.default let secs = -tz.secondsFromGMT() return localJD + Double(secs) / 86400.0 } // utc转本地时间 func jdUTCToLocalTime(utcJD: Double) -> Double { let tz = NSTimeZone.default let secs = -tz.secondsFromGMT() return utcJD - Double(secs) / 86400.0 } func jdTDtoUTC(tdJD: Double) -> Double { var _tdJD = tdJD let jd2k = tdJD - CalendarConstant.JD2000 let tian = tdUtcDeltaT2(jd2k: jd2k) _tdJD -= tian return _tdJD } func jdTDtoLocalTime(tdJD: Double) -> Double { let tmp = jdTDtoUTC(tdJD: tdJD) return jdUTCToLocalTime(utcJD: tmp) } func jdUTCtoTD(utcJD: Double) -> Double { var _utcJD = utcJD let jd2k = utcJD - CalendarConstant.JD2000 let tian = tdUtcDeltaT2(jd2k: jd2k) _utcJD += tian return _utcJD } func jdLocalTimetoTD(localJD: Double) -> Double { let tmp = jdLocalTimetoUTC(localJD: localJD) return jdUTCtoTD(utcJD: tmp) } }
988538c4b3d0182349bc85114bb9c9f8
31.87069
233
0.526619
false
false
false
false
turekj/ReactiveTODO
refs/heads/master
ReactiveTODOFramework/Classes/Logic/Messages/Impl/MessageImageFactory.swift
mit
1
import Foundation class MessageImageFactory: MessageImageFactoryProtocol { let bundle: NSBundle let priorityFormatter: PriorityImageNameFormatterProtocol let outputImageSize: CGSize init(bundle: NSBundle, priorityFormatter: PriorityImageNameFormatterProtocol, outputImageSize: CGSize) { self.bundle = bundle self.priorityFormatter = priorityFormatter self.outputImageSize = outputImageSize } func createMessageImage(note: TODONote) -> UIImage { let priorityIcon = self.priorityIcon(note) UIGraphicsBeginImageContextWithOptions(self.outputImageSize, false, 0.0) let context = UIGraphicsGetCurrentContext()! CGContextSetFillColorWithColor(context, UIColor.whiteColor().CGColor) CGContextFillRect(context, CGRect(origin: CGPointMake(0, 0), size: self.outputImageSize)) priorityIcon.drawInRect(self.priorityIconDrawRect(priorityIcon)) let img = UIGraphicsGetImageFromCurrentImageContext()! UIGraphicsEndImageContext() return img } private func priorityIcon(note: TODONote) -> UIImage { let priorityIconName = self.priorityFormatter.format(note.priority) return UIImage(named: priorityIconName, inBundle: self.bundle, compatibleWithTraitCollection: nil)! } private func priorityIconDrawRect(priorityIcon: UIImage) -> CGRect { let x = (self.outputImageSize.width - priorityIcon.size.width) * 0.5 let y = (self.outputImageSize.height - priorityIcon.size.height) * 0.5 let width = priorityIcon.size.width let height = priorityIcon.size.height return CGRectMake(x, y, width, height) } }
e9eab6c8d43d56e2f0f68135e1d88d94
37.12766
97
0.68192
false
false
false
false
jakeshi01/IFlySpeechPackage
refs/heads/master
IFlyTest/IFlyTest/SpeechRecognizerAdapter.swift
mit
1
// // SpeechRecognizerAdapter.swift // IFlyTest // // Created by Jake on 2017/7/4. // Copyright © 2017年 Jake. All rights reserved. // import Foundation import UIKit class SpeechRecognizerAdapter: NSObject { fileprivate var speechRecognizer: SpeechRecognizeable = SpeechRecognizer() fileprivate var recognizeResult: String = "" fileprivate var finishTask: Task? fileprivate var isCanceled: Bool = false var recognizerBar: SpeechRecognizerControl? { didSet{ recognizerBar?.delegate = self } } var handleView: SpeechRecognizeAction? { didSet{ handleView?.finishAction = { [weak self] in self?.recognizerBar?.speechBtn.isUserInteractionEnabled = true } } } override init() { super.init() speechRecognizer.delegate = self } } extension SpeechRecognizerAdapter: SpeechRecognizerControlDelegate { func beginSpeech() { let isBegin = speechRecognizer.startListening() guard isBegin else { return } if let task = finishTask { cancel(task) } cancel(finishTask) handleView?.isCancelHidden = true handleView?.showAnimation() handleView?.beginSpeechAction() } func willCancelSpeech() { handleView?.cancelSpeechAction() } func resumeSpeech() { handleView?.resumeSpeechAction() } func speechEnd() { handleView?.endSpeechAction() speechRecognizer.stopListening() } func speechCanceled() { isCanceled = true handleView?.dismissAnimation() speechRecognizer.cancelSpeech() handleView?.endSpeechAction() } } extension SpeechRecognizerAdapter: SpeechRecognizerDelegate { func onError(_ errorCode: IFlySpeechError) { handleView?.isCancelHidden = false finishTask = delay(1.0, task: { [weak self] in self?.handleView?.dismissAnimation() }) print("errorCode = \(errorCode.errorDesc)") if errorCode.errorCode == SpeechError.successCode.rawValue { //此处用于解决讯飞第一次短暂识别(单击,无语音)无数据(错误码应该为10118时)实际返回errorCode = 0的问题 guard recognizeResult.characters.count == 0 else { recognizeResult = "" return } handleView?.setRecognizeResult("未识别到语音") recognizeResult = "" } else if errorCode.errorCode == SpeechError.networkDisableCode.rawValue { //没有网络 } else if errorCode.errorCode == SpeechError.recordDisabelCode.rawValue { //录音初始化失败 } else{ handleView?.setRecognizeResult("未识别到语音") } } func onResults(_ recognizeResult: String) { self.recognizeResult = recognizeResult handleView?.setRecognizeResult(recognizeResult) } func onEndOfSpeech() { print("识别中") speechEnd() guard !isCanceled else { return } handleView?.showProgressHud() //识别期间禁止再次点击语音 recognizerBar?.speechBtn.isUserInteractionEnabled = false } func onCancel() { print("取消识别") } func onVolumeChanged(_ value: Int32) { handleView?.speechAnimation(with: value) } }
04c966951b2e80541d7a61bf300d4758
26.278689
82
0.610276
false
false
false
false
Ethenyl/JAMFKit
refs/heads/master
JamfKit/Tests/Models/HardwareGroup/HardwareGroupTests.swift
mit
1
// // Copyright © 2017-present JamfKit. All rights reserved. // Licensed under the MIT License. See LICENSE file in the project root for full license information. // import XCTest @testable import JamfKit class HardwareGroupTests: XCTestCase { // MARK: - Constants let subfolder = "ComputerGroup/" let defaultIdentifier: UInt = 12345 let defaultName = "computers" let defaultIsSmart = true // MARK: - Tests func testShouldInstantiate() { let actualValue = HardwareGroup(identifier: defaultIdentifier, name: defaultName) XCTAssertNotNil(actualValue) XCTAssertEqual(actualValue?.identifier, defaultIdentifier) XCTAssertEqual(actualValue?.name, defaultName) } func testShouldNotInstantiateWithInvalidParameters() { let actualValue = HardwareGroup(identifier: defaultIdentifier, name: "") XCTAssertNil(actualValue) } }
7504598b38f0c6f76ce618a066e2b7f2
25.911765
102
0.713661
false
true
false
false
stripe/stripe-ios
refs/heads/master
IntegrationTester/IntegrationTester/Views/CardSetupIntentsView.swift
mit
1
// // CardSetupIntentsView.swift // IntegrationTester // // Created by David Estes on 2/8/21. // import SwiftUI import Stripe struct CardSetupIntentsView: View { @StateObject var model = MySIModel() @State var isConfirmingSetupIntent = false @State var paymentMethodParams: STPPaymentMethodParams? var body: some View { VStack { STPPaymentCardTextField.Representable(paymentMethodParams: $paymentMethodParams) .padding() if let setupIntent = model.intentParams { Button("Setup") { setupIntent.paymentMethodParams = paymentMethodParams isConfirmingSetupIntent = true }.setupIntentConfirmationSheet(isConfirmingSetupIntent: $isConfirmingSetupIntent, setupIntentParams: setupIntent, onCompletion: model.onCompletion) .disabled(isConfirmingSetupIntent || paymentMethodParams == nil) } else { ProgressView() } if let paymentStatus = model.paymentStatus { PaymentHandlerStatusView(actionStatus: paymentStatus, lastPaymentError: model.lastPaymentError) } }.onAppear { model.prepareSetupIntent() } } } struct CardSetupIntentsView_Preview : PreviewProvider { static var previews: some View { CardSetupIntentsView() } }
87f3da7264e8337561ae00625ed255cf
31.309524
105
0.665438
false
false
false
false
kantega/tech-ex-2015
refs/heads/master
ios/TechEx/views/TechexTextField.swift
mit
1
// // TechexTextField.swift // TechEx // // Created by Kristian Lier Selnæs on 18/02/15. // Copyright (c) 2015 Technoport. All rights reserved. // import UIKit class TechexTextField: UITextField { let padding = UIEdgeInsets(top: 0, left: 5, bottom: 0, right: 5); override func textRectForBounds(bounds: CGRect) -> CGRect { return self.newBounds(bounds) } override func placeholderRectForBounds(bounds: CGRect) -> CGRect { return self.newBounds(bounds) } override func editingRectForBounds(bounds: CGRect) -> CGRect { return self.newBounds(bounds) } private func newBounds(bounds: CGRect) -> CGRect { var newBounds = bounds newBounds.origin.x += padding.left newBounds.origin.y += padding.top newBounds.size.height -= (padding.top * 2) - padding.bottom newBounds.size.width -= (padding.left * 2) - padding.right return newBounds } }
fe93a70c024bab27f6d37f2634a9e72d
24.842105
70
0.63442
false
false
false
false
gametimesf/GAMConstants
refs/heads/master
Source/GTStringsManager.swift
mit
2
// // GTStringsManager.swift // Gametime // // Created by Mike Silvis on 8/16/16. // // import UIKit public class GTStringsManager { public static let sharedInstance = GTStringsManager() public func string(key: String?) -> String { guard let key = key else { return "" } return find(key: key, safeToNotExist: false) } public func string(key: String?, args: CVaListPointer) -> String { guard let key = key else { return "" } return NSString(format: find(key: key, safeToNotExist: false), locale: Locale.current, arguments: args) as String } public func string(key: String?, safetoNotExist: Bool) -> String { guard let key = key else { return "" } return find(key: key, safeToNotExist: safetoNotExist) } // // MARK: Finders // fileprivate func find(key: String, safeToNotExist: Bool) -> String { if let string = findIntercepted(key: key) { return string } return findLocalized(key: key, safeToNotExist: safeToNotExist) } fileprivate func findLocalized(key: String, safeToNotExist: Bool) -> String { let string = NSLocalizedString(key, comment: "") if string == key { assert(safeToNotExist, "Key: \(key) does not exist. Please add it") } if safeToNotExist && string.isEmpty { return key } return string } fileprivate func findIntercepted(key: String) -> String? { return GTInterceptionManager.sharedInstance.hotFix(key: key) } } // To be used by objc only public class GTStringBridger: NSObject { @objc public static func string(key: String) -> String { return GTStringsManager.sharedInstance.string(key: key) } }
7088ffbe414cfcf3a7cf462d954082f2
24.73913
121
0.626689
false
false
false
false
safx/TypetalkKit
refs/heads/master
Example-iOS/Example-iOS/AppDelegate.swift
mit
1
// // AppDelegate.swift // iOSExample // // Created by Safx Developer on 2014/09/17. // Copyright (c) 2014年 Safx Developers. All rights reserved. // import UIKit import TypetalkKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate, UISplitViewControllerDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey : Any]? = nil) -> Bool { let splitViewController = self.window!.rootViewController as! UISplitViewController let navigationController = splitViewController.viewControllers[splitViewController.viewControllers.count-1] as! UINavigationController //navigationController.topViewController!.navigationItem.leftBarButtonItem = splitViewController.displayModeButtonItem() splitViewController.delegate = self _ = TypetalkAPI.setDeveloperSettings( clientId: "Your ClientID", clientSecret: "Your SecretID", scopes: [Scope.my, Scope.topicRead], // e.g. typetalkkit://auth/success redirectURI: "Your custome scheme") _ = TypetalkAPI.restoreTokenFromAccountStore() return true } func application(_ app: UIApplication, open url: URL, options: [UIApplicationOpenURLOptionsKey : Any] = [:]) -> Bool { if TypetalkAPI.isRedirectURL(url) { if #available(iOS 9.0, *) { if let sourceApplication = options[UIApplicationOpenURLOptionsKey.sourceApplication] as! String?, sourceApplication == "com.apple.mobilesafari" { return TypetalkAPI.authorizationDone(URL: url) } } else { // Fallback on earlier versions } } return false } // MARK: - Split view func splitViewController(_ splitViewController: UISplitViewController, collapseSecondary secondaryViewController: UIViewController, onto primaryViewController: UIViewController) -> Bool { if let secondaryAsNavController = secondaryViewController as? UINavigationController { if let topAsDetailController = secondaryAsNavController.topViewController as? DetailViewController { if topAsDetailController.detailItem == nil { // Return true to indicate that we have handled the collapse by doing nothing; the secondary controller will be discarded. return true } } } return false } }
37bfa3af8802f7b699a5cda7b4e347ec
39.666667
191
0.674473
false
false
false
false
SteveKChiu/CoreDataMonk
refs/heads/master
CoreDataMonk/CoreDataExpression.swift
mit
1
// // https://github.com/SteveKChiu/CoreDataMonk // // Copyright 2015, Steve K. Chiu <[email protected]> // // The MIT License (http://www.opensource.org/licenses/mit-license.php) // // 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 CoreData //--------------------------------------------------------------------------- public struct CoreDataQuery { let predicate: NSPredicate private init(_ predicate: NSPredicate) { self.predicate = predicate } public static func Where(_ format: String, _ args: Any...) -> CoreDataQuery { return CoreDataQuery(NSPredicate(format: format, argumentArray: args)) } public static func Where(_ predicate: NSPredicate) -> CoreDataQuery { return CoreDataQuery(predicate) } } public func && (lhs: CoreDataQuery, rhs: CoreDataQuery) -> CoreDataQuery { return .Where(NSCompoundPredicate(type: .and, subpredicates: [ lhs.predicate, rhs.predicate ])) } public func || (lhs: CoreDataQuery, rhs: CoreDataQuery) -> CoreDataQuery { return .Where(NSCompoundPredicate(type: .or, subpredicates: [ lhs.predicate, rhs.predicate ])) } public prefix func ! (lhs: CoreDataQuery) -> CoreDataQuery { return .Where(NSCompoundPredicate(type: .not, subpredicates: [ lhs.predicate ])) } //--------------------------------------------------------------------------- public enum CoreDataQueryKey { case key(String) case keyModifier(String, NSComparisonPredicate.Modifier) case keyPath([String]) var path: String { switch self { case let .key(path): return path case let .keyModifier(path, _): return path case let .keyPath(list): var path = list.first! for item in list[1 ..< list.count] { path += "." path += item } return path } } var modifier: NSComparisonPredicate.Modifier { switch self { case let .keyModifier(_, mod): return mod default: return .direct } } var list: [String] { switch self { case let .key(path): return [ path ] case let .keyModifier(path, _): return [ path ] case let .keyPath(list): return list } } public var any: CoreDataQueryKey { return .keyModifier(self.path, .any) } public var all: CoreDataQueryKey { return .keyModifier(self.path, .all) } fileprivate func compare(_ op: NSComparisonPredicate.Operator, _ key: CoreDataQueryKey) -> CoreDataQuery { return .Where(NSComparisonPredicate( leftExpression: NSExpression(forKeyPath: self.path), rightExpression: NSExpression(forKeyPath: key.path), modifier: self.modifier, type: op, options: [])) } fileprivate func compare(_ op: NSComparisonPredicate.Operator, _ value: Any) -> CoreDataQuery { return .Where(NSComparisonPredicate( leftExpression: NSExpression(forKeyPath: self.path), rightExpression: NSExpression(forConstantValue: value), modifier: self.modifier, type: op, options: [])) } } prefix operator % postfix operator % public prefix func % (key: CoreDataQueryKey) -> CoreDataQueryKey { return key } public prefix func % (name: String) -> CoreDataQueryKey { return CoreDataQueryKey.key(name) } public postfix func % (name: String) -> CoreDataQueryKey { return CoreDataQueryKey.key(name) } public func | (lhs: CoreDataQueryKey, rhs: CoreDataQueryKey) -> CoreDataQueryKey { return .keyPath(lhs.list + rhs.list) } public func == (lhs: CoreDataQueryKey, rhs: Any?) -> CoreDataQuery { return lhs.compare(.equalTo, rhs ?? NSNull()) } public func == (lhs: CoreDataQueryKey, rhs: CoreDataQueryKey) -> CoreDataQuery { return lhs.compare(.equalTo, rhs) } public func != (lhs: CoreDataQueryKey, rhs: Any?) -> CoreDataQuery { return lhs.compare(.notEqualTo, rhs ?? NSNull()) } public func != (lhs: CoreDataQueryKey, rhs: CoreDataQueryKey) -> CoreDataQuery { return lhs.compare(.notEqualTo, rhs) } public func > (lhs: CoreDataQueryKey, rhs: Any) -> CoreDataQuery { return lhs.compare(.greaterThan, rhs) } public func > (lhs: CoreDataQueryKey, rhs: CoreDataQueryKey) -> CoreDataQuery { return lhs.compare(.greaterThan, rhs) } public func < (lhs: CoreDataQueryKey, rhs: Any) -> CoreDataQuery { return lhs.compare(.lessThan, rhs) } public func < (lhs: CoreDataQueryKey, rhs: CoreDataQueryKey) -> CoreDataQuery { return lhs.compare(.lessThan, rhs) } public func >= (lhs: CoreDataQueryKey, rhs: Any) -> CoreDataQuery { return lhs.compare(.greaterThanOrEqualTo, rhs) } public func >= (lhs: CoreDataQueryKey, rhs: CoreDataQueryKey) -> CoreDataQuery { return lhs.compare(.greaterThanOrEqualTo, rhs) } public func <= (lhs: CoreDataQueryKey, rhs: Any) -> CoreDataQuery { return lhs.compare(.lessThanOrEqualTo, rhs) } public func <= (lhs: CoreDataQueryKey, rhs: CoreDataQueryKey) -> CoreDataQuery { return lhs.compare(.lessThanOrEqualTo, rhs) } //--------------------------------------------------------------------------- public struct CoreDataSelect { fileprivate let descriptions: [Any] fileprivate init(_ expression: Any) { self.descriptions = [ expression ] } fileprivate init(_ expressions: [Any]) { self.descriptions = expressions } private init(function: String, property: String, alias: String?, type: NSAttributeType) { let key = NSExpression(forKeyPath: property) let expression = NSExpression(forFunction: function, arguments: [ key ]) let description = NSExpressionDescription() description.name = alias ?? property description.expression = expression description.expressionResultType = type self.descriptions = [ description ] } public static func Select(_ keys: String...) -> CoreDataSelect { return CoreDataSelect(keys) } public static func Expression(_ expression: NSExpressionDescription) -> CoreDataSelect { return CoreDataSelect(expression) } public static func Sum(_ property: String, alias: String? = nil) -> CoreDataSelect { return CoreDataSelect(function: "sum:", property: property, alias: alias, type: .decimalAttributeType) } public static func Average(_ property: String, alias: String? = nil) -> CoreDataSelect { return CoreDataSelect(function: "average:", property: property, alias: alias, type: .decimalAttributeType) } public static func StdDev(_ property: String, alias: String? = nil) -> CoreDataSelect { return CoreDataSelect(function: "stddev:", property: property, alias: alias, type: .decimalAttributeType) } public static func Count(_ property: String, alias: String? = nil) -> CoreDataSelect { return CoreDataSelect(function: "count:", property: property, alias: alias, type: .integer64AttributeType) } public static func Max(_ property: String, alias: String? = nil) -> CoreDataSelect { return CoreDataSelect(function: "max:", property: property, alias: alias, type: .undefinedAttributeType) } public static func Min(_ property: String, alias: String? = nil) -> CoreDataSelect { return CoreDataSelect(function: "min:", property: property, alias: alias, type: .undefinedAttributeType) } public static func Median(_ property: String, alias: String? = nil) -> CoreDataSelect { return CoreDataSelect(function: "median:", property: property, alias: alias, type: .undefinedAttributeType) } private func keyPathResultType(_ key: String, entity: NSEntityDescription) throws -> NSAttributeType { if let r = key.range(of: ".") { let name = key.substring(to: r.lowerBound) let next = key.substring(from: key.index(after: r.lowerBound)) guard let relate = entity.relationshipsByName[name]?.destinationEntity else { throw CoreDataError("Can not find relationship [\(name)] of [\(entity.name)]") } return try keyPathResultType(next, entity: relate) } guard let attr = entity.attributesByName[key] else { throw CoreDataError("Can not find attribute [\(key)] of [\(entity.name)]") } return attr.attributeType } func resolve(_ entity: NSEntityDescription) throws -> [Any] { var properties = [Any]() for unknownDescription in self.descriptions { if unknownDescription is String { properties.append(unknownDescription) continue } guard let description = unknownDescription as? NSExpressionDescription else { throw CoreDataError("Can not resolve property \(unknownDescription)") } guard description.expressionResultType == .undefinedAttributeType else { properties.append(description) continue } let expression = description.expression! switch expression.expressionType { case .keyPath: properties.append(expression.keyPath) case .function: guard let argument = expression.arguments?.first, argument.expressionType == .keyPath else { throw CoreDataError("Can not resolve function result type unless its argument is key path: \(expression)") } description.expressionResultType = try keyPathResultType(argument.keyPath, entity: entity) properties.append(description) default: throw CoreDataError("Can not resolve result type of expression: \(expression)") } } return properties } } public func | (lhs: CoreDataSelect, rhs: CoreDataSelect) -> CoreDataSelect { return CoreDataSelect(lhs.descriptions + rhs.descriptions) } //--------------------------------------------------------------------------- public struct CoreDataOrderBy { let descriptors: [NSSortDescriptor] fileprivate init(_ descriptor: NSSortDescriptor) { self.descriptors = [ descriptor ] } fileprivate init(_ descriptors: [NSSortDescriptor]) { self.descriptors = descriptors } public static func Ascending(_ key: String) -> CoreDataOrderBy { return CoreDataOrderBy(NSSortDescriptor(key: key, ascending: true)) } public static func Ascending(_ key: String, selector: Selector) -> CoreDataOrderBy { return CoreDataOrderBy(NSSortDescriptor(key: key, ascending: true, selector: selector)) } public static func Descending(_ key: String) -> CoreDataOrderBy { return CoreDataOrderBy(NSSortDescriptor(key: key, ascending: false)) } public static func Descending(_ key: String, selector: Selector) -> CoreDataOrderBy { return CoreDataOrderBy(NSSortDescriptor(key: key, ascending: false, selector: selector)) } public static func Sort(_ descriptor: NSSortDescriptor) -> CoreDataOrderBy { return CoreDataOrderBy(descriptor) } } public func | (lhs: CoreDataOrderBy, rhs: CoreDataOrderBy) -> CoreDataOrderBy { return CoreDataOrderBy(lhs.descriptors + rhs.descriptors) } //--------------------------------------------------------------------------- public enum CoreDataQueryOptions { case noSubEntities case noPendingChanges case noPropertyValues case limit(Int) case offset(Int) case batch(Int) case prefetch([String]) case propertiesOnly([String]) case distinct case tweak((Any) -> Void) case multiple([CoreDataQueryOptions]) fileprivate var options: [CoreDataQueryOptions] { switch self { case let .multiple(list): return list default: return [ self ] } } func apply<T: NSFetchRequestResult>(_ request: NSFetchRequest<T>) throws { switch self { case .noSubEntities: request.includesSubentities = false case .noPendingChanges: request.includesPendingChanges = false case .noPropertyValues: request.includesPropertyValues = false case let .limit(limit): request.fetchLimit = limit case let .offset(offset): request.fetchOffset = offset case let .batch(size): request.fetchBatchSize = size case let .prefetch(keys): request.relationshipKeyPathsForPrefetching = keys case let .propertiesOnly(keys): if request.resultType == .managedObjectResultType { request.propertiesToFetch = keys } case .distinct: request.returnsDistinctResults = true case let .tweak(tweak): tweak(request) case let .multiple(list): for option in list { try option.apply(request) } } } } public func | (lhs: CoreDataQueryOptions, rhs: CoreDataQueryOptions) -> CoreDataQueryOptions { return .multiple(lhs.options + rhs.options) }
c85811562c1d25ba775f32cecd933e91
33.307512
126
0.62258
false
false
false
false
netguru/ResponseDetective
refs/heads/develop
ResponseDetective/Tests/Specs/ResponseDetectiveSpec.swift
mit
1
// // ResponseDetectiveSpec.swift // // Copyright © 2016-2020 Netguru S.A. All rights reserved. // Licensed under the MIT License. // import Foundation import Nimble import OHHTTPStubs import ResponseDetective import Quick internal final class ResponseDetectiveSpec: QuickSpec { override func spec() { describe("ResponseDetective") { beforeSuite { stub(condition: isHost("httpbin.org")) { _ in return HTTPStubsResponse(data: Data(), statusCode: 200, headers: nil) } } beforeEach { ResponseDetective.reset() } afterSuite { HTTPStubs.removeAllStubs() } describe("initial state") { it("should use default output facility") { expect(type(of: ResponseDetective.outputFacility) == ConsoleOutputFacility.self).to(beTruthy()) } it("should use default url protocol class") { expect(ResponseDetective.URLProtocolClass).to(beIdenticalTo(NSClassFromString("RDTURLProtocol")!)) } } describe("enabling in url session configuration") { let configuration = URLSessionConfiguration.default beforeEach { ResponseDetective.enable(inConfiguration: configuration) } it("should add protocol class at the beginning of array") { expect(configuration.protocolClasses!.first == ResponseDetective.URLProtocolClass).to(beTrue()) } } describe("ignoring requests") { let request = URLRequest(url: URL(string: "http://foo.bar")!) context("before adding predicate") { it("should not ignore the request") { expect { ResponseDetective.canIncercept(request: request) }.to(beTruthy()) } } context("after adding predicate") { beforeEach { ResponseDetective.ignoreRequests(matchingPredicate: NSPredicate { subject, _ in guard let subject = subject as? URLRequest, let url = subject.url else { return true } let string = url.absoluteString return string.contains("foo") }) } it("should ignore the request") { expect { ResponseDetective.canIncercept(request: request) }.to(beFalsy()) } } } describe("body deserialization") { context("before registering a custom body deserializer") { it("should return no deserialized body") { expect { ResponseDetective.deserialize(body: Data(), contentType: "foo/bar") }.to(beNil()) } } context("after registering an explicit body deserializer") { beforeEach { ResponseDetective.registerBodyDeserializer( TestBodyDeserializer(fixedDeserializedBody: "lorem ipsum"), forContentType: "foo/bar" ) } it("should return a deserialized body") { expect { ResponseDetective.deserialize(body: Data(), contentType: "foo/bar") }.to(equal("lorem ipsum")) } it("should return a deserialized body for content type containing properties") { expect { ResponseDetective.deserialize(body: Data(), contentType: "foo/bar; charset=utf8") }.to(equal("lorem ipsum")) } } context("after registering a wildcard body deserializer") { beforeEach { ResponseDetective.registerBodyDeserializer( TestBodyDeserializer(fixedDeserializedBody: "dolor sit amet"), forContentType: "foo/*" ) } it("should return a deserialized body") { expect { ResponseDetective.deserialize(body: Data(), contentType: "foo/baz") }.to(equal("dolor sit amet")) } } } describe("request interception") { let buffer = BufferOutputFacility() let configuration = URLSessionConfiguration.default beforeEach { ResponseDetective.outputFacility = buffer ResponseDetective.registerBodyDeserializer(TestBodyDeserializer(), forContentType: "*/*") ResponseDetective.enable(inConfiguration: configuration) } context("before request has been sent") { it("should intercept no requests") { expect(buffer.requestRepresentations).to(beEmpty()) } } context("after request has been sent") { let request: URLRequest = { var request = URLRequest(url: URL(string: "https://httpbin.org/post")!) request.httpMethod = "POST" request.httpBody = Data(base64Encoded: "foo", options: []) return request }() beforeEach { let session = URLSession(configuration: configuration) session.dataTask(with: request).resume() } it("should eventually intercept it") { expect(buffer.requestRepresentations.count).toEventually(beGreaterThanOrEqualTo(1), timeout: .seconds(5)) expect(buffer.responseRepresentations.last?.body).toEventuallyNot(beNil(), timeout: .seconds(5)) } } } describe("response interception") { let buffer = BufferOutputFacility() let configuration = URLSessionConfiguration.default beforeEach { ResponseDetective.outputFacility = buffer ResponseDetective.registerBodyDeserializer(TestBodyDeserializer(), forContentType: "*/*") ResponseDetective.enable(inConfiguration: configuration) } context("before request has been sent") { it("should intercept no responses") { expect(buffer.responseRepresentations).to(beEmpty()) } } context("after request has been sent") { let request = URLRequest(url: URL(string: "https://httpbin.org/get")!) beforeEach { let session = URLSession(configuration: configuration) session.dataTask(with: request).resume() } it("should eventually intercept its response") { expect(buffer.responseRepresentations.count).toEventually(beGreaterThanOrEqualTo(1), timeout: .seconds(5)) } } } describe("error interception") { let buffer = BufferOutputFacility() let configuration = URLSessionConfiguration.default beforeEach { ResponseDetective.outputFacility = buffer ResponseDetective.registerBodyDeserializer(TestBodyDeserializer(), forContentType: "*/*") ResponseDetective.enable(inConfiguration: configuration) } context("before request has been sent") { it("should intercept no errors") { expect(buffer.responseRepresentations).to(beEmpty()) } } context("after request has been sent") { let request = URLRequest(url: URL(string: "https://foobar")!) beforeEach { let session = URLSession(configuration: configuration) session.dataTask(with: request).resume() } it("should eventually intercept its error") { expect(buffer.errorRepresentations.count).toEventually(beGreaterThanOrEqualTo(1), timeout: .seconds(5)) } } } } } }
feb9789d4c8dad5dbe6d4ee8fec2144c
23.836431
112
0.66966
false
true
false
false
GYLibrary/GPRS
refs/heads/master
OznerGPRS/NetWork/GYNetWorking.swift
mit
1
// // GYNetWorking.swift // GYHelpToolsSwift // // Created by ZGY on 2017/4/12. // Copyright © 2017年 Giant. All rights reserved. // // Author: Airfight // My GitHub: https://github.com/airfight // My Blog: http://airfight.github.io/ // My Jane book: http://www.jianshu.com/users/17d6a01e3361 // Current Time: 2017/4/12 16:53 // GiantForJade: Efforts to do my best // Real developers ship. import UIKit import Alamofire public func Print<T>(_ message: T,file: String = #file,method: String = #function, line: Int = #line) { #if DEBUG print("\((file as NSString).lastPathComponent)[\(line)], \(method): \(message)") #endif } typealias AlamofireManager = Alamofire.SessionManager enum GYNetWorkStatus { /// 未知网络 case UnKnown /// 无网络 case NotReachable /// 手机网络 case ReachableViaWWAN /// WIFI case ReachableViaWiFi } enum GYRequestSerializer { /// Json格式 case Json /// 二进制格式 case Http } typealias GYHttpRequestSuccess = (AnyObject) -> Void typealias GYHttpRequestFailed = (Error) -> Void typealias GYAlamofireResponse = (DataResponse<Any>) -> Void typealias GYNetWorkState = (GYNetWorkStatus) -> Void class GYNetWorking{ static let `default`: GYNetWorking = GYNetWorking() /// 网络监听 let manager = NetworkReachabilityManager(host: "www.baidu.com") var alldataRequestTask:NSMutableDictionary = NSMutableDictionary() /// 是否只接受第一次请求 默认只接受第一次请求 var isRequest: Bool = true } // MARK: - 获取当前网络状态 extension GYNetWorking { func netWorkStatusWithBlock(_ block: @escaping GYNetWorkState) { manager?.startListening() manager?.listener = { status in switch status { case .unknown: block(.UnKnown) case .notReachable: DispatchQueue.main.async { appDelegate.window?.noticeOnlyText("无网络") } block(.NotReachable) case .reachable(.ethernetOrWiFi): block(.ReachableViaWiFi) case .reachable(.wwan): block(.ReachableViaWWAN) } } } fileprivate func isReachable() -> Bool{ return (manager?.isReachable)! } fileprivate func isWWANetwork() -> Bool { return (manager?.isReachableOnWWAN)! } fileprivate func isWiFiNetwork() -> Bool { return (manager?.isReachableOnEthernetOrWiFi)! } } // MARK: - 网络请求 extension GYNetWorking { /// 自动校验 返回Json格式 /// /// - Parameters: /// - urlRequest: urlRequest description /// - sucess: sucess description /// - failure: failure description func requestJson(_ urlRequest: URLRequestConvertible, sucess:@escaping GYHttpRequestSuccess,failure: @escaping GYHttpRequestFailed) { if !GYNetWorking.default.isReachable() { DispatchQueue.main.async { appDelegate.window?.noticeOnlyText("无网络") } // return } let hud = appDelegate.window?.pleaseWait() Print(urlRequest.urlRequest) let responseJSON: (DataResponse<Any>) -> Void = { [weak self] (response:DataResponse<Any>) in hud?.hide() if let value = urlRequest.urlRequest?.url?.absoluteString { // sleep(3) self?.alldataRequestTask.removeObject(forKey: value) } self?.handleResponse(response, sucess: sucess, failure: failure) } let task = alldataRequestTask.value(forKey: (urlRequest.urlRequest?.url?.absoluteString)!) as? DataRequest guard isRequest && (task == nil) else { return } task?.cancel() let manager = AlamofireManager.default // 此处设置超时无效 // manager.session.configuration.timeoutIntervalForRequest = 3 let dataRequest = manager.request(urlRequest) .responseJSON(completionHandler: responseJSON) alldataRequestTask.setValue(dataRequest, forKey: (urlRequest.urlRequest?.url?.absoluteString)!) } func requesttext(_ urlRequest: URLRequestConvertible, sucess:@escaping GYHttpRequestSuccess,failure: @escaping GYHttpRequestFailed) { if !GYNetWorking.default.isReachable() { DispatchQueue.main.async { appDelegate.window?.noticeOnlyText("无网络") } // return } let hud = appDelegate.window?.pleaseWait() Print(urlRequest.urlRequest) let responseJSON: (DataResponse<String>) -> Void = { [weak self] (response:DataResponse<String>) in hud?.hide() if let value = urlRequest.urlRequest?.url?.absoluteString { // sleep(3) self?.alldataRequestTask.removeObject(forKey: value) } self?.handle(response, sucess: sucess, failure: failure) } let task = alldataRequestTask.value(forKey: (urlRequest.urlRequest?.url?.absoluteString)!) as? DataRequest guard isRequest && (task == nil) else { return } task?.cancel() let manager = AlamofireManager.default // 此处设置超时无效 // manager.session.configuration.timeoutIntervalForRequest = 3 let dataRequest = manager.request(urlRequest) .validate(contentType: ["text/html"]) .responseString(completionHandler: responseJSON) alldataRequestTask.setValue(dataRequest, forKey: (urlRequest.urlRequest?.url?.absoluteString)!) } } // MARK: - 处理请求结果 extension GYNetWorking { fileprivate func handle(_ response: DataResponse<String> ,sucess:@escaping GYHttpRequestSuccess,failure: @escaping GYHttpRequestFailed) { if let _ = response.result.value { switch response.result { case .success(let value): sucess(value as AnyObject) break case .failure(let error): failure(error) default: break } } } /// 处理请求结果 (根据项目需求修改) /// /// - Parameters: /// - response: response description /// - sucess: sucess description /// - failure: failure description fileprivate func handleResponse(_ response: DataResponse<Any> ,sucess:@escaping GYHttpRequestSuccess,failure: @escaping GYHttpRequestFailed) { if let _ = response.result.value { switch response.result { case .success(let json): // var result = json as! [String:AnyObject] // Print(json) // guard let code = result["status"] as? NSInteger else { // return // } // if code > 0 { sucess(json as AnyObject) // } else { // // var str = result["msg"] as? String ?? "未知错误" // // if code == -10002 { // str = "服务器异常" // } // // let errorString = str // let userInfo = [NSLocalizedDescriptionKey:errorString] // let error: NSError = NSError(domain: errorString, code: code, userInfo: userInfo) // // // DispatchQueue.main.async { // if errorString == "该用户未填写详细信息" { // // } else { // // appDelegate.window?.noticeOnlyText(errorString) // // } // // } // failure(error) // } case .failure(let error): failure(error) } } else { DispatchQueue.main.async { if response.result.debugDescription.contains("Code=-1001") { appDelegate.window?.noticeOnlyText("请求超时") } else { Print(response.value) } // response.result Print(response.result.error?.localizedDescription) if response.result.error != nil { failure(response.result.error!) } } } } }
30959095761bae73fcb128d2f4a23225
27.908197
146
0.528184
false
false
false
false
LeeShiYoung/DouYu
refs/heads/master
DouYuAPP/DouYuAPP/Classes/Home/Controller/Yo_GameViewController.swift
apache-2.0
1
// // Yo_GameViewController.swift // DouYuAPP // // Created by shying li on 2017/3/28. // Copyright © 2017年 李世洋. All rights reserved. // import UIKit class Yo_GameViewController: GenericViewController<Yo_GameContentView> { override func viewDidLoad() { super.viewDidLoad() contentView.setupUI() loadGameData() commonGameViewModel.registerCell {[weak self] () -> (listView: UICollectionView, cell: [String : UICollectionViewCell.Type]) in return ((self?.contentView.commonGameView)!, [CommonGameViewCell: Yo_CommonGameViewCell.self]) } allGameViewModel.registerReusableView(Kind: UICollectionElementKindSectionHeader) {[weak self] () -> (listView: UICollectionView, view: [String : UIView.Type]) in return ((self?.contentView.allGameView)!, [AllGameHeaderView: Yo_BaseSectionHeaderView.self]) } allGameViewModel.registerCell {[weak self] () -> (listView: UICollectionView, cell: [String : UICollectionViewCell.Type]) in return ((self?.contentView.allGameView)!, [AllGameViewCellID: Yo_AllGameViewCell.self]) } } fileprivate lazy var gameViewModel = Yo_GameViewModel() fileprivate lazy var commonGameViewModel: Yo_CommonGameCollectionViewModel = {[weak self] in let commonGameViewModel = Yo_CommonGameCollectionViewModel(sourceView: (self?.contentView.commonGameView)!) return commonGameViewModel }() fileprivate lazy var allGameViewModel: Yo_AllGameCollectionViewModel = {[weak self] in let allGameViewModel = Yo_AllGameCollectionViewModel(sourceView: (self?.contentView.allGameView)!) return allGameViewModel }() } extension Yo_GameViewController { fileprivate func loadGameData() { gameViewModel.loadGameData { (commonGame, allGame) in self.commonGameViewModel.set(DataSource: { () -> [Yo_GameModel] in return commonGame }, completion: { self.contentView.commonGameView.reloadData() }) self.allGameViewModel.set(DataSource: { () -> [Yo_GameModel] in return allGame }, completion: { self.contentView.allGameView.reloadData() }) } } }
c140f0bcb6f9df8dd77fe92b5bb03b2a
36.09375
170
0.640691
false
false
false
false
Mykhailo-Vorontsov-owo/OfflineCommute
refs/heads/master
OfflineCommute/Sources/Controllers/SyncOperations/UpdateDistanceSyncOperation.swift
mit
1
// // UpdateDistanceSyncOperation.swift // OfflineCommute // // Created by Mykhailo Vorontsov on 27/02/2016. // Copyright © 2016 Mykhailo Vorontsov. All rights reserved. // import UIKit import MapKit import CoreData class UpdateDistanceSyncOperation: DataRetrievalOperation, ManagedObjectRetrievalOperationProtocol { let center:CLLocationCoordinate2D var dataManager: CoreDataManager! init(center:CLLocationCoordinate2D) { self.center = center super.init() } // override func main() { override func parseData() throws { var internalError:ErrorType? = nil let context = dataManager.dataContext context.performBlockAndWait { () -> Void in // Clear old data do { guard let allDocks = try context.executeFetchRequest(NSFetchRequest(entityName: "DockStation")) as? [DockStation] else { return } let location = CLLocation(latitude: self.center.latitude, longitude: self.center.longitude) for dock in allDocks { let dockLocation = CLLocation(latitude:dock.latitude.doubleValue, longitude: dock.longitude.doubleValue) let distance = location.distanceFromLocation(dockLocation) dock.distance = distance } try context.save() } catch { internalError = error } } guard nil == internalError else { throw internalError! } } }
e95e1c95a5160bb7e69e1e68ea9c646a
24.310345
128
0.653951
false
false
false
false
kinetic-fit/sensors-swift
refs/heads/master
Sources/SwiftySensors/Sensor.swift
mit
1
// // Sensor.swift // SwiftySensors // // https://github.com/kinetic-fit/sensors-swift // // Copyright © 2017 Kinetic. All rights reserved. // import CoreBluetooth import Signals /** Sensor wraps a CoreBluetooth Peripheral and manages the hierarchy of Services and Characteristics. */ open class Sensor: NSObject { // Internal Constructor. SensorManager manages the instantiation and destruction of Sensor objects /// :nodoc: required public init(peripheral: CBPeripheral, advertisements: [CBUUID] = []) { self.peripheral = peripheral self.advertisements = advertisements super.init() peripheral.delegate = self peripheral.addObserver(self, forKeyPath: "state", options: [.new, .old], context: &myContext) } deinit { peripheral.removeObserver(self, forKeyPath: "state") peripheral.delegate = nil rssiPingTimer?.invalidate() } /// Backing CoreBluetooth Peripheral public let peripheral: CBPeripheral /// Discovered Services public fileprivate(set) var services = Dictionary<String, Service>() /// Advertised UUIDs public let advertisements: [CBUUID] /// Raw Advertisement Data public internal(set) var advertisementData: [String: Any]? { didSet { onAdvertisementDataUpdated => advertisementData } } /// Advertisement Data Changed Signal public let onAdvertisementDataUpdated = Signal<([String: Any]?)>() /// Name Changed Signal public let onNameChanged = Signal<Sensor>() /// State Changed Signal public let onStateChanged = Signal<Sensor>() /// Service Discovered Signal public let onServiceDiscovered = Signal<(Sensor, Service)>() /// Service Features Identified Signal public let onServiceFeaturesIdentified = Signal<(Sensor, Service)>() /// Characteristic Discovered Signal public let onCharacteristicDiscovered = Signal<(Sensor, Characteristic)>() /// Characteristic Value Updated Signal public let onCharacteristicValueUpdated = Signal<(Sensor, Characteristic)>() /// Characteristic Value Written Signal public let onCharacteristicValueWritten = Signal<(Sensor, Characteristic)>() /// RSSI Changed Signal public let onRSSIChanged = Signal<(Sensor, Int)>() /// Most recent RSSI value public internal(set) var rssi: Int = Int.min { didSet { onRSSIChanged => (self, rssi) } } /// Last time of Sensor Communication with the Sensor Manager (Time Interval since Reference Date) public fileprivate(set) var lastSensorActivity = Date.timeIntervalSinceReferenceDate /** Get a service by its UUID or by Type - parameter uuid: UUID string - returns: Service */ public func service<T: Service>(_ uuid: String? = nil) -> T? { if let uuid = uuid { return services[uuid] as? T } for service in services.values { if let s = service as? T { return s } } return nil } /** Check if a Sensor advertised a specific UUID Service - parameter uuid: UUID string - returns: `true` if the sensor advertised the `uuid` service */ open func advertisedService(_ uuid: String) -> Bool { let service = CBUUID(string: uuid) for advertisement in advertisements { if advertisement.isEqual(service) { return true } } return false } ////////////////////////////////////////////////////////////////// // Private / Internal Classes, Properties and Constants ////////////////////////////////////////////////////////////////// internal weak var serviceFactory: SensorManager.ServiceFactory? private var rssiPingTimer: Timer? private var myContext = 0 /// :nodoc: override open func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) { if context == &myContext { if keyPath == "state" { peripheralStateChanged() } } else { super.observeValue(forKeyPath: keyPath, of: object, change: change, context: context) } } fileprivate var rssiPingEnabled: Bool = false { didSet { if rssiPingEnabled { if rssiPingTimer == nil { rssiPingTimer = Timer.scheduledTimer(timeInterval: SensorManager.RSSIPingInterval, target: self, selector: #selector(Sensor.rssiPingTimerHandler), userInfo: nil, repeats: true) } } else { rssi = Int.min rssiPingTimer?.invalidate() rssiPingTimer = nil } } } } // Private Funtions extension Sensor { fileprivate func peripheralStateChanged() { switch peripheral.state { case .connected: rssiPingEnabled = true case .connecting: break case .disconnected: fallthrough default: rssiPingEnabled = false services.removeAll() } SensorManager.logSensorMessage?("Sensor: peripheralStateChanged: \(peripheral.state.rawValue)") onStateChanged => self } fileprivate func serviceDiscovered(_ cbs: CBService) { if let service = services[cbs.uuid.uuidString], service.cbService == cbs { return } if let ServiceType = serviceFactory?.serviceTypes[cbs.uuid.uuidString] { let service = ServiceType.init(sensor: self, cbs: cbs) services[cbs.uuid.uuidString] = service onServiceDiscovered => (self, service) SensorManager.logSensorMessage?("Sensor: Service Created: \(service)") if let sp = service as? ServiceProtocol { let charUUIDs: [CBUUID] = type(of: sp).characteristicTypes.keys.map { uuid in return CBUUID(string: uuid) } peripheral.discoverCharacteristics(charUUIDs.count > 0 ? charUUIDs : nil, for: cbs) } } else { SensorManager.logSensorMessage?("Sensor: Service Ignored: \(cbs)") } } fileprivate func characteristicDiscovered(_ cbc: CBCharacteristic, cbs: CBService) { guard let service = services[cbs.uuid.uuidString] else { return } if let characteristic = service.characteristic(cbc.uuid.uuidString), characteristic.cbCharacteristic == cbc { return } guard let sp = service as? ServiceProtocol else { return } if let CharType = type(of: sp).characteristicTypes[cbc.uuid.uuidString] { let characteristic = CharType.init(service: service, cbc: cbc) service.characteristics[cbc.uuid.uuidString] = characteristic characteristic.onValueUpdated.subscribe(with: self) { [weak self] c in if let s = self { s.onCharacteristicValueUpdated => (s, c) } } characteristic.onValueWritten.subscribe(with: self) { [weak self] c in if let s = self { s.onCharacteristicValueWritten => (s, c) } } SensorManager.logSensorMessage?("Sensor: Characteristic Created: \(characteristic)") onCharacteristicDiscovered => (self, characteristic) } else { SensorManager.logSensorMessage?("Sensor: Characteristic Ignored: \(cbc)") } } @objc func rssiPingTimerHandler() { if peripheral.state == .connected { peripheral.readRSSI() } } internal func markSensorActivity() { lastSensorActivity = Date.timeIntervalSinceReferenceDate } } extension Sensor: CBPeripheralDelegate { /// :nodoc: public func peripheralDidUpdateName(_ peripheral: CBPeripheral) { onNameChanged => self markSensorActivity() } /// :nodoc: public func peripheral(_ peripheral: CBPeripheral, didDiscoverServices error: Error?) { guard let cbss = peripheral.services else { return } for cbs in cbss { serviceDiscovered(cbs) } markSensorActivity() } /// :nodoc: public func peripheral(_ peripheral: CBPeripheral, didDiscoverCharacteristicsFor service: CBService, error: Error?) { guard let cbcs = service.characteristics else { return } for cbc in cbcs { characteristicDiscovered(cbc, cbs: service) } markSensorActivity() } /// :nodoc: public func peripheral(_ peripheral: CBPeripheral, didUpdateValueFor characteristic: CBCharacteristic, error: Error?) { guard let service = services[characteristic.service.uuid.uuidString] else { return } guard let char = service.characteristics[characteristic.uuid.uuidString] else { return } if char.cbCharacteristic !== characteristic { char.cbCharacteristic = characteristic } char.valueUpdated() markSensorActivity() } /// :nodoc: public func peripheral(_ peripheral: CBPeripheral, didWriteValueFor characteristic: CBCharacteristic, error: Error?) { guard let service = services[characteristic.service.uuid.uuidString] else { return } guard let char = service.characteristics[characteristic.uuid.uuidString] else { return } if char.cbCharacteristic !== characteristic { char.cbCharacteristic = characteristic } char.valueWritten() markSensorActivity() } /// :nodoc: public func peripheral(_ peripheral: CBPeripheral, didReadRSSI RSSI: NSNumber, error: Error?) { if RSSI.intValue < 0 { rssi = RSSI.intValue markSensorActivity() } } }
b6d116fa0a8c3ea20082df2e0674a994
32.13355
196
0.600767
false
false
false
false
GoogleCloudPlatform/ios-docs-samples
refs/heads/master
translation/swift/Translation/ViewController.swift
apache-2.0
1
// // Copyright 2019 Google 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 UIKit import MaterialComponents import googleapis class ViewController: UIViewController { var appBar = MDCAppBar() // Text Field var inputTextField: MDCTextField = { let textField = MDCTextField() textField.translatesAutoresizingMaskIntoConstraints = false return textField }() var textFieldBottomConstraint: NSLayoutConstraint! let inputTextFieldController: MDCTextInputControllerOutlined var tableViewDataSource = [[String: String]]() @IBOutlet weak var tableView: UITableView! @IBOutlet weak var pickerView: UIPickerView! @IBOutlet weak var pickerBackgroundView: UIView! @IBOutlet weak var pickerSwapButton: UIBarButtonItem! @IBOutlet weak var pickerSourceButton: UIBarButtonItem! @IBOutlet weak var pickerTagerButton: UIBarButtonItem! var sourceLanguageCode = [String]() var targetLanguageCode = [String]() var glossaryList = [Glossary]() var isPickerForLanguage = true //init with nib name override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) { inputTextFieldController = MDCTextInputControllerOutlined(textInput: inputTextField) super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) inputTextFieldController.placeholderText = ApplicationConstants.queryTextFieldPlaceHolder } //init with coder required init?(coder aDecoder: NSCoder) { inputTextFieldController = MDCTextInputControllerOutlined(textInput: inputTextField) super.init(coder: aDecoder) } override func viewDidLoad() { super.viewDidLoad() self.view.tintColor = .black self.view.backgroundColor = ApplicationScheme.shared.colorScheme.surfaceColor self.title = ApplicationConstants.title setUpNavigationBarAndItems() registerKeyboardNotifications() self.view.addSubview(inputTextField) inputTextField.backgroundColor = .white inputTextField.returnKeyType = .send inputTextFieldController.placeholderText = ApplicationConstants.queryTextFieldPlaceHolder inputTextField.delegate = self // Constraints textFieldBottomConstraint = NSLayoutConstraint(item: inputTextField, attribute: .bottom, relatedBy: .equal, toItem: view, attribute: .bottom, multiplier: 1, constant: 0) var constraints = [NSLayoutConstraint]() constraints.append(textFieldBottomConstraint) constraints.append(contentsOf: NSLayoutConstraint.constraints(withVisualFormat: "H:|-[intentTF]-|", options: [], metrics: nil, views: [ "intentTF" : inputTextField])) NSLayoutConstraint.activate(constraints) let colorScheme = ApplicationScheme.shared.colorScheme MDCTextFieldColorThemer.applySemanticColorScheme(colorScheme, to: self.inputTextFieldController) } @IBAction func dismissKeyboardAction(_ sender:Any) { inputTextField.resignFirstResponder() } @IBAction func reverseLanguagesAction(_ sender: Any) { print("reverseLanguagesAction") let sourceCodeIndex = pickerView.selectedRow(inComponent: 0) let targetCodeIndex = pickerView.selectedRow(inComponent: 1) pickerView.selectRow(targetCodeIndex, inComponent: 0, animated: true) pickerView.selectRow(sourceCodeIndex, inComponent: 1, animated: true) } @IBAction func doneButtonAction(_ sender: Any) { pickerBackgroundView.isHidden = true view.sendSubviewToBack(pickerBackgroundView) if isPickerForLanguage { let sourceCodeIndex = pickerView.selectedRow(inComponent: 0) let targetCodeIndex = pickerView.selectedRow(inComponent: 1) let sourceCode = sourceLanguageCode[sourceCodeIndex] let targetCode = targetLanguageCode[targetCodeIndex] print("SourceCode = \(sourceCode), TargetCode = \(targetCode)") UserDefaults.standard.set(sourceCode, forKey: ApplicationConstants.sourceLanguageCode) UserDefaults.standard.set(targetCode, forKey: ApplicationConstants.targetLanguageCode) } else { let sourceCodeIndex = pickerView.selectedRow(inComponent: 0) let sourceCode = glossaryList[sourceCodeIndex].name UserDefaults.standard.set(sourceCode, forKey: "SelectedGlossary") } } @IBAction func cancelButtonAction(_ sender: Any) { pickerBackgroundView.isHidden = true view.sendSubviewToBack(pickerBackgroundView) } func setUpNavigationBarAndItems() { //Initialize and add AppBar self.addChild(appBar.headerViewController) appBar.addSubviewsToParent() let barButtonLeadingItem = UIBarButtonItem() barButtonLeadingItem.tintColor = ApplicationScheme.shared.colorScheme.primaryColorVariant barButtonLeadingItem.image = #imageLiteral(resourceName: "baseline_swap_horiz_black_48pt") barButtonLeadingItem.target = self barButtonLeadingItem.action = #selector(presentNavigationDrawer) appBar.navigationBar.backItem = barButtonLeadingItem let rightBarButton = UIBarButtonItem() rightBarButton.tintColor = ApplicationScheme.shared.colorScheme.primaryColorVariant rightBarButton.title = ApplicationConstants.glossaryButton rightBarButton.target = self rightBarButton.action = #selector(glossaryButtonTapped) appBar.navigationBar.rightBarButtonItem = rightBarButton MDCAppBarColorThemer.applySemanticColorScheme(ApplicationScheme.shared.colorScheme, to:self.appBar) } @objc func glossaryButtonTapped() { let glossaryStatus = UserDefaults.standard.bool(forKey: ApplicationConstants.glossaryStatus) let alertVC = UIAlertController(title: ApplicationConstants.glossaryAlertTitle, message: glossaryStatus ? ApplicationConstants.glossaryDisbleAlertMessage : ApplicationConstants.glossaryEnableAlertMessage, preferredStyle: .alert) alertVC.addAction(UIAlertAction(title: glossaryStatus ? ApplicationConstants.glossaryAlerOKDisableTitle : ApplicationConstants.glossaryAlertOKEnableTitle, style: .default, handler: { (_) in UserDefaults.standard.set(!glossaryStatus, forKey: ApplicationConstants.glossaryStatus) if !glossaryStatus { self.getListOfGlossary() } })) if glossaryStatus { alertVC.addAction(UIAlertAction(title: "Choose glossary" , style: .default, handler: {(_) in self.getListOfGlossary() })) } alertVC.addAction(UIAlertAction(title: ApplicationConstants.glossaryAlertCacelTitle, style: .default)) present(alertVC, animated: true) } @objc func presentNavigationDrawer() { // present picker view with languages // self.presentPickerView() TextToTranslationService.sharedInstance.getLanguageCodes { (responseObj, error) in if let errorText = error { self.handleError(error: errorText) return } guard let supportedLanguages = responseObj else {return} if supportedLanguages.languagesArray_Count > 0, let languages = supportedLanguages.languagesArray as? [SupportedLanguage] { self.sourceLanguageCode = languages.filter({return $0.supportSource }).map({ (supportedLanguage) -> String in return supportedLanguage.languageCode }) self.targetLanguageCode = languages.filter({return $0.supportTarget }).map({ (supportedLanguage) -> String in return supportedLanguage.languageCode }) self.isPickerForLanguage = true self.presentPickerView() } } } func getListOfGlossary() { isPickerForLanguage = false TextToTranslationService.sharedInstance.getListOfGlossary { (responseObj, error) in if let errorText = error { self.handleError(error: errorText) return } guard let response = responseObj else {return} print("getListOfGlossary") if let glossaryArray = response.glossariesArray as? [Glossary] { self.glossaryList = glossaryArray self.presentPickerView() } } } func presentPickerView() { pickerBackgroundView.isHidden = false view.bringSubviewToFront(pickerBackgroundView) pickerView.reloadAllComponents() if isPickerForLanguage { pickerSourceButton.title = "Source" pickerSwapButton.image = #imageLiteral(resourceName: "baseline_swap_horiz_black_48pt") pickerTagerButton.title = "Target" guard let sourceCode = UserDefaults.standard.value(forKey: ApplicationConstants.sourceLanguageCode) as? String, let targetCode = UserDefaults.standard.value(forKey: ApplicationConstants.targetLanguageCode) as? String, let sourceIndex = sourceLanguageCode.firstIndex(of: sourceCode), let targetIndex = targetLanguageCode.firstIndex(of: targetCode) else { return } pickerView.selectRow(sourceIndex, inComponent: 0, animated: true) pickerView.selectRow(targetIndex, inComponent: 1, animated: true) } else { pickerSourceButton.title = "List of Glossaries" pickerSwapButton.image = nil pickerTagerButton.title = "" guard let selectedGlossary = UserDefaults.standard.value(forKey: "SelectedGlossary") as? String, let sourceIndex = glossaryList.firstIndex(where: { $0.name == selectedGlossary }) else { return } pickerView.selectRow(sourceIndex, inComponent: 0, animated: true) } } } extension ViewController: UIPickerViewDelegate, UIPickerViewDataSource { func numberOfComponents(in pickerView: UIPickerView) -> Int { return isPickerForLanguage ? 2 : 1 } func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int { return isPickerForLanguage ? max(sourceLanguageCode.count, targetLanguageCode.count) : glossaryList.count } func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? { if isPickerForLanguage { if component == 0 { return sourceLanguageCode.count > row ? sourceLanguageCode[row] : "" } else { return targetLanguageCode.count > row ? targetLanguageCode[row] : "" } } else { return glossaryList.count > row ? (glossaryList[row].name.components(separatedBy: "/").last ?? "") : "" } } } // MARK: - Keyboard Handling extension ViewController { func registerKeyboardNotifications() { NotificationCenter.default.addObserver( self, selector: #selector(self.keyboardWillShow), name: UIResponder.keyboardDidShowNotification, object: nil) NotificationCenter.default.addObserver( self, selector: #selector(self.keyboardWillHide), name: UIResponder.keyboardWillHideNotification, object: nil) } @objc func keyboardWillShow(notification: NSNotification) { let keyboardFrame = (notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as! NSValue).cgRectValue textFieldBottomConstraint.constant = -keyboardFrame.height } @objc func keyboardWillHide(notification: NSNotification) { textFieldBottomConstraint.constant = 0 } } //MARK: Textfield delegate extension ViewController: UITextFieldDelegate { //Captures the query typed by user func textFieldShouldReturn(_ textField: UITextField) -> Bool { textField.resignFirstResponder() if let text = textField.text, text.count > 0 { textToTranslation(text: text) tableViewDataSource.append([ApplicationConstants.selfKey: text]) tableView.insertRows(at: [IndexPath(row: tableViewDataSource.count - 1, section: 0)], with: .automatic) } textField.text = "" return true } func handleError(error: String) { let alertVC = UIAlertController(title: "Error", message: error, preferredStyle: .alert) alertVC.addAction(UIAlertAction(title: "OK", style: .default)) present(alertVC, animated: true) } //start sending text func textToTranslation(text: String) { TextToTranslationService.sharedInstance.textToTranslate(text: text, completionHandler: { (responseObj, error) in if let errorText = error { self.handleError(error: errorText) return } guard let response = responseObj else {return} //Handle success response var responseText = "" if response.glossaryTranslationsArray_Count > 0, let tResponse = response.glossaryTranslationsArray.firstObject as? Translation { responseText = "Glossary: " + tResponse.translatedText + "\n\n" } if response.translationsArray_Count > 0, let tResponse = response.translationsArray.firstObject as? Translation { responseText += ("Translated: " + tResponse.translatedText) } if !responseText.isEmpty { self.tableViewDataSource.append([ApplicationConstants.botKey: responseText]) self.tableView.insertRows(at: [IndexPath(row: self.tableViewDataSource.count - 1, section: 0)], with: .automatic) self.tableView.scrollToBottom() } }) } } // MARK: Table delegate handling extension ViewController: UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return tableViewDataSource.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let data = tableViewDataSource[indexPath.row] let cell = tableView.dequeueReusableCell(withIdentifier: data[ApplicationConstants.selfKey] != nil ? "selfCI" : "intentCI", for: indexPath) as! ChatTableViewCell if data[ApplicationConstants.selfKey] != nil { cell.selfText.text = data[ApplicationConstants.selfKey] } else { cell.botResponseText.text = data[ApplicationConstants.botKey] } return cell } } extension UITableView { func scrollToBottom(animated: Bool = true) { let sections = self.numberOfSections let rows = self.numberOfRows(inSection: sections - 1) if (rows > 0) { self.scrollToRow(at: NSIndexPath(row: rows - 1, section: sections - 1) as IndexPath, at: .bottom, animated: true) } } }
fb686a7faaf75518e2b2ec6a88e1516e
40.416667
232
0.710262
false
false
false
false
vector-im/riot-ios
refs/heads/develop
Riot/Modules/Common/Buttons/Close/RoundedButton.swift
apache-2.0
1
/* Copyright 2020 New Vector Ltd Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ import UIKit final class RoundedButton: UIButton, Themable { // MARK: - Constants private enum Constants { static let backgroundColorAlpha: CGFloat = 0.2 static let cornerRadius: CGFloat = 6.0 static let fontSize: CGFloat = 17.0 } // MARK: - Properties // MARK: Private private var theme: Theme? // MARK: Public var actionStyle: UIAlertAction.Style = .default { didSet { self.updateButtonStyle() } } // MARK: - Life cycle override func awakeFromNib() { super.awakeFromNib() self.layer.masksToBounds = true self.titleLabel?.font = UIFont.systemFont(ofSize: Constants.fontSize) self.update(theme: ThemeService.shared().theme) } override func layoutSubviews() { super.layoutSubviews() self.layer.cornerRadius = Constants.cornerRadius } // MARK: - Private private func updateButtonStyle() { guard let theme = theme else { return } let backgroundColor: UIColor switch self.actionStyle { case .default: backgroundColor = theme.tintColor default: backgroundColor = theme.noticeColor } self.vc_setBackgroundColor(backgroundColor.withAlphaComponent(Constants.backgroundColorAlpha), for: .normal) self.setTitleColor(backgroundColor, for: .normal) } // MARK: - Themable func update(theme: Theme) { self.theme = theme self.updateButtonStyle() } }
60924064e0373a0e53cf432ebddc0395
25.2
116
0.626852
false
false
false
false