repo_name
stringlengths
7
91
path
stringlengths
8
658
copies
stringclasses
125 values
size
stringlengths
3
6
content
stringlengths
118
674k
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
6.09
99.2
line_max
int64
17
995
alpha_frac
float64
0.3
0.9
ratio
float64
2
9.18
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
RevenueCat/purchases-ios
Sources/Identity/CustomerInfoManager.swift
1
10977
// // Copyright RevenueCat Inc. All Rights Reserved. // // Licensed under the MIT License (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://opensource.org/licenses/MIT // // CustomerInfoManager.swift // // Created by Joshua Liebowitz on 8/5/21. import Foundation class CustomerInfoManager { typealias CustomerInfoCompletion = @MainActor @Sendable (Result<CustomerInfo, BackendError>) -> Void private(set) var lastSentCustomerInfo: CustomerInfo? private let operationDispatcher: OperationDispatcher private let deviceCache: DeviceCache private let backend: Backend private let systemInfo: SystemInfo private let customerInfoCacheLock = Lock() init(operationDispatcher: OperationDispatcher, deviceCache: DeviceCache, backend: Backend, systemInfo: SystemInfo) { self.operationDispatcher = operationDispatcher self.deviceCache = deviceCache self.backend = backend self.systemInfo = systemInfo } func fetchAndCacheCustomerInfo(appUserID: String, isAppBackgrounded: Bool, completion: CustomerInfoCompletion?) { self.backend.getCustomerInfo(appUserID: appUserID, withRandomDelay: isAppBackgrounded) { result in switch result { case let .failure(error): self.deviceCache.clearCustomerInfoCacheTimestamp(appUserID: appUserID) Logger.warn(Strings.customerInfo.customerinfo_updated_from_network_error(error)) case let .success(info): self.cache(customerInfo: info, appUserID: appUserID) Logger.rcSuccess(Strings.customerInfo.customerinfo_updated_from_network) } if let completion = completion { self.operationDispatcher.dispatchOnMainActor { completion(result) } } } } func fetchAndCacheCustomerInfoIfStale(appUserID: String, isAppBackgrounded: Bool, completion: CustomerInfoCompletion?) { let cachedCustomerInfo = self.cachedCustomerInfo(appUserID: appUserID) let isCacheStale = self.deviceCache.isCustomerInfoCacheStale(appUserID: appUserID, isAppBackgrounded: isAppBackgrounded) guard !isCacheStale, let customerInfo = cachedCustomerInfo else { Logger.debug(isAppBackgrounded ? Strings.customerInfo.customerinfo_stale_updating_in_background : Strings.customerInfo.customerinfo_stale_updating_in_foreground) self.fetchAndCacheCustomerInfo(appUserID: appUserID, isAppBackgrounded: isAppBackgrounded, completion: completion) return } if let completion = completion { self.operationDispatcher.dispatchOnMainActor { completion(.success(customerInfo)) } } } func sendCachedCustomerInfoIfAvailable(appUserID: String) { guard let info = cachedCustomerInfo(appUserID: appUserID) else { return } sendUpdateIfChanged(customerInfo: info) } func customerInfo( appUserID: String, fetchPolicy: CacheFetchPolicy, completion: CustomerInfoCompletion? ) { switch fetchPolicy { case .fromCacheOnly: self.operationDispatcher.dispatchOnMainActor { completion?( Result(self.cachedCustomerInfo(appUserID: appUserID), .missingCachedCustomerInfo()) ) } case .fetchCurrent: self.systemInfo.isApplicationBackgrounded { isAppBackgrounded in self.fetchAndCacheCustomerInfo(appUserID: appUserID, isAppBackgrounded: isAppBackgrounded, completion: completion) } case .cachedOrFetched: let infoFromCache = self.cachedCustomerInfo(appUserID: appUserID) var completionCalled = false if let infoFromCache = infoFromCache { Logger.debug(Strings.customerInfo.vending_cache) if let completion = completion { completionCalled = true self.operationDispatcher.dispatchOnMainActor { completion(.success(infoFromCache)) } } } // Prevent calling completion twice. let completionIfNotCalledAlready = completionCalled ? nil : completion self.systemInfo.isApplicationBackgrounded { isAppBackgrounded in self.fetchAndCacheCustomerInfoIfStale(appUserID: appUserID, isAppBackgrounded: isAppBackgrounded, completion: completionIfNotCalledAlready) } case .notStaleCachedOrFetched: let infoFromCache = self.cachedCustomerInfo(appUserID: appUserID) self.systemInfo.isApplicationBackgrounded { isAppBackgrounded in let isCacheStale = self.deviceCache.isCustomerInfoCacheStale(appUserID: appUserID, isAppBackgrounded: isAppBackgrounded) if let infoFromCache = infoFromCache, !isCacheStale { Logger.debug(Strings.customerInfo.vending_cache) if let completion = completion { self.operationDispatcher.dispatchOnMainActor { completion(.success(infoFromCache)) } } } else { self.fetchAndCacheCustomerInfo(appUserID: appUserID, isAppBackgrounded: isAppBackgrounded, completion: completion) } } } } func cachedCustomerInfo(appUserID: String) -> CustomerInfo? { guard let customerInfoData = self.deviceCache.cachedCustomerInfoData(appUserID: appUserID) else { return nil } do { let info: CustomerInfo = try JSONDecoder.default.decode(jsonData: customerInfoData) if info.isInCurrentSchemaVersion { return info } else { return nil } } catch { Logger.error("Error loading customer info from cache:\n \(error.localizedDescription)") return nil } } func cache(customerInfo: CustomerInfo, appUserID: String) { do { let jsonData = try JSONEncoder.default.encode(customerInfo) self.deviceCache.cache(customerInfo: jsonData, appUserID: appUserID) self.sendUpdateIfChanged(customerInfo: customerInfo) } catch { Logger.error(Strings.customerInfo.error_encoding_customerinfo(error)) } } func clearCustomerInfoCache(forAppUserID appUserID: String) { self.customerInfoCacheLock.perform { self.deviceCache.clearCustomerInfoCache(appUserID: appUserID) self.lastSentCustomerInfo = nil } } @available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.2, *) var customerInfoStream: AsyncStream<CustomerInfo> { return AsyncStream(bufferingPolicy: .bufferingNewest(1)) { continuation in if let lastSentCustomerInfo = self.lastSentCustomerInfo { continuation.yield(lastSentCustomerInfo) } let disposable = self.monitorChanges { continuation.yield($0) } continuation.onTermination = { @Sendable _ in disposable() } } } /// Observers keyed by a monotonically increasing identifier. /// This allows cancelling observations by deleting them from this dictionary. /// These observers are used both for ``Purchases/customerInfoStream`` and /// `PurchasesDelegate/purchases(_:receivedUpdated:)``. private var customerInfoObserversByIdentifier: [Int: (CustomerInfo) -> Void] = [:] /// Allows monitoring changes to the active `CustomerInfo`. /// - Returns: closure that removes the created observation. /// - Note: this method is not thread-safe. func monitorChanges(_ changes: @escaping (CustomerInfo) -> Void) -> () -> Void { let lastIdentifier = self.customerInfoObserversByIdentifier.keys .sorted() .last let nextIdentifier = lastIdentifier .map { $0 + 1 } // Next index ?? 0 // Or default to 0 self.customerInfoObserversByIdentifier[nextIdentifier] = changes return { [weak self] in self?.customerInfoObserversByIdentifier.removeValue(forKey: nextIdentifier) } } private func sendUpdateIfChanged(customerInfo: CustomerInfo) { self.customerInfoCacheLock.perform { guard !self.customerInfoObserversByIdentifier.isEmpty, self.lastSentCustomerInfo != customerInfo else { return } if lastSentCustomerInfo != nil { Logger.debug(Strings.customerInfo.sending_updated_customerinfo_to_delegate) } else { Logger.debug(Strings.customerInfo.sending_latest_customerinfo_to_delegate) } self.lastSentCustomerInfo = customerInfo self.operationDispatcher.dispatchOnMainThread { [observers = self.customerInfoObserversByIdentifier] in for closure in observers.values { closure(customerInfo) } } } } } extension CustomerInfoManager { @available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.2, *) func customerInfo( appUserID: String, fetchPolicy: CacheFetchPolicy ) async throws -> CustomerInfo { return try await withCheckedThrowingContinuation { continuation in return self.customerInfo(appUserID: appUserID, fetchPolicy: fetchPolicy, completion: { @Sendable in continuation.resume(with: $0) }) } } } // @unchecked because: // - Class is not `final` (it's mocked). This implicitly makes subclasses `Sendable` even if they're not thread-safe. // - It has mutable state, but it's made thread-safe through `customerInfoCacheLock`. extension CustomerInfoManager: @unchecked Sendable {}
mit
4b12ae5b43169e4eb6ec776fa87cb972
38.916364
117
0.595609
5.771293
false
false
false
false
lxian/Fuzzywuzzy_swift
Fuzzywuzzy_swift/StringMatcher.swift
1
761
// // StringMatcher.swift // Fuzzywuzzy_swift // // Created by XianLi on 30/8/2016. // Copyright © 2016 LiXian. All rights reserved. // import UIKit class StringMatcher: NSObject { let str1: String let str2: String lazy var levenshteinDistance: Int = LevenshteinDistance.distance(str1: self.str1, str2: self.str2) lazy var commonSubStringPairs: [CommonSubstringPair] = CommonSubstrings.pairs(str1: self.str1, str2: self.str2) init(str1: String, str2: String) { self.str1 = str1 self.str2 = str2 super.init() } func fuzzRatio() -> Float { let lenSum = (str1.count + str2.count) if lenSum == 0 { return 1 } return Float(lenSum - levenshteinDistance) / Float(lenSum) } }
mit
6d465c28bc9235622b8d8b85d661509d
22.75
115
0.647368
3.348018
false
false
false
false
LiuDeng/FYIM
FYIM/Module/Message/Controller/MainTableViewController.swift
2
3049
// // MainTableViewController.swift // FYIM // // Created by dai.fengyi on 15/7/17. // Copyright (c) 2015年 childrenOurFuture. All rights reserved. // import UIKit class MainTableViewController: UITableViewController { override func viewDidLoad() { super.viewDidLoad() // Uncomment the following line to preserve selection between presentations // self.clearsSelectionOnViewWillAppear = false // Uncomment the following line to display an Edit button in the navigation bar for this view controller. // self.navigationItem.rightBarButtonItem = self.editButtonItem() } // MARK: - Table view data source override func numberOfSectionsInTableView(tableView: UITableView) -> Int { // #warning Potentially incomplete method implementation. // Return the number of sections. return 0 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // #warning Incomplete method implementation. // Return the number of rows in the section. return 0 } /* override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("reuseIdentifier", forIndexPath: indexPath) as! UITableViewCell // Configure the cell... return cell } */ /* // Override to support conditional editing of the table view. override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return NO 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 NO 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. } */ }
mit
c1f131fe40034fb53cdbb9e88a11aa21
32.119565
155
0.713817
5.271626
false
false
false
false
wowiwj/Yeep
Yeep/Yeep/Services/YeepServiceSync.swift
1
22917
// // YeepServiceSync.swift // Yeep // // Created by wangju on 16/7/20. // Copyright © 2016年 wangju. All rights reserved. // import UIKit import RealmSwift func getOrCreateUserWithDiscoverUser(discoveredUser: DiscoveredUser, inRealm realm: Realm) -> User? { var user = userWithUserID(discoveredUser.id, inRealm: realm) if user == nil { let newUser = User() newUser.userID = discoveredUser.id newUser.friendState = UserFriendState.Stranger.rawValue realm.add(newUser) user = newUser } if let user = user { // 只更新用户信息即可 user.lastSignInUnixTime = discoveredUser.lastSignInUnixTime user.username = discoveredUser.username ?? "" user.nickname = discoveredUser.nickname if let introduction = discoveredUser.introduction { user.introduction = introduction } user.avatarURLString = discoveredUser.avatarURLString user.longitude = discoveredUser.longitude user.latitude = discoveredUser.latitude if let badge = discoveredUser.badge { user.badge = badge } if let blogURLString = discoveredUser.blogURLString { user.blogURLString = blogURLString } } return user } func userSkillsFromSkillsData(skillsData: [JSONDictionary], inRealm realm: Realm) -> [UserSkill] { var userSkills = [UserSkill]() for skillInfo in skillsData { if let skillID = skillInfo["id"] as? String, skillName = skillInfo["name"] as? String, skillLocalName = skillInfo["name_string"] as? String { var userSkill = userSkillWithSkillID(skillID, inRealm: realm) if userSkill == nil { let newUserSkill = UserSkill() newUserSkill.skillID = skillID realm.add(newUserSkill) userSkill = newUserSkill } if let userSkill = userSkill { // create or update detail userSkill.name = skillName userSkill.localName = skillLocalName if let coverURLString = skillInfo["cover_url"] as? String { userSkill.coverURLString = coverURLString } if let categoryData = skillInfo["category"] as? JSONDictionary, skillCategoryID = categoryData["id"] as? String, skillCategoryName = categoryData["name"] as? String, skillCategoryLocalName = categoryData["name_string"] as? String { var userSkillCategory = userSkillCategoryWithSkillCategoryID(skillCategoryID, inRealm: realm) if userSkillCategory == nil { let newUserSkillCategory = UserSkillCategory() newUserSkillCategory.skillCategoryID = skillCategoryID newUserSkillCategory.name = skillCategoryName newUserSkillCategory.localName = skillCategoryLocalName realm.add(newUserSkillCategory) userSkillCategory = newUserSkillCategory } if let userSkillCategory = userSkillCategory { userSkill.category = userSkillCategory } } userSkills.append(userSkill) } } } return userSkills } func userSocialAccountProvidersFromSocialAccountProviders(socialAccountProviders: [DiscoveredUser.SocialAccountProvider]) -> [UserSocialAccountProvider] { return socialAccountProviders.map({ _provider -> UserSocialAccountProvider in let provider = UserSocialAccountProvider() provider.name = _provider.name provider.enabled = _provider.enabled return provider }) } func userSkillsFromSkills(skills: [Skill], inRealm realm: Realm) -> [UserSkill] { return skills.map({ skill -> UserSkill? in let skillID = skill.id var userSkill = userSkillWithSkillID(skillID, inRealm: realm) if userSkill == nil { let newUserSkill = UserSkill() newUserSkill.skillID = skillID realm.add(newUserSkill) userSkill = newUserSkill } if let userSkill = userSkill { // create or update detail userSkill.name = skill.name userSkill.localName = skill.localName if let coverURLString = skill.coverURLString { userSkill.coverURLString = coverURLString } if let skillCategory = skill.category, skillCategoryID = skill.category?.id { var userSkillCategory = userSkillCategoryWithSkillCategoryID(skillCategoryID, inRealm: realm) if userSkillCategory == nil { let newUserSkillCategory = UserSkillCategory() newUserSkillCategory.skillCategoryID = skillCategoryID newUserSkillCategory.name = skillCategory.name newUserSkillCategory.localName = skillCategory.localName realm.add(newUserSkillCategory) userSkillCategory = newUserSkillCategory } if let userSkillCategory = userSkillCategory { userSkill.category = userSkillCategory } } } return userSkill }).filter({ $0 != nil }).map({ skill in skill! }) } /// 同步用户信息 func syncMyInfoAndDoFurtherAction(furtherAction: () -> Void) { userInfo(failureHandler: { (reason, errorMessage) in defaultFailureHandler(reason: reason, errorMessage: errorMessage) furtherAction() }) { friendInfo in print("my userInfo: \(friendInfo)") dispatch_async(realmQueue) { if let myUserID = YeepUserDefaults.userID.value { guard let realm = try? Realm() else { return } var me = userWithUserID(myUserID, inRealm: realm) if me == nil { let newUser = User() newUser.userID = myUserID newUser.friendState = UserFriendState.Me.rawValue if let createdUnixTime = friendInfo["created_at"] as? NSTimeInterval { newUser.createdUnixTime = createdUnixTime } let _ = try? realm.write { realm.add(newUser) } me = newUser } if let user = me { // 更新用户信息 let _ = try? realm.write { updateUserWithUserID(user.userID, useUserInfo: friendInfo, inRealm: realm) } if let fromString = friendInfo["mute_started_at_string"] as? String, toString = friendInfo["mute_ended_at_string"] as? String { if !fromString.isEmpty && !toString.isEmpty { var userDoNotDisturb = user.doNotDisturb if userDoNotDisturb == nil { let _userDoNotDisturb = UserDoNotDisturb() _userDoNotDisturb.isOn = true let _ = try? realm.write { user.doNotDisturb = _userDoNotDisturb } userDoNotDisturb = _userDoNotDisturb } if let userDoNotDisturb = userDoNotDisturb { let convert: (Int, Int) -> (Int, Int) = { serverHour, serverMinute in let localHour: Int let localMinute: Int if serverMinute + userDoNotDisturb.minuteOffset >= 60 { localHour = (serverHour + userDoNotDisturb.hourOffset + 1) % 24 } else { localHour = (serverHour + userDoNotDisturb.hourOffset) % 24 } localMinute = (serverMinute + userDoNotDisturb.minuteOffset) % 60 return (localHour, localMinute) } let _ = try? realm.write { let fromParts = fromString.componentsSeparatedByString(":") if let fromHourString = fromParts[safe: 0], fromHour = Int(fromHourString), fromMinuteString = fromParts[safe: 1], fromMinute = Int(fromMinuteString) { (userDoNotDisturb.fromHour, userDoNotDisturb.fromMinute) = convert(fromHour, fromMinute) } let toParts = toString.componentsSeparatedByString(":") if let toHourString = toParts[safe: 0], toHour = Int(toHourString), toMinuteString = toParts[safe: 1], toMinute = Int(toMinuteString) { (userDoNotDisturb.toHour, userDoNotDisturb.toMinute) = convert(toHour, toMinute) } } } }else { if let userDoNotDisturb = user.doNotDisturb { realm.delete(userDoNotDisturb) } } } // also save some infomation in YepUserDefaults if let nickname = friendInfo["nickname"] as? String { YeepUserDefaults.nickname.value = nickname } if let introduction = friendInfo["introduction"] as? String where !introduction.isEmpty { YeepUserDefaults.introduction.value = introduction } if let avatarInfo = friendInfo["avatar"] as? JSONDictionary, avatarURLString = avatarInfo["url"] as? String { YeepUserDefaults.avatarURLString.value = avatarURLString } if let badge = friendInfo["badge"] as? String { YeepUserDefaults.badge.value = badge } if let blogURLString = friendInfo["website_url"] as? String where !blogURLString.isEmpty { YeepUserDefaults.blogURLString.value = blogURLString } if let blogTitle = friendInfo["website_title"] as? String where !blogTitle.isEmpty { YeepUserDefaults.blogTitle.value = blogTitle } if let areaCode = friendInfo["phone_code"] as? String { YeepUserDefaults.areaCode.value = areaCode } if let mobile = friendInfo["mobile"] as? String { YeepUserDefaults.mobile.value = mobile } } } furtherAction() } } } var isFetchingUnreadMessages = Listenable<Bool>(false) { _ in } /// 同步消息数据 func syncMyConversations(maxMessageID maxMessageID: String? = nil) { myConversations(maxMessageID: maxMessageID, failureHandler: nil) { result in guard let realm = try? Realm() else { return } realm.beginWrite() if let userInfos = result["users"] as? [JSONDictionary] { // flatMap 过滤期中的nil的值 let discoverUsers = userInfos.map{ parseDiscoveredUser($0) }.flatMap{$0} // discoverUsers.forEach({ _ = conversationWithDiscoveredUser($0, inRealm: realm) }) dispatch_async(dispatch_get_main_queue()) { NSNotificationCenter.defaultCenter().postNotificationName(YeepConfig.Notification.changedConversation, object: nil) } } if let groupInfos = result["circles"] as? [JSONDictionary] { groupInfos.forEach({ syncFeedGroupWithGroupInfo($0, inRealm: realm) }) dispatch_async(dispatch_get_main_queue()) { NSNotificationCenter.defaultCenter().postNotificationName(YeepConfig.Notification.changedFeedConversation, object: nil) } } // var lastMessageID: String? // // if let messageInfos = result["messages"] as? [JSONDictionary] { // // messageInfos.forEach({ // syncMessageWithMessageInfo($0, messageAge: .Old, inRealm: realm) { _ in // } // }) // // let messageIDs: [String] = messageInfos.map({ $0["id"] as? String }).flatMap({ $0 }) // messageIDs.forEach({ // if let message = messageWithMessageID($0, inRealm: realm) { // if let conversation = message.conversation { // conversation.updatedUnixTime = message.createdUnixTime // } // } // }) // // lastMessageID = messageIDs.last // } let _ = try? realm.commitWrite() dispatch_async(dispatch_get_main_queue()) { NSNotificationCenter.defaultCenter().postNotificationName(YeepConfig.Notification.changedConversation, object: nil) NSNotificationCenter.defaultCenter().postNotificationName(YeepConfig.Notification.changedFeedConversation, object: nil) } // if let lastMessageID = lastMessageID { // if let count = result["count"] as? Int, perPage = result["per_page"] as? Int { // if count > perPage { // syncMyConversations(maxMessageID: lastMessageID) // } // } // } YeepUserDefaults.syncedConversations.value = true } } func syncFeedGroupWithGroupInfo(groupInfo: JSONDictionary, inRealm realm: Realm) { let group = syncGroupWithGroupInfo(groupInfo, inRealm: realm) group?.includeMe = true //Sync Feed if let feedInfo = groupInfo["topic"] as? JSONDictionary, feed = DiscoveredFeed.fromFeedInfo(feedInfo, groupInfo: groupInfo), group = group { saveFeedWithDiscoveredFeed(feed, group: group, inRealm: realm) } else { print("no sync feed from groupInfo: \(groupInfo)") } } func syncGroupWithGroupInfo(groupInfo: JSONDictionary, inRealm realm: Realm) -> Group? { if let groupID = groupInfo["id"] as? String { var group = groupWithGroupID(groupID, inRealm: realm) if group == nil { let newGroup = Group() newGroup.groupID = groupID if let groupName = groupInfo["name"] as? String { newGroup.groupName = groupName } realm.add(newGroup) group = newGroup } if let group = group { // 有 topic 标记 groupType 为 Public,否则 Private if let _ = groupInfo["topic"] { group.groupType = GroupType.Public.rawValue } else { group.groupType = GroupType.Private.rawValue } print("group.groupType: \(group.groupType)") if group.conversation == nil { let conversation = Conversation() conversation.type = ConversationType.Group.rawValue conversation.withGroup = group if let updatedUnixTime = groupInfo["updated_at"] as? NSTimeInterval { conversation.updatedUnixTime = max(updatedUnixTime, conversation.updatedUnixTime) } realm.add(conversation) } // Group Owner if let ownerInfo = groupInfo["owner"] as? JSONDictionary { if let ownerID = ownerInfo["id"] as? String { var owner = userWithUserID(ownerID, inRealm: realm) if owner == nil { let newUser = User() newUser.userID = ownerID if let createdUnixTime = ownerInfo["created_at"] as? NSTimeInterval { newUser.createdUnixTime = createdUnixTime } if let myUserID = YeepUserDefaults.userID.value { if myUserID == ownerID { newUser.friendState = UserFriendState.Me.rawValue } else { newUser.friendState = UserFriendState.Stranger.rawValue } } else { newUser.friendState = UserFriendState.Stranger.rawValue } realm.add(newUser) owner = newUser } if let owner = owner { // 更新个人信息 updateUserWithUserID(owner.userID, useUserInfo: ownerInfo, inRealm: realm) group.owner = owner } } } // 同步 Group 的成员 if let remoteMembers = groupInfo["members"] as? [JSONDictionary] { var memberIDSet = Set<String>() for memberInfo in remoteMembers { if let memberID = memberInfo["id"] as? String { memberIDSet.insert(memberID) } } let localMembers = group.members // 去除远端没有的 member for (index, member) in localMembers.enumerate() { let user = member if !memberIDSet.contains(user.userID) { localMembers.removeAtIndex(index) } } // 加上本地没有的 member for memberInfo in remoteMembers { if let memberID = memberInfo["id"] as? String { var member = userWithUserID(memberID, inRealm: realm) if member == nil { let newMember = User() newMember.userID = memberID if let createdUnixTime = memberInfo["created_at"] as? NSTimeInterval { newMember.createdUnixTime = createdUnixTime } if let myUserID = YeepUserDefaults.userID.value { if myUserID == memberID { newMember.friendState = UserFriendState.Me.rawValue } else { newMember.friendState = UserFriendState.Stranger.rawValue } } else { newMember.friendState = UserFriendState.Stranger.rawValue } realm.add(newMember) localMembers.append(newMember) member = newMember } if let member = member { // 更新个人信息 updateUserWithUserID(member.userID, useUserInfo: memberInfo, inRealm: realm) } } } group.members.removeAll() group.members.appendContentsOf(localMembers) } } return group } return nil } func attachmentFromDiscoveredAttachment(discoverAttachments: [DiscoveredAttachment]) -> [Attachment]{ return discoverAttachments.map({ discoverAttachment -> Attachment? in let newAttachment = Attachment() //newAttachment.kind = discoverAttachment.kind.rawValue newAttachment.metadata = discoverAttachment.metadata newAttachment.URLString = discoverAttachment.URLString return newAttachment }).filter({ $0 != nil }).map({ discoverAttachment in discoverAttachment! }) }
mit
c36e887de58d3811701155b0b8332cd9
35.904376
154
0.466974
6.298755
false
false
false
false
hrscy/TodayNews
News/News/Classes/Mine/View/DongtaiOriginThreadView.swift
1
1762
// // DongtaiOriginThreadView.swift // News // // Created by 杨蒙 on 2017/12/10. // Copyright © 2017年 hrscy. All rights reserved. // import UIKit class DongtaiOriginThreadView: UIView, NibLoadable { let emojiManager = EmojiManager() var isPostSmallVideo = false var originthread = DongtaiOriginThread() { didSet { // 如果原内容已经删除 if originthread.delete || !originthread.show_origin { contentLabel.text = originthread.show_tips != "" ? originthread.show_tips : originthread.content contentLabel.textAlignment = .center contentLabelHeight.constant = originthread.contentH } else { contentLabel.attributedText = originthread.attributedContent contentLabelHeight.constant = originthread.contentH collectionView.isDongtaiDetail = originthread.isDongtaiDetail collectionView.thumbImages = originthread.thumb_image_list collectionView.largeImages = originthread.large_image_list collectionViewWidth.constant = originthread.collectionViewW layoutIfNeeded() } } } @IBOutlet weak var contentLabel: UILabel! @IBOutlet weak var contentLabelHeight: NSLayoutConstraint! @IBOutlet weak var collectionView: DongtaiCollectionView! @IBOutlet weak var collectionViewWidth: NSLayoutConstraint! override func awakeFromNib() { super.awakeFromNib() theme_backgroundColor = "colors.grayColor247" } override func layoutSubviews() { super.layoutSubviews() height = originthread.height width = screenWidth } }
mit
367b777e033ebf8ebd95902eb78ee81e
31.166667
112
0.645366
5.311927
false
false
false
false
blockchain/My-Wallet-V3-iOS
Modules/Platform/Sources/PlatformUIKit/SecureChannel/SecureChannelDetailsPresenter+ContentReducer.swift
1
5202
// Copyright © Blockchain Luxembourg S.A. All rights reserved. import Localization import PlatformKit import RxCocoa import RxSwift extension SecureChannelDetailsPresenter { class ContentReducer { private typealias LocalizedString = LocalizationConstants.SecureChannel.ConfirmationSheet let cells: [DetailsScreen.CellType] let headers: [Int: HeaderBuilder] var buttons: [ButtonViewModel] { [approveButton, denyButton] } var approveTapped: PublishRelay<Void> { approveButton.tapRelay } var denyTapped: PublishRelay<Void> { denyButton.tapRelay } private let approveButton: ButtonViewModel private let denyButton: ButtonViewModel init(candidate: SecureChannelConnectionCandidate) { // MARK: Buttons denyButton = ButtonViewModel.cancel(with: LocalizedString.CTA.deny) approveButton = ButtonViewModel.primary(with: LocalizedString.CTA.approve) // MARK: Header let title: String, subtitle: String if candidate.isAuthorized { title = LocalizedString.Authorized.title subtitle = LocalizedString.Authorized.subtitle } else { title = LocalizedString.New.title subtitle = LocalizedString.New.subtitle } let image = ImageViewContent( imageResource: .local(name: "icon-laptop", bundle: .platformUIKit), accessibility: .none, renderingMode: .normal ) let model = AccountPickerHeaderModel( imageContent: image, subtitle: subtitle, tableTitle: nil, title: title ) headers = [ 0: AccountPickerHeaderBuilder(headerType: .default(model)) ] // MARK: Cells let locationPresenter = DefaultLineItemCellPresenter( interactor: DefaultLineItemCellInteractor( title: DefaultLabelContentInteractor(knownValue: LocalizedString.Fields.location), description: DefaultLabelContentInteractor(knownValue: candidate.details.originCountry) ), accessibilityIdPrefix: "" ) let ipPresenter = DefaultLineItemCellPresenter( interactor: DefaultLineItemCellInteractor( title: DefaultLabelContentInteractor(knownValue: LocalizedString.Fields.ipAddress), description: DefaultLabelContentInteractor(knownValue: candidate.details.originIP) ), accessibilityIdPrefix: "" ) let browserPresenter = DefaultLineItemCellPresenter( interactor: DefaultLineItemCellInteractor( title: DefaultLabelContentInteractor(knownValue: LocalizedString.Fields.browser), description: DefaultLabelContentInteractor(knownValue: candidate.details.originBrowser) ), accessibilityIdPrefix: "" ) let datePresenter = DefaultLineItemCellPresenter( interactor: DefaultLineItemCellInteractor( title: DefaultLabelContentInteractor(knownValue: LocalizedString.Fields.date), description: DefaultLabelContentInteractor( knownValue: DateFormatter.elegantDateFormatter.string(from: candidate.timestamp) ) ), accessibilityIdPrefix: "" ) let lastSeen: String if let lastUsed = candidate.lastUsed { lastSeen = "\(lastUsed)" } else { lastSeen = LocalizedString.Fields.never } let lastSeenPresenter = DefaultLineItemCellPresenter( interactor: DefaultLineItemCellInteractor( title: DefaultLabelContentInteractor(knownValue: LocalizedString.Fields.lastSeen), description: DefaultLabelContentInteractor( knownValue: lastSeen ) ), accessibilityIdPrefix: "" ) let labelPresenter = DefaultLabelContentPresenter( knownValue: LocalizedString.Text.warning, descriptors: .body(accessibilityId: "") ) var baseCells: [DetailsScreen.CellType] = [ .separator, .lineItem(locationPresenter), .separator, .lineItem(ipPresenter), .separator, .lineItem(browserPresenter), .separator, .lineItem(datePresenter) ] if candidate.isAuthorized { baseCells += [ .separator, .lineItem(lastSeenPresenter) ] } baseCells += [ .separator, .label(labelPresenter) ] cells = baseCells } } }
lgpl-3.0
a512475d6e2c37c881c3e87cdacd380c
36.963504
107
0.56643
6.46087
false
false
false
false
AnthonyMDev/AmazonS3RequestManager
Example/Tests/AmazonS3RequestSerializerTests.swift
1
11913
// // AmazonS3RequestSerializerTests.swift // AmazonS3RequestManager // // Created by Anthony Miller on 10/14/15. // Copyright © 2015 Anthony Miller. All rights reserved. // import XCTest import Nimble @testable import AmazonS3RequestManager class AmazonS3RequestSerializerTests: XCTestCase { var sut: AmazonS3RequestSerializer! let accessKey = "key" let secret = "secret" let bucket = "bucket" let region = Region.USWest1 override func setUp() { super.setUp() sut = AmazonS3RequestSerializer(accessKey: accessKey, secret: secret, region: region, bucket: bucket) } /* * MARK: - Initialization - Tests */ func test__inits__withConfiguredRequestSerializer() { expect(self.sut.accessKey).to(equal(self.accessKey)) expect(self.sut.secret).to(equal(self.secret)) expect(self.sut.bucket).to(equal(self.bucket)) expect(self.sut.region.hostName).to(equal(self.region.hostName)) } /* * MARK: Amazon URL Request Serialization - Tests */ func test__amazonURLRequest__setsURLWithEndpointURL() { // given let path = "TestPath" let expectedURL = URL(string: "https://\(region.endpoint)/\(bucket)/\(path)")! // when let request = sut.amazonURLRequest(method: .get, path: path) // then XCTAssertEqual(request.url!, expectedURL) } func test__amazonURLRequest__givenCustomRegion_setsURLWithEndpointURL() { // given let path = "TestPath" let expectedEndpoint = "test.endpoint.com" let region = Region.custom(hostName: "", endpoint: expectedEndpoint) sut.region = region let expectedURL = URL(string: "https://\(expectedEndpoint)/\(bucket)/\(path)")! // when let request = sut.amazonURLRequest(method: .get, path: path) // then XCTAssertEqual(request.url!, expectedURL) } func test__amazonURLRequest__givenNoBucket__setsURLWithEndpointURL() { // given sut.bucket = nil let path = "TestPath" let expectedURL = URL(string: "https://\(region.endpoint)/\(path)")! // when let request = sut.amazonURLRequest(method: .get, path: path) // then XCTAssertEqual(request.url!, expectedURL) } func test__amazonURLRequest__givenNoPath() { // given sut.bucket = "test" let expectedURL = URL(string: "https://\(region.endpoint)/test")! // when let request = sut.amazonURLRequest(method: .get) // then XCTAssertEqual(request.url!, expectedURL) } func test__amazonURLRequest__givenUseSSL_false_setsURLWithEndpointURL_usingHTTP() { // given sut.useSSL = false let path = "TestPath" let expectedURL = URL(string: "http://\(region.endpoint)/\(bucket)/\(path)")! // when let request = sut.amazonURLRequest(method: .get, path: path) // then XCTAssertEqual(request.url!, expectedURL) } func test__amazonURLRequest__setsHTTPMethod() { // given let expected = "GET" // when let request = sut.amazonURLRequest(method: .get, path: "test") // then XCTAssertEqual(request.httpMethod!, expected) } func test__amazonURLRequest__setsCachePolicy() { // given let expected = URLRequest.CachePolicy.reloadIgnoringLocalCacheData // when let request = sut.amazonURLRequest(method: .get, path: "test") // then XCTAssertEqual(request.cachePolicy, expected) } func test__amazonURLRequest__givenNoPathExtension_setsHTTPHeader_ContentType() { // given let request = sut.amazonURLRequest(method: .get, path: "test") // when let headers = request.allHTTPHeaderFields! let typeHeader: String? = headers["Content-Type"] // then XCTAssertNotNil(typeHeader, "Should have 'Content-Type' header field") XCTAssertEqual(typeHeader!, "application/octet-stream") } func test__amazonURLRequest__givenJPGPathExtension_setsHTTPHeader_ContentType() { // given let request = sut.amazonURLRequest(method: .get, path: "test.jpg") // when let headers = request.allHTTPHeaderFields! let typeHeader: String? = headers["Content-Type"] // then XCTAssertNotNil(typeHeader, "Should have 'Content-Type' header field") expect(typeHeader).to(equal("image/jpeg")) } func test__amazonURLRequest__givenTXTPathExtension_setsHTTPHeader_ContentType() { // given let request = sut.amazonURLRequest(method: .get, path: "test.txt") // when let headers = request.allHTTPHeaderFields! let typeHeader: String? = headers["Content-Type"] // then XCTAssertNotNil(typeHeader, "Should have 'Content-Type' header field") XCTAssertEqual(typeHeader!, "text/plain") } func test__amazonURLRequest__givenMarkDownPathExtension_setsHTTPHeader_ContentType() { // given let request = sut.amazonURLRequest(method: .get, path: "test.md") // when let headers = request.allHTTPHeaderFields! let typeHeader: String? = headers["Content-Type"] // then XCTAssertNotNil(typeHeader, "Should have 'Content-Type' header field") #if os(iOS) || os(watchOS) || os(tvOS) expect(typeHeader).to(equal("application/octet-stream")) #elseif os(OSX) expect(typeHeader).to(equal("text/markdown")) #endif } func test__amazonURLRequest__setsHTTPHeader_Date() { // given let request = sut.amazonURLRequest(method: .get, path: "test") // when let headers = request.allHTTPHeaderFields! let dateHeader: String? = headers["Date"] // then XCTAssertNotNil(dateHeader, "Should have 'Date' header field") XCTAssertTrue(dateHeader!.hasSuffix("GMT")) } func test__amazonURLRequest__setsHTTPHeader_Authorization() { // given let request = sut.amazonURLRequest(method: .get, path: "test") // when let headers = request.allHTTPHeaderFields! let authHeader: String? = headers["Authorization"] // then XCTAssertNotNil(authHeader, "Should have 'Authorization' header field") XCTAssertTrue(authHeader!.hasPrefix("AWS \(accessKey):"), "Authorization header should begin with 'AWS [accessKey]'.") } func test__amazonURLRequest__givenACL__setsHTTPHeader_ACL() { // given let acl = PredefinedACL.publicReadWrite let request = sut.amazonURLRequest(method: .get, path: "test", acl: acl) // when let headers = request.allHTTPHeaderFields! let aclHeader: String? = headers["x-amz-acl"] // then XCTAssertNotNil(aclHeader, "Should have ACL header field") } func test__amazonURLRequest__givenMetaData__setsHTTPHeader_amz_meta() { // given let metaData = ["demo" : "foo"] let request = sut.amazonURLRequest(method: .head, path: "test", acl: nil, metaData: metaData) // when let headers = request.allHTTPHeaderFields! let metaDataHeader: String? = headers["x-amz-meta-demo"] // then XCTAssertEqual(metaDataHeader, "foo", "Meta data header field is not set correctly.") } func test__amazonURLRequest__givenCustomParameters_setsURLWithEndpointURL() { // given let path = "TestPath" let expectedEndpoint = "test.endpoint.com" let region = Region.custom(hostName: "", endpoint: expectedEndpoint) sut.region = region let expectedURL = URL(string: "https://\(expectedEndpoint)/\(bucket)/\(path)?custom-param=custom%20value%21%2F")! // when let request = sut.amazonURLRequest(method: .get, path: path, customParameters: ["custom-param" : "custom value!/"]) // then XCTAssertEqual(request.url!, expectedURL) } func test__amazonURLRequest__givenCustomParameters_setsURLWithEndpointURL_ContinuationToken() { // given let path = "TestPath" let expectedEndpoint = "test.endpoint.com" let region = Region.custom(hostName: "", endpoint: expectedEndpoint) sut.region = region let expectedURL = URL(string: "https://\(expectedEndpoint)/\(bucket)/\(path)?continuation-token=1%2FkCRyYIP%2BApo2oop%2FGa8%2FnVMR6hC7pDH%2FlL6JJrSZ3blAYaZkzJY%2FRVMcJ")! // when let request = sut.amazonURLRequest(method: .get, path: path, customParameters: ["continuation-token" : "1/kCRyYIP+Apo2oop/Ga8/nVMR6hC7pDH/lL6JJrSZ3blAYaZkzJY/RVMcJ"]) // then XCTAssertEqual(request.url!, expectedURL) } func test_amazonURLRequest__givenCustomHeaders() { // given let headers = ["header-demo" : "foo", "header-test" : "bar"] let request = sut.amazonURLRequest(method: .head, path: "test", customHeaders: headers) // when let httpHeaders = request.allHTTPHeaderFields! let header1: String? = httpHeaders["header-demo"] let header2: String? = httpHeaders["header-test"] // then XCTAssertEqual(header1, "foo", "Meta data header field is not set correctly.") XCTAssertEqual(header2, "bar", "Meta data header field is not set correctly.") } // MARK: Amazon Request URL Serialization - Tests func test__url_for_path__returnsURLWithEndpointURL() { // given let path = "TestPath" let expectedURL = URL(string: "https://\(region.endpoint)/\(bucket)/\(path)")! // when let url = sut.url(withPath: path) // then XCTAssertEqual(url, expectedURL) } func test__url_for_path__givenCustomRegion_setsURLWithEndpointURL() { // given let path = "TestPath" let expectedEndpoint = "test.endpoint.com" let region = Region.custom(hostName: "", endpoint: expectedEndpoint) sut.region = region let expectedURL = URL(string: "https://\(expectedEndpoint)/\(bucket)/\(path)")! // when let url = sut.url(withPath: path) // then XCTAssertEqual(url, expectedURL) } func test__url_for_path__givenNoBucket__setsURLWithEndpointURL() { // given sut.bucket = nil let path = "TestPath" let expectedURL = URL(string: "https://\(region.endpoint)/\(path)")! // when let url = sut.url(withPath: path) // then XCTAssertEqual(url, expectedURL) } func test__url_for_path__givenNoPath() { // given sut.bucket = "test" let expectedURL = URL(string: "https://\(region.endpoint)/test")! // when let url = sut.url(withPath: nil) // then XCTAssertEqual(url, expectedURL) } func test__url_for_path__givenUseSSL_false_setsURLWithEndpointURL_usingHTTP() { // given sut.useSSL = false let path = "TestPath" let expectedURL = URL(string: "http://\(region.endpoint)/\(bucket)/\(path)")! // when let url = sut.url(withPath: path) // then XCTAssertEqual(url, expectedURL) } func test__url_for_path__givenCustomParameters_setsURLWithEndpointURL() { // given let path = "TestPath" let expectedEndpoint = "test.endpoint.com" let region = Region.custom(hostName: "", endpoint: expectedEndpoint) sut.region = region let expectedURL = URL(string: "https://\(expectedEndpoint)/\(bucket)/\(path)?custom-param=custom%20value%21%2F")! // when let url = sut.url(withPath: path, customParameters: ["custom-param" : "custom value!/"]) // then XCTAssertEqual(url, expectedURL) } func test__url_for_path__givenCustomParameters_setsURLWithEndpointURL_ContinuationToken() { // given let path = "TestPath" let expectedEndpoint = "test.endpoint.com" let region = Region.custom(hostName: "", endpoint: expectedEndpoint) sut.region = region let expectedURL = URL(string: "https://\(expectedEndpoint)/\(bucket)/\(path)?continuation-token=1%2FkCRyYIP%2BApo2oop%2FGa8%2FnVMR6hC7pDH%2FlL6JJrSZ3blAYaZkzJY%2FRVMcJ")! // when let url = sut.url(withPath: path, customParameters: ["continuation-token" : "1/kCRyYIP+Apo2oop/Ga8/nVMR6hC7pDH/lL6JJrSZ3blAYaZkzJY/RVMcJ"]) // then XCTAssertEqual(url, expectedURL) } }
mit
9e6b79bd0b35c258b0feebf00d241638
29.622108
174
0.662189
4.069696
false
true
false
false
StYaphet/firefox-ios
Client/Frontend/Widgets/PhotonActionSheet/TrackingProtectionMenu.swift
2
11554
/* 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 Shared public struct NestedTableViewDelegate { var dataSource: UITableViewDataSource & UITableViewDelegate } fileprivate var nestedTableView: UITableView? class NestedTableDataSource: NSObject, UITableViewDataSource, UITableViewDelegate { var data = [String]() init(data: [String]) { self.data = data } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return data.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = UITableViewCell(style: .default, reuseIdentifier: nil) cell.textLabel?.text = data[indexPath.row] cell.backgroundColor = .clear cell.textLabel?.backgroundColor = .clear cell.contentView.backgroundColor = .clear cell.textLabel?.textColor = UIColor.theme.tableView.rowDetailText return cell } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 30.0 } } fileprivate var nestedTableViewDomainList: NestedTableViewDelegate? extension PhotonActionSheetProtocol { @available(iOS 11.0, *) private func menuActionsForNotBlocking() -> [PhotonActionSheetItem] { return [PhotonActionSheetItem(title: Strings.SettingsTrackingProtectionSectionName, text: Strings.TPNoBlockingDescription, iconString: "menu-TrackingProtection")] } @available(iOS 11.0, *) func getTrackingSubMenu(for tab: Tab) -> [[PhotonActionSheetItem]] { guard let blocker = tab.contentBlocker else { return [] } switch blocker.status { case .noBlockedURLs: return menuActionsForTrackingProtectionEnabled(for: tab) case .blocking: return menuActionsForTrackingProtectionEnabled(for: tab) case .disabled: return menuActionsForTrackingProtectionDisabled(for: tab) case .safelisted: return menuActionsForTrackingProtectionEnabled(for: tab, isSafelisted: true) } } @available(iOS 11.0, *) private func menuActionsForTrackingProtectionDisabled(for tab: Tab) -> [[PhotonActionSheetItem]] { let enableTP = PhotonActionSheetItem(title: Strings.EnableTPBlockingGlobally, iconString: "menu-TrackingProtection") { _, _ in FirefoxTabContentBlocker.toggleTrackingProtectionEnabled(prefs: self.profile.prefs) tab.reload() } var moreInfo = PhotonActionSheetItem(title: "", text: Strings.TPBlockingMoreInfo, iconString: "menu-Info") { _, _ in let url = SupportUtils.URLForTopic("tracking-protection-ios")! tab.loadRequest(URLRequest(url: url)) } moreInfo.customHeight = { _ in return PhotonActionSheetUX.RowHeight + 20 } return [[moreInfo], [enableTP]] } private func showDomainTable(title: String, description: String, blocker: FirefoxTabContentBlocker, categories: [BlocklistCategory]) { guard let urlbar = (self as? BrowserViewController)?.urlBar else { return } guard let bvc = self as? PresentableVC else { return } let stats = blocker.stats var data = [String]() for category in categories { data += Array(stats.domains[category] ?? Set<String>()) } nestedTableViewDomainList = NestedTableViewDelegate(dataSource: NestedTableDataSource(data: data)) var list = PhotonActionSheetItem(title: "") list.customRender = { _, contentView in if nestedTableView != nil { nestedTableView?.removeFromSuperview() } let tv = UITableView(frame: .zero, style: .plain) tv.dataSource = nestedTableViewDomainList?.dataSource tv.delegate = nestedTableViewDomainList?.dataSource tv.allowsSelection = false tv.backgroundColor = .clear tv.separatorStyle = .none contentView.addSubview(tv) tv.snp.makeConstraints { make in make.edges.equalTo(contentView) } nestedTableView = tv } list.customHeight = { _ in return PhotonActionSheetUX.RowHeight * 5 } let back = PhotonActionSheetItem(title: Strings.BackTitle, iconString: "goBack") { _, _ in guard let urlbar = (self as? BrowserViewController)?.urlBar else { return } (self as? BrowserViewController)?.urlBarDidTapShield(urlbar) } var info = PhotonActionSheetItem(title: description, accessory: .None) info.customRender = { (label, contentView) in label.numberOfLines = 0 } info.customHeight = { _ in return UITableView.automaticDimension } let actions = UIDevice.current.userInterfaceIdiom == .pad ? [[back], [info], [list]] : [[info], [list], [back]] self.presentSheetWith(title: title, actions: actions, on: bvc, from: urlbar) } @available(iOS 11.0, *) private func menuActionsForTrackingProtectionEnabled(for tab: Tab, isSafelisted: Bool = false) -> [[PhotonActionSheetItem]] { guard let blocker = tab.contentBlocker, let currentURL = tab.url else { return [] } var blockedtitle = PhotonActionSheetItem(title: Strings.TPPageMenuBlockedTitle, accessory: .Text, bold: true) blockedtitle.customRender = { label, _ in label.font = DynamicFontHelper.defaultHelper.DeviceFontSmallBold } blockedtitle.customHeight = { _ in return PhotonActionSheetUX.RowHeight - 10 } let xsitecookies = PhotonActionSheetItem(title: Strings.TPCrossSiteCookiesBlocked, iconString: "tp-cookie", accessory: .Disclosure) { action, _ in let desc = Strings.TPCategoryDescriptionCrossSite self.showDomainTable(title: action.title, description: desc, blocker: blocker, categories: [BlocklistCategory.advertising, BlocklistCategory.analytics]) } let social = PhotonActionSheetItem(title: Strings.TPSocialBlocked, iconString: "tp-socialtracker", accessory: .Disclosure) { action, _ in let desc = Strings.TPCategoryDescriptionSocial self.showDomainTable(title: action.title, description: desc, blocker: blocker, categories: [BlocklistCategory.social]) } let fingerprinters = PhotonActionSheetItem(title: Strings.TPFingerprintersBlocked, iconString: "tp-fingerprinter", accessory: .Disclosure) { action, _ in let desc = Strings.TPCategoryDescriptionFingerprinters self.showDomainTable(title: action.title, description: desc, blocker: blocker, categories: [BlocklistCategory.fingerprinting]) } let cryptomining = PhotonActionSheetItem(title: Strings.TPCryptominersBlocked, iconString: "tp-cryptominer", accessory: .Disclosure) { action, _ in let desc = Strings.TPCategoryDescriptionCryptominers self.showDomainTable(title: action.title, description: desc, blocker: blocker, categories: [BlocklistCategory.cryptomining]) } var addToSafelist = PhotonActionSheetItem(title: Strings.ETPOn, isEnabled: !isSafelisted, accessory: .Switch) { _, cell in LeanPlumClient.shared.track(event: .trackingProtectionSafeList) UnifiedTelemetry.recordEvent(category: .action, method: .add, object: .trackingProtectionSafelist) ContentBlocker.shared.safelist(enable: tab.contentBlocker?.status != .safelisted, url: currentURL) { tab.reload() // trigger a call to customRender cell.backgroundView?.setNeedsDisplay() } } addToSafelist.customRender = { title, _ in if tab.contentBlocker?.status == .safelisted { title.text = Strings.ETPOff } else { title.text = Strings.ETPOn } } addToSafelist.accessibilityId = "tp.add-to-safelist" addToSafelist.customHeight = { _ in return PhotonActionSheetUX.RowHeight } let settings = PhotonActionSheetItem(title: Strings.TPProtectionSettings, iconString: "settings") { _, _ in let settingsTableViewController = AppSettingsTableViewController() settingsTableViewController.profile = self.profile settingsTableViewController.tabManager = self.tabManager guard let bvc = self as? BrowserViewController else { return } settingsTableViewController.settingsDelegate = bvc settingsTableViewController.showContentBlockerSetting = true let controller = ThemedNavigationController(rootViewController: settingsTableViewController) controller.presentingModalViewControllerDelegate = bvc // Wait to present VC in an async dispatch queue to prevent a case where dismissal // of this popover on iPad seems to block the presentation of the modal VC. DispatchQueue.main.async { bvc.present(controller, animated: true, completion: nil) } } var items = [[blockedtitle]] let count = [BlocklistCategory.analytics, BlocklistCategory.advertising].reduce(0) { result, item in return result + (blocker.stats.domains[item]?.count ?? 0) } if count > 0 { items[0].append(xsitecookies) } if !(blocker.stats.domains[.social]?.isEmpty ?? true) { items[0].append(social) } if !(blocker.stats.domains[.fingerprinting]?.isEmpty ?? true) { items[0].append(fingerprinters) } if !(blocker.stats.domains[.cryptomining]?.isEmpty ?? true) { items[0].append(cryptomining) } if items[0].count == 1 { // no items were blocked var noblockeditems = PhotonActionSheetItem(title: "", accessory: .Text) noblockeditems.customRender = { title, contentView in let l = UILabel() l.numberOfLines = 0 l.textAlignment = .center l.textColor = UIColor.theme.tableView.headerTextLight l.text = Strings.TPPageMenuNoTrackersBlocked l.accessibilityIdentifier = "tp.no-trackers-blocked" contentView.addSubview(l) l.snp.makeConstraints { make in make.center.equalToSuperview() make.width.equalToSuperview().inset(40) } } noblockeditems.customHeight = { _ in return 180 } items = [[noblockeditems]] } items = [[addToSafelist]] + items + [[settings]] return items } @available(iOS 11.0, *) private func menuActionsForSafelistedSite(for tab: Tab) -> [[PhotonActionSheetItem]] { guard let currentURL = tab.url else { return [] } let removeFromSafelist = PhotonActionSheetItem(title: Strings.TPSafeListRemove, iconString: "menu-TrackingProtection") { _, _ in ContentBlocker.shared.safelist(enable: false, url: currentURL) { tab.reload() } } return [[removeFromSafelist]] } }
mpl-2.0
1eb7cb7303b8c37ef852d6fd3a3748c2
42.11194
170
0.643846
5.012581
false
false
false
false
ZulwiyozaPutra/Alien-Adventure-Tutorial
Alien Adventure/MatchMoonRocks.swift
1
761
// // MatchMoonRocks.swift // Alien Adventure // // Created by Jarrod Parkes on 9/30/15. // Copyright © 2015 Udacity. All rights reserved. // extension Hero { func matchMoonRocks(inventory: [UDItem]) -> [UDItem] { var inventoryToReturn: [UDItem] = [] for item in inventory { let inventoryName = item.name if inventoryName == "MoonRock" { inventoryToReturn.append(item) } } return inventoryToReturn } } // If you have completed this function and it is working correctly, feel free to skip this part of the adventure by opening the "Under the Hood" folder, and making the following change in Settings.swift: "static var RequestsToSkip = 2"
mit
b4c197c903bead76d9b13eac922e1fcd
28.230769
235
0.626316
4.367816
false
false
false
false
izhuster/TechnicalTest
TechnicalTest/Pods/Alamofire/Source/ServerTrustPolicy.swift
1
14051
// // ServerTrustPolicy.swift // // Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import Foundation /// Responsible for managing the mapping of `ServerTrustPolicy` objects to a given host. public class ServerTrustPolicyManager { /// The dictionary of policies mapped to a particular host. public let policies: [String: ServerTrustPolicy] /** Initializes the `ServerTrustPolicyManager` instance with the given policies. Since different servers and web services can have different leaf certificates, intermediate and even root certficates, it is important to have the flexibility to specify evaluation policies on a per host basis. This allows for scenarios such as using default evaluation for host1, certificate pinning for host2, public key pinning for host3 and disabling evaluation for host4. - parameter policies: A dictionary of all policies mapped to a particular host. - returns: The new `ServerTrustPolicyManager` instance. */ public init(policies: [String: ServerTrustPolicy]) { self.policies = policies } /** Returns the `ServerTrustPolicy` for the given host if applicable. By default, this method will return the policy that perfectly matches the given host. Subclasses could override this method and implement more complex mapping implementations such as wildcards. - parameter host: The host to use when searching for a matching policy. - returns: The server trust policy for the given host if found. */ public func serverTrustPolicyForHost(host: String) -> ServerTrustPolicy? { return policies[host] } } // MARK: - extension NSURLSession { private struct AssociatedKeys { static var ManagerKey = "NSURLSession.ServerTrustPolicyManager" } var serverTrustPolicyManager: ServerTrustPolicyManager? { get { return objc_getAssociatedObject(self, &AssociatedKeys.ManagerKey) as? ServerTrustPolicyManager } set (manager) { objc_setAssociatedObject(self, &AssociatedKeys.ManagerKey, manager, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } } } // MARK: - ServerTrustPolicy /** The `ServerTrustPolicy` evaluates the server trust generally provided by an `NSURLAuthenticationChallenge` when connecting to a server over a secure HTTPS connection. The policy configuration then evaluates the server trust with a given set of criteria to determine whether the server trust is valid and the connection should be made. Using pinned certificates or public keys for evaluation helps prevent man-in-the-middle (MITM) attacks and other vulnerabilities. Applications dealing with sensitive customer data or financial information are strongly encouraged to route all communication over an HTTPS connection with pinning enabled. - PerformDefaultEvaluation: Uses the default server trust evaluation while allowing you to control whether to validate the host provided by the challenge. Applications are encouraged to always validate the host in production environments to guarantee the validity of the server's certificate chain. - PinCertificates: Uses the pinned certificates to validate the server trust. The server trust is considered valid if one of the pinned certificates match one of the server certificates. By validating both the certificate chain and host, certificate pinning provides a very secure form of server trust validation mitigating most, if not all, MITM attacks. Applications are encouraged to always validate the host and require a valid certificate chain in production environments. - PinPublicKeys: Uses the pinned public keys to validate the server trust. The server trust is considered valid if one of the pinned public keys match one of the server certificate public keys. By validating both the certificate chain and host, public key pinning provides a very secure form of server trust validation mitigating most, if not all, MITM attacks. Applications are encouraged to always validate the host and require a valid certificate chain in production environments. - DisableEvaluation: Disables all evaluation which in turn will always consider any server trust as valid. - CustomEvaluation: Uses the associated closure to evaluate the validity of the server trust. */ public enum ServerTrustPolicy { case PerformDefaultEvaluation(validateHost: Bool) case PinCertificates(certificates: [SecCertificate], validateCertificateChain: Bool, validateHost: Bool) case PinPublicKeys(publicKeys: [SecKey], validateCertificateChain: Bool, validateHost: Bool) case DisableEvaluation case CustomEvaluation((serverTrust: SecTrust, host: String) -> Bool) // MARK: - Bundle Location /** Returns all certificates within the given bundle with a `.cer` file extension. - parameter bundle: The bundle to search for all `.cer` files. - returns: All certificates within the given bundle. */ public static func certificatesInBundle(bundle: NSBundle = NSBundle.mainBundle()) -> [SecCertificate] { var certificates: [SecCertificate] = [] let paths = Set([".cer", ".CER", ".crt", ".CRT", ".der", ".DER"].map { fileExtension in bundle.pathsForResourcesOfType(fileExtension, inDirectory: nil) }.flatten()) for path in paths { if let certificateData = NSData(contentsOfFile: path), certificate = SecCertificateCreateWithData(nil, certificateData) { certificates.append(certificate) } } return certificates } /** Returns all public keys within the given bundle with a `.cer` file extension. - parameter bundle: The bundle to search for all `*.cer` files. - returns: All public keys within the given bundle. */ public static func publicKeysInBundle(bundle: NSBundle = NSBundle.mainBundle()) -> [SecKey] { var publicKeys: [SecKey] = [] for certificate in certificatesInBundle(bundle) { if let publicKey = publicKeyForCertificate(certificate) { publicKeys.append(publicKey) } } return publicKeys } // MARK: - Evaluation /** Evaluates whether the server trust is valid for the given host. - parameter serverTrust: The server trust to evaluate. - parameter host: The host of the challenge protection space. - returns: Whether the server trust is valid. */ public func evaluateServerTrust(serverTrust: SecTrust, isValidForHost host: String) -> Bool { var serverTrustIsValid = false switch self { case let .PerformDefaultEvaluation(validateHost): let policy = SecPolicyCreateSSL(true, validateHost ? host as CFString : nil) #if swift(>=2.3) SecTrustSetPolicies(serverTrust, policy) #else SecTrustSetPolicies(serverTrust, [policy]) #endif serverTrustIsValid = trustIsValid(serverTrust) case let .PinCertificates(pinnedCertificates, validateCertificateChain, validateHost): if validateCertificateChain { let policy = SecPolicyCreateSSL(true, validateHost ? host as CFString : nil) #if swift(>=2.3) SecTrustSetPolicies(serverTrust, policy) #else SecTrustSetPolicies(serverTrust, [policy]) #endif SecTrustSetAnchorCertificates(serverTrust, pinnedCertificates) SecTrustSetAnchorCertificatesOnly(serverTrust, true) serverTrustIsValid = trustIsValid(serverTrust) } else { let serverCertificatesDataArray = certificateDataForTrust(serverTrust) let pinnedCertificatesDataArray = certificateDataForCertificates(pinnedCertificates) outerLoop: for serverCertificateData in serverCertificatesDataArray { for pinnedCertificateData in pinnedCertificatesDataArray { if serverCertificateData.isEqualToData(pinnedCertificateData) { serverTrustIsValid = true break outerLoop } } } } case let .PinPublicKeys(pinnedPublicKeys, validateCertificateChain, validateHost): var certificateChainEvaluationPassed = true if validateCertificateChain { let policy = SecPolicyCreateSSL(true, validateHost ? host as CFString : nil) #if swift(>=2.3) SecTrustSetPolicies(serverTrust, policy) #else SecTrustSetPolicies(serverTrust, [policy]) #endif certificateChainEvaluationPassed = trustIsValid(serverTrust) } if certificateChainEvaluationPassed { outerLoop: for serverPublicKey in ServerTrustPolicy.publicKeysForTrust(serverTrust) as [AnyObject] { for pinnedPublicKey in pinnedPublicKeys as [AnyObject] { if serverPublicKey.isEqual(pinnedPublicKey) { serverTrustIsValid = true break outerLoop } } } } case .DisableEvaluation: serverTrustIsValid = true case let .CustomEvaluation(closure): serverTrustIsValid = closure(serverTrust: serverTrust, host: host) } return serverTrustIsValid } // MARK: - Private - Trust Validation private func trustIsValid(trust: SecTrust) -> Bool { var isValid = false #if swift(>=2.3) var result = SecTrustResultType(rawValue: SecTrustResultType.Invalid.rawValue) let status = SecTrustEvaluate(trust, &result!) #else var result = SecTrustResultType(kSecTrustResultInvalid) let status = SecTrustEvaluate(trust, &result) #endif if status == errSecSuccess { #if swift(>=2.3) let unspecified = SecTrustResultType(rawValue: SecTrustResultType.Unspecified.rawValue) let proceed = SecTrustResultType(rawValue: SecTrustResultType.Proceed.rawValue) #else // Xcode 8 // let unspecified = SecTrustResultType(SecTrustResultType.Unspecified) // let proceed = SecTrustResultType(SecTrustResultType.Proceed) // Xcode 7 let unspecified = SecTrustResultType(kSecTrustResultUnspecified) let proceed = SecTrustResultType(kSecTrustResultProceed) #endif isValid = result == unspecified || result == proceed } return isValid } // MARK: - Private - Certificate Data private func certificateDataForTrust(trust: SecTrust) -> [NSData] { var certificates: [SecCertificate] = [] for index in 0..<SecTrustGetCertificateCount(trust) { if let certificate = SecTrustGetCertificateAtIndex(trust, index) { certificates.append(certificate) } } return certificateDataForCertificates(certificates) } private func certificateDataForCertificates(certificates: [SecCertificate]) -> [NSData] { return certificates.map { SecCertificateCopyData($0) as NSData } } // MARK: - Private - Public Key Extraction private static func publicKeysForTrust(trust: SecTrust) -> [SecKey] { var publicKeys: [SecKey] = [] for index in 0..<SecTrustGetCertificateCount(trust) { if let certificate = SecTrustGetCertificateAtIndex(trust, index), publicKey = publicKeyForCertificate(certificate) { publicKeys.append(publicKey) } } return publicKeys } private static func publicKeyForCertificate(certificate: SecCertificate) -> SecKey? { var publicKey: SecKey? let policy = SecPolicyCreateBasicX509() var trust: SecTrust? let trustCreationStatus = SecTrustCreateWithCertificates(certificate, policy, &trust) if let trust = trust where trustCreationStatus == errSecSuccess { publicKey = SecTrustCopyPublicKey(trust) } return publicKey } }
mit
907b1ed27dfd1e1c291491ad53398d31
41.578788
120
0.655042
5.986792
false
false
false
false
PureSwift/Bluetooth
Sources/BluetoothGAP/GAPSimplePairingRandomizerR.swift
1
2299
// // GAPSimplePairingRandomizerR.swift // Bluetooth // // Created by Carlos Duclos on 6/13/18. // Copyright © 2018 PureSwift. All rights reserved. // import Foundation /// Specifies the Simple Pairing Randomizer /// Size: 16 octets /// Format defined in [Vol. 2], Part H Section 7.2.2 @frozen public struct GAPSimplePairingRandomizerR: GAPData, Equatable, Hashable { public static let dataType: GAPDataType = .simplePairingRandomizerR public let uuid: UUID public init(uuid: UUID) { self.uuid = uuid } } public extension GAPSimplePairingRandomizerR { init?(data: Data) { guard data.count == UInt128.length else { return nil } let uuid = UUID(UInt128(littleEndian: UInt128(bytes: (data[0], data[1], data[2], data[3], data[4], data[5], data[6], data[7], data[8], data[9], data[10], data[11], data[12], data[13], data[14], data[15])))) self.init(uuid: uuid) } func append(to data: inout Data) { data += UInt128(uuid: uuid).littleEndian } var dataLength: Int { return UInt128.length } } // MARK: - CustomStringConvertible extension GAPSimplePairingRandomizerR: CustomStringConvertible { public var description: String { return uuid.description } }
mit
416e95b680c66c0ca5fdfc2f08afde16
30.479452
74
0.36597
6.365651
false
false
false
false
bitboylabs/selluv-ios
selluv-ios/Pods/ALCameraViewController/ALCameraViewController/Views/CameraView.swift
1
8220
// // CameraView.swift // ALCameraViewController // // Created by Alex Littlejohn on 2015/06/17. // Copyright (c) 2015 zero. All rights reserved. // import UIKit import AVFoundation public class CameraView: UIView { var session: AVCaptureSession! var input: AVCaptureDeviceInput! var device: AVCaptureDevice! var imageOutput: AVCaptureStillImageOutput! var preview: AVCaptureVideoPreviewLayer! let cameraQueue = DispatchQueue(label: "com.zero.ALCameraViewController.Queue") let focusView = CropOverlay(frame: CGRect(x: 0, y: 0, width: 80, height: 80)) public var currentPosition = CameraGlobals.shared.defaultCameraPosition public func startSession() { session = AVCaptureSession() session.sessionPreset = AVCaptureSessionPresetPhoto device = cameraWithPosition(position: currentPosition) if let device = device , device.hasFlash { do { try device.lockForConfiguration() device.flashMode = .auto device.unlockForConfiguration() } catch _ {} } let outputSettings = [AVVideoCodecKey: AVVideoCodecJPEG] do { input = try AVCaptureDeviceInput(device: device) } catch let error as NSError { input = nil print("Error: \(error.localizedDescription)") return } if session.canAddInput(input) { session.addInput(input) } imageOutput = AVCaptureStillImageOutput() imageOutput.outputSettings = outputSettings session.addOutput(imageOutput) cameraQueue.sync { session.startRunning() DispatchQueue.main.async() { [weak self] in self?.createPreview() } } } public func stopSession() { cameraQueue.sync { session?.stopRunning() preview?.removeFromSuperlayer() session = nil input = nil imageOutput = nil preview = nil device = nil } } public override func layoutSubviews() { super.layoutSubviews() preview?.frame = bounds } public func configureFocus() { if let gestureRecognizers = gestureRecognizers { gestureRecognizers.forEach({ removeGestureRecognizer($0) }) } let tapGesture = UITapGestureRecognizer(target: self, action: #selector(focus(gesture:))) addGestureRecognizer(tapGesture) isUserInteractionEnabled = true addSubview(focusView) focusView.isHidden = true let lines = focusView.horizontalLines + focusView.verticalLines + focusView.outerLines lines.forEach { line in line.alpha = 0 } } internal func focus(gesture: UITapGestureRecognizer) { let point = gesture.location(in: self) guard focusCamera(toPoint: point) else { return } focusView.isHidden = false focusView.center = point focusView.alpha = 0 focusView.transform = CGAffineTransform(scaleX: 1.2, y: 1.2) bringSubview(toFront: focusView) UIView.animateKeyframes(withDuration: 1.5, delay: 0, options: UIViewKeyframeAnimationOptions(), animations: { UIView.addKeyframe(withRelativeStartTime: 0, relativeDuration: 0.15, animations: { [weak self] in self?.focusView.alpha = 1 self?.focusView.transform = CGAffineTransform.identity }) UIView.addKeyframe(withRelativeStartTime: 0.80, relativeDuration: 0.20, animations: { [weak self] in self?.focusView.alpha = 0 self?.focusView.transform = CGAffineTransform(scaleX: 0.8, y: 0.8) }) }, completion: { [weak self] finished in if finished { self?.focusView.isHidden = true } }) } private func createPreview() { preview = AVCaptureVideoPreviewLayer(session: session) preview.videoGravity = AVLayerVideoGravityResizeAspectFill preview.frame = bounds layer.addSublayer(preview) } private func cameraWithPosition(position: AVCaptureDevicePosition) -> AVCaptureDevice? { guard let devices = AVCaptureDevice.devices(withMediaType: AVMediaTypeVideo) as? [AVCaptureDevice] else { return nil } return devices.filter { $0.position == position }.first } public func capturePhoto(completion: @escaping CameraShotCompletion) { isUserInteractionEnabled = false guard let output = imageOutput, let orientation = AVCaptureVideoOrientation(rawValue: UIDevice.current.orientation.rawValue) else { completion(nil) return } let size = frame.size cameraQueue.sync { takePhoto(output, videoOrientation: orientation, cropSize: size) { image in DispatchQueue.main.async() { [weak self] in self?.isUserInteractionEnabled = true completion(image) } } } } public func focusCamera(toPoint: CGPoint) -> Bool { guard let device = device, let preview = preview, device.isFocusModeSupported(.continuousAutoFocus) else { return false } do { try device.lockForConfiguration() } catch { return false } let focusPoint = preview.captureDevicePointOfInterest(for: toPoint) device.focusPointOfInterest = focusPoint device.focusMode = .continuousAutoFocus device.exposurePointOfInterest = focusPoint device.exposureMode = .continuousAutoExposure device.unlockForConfiguration() return true } public func cycleFlash() { guard let device = device, device.hasFlash else { return } do { try device.lockForConfiguration() if device.flashMode == .on { device.flashMode = .off } else if device.flashMode == .off { device.flashMode = .auto } else { device.flashMode = .on } device.unlockForConfiguration() } catch _ { } } public func swapCameraInput() { guard let session = session, let currentInput = input else { return } session.beginConfiguration() session.removeInput(currentInput) if currentInput.device.position == AVCaptureDevicePosition.back { currentPosition = AVCaptureDevicePosition.front device = cameraWithPosition(position: currentPosition) } else { currentPosition = AVCaptureDevicePosition.back device = cameraWithPosition(position: currentPosition) } guard let newInput = try? AVCaptureDeviceInput(device: device) else { return } input = newInput session.addInput(newInput) session.commitConfiguration() } public func rotatePreview() { guard preview != nil else { return } switch UIApplication.shared.statusBarOrientation { case .portrait: preview?.connection.videoOrientation = AVCaptureVideoOrientation.portrait break case .portraitUpsideDown: preview?.connection.videoOrientation = AVCaptureVideoOrientation.portraitUpsideDown break case .landscapeRight: preview?.connection.videoOrientation = AVCaptureVideoOrientation.landscapeRight break case .landscapeLeft: preview?.connection.videoOrientation = AVCaptureVideoOrientation.landscapeLeft break default: break } } }
mit
f0df9c1af94863c18f398b7b402b8a8a
30.136364
139
0.58528
6.021978
false
false
false
false
acusti/gratituity
Gratituity/ViewController.swift
1
8298
// // ViewController.swift // Swift Tip Calculator // // Created by Andrew Patton on 2014-12-02. // Copyright (c) 2014 acusti.ca. All rights reserved. // import UIKit class ViewController: UIViewController, UITextFieldDelegate { // Declare storyboard's Interface Builder outlets @IBOutlet weak var textMealCost: UITextField! @IBOutlet weak var sliderTip: UISlider! @IBOutlet weak var labelTipValue: UILabel! @IBOutlet weak var labelTipCalculated: UILabel! @IBOutlet weak var labelTotalCalculated: UILabel! @IBOutlet weak var segmentedNumberPeople: UISegmentedControl! @IBOutlet weak var labelTipCalculatedPerPerson: UILabel! @IBOutlet weak var labelTotalCalculatedPerPerson: UILabel! // Declare defaults for resetting UI state var sliderTipDefault: Float = 0 var labelTipCalculatedDefault: String = "" var labelTotalCalculatedDefault: String = "" var segmentedNumberPeopleDefault: Int = 0 var labelTipCalculatedPerPersonDefault: String = "" var labelTotalCalculatedPerPersonDefault: String = "" var segmentedNumberPeopleOffset: Int = 2 // Fetch app styling constants let appStyles = GratuityStyles() // Kick it off override func viewDidLoad() { super.viewDidLoad() // Set default tint color self.view.tintColor = appStyles.colors["accent"] // Set up defaults textMealCost.delegate = self sliderTipDefault = sliderTip.value labelTipCalculatedDefault = labelTipCalculated.text! labelTotalCalculatedDefault = labelTotalCalculated.text! segmentedNumberPeopleDefault = segmentedNumberPeople.selectedSegmentIndex + segmentedNumberPeopleOffset labelTipCalculatedPerPersonDefault = labelTipCalculatedPerPerson.text! labelTotalCalculatedPerPersonDefault = labelTotalCalculatedPerPerson.text! // Set up Done toolbar for “cost of meal” numeric keyboard // If applicationFrame height is not tall enough if UIScreen.mainScreen().applicationFrame.height < 640 { let textMealCostDoneButton = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Done, target: self, action: "didTextMealCostEndEditing") let textMealCostSpaceButton = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil) let textMealCostToolbarButtons = [textMealCostSpaceButton, textMealCostDoneButton] let textMealCostToolbar = UIToolbar() textMealCostToolbar.sizeToFit() textMealCostToolbar.tintColor = appStyles.colors["accent"] textMealCostToolbar.barStyle = UIBarStyle.Black textMealCostToolbar.setItems(textMealCostToolbarButtons, animated: false) // Set toolbar as inputAccessoryView of textMealCost textMealCost.inputAccessoryView = textMealCostToolbar } // Give text meal cost field focus and show keyboard textMealCost.becomeFirstResponder() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // Use UITextField's shouldChangeCharactersInRange delegated action to trigger calculateTip func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString addedCharacter: String) -> Bool { // First validate to make sure we are not adding multiple decimal points if addedCharacter == "." && find(textField.text, ".") != nil { return false } // Reconstruct value of textfield for calculateTip() // The range represents what part of the text should be replaced by replacementString // If user added text, range length is 0; if user deleted, range length is 1 and replacementString is empty // Lastly, need to cast textField.text to NSString because range is an NSRange let textFieldBefore: NSString = textField.text var textFieldValue: String = textFieldBefore.substringToIndex(range.location) + addedCharacter + textFieldBefore.substringFromIndex(range.location + range.length) self.calculateTip(textFieldValue) return true } // Use UITextField's editing changed event to manage "$" prefix @IBAction func didTextMealCostChanged(sender: UITextField) { // Add "$" if not yet present (textfield is not empty and doesn't yet have "$") if countElements(sender.text) > 0 && sender.text[sender.text.startIndex] != "$" { sender.text = "$" + sender.text } } // When user clicks clear button in textfield, reset app state func textFieldShouldClear(textField: UITextField) -> Bool { resetState() return true } func didTextMealCostEndEditing() { textMealCost.resignFirstResponder() } // Calculate new tip when tip slider's value changes @IBAction func didSliderTipChange(sender: UISlider) { var tipFormat = NSString(format: "%0.f", sliderTip.value) labelTipValue.text = "\(tipFormat)%" calculateTip() } // Calculate new tip breakdown when number of diners value changes @IBAction func didSegmentedNumberPeopleChange(sender: UISegmentedControl) { calculateTip() } // Function to reset the app state // @param optional Bool isSliderTipReset indicates whether to also reset tipSlider func resetState(isSliderTipReset : Bool = false) { textMealCost.text = "" labelTipCalculated.text = labelTipCalculatedDefault labelTotalCalculated.text = labelTotalCalculatedDefault labelTipCalculatedPerPerson.text = labelTipCalculatedPerPersonDefault labelTotalCalculatedPerPerson.text = labelTotalCalculatedPerPersonDefault if isSliderTipReset { sliderTip.value = sliderTipDefault labelTipValue.text = "\(sliderTipDefault)" } } // Main logic to calculate the tip and display it (with function overloading) func calculateTip() -> Bool { return calculateTip(textMealCost.text) } func calculateTip(mealCost:String) -> Bool { // Tip percentage must be rounded to match label var tipPercentage: Float = round(sliderTip.value) // Make sure meal cost has no dollar sign var mealCostSanitized = mealCost if (countElements(mealCost) > 0 && mealCost[mealCost.startIndex] == "$") { mealCostSanitized = mealCost.substringFromIndex(advance(mealCost.startIndex, 1)) } var floatMealCost = (mealCostSanitized as NSString).floatValue var calculatedTip = floatMealCost * tipPercentage / 100 var calculatedTotal = calculatedTip + floatMealCost // Format calculations as currency var calculatedTipFormat = NSString(format: "%0.2f", calculatedTip) var calculatedTotalFormat = NSString(format: "%0.2f", calculatedTotal) labelTipCalculated.text = "$\(calculatedTipFormat)" labelTotalCalculated.text = "$\(calculatedTotalFormat)" // Now calculate tip and totals per person var numberPeople = Float(segmentedNumberPeople.selectedSegmentIndex + segmentedNumberPeopleOffset) var calculatedTipPerPerson = calculatedTip / numberPeople var calculatedTotalPerPerson = calculatedTotal / numberPeople // Format calculations as currency var calculatedTipPerPersonFormat = NSString(format: "%0.2f", calculatedTipPerPerson) var calculatedTotalPerPersonFormat = NSString(format: "%0.2f", calculatedTotalPerPerson) labelTipCalculatedPerPerson.text = "$\(calculatedTipPerPersonFormat)" labelTotalCalculatedPerPerson.text = "$\(calculatedTotalPerPersonFormat)" return true } }
unlicense
ef5f3346286eaef2105bb80c45e8d4c8
45.077778
157
0.669279
5.236111
false
false
false
false
mamelend/toDoListSwift
todolist/FirstViewController.swift
1
1718
// // FirstViewController.swift // todolist // // Created by Miguel Melendez on 3/27/16. // Copyright © 2016 Miguel Melendez. All rights reserved. // import UIKit var toDoList = [String]() class FirstViewController: UIViewController, UITableViewDelegate { @IBOutlet weak var tableView: UITableView! override func viewDidLoad() { super.viewDidLoad() if (NSUserDefaults.standardUserDefaults().objectForKey("toDoList") != nil) { toDoList = NSUserDefaults.standardUserDefaults().objectForKey("toDoList") as! [String] } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return toDoList.count } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: "Cell") cell.textLabel?.text = toDoList[indexPath.row] return cell } func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { if editingStyle == UITableViewCellEditingStyle.Delete { toDoList.removeAtIndex(indexPath.row) NSUserDefaults.standardUserDefaults().setObject(toDoList, forKey: "toDoList") tableView.reloadData() } } override func viewDidAppear(animated: Bool) { tableView.reloadData() } }
mit
bf884c09676b2aa4deb9afaff2b6ddf4
27.616667
148
0.663949
5.556634
false
false
false
false
nkirby/Humber
_lib/HMCore/_src/Sync Controller/SyncController.swift
1
560
// ======================================================= // HMCore // Nathaniel Kirby // ======================================================= import Foundation import ReactiveCocoa public enum SyncError: ErrorType { case UnableToSync case MissingNetworkConnection case Unknown } // ======================================================= public class SyncController: NSObject { public let userID: String public init(context: ServiceContext) { self.userID = context.userIdentifier super.init() } }
mit
189e366494bd82baa668be1534b377e6
21.4
58
0.469643
6.292135
false
false
false
false
darina/omim
iphone/Maps/Classes/Components/ExpandableReviewView/ExpandableReviewView.swift
5
4380
final class ExpandableReviewView: UIView { var contentLabel: UILabel = { let label = UILabel(frame: .zero) label.numberOfLines = 0 label.clipsToBounds = true label.translatesAutoresizingMaskIntoConstraints = false return label }() var moreLabel: UILabel = { let label = UILabel(frame: .zero) label.clipsToBounds = true label.translatesAutoresizingMaskIntoConstraints = false return label }() var moreLabelZeroHeight: NSLayoutConstraint! private var settings: ExpandableReviewSettings = ExpandableReviewSettings() private var isExpanded = false private var onUpdateHandler: (() -> Void)? override init(frame: CGRect) { super.init(frame: frame) configureContent() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) configureContent() } override func layoutSubviews() { super.layoutSubviews() updateRepresentation() } func configureContent() { self.addSubview(contentLabel) self.addSubview(moreLabel) let labels: [String: Any] = ["contentLabel": contentLabel, "moreLabel": moreLabel] var contentConstraints: [NSLayoutConstraint] = [] let verticalConstraints = NSLayoutConstraint.constraints(withVisualFormat: "V:|[contentLabel][moreLabel]", metrics: nil, views: labels) contentConstraints += verticalConstraints let moreBottomConstraint = bottomAnchor.constraint(equalTo: moreLabel.bottomAnchor) moreBottomConstraint.priority = .defaultLow contentConstraints.append(moreBottomConstraint) let contentHorizontalConstraints = NSLayoutConstraint.constraints(withVisualFormat: "H:|[contentLabel]|", metrics: nil, views: labels) contentConstraints += contentHorizontalConstraints let moreHorizontalConstraints = NSLayoutConstraint.constraints(withVisualFormat: "H:|[moreLabel]|", metrics: nil, views: labels) contentConstraints += moreHorizontalConstraints NSLayoutConstraint.activate(contentConstraints) moreLabelZeroHeight = moreLabel.heightAnchor.constraint(equalToConstant: 0.0) apply(settings: settings) layer.backgroundColor = UIColor.clear.cgColor isOpaque = true gestureRecognizers = nil addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(onTap))) } func apply(settings: ExpandableReviewSettings) { self.settings = settings self.contentLabel.textColor = settings.textColor self.contentLabel.font = settings.textFont self.moreLabel.font = settings.textFont self.moreLabel.textColor = settings.expandTextColor self.moreLabel.text = settings.expandText } override func applyTheme() { super.applyTheme() settings.textColor = settings.textColor.opposite() settings.expandTextColor = settings.expandTextColor.opposite() } func configure(text: String, isExpanded: Bool, onUpdate: @escaping () -> Void) { contentLabel.text = text self.isExpanded = isExpanded contentLabel.numberOfLines = isExpanded ? 0 : settings.numberOfCompactLines onUpdateHandler = onUpdate } @objc private func onTap() { if !isExpanded { isExpanded = true updateRepresentation() contentLabel.numberOfLines = 0 onUpdateHandler?() } } func updateRepresentation() { if let text = contentLabel.text, !text.isEmpty, !isExpanded { let height = (text as NSString).boundingRect(with: CGSize(width: contentLabel.bounds.width, height: .greatestFiniteMagnitude), options: .usesLineFragmentOrigin, attributes: [.font: contentLabel.font ?? UIFont.regular16], context: nil).height if height > contentLabel.bounds.height { moreLabelZeroHeight.isActive = false return } } moreLabelZeroHeight.isActive = true } }
apache-2.0
47f1ba58760e62b9286de098fb0aad1f
37.421053
110
0.629224
5.740498
false
false
false
false
qianyu09/AppLove
App Love/UI/ViewControllers/TableViewDataSources/AppSearchExtension.swift
1
1596
// // AppSearchExtension.swift // App Love // // Created by Woodie Dovich on 2016-04-04. // Copyright © 2016 Snowpunch. All rights reserved. // // Table for search results. Can multi-select rows. // import UIKit extension AppSearchViewController { func setTableStyle() { self.tableView.separatorStyle = .None self.tableView.allowsMultipleSelection = true; } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("AppSelectCellID", forIndexPath: indexPath) as! AppSelectCell let model = self.apps[indexPath.row] cell.setup(model) return cell } // select app override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { let cell = tableView.cellForRowAtIndexPath(indexPath) as! AppSelectCell cell.addSwitch.setOn(true, animated: true) let model = self.apps[indexPath.row] SearchList.sharedInst.addAppModel(model) } // deselect app override func tableView(tableView: UITableView, didDeselectRowAtIndexPath indexPath: NSIndexPath) { let cell = tableView.cellForRowAtIndexPath(indexPath) as! AppSelectCell cell.addSwitch.setOn(false, animated: true) let model = self.apps[indexPath.row] SearchList.sharedInst.removeAppModel(model) } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return apps.count } }
mit
96293e52a4e7ec812eb30319208d291f
33.695652
124
0.702821
4.732938
false
false
false
false
wangzheng0822/algo
swift/09_queue/QueueBasedOnLinkedList.swift
1
1151
// // Created by Jiandan on 2018/10/11. // Copyright (c) 2018 Jiandan. All rights reserved. // import Foundation struct QueueBasedOnLinkedList<Element>: Queue { /// 队首 var head: Node<Element>? /// 队尾 var tail: Node<Element>? // MARK: Protocol: Queue var isEmpty: Bool { return head == nil } var size: Int { if isEmpty { return 0 } var count = 1 // head 本身算一个 while head?.next != nil { count += 1 } return count } var peek: Element? { return head?.value } mutating func enqueue(newElement: Element) -> Bool { if isEmpty { // 空队列 let node = Node(value: newElement) head = node tail = node } else { tail!.next = Node(value: newElement) tail = tail!.next } return true } mutating func dequeue() -> Element? { if isEmpty { return nil } let node = head head = head!.next return node?.value } }
apache-2.0
a099c9594ab5f44d9ac3553ca99d4bbd
19.490909
56
0.478261
4.454545
false
false
false
false
davejlin/treehouse
swift/swift2/scrollview-tutorial/ScrollViewTutorial/PageView.swift
1
714
// // PageView.swift // ScrollViewTutorial // // Created by Lin David, US-205 on 11/6/16. // Copyright © 2016 Lin David. All rights reserved. // import UIKit class PageView: UIView { @IBOutlet weak var label: UILabel! @IBOutlet weak var imageView: UIImageView! class func loadFromNib() -> PageView { let bundle = NSBundle(forClass: self) let nib = UINib(nibName: "PageView", bundle: bundle) let view = nib.instantiateWithOwner(self, options: nil)[0] as! PageView return view } func configure(data: [String: String]) { label.text = data["title"] let image = UIImage(named: data["image"]!) imageView.image = image } }
unlicense
958f4ccf012123e2d039f905ef4c327a
24.464286
79
0.624123
4.028249
false
false
false
false
jingchc/Mr-Ride-iOS
Mr-Ride-iOS/AppDelegate.swift
1
6168
// // AppDelegate.swift // Mr-Ride-iOS // // Created by 莊晶涵 on 2016/5/23. // Copyright © 2016年 AppWorks School Jing. All rights reserved. // import UIKit import CoreData import FBSDKCoreKit import Fabric import Crashlytics @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { Fabric.with([Crashlytics.self]) return FBSDKApplicationDelegate.sharedInstance().application(application, didFinishLaunchingWithOptions: launchOptions) } func applicationWillResignActive(application: UIApplication) { FBSDKAppEvents.activateApp() } func application(application: UIApplication, openURL url: NSURL, sourceApplication: String?, annotation: AnyObject) -> Bool { return FBSDKApplicationDelegate.sharedInstance().application(application, openURL: url, sourceApplication: sourceApplication, annotation: annotation) } 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:. // Saves changes in the application's managed object context before the application terminates. self.saveContext() } // MARK: - Core Data stack lazy var applicationDocumentsDirectory: NSURL = { // The directory the application uses to store the Core Data store file. This code uses a directory named "com.appworks-school-Jing.Mr_Ride_iOS" in the application's documents Application Support directory. let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask) return urls[urls.count-1] }() lazy var managedObjectModel: NSManagedObjectModel = { // The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model. let modelURL = NSBundle.mainBundle().URLForResource("Mr_Ride_iOS", withExtension: "momd")! return NSManagedObjectModel(contentsOfURL: modelURL)! }() lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator = { // The persistent store coordinator for the application. This implementation creates and returns a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail. // Create the coordinator and store let coordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel) let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("SingleViewCoreData.sqlite") var failureReason = "There was an error creating or loading the application's saved data." do { try coordinator.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil) } catch { // Report any error we got. var dict = [String: AnyObject]() dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data" dict[NSLocalizedFailureReasonErrorKey] = failureReason dict[NSUnderlyingErrorKey] = error as NSError let wrappedError = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict) // Replace this with code to handle the error appropriately. // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. NSLog("Unresolved error \(wrappedError), \(wrappedError.userInfo)") abort() } return coordinator }() lazy var managedObjectContext: NSManagedObjectContext = { // Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail. let coordinator = self.persistentStoreCoordinator var managedObjectContext = NSManagedObjectContext(concurrencyType: .MainQueueConcurrencyType) managedObjectContext.persistentStoreCoordinator = coordinator return managedObjectContext }() // MARK: - Core Data Saving support func saveContext () { if managedObjectContext.hasChanges { do { try managedObjectContext.save() } catch { // Replace this implementation with code to handle the error appropriately. // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. let nserror = error as NSError NSLog("Unresolved error \(nserror), \(nserror.userInfo)") abort() } } } }
apache-2.0
60e378d4b6a9f5924e12555414171bf4
50.756303
291
0.71976
5.899425
false
false
false
false
darthpelo/SurviveAmsterdam
mobile/Pods/QuadratTouch/Source/Shared/Endpoints/Pages.swift
4
2631
// // Pages.swift // Quadrat // // Created by Constantine Fry on 06/11/14. // Copyright (c) 2014 Constantine Fry. All rights reserved. // import Foundation public class Pages: Endpoint { override var endpoint: String { return "pages" } // MARK: - General /** https://developer.foursquare.com/docs/pages/add */ public func add(name: String, completionHandler: ResponseClosure? = nil) -> Task { let path = "add" let parameters = [Parameter.name: name] return self.postWithPath(path, parameters: parameters, completionHandler: completionHandler) } /** https://developer.foursquare.com/docs/pages/managing */ public func managing(completionHandler: ResponseClosure? = nil) -> Task { let path = "managing" return self.getWithPath(path, parameters: nil, completionHandler: completionHandler) } // MARK: - Aspects /** https://developer.foursquare.com/docs/pages/access */ public func access(userId: String, completionHandler: ResponseClosure? = nil) -> Task { let path = userId + "/access" return self.getWithPath(path, parameters: nil, completionHandler: completionHandler) } /** https://developer.foursquare.com/docs/pages/similar */ public func similar(userId: String, parameters: Parameters?, completionHandler: ResponseClosure? = nil) -> Task { let path = userId + "/similar" return self.getWithPath(path, parameters: parameters, completionHandler: completionHandler) } /** https://developer.foursquare.com/docs/pages/timeseries */ public func timeseries(pageId: String, parameters: Parameters?, completionHandler: ResponseClosure? = nil) -> Task { let path = pageId + "/timeseries" return self.getWithPath(path, parameters: parameters, completionHandler: completionHandler) } /** https://developer.foursquare.com/docs/pages/venues */ public func venues(pageId: String, parameters: Parameters?, completionHandler: ResponseClosure? = nil) -> Task { let path = pageId + "/venues" return self.getWithPath(path, parameters: parameters, completionHandler: completionHandler) } // MARK: - Actions /** https://developer.foursquare.com/docs/pages/follow */ public func follow(pageId: String, follow: Bool, completionHandler: ResponseClosure? = nil) -> Task { let path = pageId + "/follow" let parameters = [Parameter.set: (follow) ? "1":"0"] return self.postWithPath(path, parameters: parameters, completionHandler: completionHandler) } }
mit
7a81342d1cde278c95ba8455f173d59a
38.268657
120
0.668187
4.615789
false
false
false
false
myTargetSDK/mytarget-ios
myTargetDemoSwift/myTargetDemo/Controllers/NativeBannerViewController.swift
1
4736
// // NativeBannerViewController.swift // myTargetDemo // // Created by Andrey Seredkin on 01/04/2020. // Copyright © 2020 Mail.Ru Group. All rights reserved. // import UIKit import MyTargetSDK class NativeBannerViewController: UIViewController, AdViewController, MTRGNativeBannerAdDelegate { var query: [String : String]? var slotId: UInt? private var nativeBannerAds = [MTRGNativeBannerAd]() private var nativeBannerAdLoader: MTRGNativeBannerAdLoader? private var nativeBannerViews = [UIView]() private var notificationView: NotificationView? private let collectionController = CollectionViewController() @IBOutlet weak var showButton: CustomButton! override func viewDidLoad() { super.viewDidLoad() navigationItem.title = "Native Banner Ad" notificationView = NotificationView.create(view: view) notificationView?.navigationBarHeight = navigationController?.navigationBar.frame.height ?? 0.0 collectionController.adViewController = self } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) notificationView?.view = view } private func createNativeBanner(_ banner: MTRGNativeBanner) -> UIView? { let nativeBannerAdView = MTRGNativeViewsFactory.createNativeBannerAdView() nativeBannerAdView.banner = banner let nativeAdContainer = MTRGNativeAdContainer.create(withAdView: nativeBannerAdView) nativeAdContainer.ageRestrictionsView = nativeBannerAdView.ageRestrictionsLabel nativeAdContainer.advertisingView = nativeBannerAdView.adLabel nativeAdContainer.iconView = nativeBannerAdView.iconAdView nativeAdContainer.domainView = nativeBannerAdView.domainLabel nativeAdContainer.disclaimerView = nativeBannerAdView.disclaimerLabel nativeAdContainer.ratingView = nativeBannerAdView.ratingStarsLabel nativeAdContainer.votesView = nativeBannerAdView.votesLabel nativeAdContainer.ctaView = nativeBannerAdView.buttonView nativeAdContainer.titleView = nativeBannerAdView.titleLabel return nativeAdContainer } @IBAction func show(_ sender: CustomButton) { refresh() notificationView?.view = collectionController.view navigationController?.pushViewController(collectionController, animated: true) } func refresh() { let slotId = self.slotId ?? Slot.nativeBanner.rawValue let nativeBannerAdLoader = MTRGNativeBannerAdLoader.init(forCount: 3, slotId: slotId) self.nativeBannerAdLoader = nativeBannerAdLoader self.setQueryParams(for: nativeBannerAdLoader) nativeBannerAds.removeAll() nativeBannerViews.removeAll() notificationView?.showMessage("Loading...") nativeBannerAdLoader.load { (nativeBannerAds: [MTRGNativeBannerAd]) in self.notificationView?.showMessage("Loaded \(nativeBannerAds.count) ads") self.nativeBannerAds = nativeBannerAds for nativeBannerAd in nativeBannerAds { if let banner = nativeBannerAd.banner, let adView = self.createNativeBanner(banner) { self.nativeBannerViews.append(adView) nativeBannerAd.register(adView, with: self.collectionController) } } self.collectionController.adViews = self.nativeBannerViews } } func loadMore() { let slotId = self.slotId ?? Slot.nativeBanner.rawValue let nativeBannerAd = MTRGNativeBannerAd(slotId: slotId) nativeBannerAd.delegate = self self.setQueryParams(for: nativeBannerAd) nativeBannerAd.load() nativeBannerAds.append(nativeBannerAd) notificationView?.showMessage("Loading...") } func supportsInfiniteScroll() -> Bool { return true } // MARK: - MTRGNativeBannerAdDelegate func onLoad(with banner: MTRGNativeBanner, nativeBannerAd: MTRGNativeBannerAd) { showButton.isEnabled = true notificationView?.showMessage("onLoad() called") if let adView = createNativeBanner(banner) { nativeBannerViews.append(adView) nativeBannerAd.register(adView, with: collectionController) } collectionController.adViews = nativeBannerViews } func onNoAd(withReason reason: String, nativeBannerAd: MTRGNativeBannerAd) { notificationView?.showMessage("onNoAd(\(reason)) called") collectionController.adViews = nativeBannerViews } func onAdShow(with nativeBannerAd: MTRGNativeBannerAd) { notificationView?.showMessage("onAdShow() called") } func onAdClick(with nativeBannerAd: MTRGNativeBannerAd) { notificationView?.showMessage("onAdClick() called") } func onShowModal(with nativeBannerAd: MTRGNativeBannerAd) { notificationView?.showMessage("onShowModal() called") } func onDismissModal(with nativeBannerAd: MTRGNativeBannerAd) { notificationView?.showMessage("onDismissModal() called") } func onLeaveApplication(with nativeBannerAd: MTRGNativeBannerAd) { notificationView?.showMessage("onLeaveApplication() called") } }
lgpl-3.0
ef029845ceb8191aa173f2305463d210
28.779874
97
0.78754
4.005922
false
false
false
false
wireapp/wire-ios-data-model
Tests/Source/Model/Observer/ChangedIndexesTests.swift
1
9935
// // 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 XCTest @testable import WireDataModel class ChangedIndexesTests: ZMBaseManagedObjectTest { // MARK: CollectionView func testThatItCalculatesInsertsAndDeletesBetweenSets() { // given let startState = WireDataModel.OrderedSetState(array: ["A", "B", "C", "D", "E"]) let endState = WireDataModel.OrderedSetState(array: ["A", "F", "E", "C", "D"]) // when let sut = WireDataModel.ChangedIndexes(start: startState, end: endState, updated: Set()) // then XCTAssertEqual(sut.deletedIndexes, [1]) XCTAssertEqual(sut.insertedIndexes, [1]) } func testThatItCalculatesMovesCorrectly() { // given let startState = WireDataModel.OrderedSetState(array: ["A", "B", "C", "D", "E"]) let endState = WireDataModel.OrderedSetState(array: ["A", "F", "D", "C", "E"]) // when let sut = WireDataModel.ChangedIndexes(start: startState, end: endState, updated: Set()) // then // [A,B,C,D,E] -> [A,F,C,D,E] delete & insert var callCount = 0 sut.enumerateMovedIndexes { (from, to) in if callCount == 0 { // D: [3->2] XCTAssertEqual(from, 3) XCTAssertEqual(to, 2) } callCount += 1 } XCTAssertEqual(callCount, 1) var result = ["A", "B", "C", "D", "E"] sut.deletedIndexes.forEach {result.remove(at: $0)} sut.insertedIndexes.forEach {result.insert(endState.array[$0], at: $0)} sut.enumerateMovedIndexes { (from, to) in let item = startState.array[from] result.remove(at: result.firstIndex(of: item)!) result.insert(item, at: to) } XCTAssertEqual(result, ["A", "F", "D", "C", "E"]) } func testThatItCalculatesMovesCorrectly_2() { // given let startState = WireDataModel.OrderedSetState(array: ["A", "B", "C", "D", "E"]) let endState = WireDataModel.OrderedSetState(array: ["A", "D", "E", "F", "C"]) // when let sut = WireDataModel.ChangedIndexes(start: startState, end: endState, updated: Set()) // then // [A,B,C,D,E] -> [A,C,D,F,E] delete & insert var callCount = 0 sut.enumerateMovedIndexes { (from, to) in if callCount == 0 { // ACDFE // E: [3->1] -> ADCFE XCTAssertEqual(from, 3) XCTAssertEqual(to, 1) } if callCount == 1 { // ADCFE // D: [4->2] -> ADECF XCTAssertEqual(from, 4) XCTAssertEqual(to, 2) } if callCount == 2 { // ADECF // C: [2->4] -> ADEFC XCTAssertEqual(from, 2) XCTAssertEqual(to, 4) } callCount += 1 } XCTAssertEqual(callCount, 3) var result = ["A", "B", "C", "D", "E"] sut.deletedIndexes.forEach {result.remove(at: $0)} sut.insertedIndexes.forEach {result.insert(endState.array[$0], at: $0)} sut.enumerateMovedIndexes { (from, to) in let item = startState.array[from] result.remove(at: result.firstIndex(of: item)!) result.insert(item, at: to) } XCTAssertEqual(result, ["A", "D", "E", "F", "C"]) } func testThatItCalculatesMovedIndexesForSwappedIndexesCorrectly() { // If you move an item from 0->1 another item has to move to index 0 // given let startState = WireDataModel.OrderedSetState(array: ["A", "B", "C"]) let endState = WireDataModel.OrderedSetState(array: ["C", "B", "A"]) // when let sut = WireDataModel.ChangedIndexes(start: startState, end: endState, updated: Set()) // then XCTAssertEqual(sut.deletedIndexes, IndexSet()) XCTAssertEqual(sut.insertedIndexes, IndexSet()) // then var callCount = 0 sut.enumerateMovedIndexes { (from, to) in if callCount == 0 { XCTAssertEqual(from, 2) XCTAssertEqual(to, 0) } if callCount == 1 { XCTAssertEqual(from, 1) XCTAssertEqual(to, 1) } callCount += 1 } XCTAssertEqual(callCount, 2) var result = ["A", "B", "C"] sut.enumerateMovedIndexes { (from, to) in let item = startState.array[from] result.remove(at: result.firstIndex(of: item)!) result.insert(item, at: to) } XCTAssertEqual(result, ["C", "B", "A"]) } func testThatItCalculatesUpdatesCorrectly() { // Updated indexes refer to the indexes after the update // given let startState = WireDataModel.OrderedSetState(array: ["A", "B", "C"]) let endState = WireDataModel.OrderedSetState(array: ["C", "D", "B", "A"]) // when let sut = WireDataModel.ChangedIndexes(start: startState, end: endState, updated: Set(["B"])) // then XCTAssertEqual(sut.updatedIndexes, IndexSet([2])) } // MARK: TableView func testThatItCalculatesMovesCorrectly_tableView() { // given let startState = WireDataModel.OrderedSetState(array: ["A", "B", "C", "D", "E"]) let endState = WireDataModel.OrderedSetState(array: ["A", "F", "D", "C", "E"]) // when let sut = WireDataModel.ChangedIndexes(start: startState, end: endState, updated: Set(), moveType: .uiTableView) // then // [A,B,C,D,E] -> [A,F,C,D,E] delete & insert var callCount = 0 sut.enumerateMovedIndexes { (from, to) in if callCount == 0 { // D: [3->2] XCTAssertEqual(from, 3) XCTAssertEqual(to, 2) } callCount += 1 } XCTAssertEqual(callCount, 1) var result = ["A", "B", "C", "D", "E"] sut.deletedIndexes.forEach {result.remove(at: $0)} sut.insertedIndexes.forEach {result.insert(endState.array[$0], at: $0)} sut.enumerateMovedIndexes { (from, to) in let item = result.remove(at: from) result.insert(item, at: to) } XCTAssertEqual(result, ["A", "F", "D", "C", "E"]) } func testThatItCalculatesMovesCorrectly_2_tableView() { // given let startState = WireDataModel.OrderedSetState(array: ["A", "B", "C", "D", "E"]) let endState = WireDataModel.OrderedSetState(array: ["A", "D", "E", "F", "C"]) // when let sut = WireDataModel.ChangedIndexes(start: startState, end: endState, updated: Set(), moveType: .uiTableView) // then // [A,B,C,D,E] -> [A,C,D,F,E] delete & insert var callCount = 0 sut.enumerateMovedIndexes { (from, to) in if callCount == 0 { // ACDFE // E: [3->1] -> ADCFE XCTAssertEqual(from, 2) XCTAssertEqual(to, 1) } if callCount == 1 { // ADCFE // D: [4->2] -> ADECF XCTAssertEqual(from, 4) XCTAssertEqual(to, 2) } if callCount == 2 { // ADECF // C: [2->4] -> ADEFC XCTAssertEqual(from, 4) XCTAssertEqual(to, 3) } callCount += 1 } XCTAssertEqual(callCount, 3) var result = ["A", "B", "C", "D", "E"] sut.deletedIndexes.forEach {result.remove(at: $0)} sut.insertedIndexes.forEach {result.insert(endState.array[$0], at: $0)} sut.enumerateMovedIndexes { (from, to) in let item = result.remove(at: from) result.insert(item, at: to) } XCTAssertEqual(result, ["A", "D", "E", "F", "C"]) } func testThatItCalculatesMovedIndexesForSwappedIndexesCorrectly_tableView() { // If you move an item from 0->1 the item at index 1 moves implicitly to 0, its move do not need to be defined // given let startState = WireDataModel.OrderedSetState(array: ["A", "B", "C"]) let endState = WireDataModel.OrderedSetState(array: ["C", "B", "A"]) // when let sut = WireDataModel.ChangedIndexes(start: startState, end: endState, updated: Set(), moveType: .uiTableView) // then XCTAssertEqual(sut.deletedIndexes, IndexSet()) XCTAssertEqual(sut.insertedIndexes, IndexSet()) // then var callCount = 0 sut.enumerateMovedIndexes { (from, to) in if callCount == 0 { XCTAssertEqual(from, 2) XCTAssertEqual(to, 0) } if callCount == 1 { XCTAssertEqual(from, 2) XCTAssertEqual(to, 1) } callCount += 1 } XCTAssertEqual(callCount, 2) var result = ["A", "B", "C"] sut.enumerateMovedIndexes { (from, to) in let item = result.remove(at: from) result.insert(item, at: to) } XCTAssertEqual(result, ["C", "B", "A"]) } }
gpl-3.0
ffd3e47f4aad2690ad850b49e6386ad2
33.737762
120
0.540815
4.070053
false
false
false
false
realm/SwiftLint
Source/SwiftLintFramework/Rules/Style/ImplicitReturnRuleExamples.swift
1
4790
internal struct ImplicitReturnRuleExamples { internal struct GenericExamples { static let nonTriggeringExamples = [Example("if foo {\n return 0\n}")] } internal struct ClosureExamples { static let nonTriggeringExamples = [ Example("foo.map { $0 + 1 }"), Example("foo.map({ $0 + 1 })"), Example("foo.map { value in value + 1 }"), Example(""" [1, 2].first(where: { true }) """) ] static let triggeringExamples = [ Example(""" foo.map { value in return value + 1 } """), Example(""" foo.map { return $0 + 1 } """), Example("foo.map({ return $0 + 1})"), Example(""" [1, 2].first(where: { return true }) """) ] static let corrections = [ Example("foo.map { value in\n return value + 1\n}"): Example("foo.map { value in\n value + 1\n}"), Example("foo.map {\n return $0 + 1\n}"): Example("foo.map {\n $0 + 1\n}"), Example("foo.map({ return $0 + 1})"): Example("foo.map({ $0 + 1})"), Example("[1, 2].first(where: {\n return true })"): Example("[1, 2].first(where: {\n true })") ] } internal struct FunctionExamples { static let nonTriggeringExamples = [ Example(""" func foo() -> Int { 0 } """), Example(""" class Foo { func foo() -> Int { 0 } } """), Example(""" func fetch() -> Data? { do { return try loadData() } catch { return nil } } """) ] static let triggeringExamples = [ Example(""" func foo() -> Int { return 0 } """), Example(""" class Foo { func foo() -> Int { return 0 } } """) ] static let corrections = [ Example("func foo() -> Int {\n return 0\n}"): Example("func foo() -> Int {\n 0\n}"), // swiftlint:disable:next line_length Example("class Foo {\n func foo() -> Int {\n return 0\n }\n}"): Example("class Foo {\n func foo() -> Int {\n 0\n }\n}") ] } internal struct GetterExamples { static let nonTriggeringExamples = [ Example("var foo: Bool { true }"), Example(""" class Foo { var bar: Int { get { 0 } } } """), Example(""" class Foo { static var bar: Int { 0 } } """) ] static let triggeringExamples = [ Example("var foo: Bool { return true }"), Example(""" class Foo { var bar: Int { get { return 0 } } } """), Example(""" class Foo { static var bar: Int { return 0 } } """) ] static let corrections = [ Example("var foo: Bool { return true }"): Example("var foo: Bool { true }"), // swiftlint:disable:next line_length Example("class Foo {\n var bar: Int {\n get {\n return 0\n }\n }\n}"): Example("class Foo {\n var bar: Int {\n get {\n 0\n }\n }\n}") ] } static let nonTriggeringExamples = GenericExamples.nonTriggeringExamples + ClosureExamples.nonTriggeringExamples + FunctionExamples.nonTriggeringExamples + GetterExamples.nonTriggeringExamples static let triggeringExamples = ClosureExamples.triggeringExamples + FunctionExamples.triggeringExamples + GetterExamples.triggeringExamples static var corrections: [Example: Example] { let corrections: [[Example: Example]] = [ ClosureExamples.corrections, FunctionExamples.corrections, GetterExamples.corrections ] return corrections.reduce(into: [:]) { result, element in result.merge(element) { _, _ in preconditionFailure("Duplicate correction in implicit return rule examples.") } } } }
mit
e6ed45deceacd1cdb3ad121241958b2b
29.316456
171
0.41858
5.206522
false
false
false
false
loisie123/Cuisine-Project
Cuisine/CormetStandardViewController.swift
1
3902
// // CormetStandardViewController.swift // Cuisine // // Created by Lois van Vliet on 24-01-17. // Copyright © 2017 Lois van Vliet. All rights reserved. // import UIKit import Firebase class CormetStandardViewController: UIViewController,UITableViewDelegate, UITableViewDataSource { var ref: FIRDatabaseReference? var databaseHandle: FIRDatabaseHandle? var listAllNames = [[String]]() var listCategoryName = [String]() var listOfmeals = [meals]() @IBOutlet weak var standaardAssortimentTableView: UITableView! override func viewDidLoad() { getStandardAssortiment() super.viewDidLoad() ref = FIRDatabase.database().reference() } //MARK:- Get dishes from firebase and fill the different lists that are used to make the tableView //referencen: https://firebase.google.com/docs/database/admin/retrieve-data func getStandardAssortiment() { // Maak de lijsten leeg: listAllNames = [[String]]() listOfmeals = [meals]() print ("wanneer gaat hij hier doorheen") let ref = FIRDatabase.database().reference() let categories = ["Bread", "Dairy", "Drinks", "Fruits", "Salads", "Warm food", "Wraps", "Remaining Categories"] ref.child("cormet").child("Standard Assortment").queryOrderedByKey().observeSingleEvent(of: .value, with: { (snapshot) in (self.listAllNames, self.listOfmeals) = self.getMealInformation(snapshot: snapshot, categories: categories, kindOfCategorie: "categorie") self.standaardAssortimentTableView.reloadData() }) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } //MARK:- TableView with sections func numberOfSections(in tableView: UITableView) -> Int { return listAllNames.count } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 100 } func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) { if editingStyle == .delete { let index = indexPath.row let removelist = listAllNames[indexPath.section] let remove = removelist[index + 1] myDeleteFunction(firstTree: "cormet", secondTree: "Standard Assortment", childIWantToRemove: remove) } viewDidLoad() } func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { var returnedView = UIView(frame: CGRect(x: 0, y: 0, width: view.frame.size.width, height: 50)) returnedView = makeSectionHeader(returnedView: returnedView, section: section, listAllNames: listAllNames) return returnedView } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return listAllNames[section].count-1 } func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { return listAllNames[section][0] } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "standaardCell", for: indexPath) as! CormetStandaardTableViewCell for meal in listOfmeals{ if meal.name == listAllNames[indexPath.section][indexPath.row+1]{ cell.nameMeal.text = meal.name cell.priceMeal.text = "€ \(meal.price!)" cell.likesMeal.text = " \(meal.likes!) likes" } } return cell } }
mit
a9bce1b52aa1fc91e229c8cf1c38fe9e
32.042373
149
0.632726
4.843478
false
false
false
false
frootloops/swift
test/SILOptimizer/definite_init_objc_factory_init.swift
1
4158
// RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) -I %S/../IDE/Inputs/custom-modules %s -emit-sil -enable-sil-ownership | %FileCheck %s // REQUIRES: objc_interop import Foundation import ImportAsMember.Class // CHECK-LABEL: sil shared [serializable] [thunk] @_T0So4HiveCSQyABGSQySo3BeeCG5queen_tcfCTO : $@convention(method) (@owned Optional<Bee>, @thick Hive.Type) -> @owned Optional<Hive> func testInstanceTypeFactoryMethod(queen: Bee) { // CHECK: bb0([[QUEEN:%[0-9]+]] : $Optional<Bee>, [[HIVE_META:%[0-9]+]] : $@thick Hive.Type): // CHECK-NEXT: [[HIVE_META_OBJC:%[0-9]+]] = thick_to_objc_metatype [[HIVE_META]] : $@thick Hive.Type to $@objc_metatype Hive.Type // CHECK-NEXT: [[FACTORY:%[0-9]+]] = objc_method [[HIVE_META_OBJC]] : $@objc_metatype Hive.Type, #Hive.init!allocator.1.foreign : (Hive.Type) -> (Bee!) -> Hive!, $@convention(objc_method) (Optional<Bee>, @objc_metatype Hive.Type) -> @autoreleased Optional<Hive> // CHECK-NEXT: [[HIVE:%[0-9]+]] = apply [[FACTORY]]([[QUEEN]], [[HIVE_META_OBJC]]) : $@convention(objc_method) (Optional<Bee>, @objc_metatype Hive.Type) -> @autoreleased Optional<Hive> // CHECK-NEXT: release_value [[QUEEN]] // CHECK-NEXT: return [[HIVE]] : $Optional<Hive> var hive1 = Hive(queen: queen) } extension Hive { // FIXME: This whole approach is wrong. This should be a factory // initializer, not a convenience initializer, which means it does // not have an initializing entry point at all. // CHECK-LABEL: sil hidden @_T0So4HiveC027definite_init_objc_factory_C0EABSo3BeeC10otherQueen_tcfc : $@convention(method) (@owned Bee, @owned Hive) -> @owned Hive convenience init(otherQueen other: Bee) { // CHECK: [[SELF_ADDR:%[0-9]+]] = alloc_stack $Hive // CHECK: store [[OLD_SELF:%[0-9]+]] to [[SELF_ADDR]] // CHECK: [[META:%[0-9]+]] = value_metatype $@thick Hive.Type, [[OLD_SELF]] : $Hive // CHECK: [[OBJC_META:%[0-9]+]] = thick_to_objc_metatype [[META]] : $@thick Hive.Type to $@objc_metatype Hive.Type // CHECK: [[FACTORY:%[0-9]+]] = objc_method [[OBJC_META]] : $@objc_metatype Hive.Type, #Hive.init!allocator.1.foreign : (Hive.Type) -> (Bee!) -> Hive!, $@convention(objc_method) (Optional<Bee>, @objc_metatype Hive.Type) -> @autoreleased Optional<Hive> // CHECK: apply [[FACTORY]]([[QUEEN:%[0-9]+]], [[OBJC_META]]) : $@convention(objc_method) (Optional<Bee>, @objc_metatype Hive.Type) -> @autoreleased Optional<Hive> // CHECK: store [[NEW_SELF:%[0-9]+]] to [[SELF_ADDR]] // CHECK: [[METATYPE:%.*]] = value_metatype $@thick Hive.Type, [[OLD_SELF]] : $Hive // CHECK: dealloc_partial_ref [[OLD_SELF]] : $Hive, [[METATYPE]] : $@thick Hive.Type // CHECK: dealloc_stack [[SELF_ADDR]] // CHECK: return [[NEW_SELF]] self.init(queen: other) } convenience init(otherFlakyQueen other: Bee) throws { try self.init(flakyQueen: other) } } extension SomeClass { // SIL-LABEL: sil hidden @_TFE16import_as_memberCSo9SomeClasscfT6doubleSd_S0_ // SIL: bb0([[DOUBLE:%[0-9]+]] : $Double // SIL-NOT: value_metatype // SIL: [[FNREF:%[0-9]+]] = function_ref @MakeIAMSomeClass // SIL: apply [[FNREF]]([[DOUBLE]]) convenience init(double: Double) { self.init(value: double) } } class SubHive : Hive { // CHECK-LABEL: sil hidden @_T0027definite_init_objc_factory_B07SubHiveCACyt20delegatesToInherited_tcfc : $@convention(method) (@owned SubHive) -> @owned SubHive convenience init(delegatesToInherited: ()) { // CHECK: [[UPCAST:%.*]] = upcast %0 : $SubHive to $Hive // CHECK: [[METATYPE:%.*]] = value_metatype $@thick Hive.Type, [[UPCAST]] : $Hive // CHECK: [[OBJC:%.*]] = thick_to_objc_metatype [[METATYPE]] : $@thick Hive.Type to $@objc_metatype Hive.Type // CHECK: [[METHOD:%.*]] = objc_method [[OBJC]] : $@objc_metatype Hive.Type, #Hive.init!allocator.1.foreign : (Hive.Type) -> (Bee!) -> Hive! // CHECK: apply [[METHOD]]({{.*}}, [[OBJC]]) // CHECK: [[METATYPE:%.*]] = value_metatype $@thick SubHive.Type, %0 : $SubHive // CHECK-NEXT: dealloc_partial_ref %0 : $SubHive, [[METATYPE]] : $@thick SubHive.Type // CHECK: return {{%.*}} : $SubHive self.init(queen: Bee()) } }
apache-2.0
a5b655e98d29f73b291d5ec82181fa59
57.56338
265
0.643338
3.353226
false
false
false
false
andrea-prearo/LiteJSONConvertible
LiteJSONConvertibleTests/Utils.swift
1
4795
// // Utils.swift // LiteJSONConvertible // // Created by Andrea Prearo on 4/5/16. // Copyright © 2016 Andrea Prearo // import Foundation import LiteJSONConvertible import XCTest class Utils { class func loadJsonFrom(baseFileName: String) throws -> AnyObject? { var responseDict: AnyObject? if let fileURL = NSBundle(forClass: self).URLForResource(baseFileName, withExtension: "json") { if let jsonData = NSData(contentsOfURL: fileURL) { responseDict = try! NSJSONSerialization.JSONObjectWithData(jsonData, options: .AllowFragments) } } return responseDict } class func loadJsonData(data: NSData) throws -> AnyObject? { return try! NSJSONSerialization.JSONObjectWithData(data, options: .AllowFragments) } class func comparePhone(phones: [Phone?]?, json: [JSON]?) { if let phones = phones, json = json { for (var i=0; i < phones.count; i++) { let json = json[i] if let phone = phones[i] { if let label = phone.label { XCTAssertEqual(label, json <| "label") } else { XCTAssertNil(json <| "label") } if let number = phone.number { XCTAssertEqual(number, json <| "number") } else { XCTAssertNil(json <| "number") } } else { XCTFail("Phone comparison failed") } } } else { XCTFail("Phone parsing failed") } } class func compareEmail(emails: [Email?]?, json: [JSON]?) { if let emails = emails, json = json { for (var i=0; i < emails.count; i++) { let json = json[i] if let email = emails[i] { if let label = email.label { XCTAssertEqual(label, json <| "label") } else { XCTAssertNil(json <| "label") } if let address = email.address { XCTAssertEqual(address, json <| "address") } else { XCTAssertNil(json <| "address") } } else { XCTFail("Email comparison failed") } } } else { XCTFail("Email parsing failed") } } class func compareLocation(locations: [Location?]?, json: [JSON]?) { if let locations = locations, json = json { for (var i=0; i < locations.count; i++) { let json = json[i] if let location = locations[i] { if let label = location.label { XCTAssertEqual(label, json <| "label") } else { XCTAssertNil(json <| "label") } if let data = location.data { compareLocationData(data, json: json <| "data") } else { XCTAssertNil(json <| "data") } } else { XCTFail("Location comparison failed") } } } else { XCTFail("Location parsing failed") } } class func compareLocationData(locationData: LocationData?, json: JSON?) { if let locationData = locationData, json = json { if let address = locationData.address { XCTAssertEqual(address, json <| "address") } else { XCTAssertNil(json <| "address") } if let city = locationData.city { XCTAssertEqual(city, json <| "city") } else { XCTAssertNil(json <| "city") } if let state = locationData.state { XCTAssertEqual(state, json <| "state") } else { XCTAssertNil(json <| "state") } if let country = locationData.country { XCTAssertEqual(country, json <| "country") } else { XCTAssertNil(json <| "country") } } else { XCTFail("LocationData comparison failed") } } }
mit
464c5f6daf9cfc5d3468610427717686
35.318182
110
0.426366
5.741317
false
false
false
false
TheDarkCode/Example-Swift-Apps
Exercises and Basic Principles/neighborhood-app-exercise/neighborhood-app-exercise/ViewController.swift
1
2714
// // ViewController.swift // neighborhood-app-exercise // // Created by Mark Hamilton on 2/25/16. // Copyright © 2016 dryverless. All rights reserved. // import UIKit class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource { @IBOutlet weak var tableView: UITableView! // var posts = [Post]() override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. tableView.delegate = self tableView.dataSource = self // let (post1, post2, post3) = (Post(imagePath: "", title: "Post 1", postDetails: "Post 1 Description"), // Post(imagePath: "", title: "Post 2", postDetails: "Post 2 Description"), // Post(imagePath: "", title: "Post 3", postDetails: "Post 3 Description")) // // posts.append(post1); posts.append(post2); posts.append(post3) // // tableView.reloadData() DataService.instance.loadPosts() NSNotificationCenter.defaultCenter().addObserver(self, selector: "onPostsLoaded:", name: "postsLoaded", object: nil) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return DataService.instance.loadedPosts.count } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let post = DataService.instance.loadedPosts[indexPath.row] if let cell = tableView.dequeueReusableCellWithIdentifier("postCell") as? PostCell { // If existing cell, reuse and configure cell.configureCell(post) return cell } else { // Make new one and configure let cell = PostCell() cell.configureCell(post) return cell } } func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { return 98.0 } func tableView(tableView: UITableView, didDeselectRowAtIndexPath indexPath: NSIndexPath) { // When you select a row and do something else } func onPostsLoaded(notif: AnyObject) { tableView.reloadData() } }
mit
3ea93f685a676df34fcb2e4fb9614548
29.483146
124
0.591596
5.309198
false
false
false
false
orih/GitLabKit
GitLabKitTests/ProjectMergeRequestTests.swift
1
4775
// // ProjectMergeRequestTests.swift // GitLabKitTests // // Copyright (c) 2017 toricls. All rights reserved. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import Cocoa import XCTest import OHHTTPStubs class ProjectMergeRequestTests: GitLabKitTests { override func setUp() { super.setUp() OHHTTPStubs.stubRequests(passingTest: { (request: URLRequest!) -> Bool in return request.url?.path.hasPrefix("/api/v3/projects/") == true }, withStubResponse: ( { (request: URLRequest!) -> OHHTTPStubsResponse in var filename: String = "test-error.json" var statusCode: Int32 = 200 if let path = request.url?.path { switch path { case let "/api/v3/projects/1/merge_requests": filename = "project-mrs.json" case let "/api/v3/projects/1/merge_requests?state=closed": filename = "project-mrs-by-status.json" case let "/api/v3/projects/1/merge_requests?state=merged": filename = "project-mrs-by-status-merged.json" default: Logger.log("Unknown path: \(path)" as AnyObject) statusCode = 500 break } } return OHHTTPStubsResponse(fileAtPath: self.resolvePath(filename), statusCode: statusCode, headers: ["Content-Type" : "text/json", "Cache-Control" : "no-cache"]) })) } /** https://gitlab.com/help/api/merge_requests.md#list-merge-requests */ func testFetchingProjectMergeRequests() { let expectation = self.expectation(description: "testFetchingProjectMergeRequests") let params = ProjectMergeRequestQueryParamBuilder(projectId: 1) client.get(params, handler: { (response: GitLabResponse<MergeRequest>?, error: NSError?) -> Void in expectation.fulfill() }) self.waitForExpectations(timeout: 5, handler: nil) } /** https://gitlab.com/help/api/merge_requests.md#list-merge-requests */ func testFetchingProjectClosedMergeRequests() { let expectation = self.expectation(description: "testFetchingProjectClosedMergeRequests") let params = ProjectMergeRequestQueryParamBuilder(projectId: 1).state(.Closed) client.get(params, handler: { (response: GitLabResponse<MergeRequest>?, error: NSError?) -> Void in expectation.fulfill() }) self.waitForExpectations(timeout: 5, handler: nil) } /** https://gitlab.com/help/api/merge_requests.md#list-merge-requests */ func testFetchingProjectMergedMergeRequests() { let expectation = self.expectation(description: "testFetchingProjectMergedMergeRequests") let params = ProjectMergeRequestQueryParamBuilder(projectId: 1).state(.Merged) client.get(params, handler: { (response: GitLabResponse<MergeRequest>?, error: NSError?) -> Void in expectation.fulfill() }) self.waitForExpectations(timeout: 5, handler: nil) } // TODO: https://gitlab.com/help/api/merge_requests.md#get-single-mr // TODO: https://gitlab.com/help/api/merge_requests.md#create-mr // TODO: https://gitlab.com/help/api/merge_requests.md#update-mr // TODO: https://gitlab.com/help/api/merge_requests.md#accept-mr // TODO: https://gitlab.com/help/api/merge_requests.md#post-comment-to-mr // TODO: https://gitlab.com/help/api/merge_requests.md#get-the-comments-on-a-mr override func tearDown() { OHHTTPStubs.removeAllStubs() super.tearDown() } }
mit
252327b907c302880bb79b3f8c40cf01
45.359223
177
0.651937
4.392824
false
true
false
false
chicio/RangeUISlider
Source/Logic/KnobsLabelAnimator.swift
1
3047
// // KnobsLabelAnimator.swift // RangeUISlider // // Created by Fabrizio Duroni on 24/02/21. // 2021 Fabrizio Duroni. // import UIKit class KnobsLabelAnimator { private unowned let leftKnob: Knob private unowned let rightKnob: Knob private var canAnimateMoveAway: Bool = true private var canAnimateCenter: Bool = false private let spaceBetweenLabelsPerKnob: CGFloat = 2.5 init(leftKnob: Knob, rightKnob: Knob) { self.leftKnob = leftKnob self.rightKnob = rightKnob } func animate(shouldShow: Bool) { if shouldShow { tryToAnimateMoveAway() tryToAnimateMoveToCenter() } } private func tryToAnimateMoveAway() { if shouldMoveLabelAway() { animation( constraintsValues: (left: moveAwayLeftKnobValue(), right: moveAwayRightKnobValue()), animationStart: { [unowned self] in self.canAnimateMoveAway = false }, animationCompleted: { [unowned self] (_) in self.canAnimateCenter = true } ) } } private func tryToAnimateMoveToCenter() { if shouldMoveToCenter() { animation( constraintsValues: (left: 0, right: 0), animationStart: { [unowned self] in self.canAnimateCenter = false }, animationCompleted: { [unowned self] (_) in self.canAnimateMoveAway = true } ) } } private func animation( constraintsValues: (left: CGFloat, right: CGFloat), animationStart: () -> Void, animationCompleted: @escaping (Bool) -> Void ) { UIView.animate( withDuration: 0.2, animations: { self.leftKnob.components.knobLabel.setXPositionConstraint(constraintsValues.left) self.rightKnob.components.knobLabel.setXPositionConstraint(constraintsValues.right) self.canAnimateCenter = false self.leftKnob.layoutIfNeeded() self.rightKnob.layoutIfNeeded() }, completion: animationCompleted) } private func moveAwayLeftKnobValue() -> CGFloat { return -(self.leftKnob.components.knobLabel.label.frame.width / 2) - spaceBetweenLabelsPerKnob } private func moveAwayRightKnobValue() -> CGFloat { return (self.rightKnob.components.knobLabel.label.frame.width) / 2 + spaceBetweenLabelsPerKnob } private func shouldMoveToCenter() -> Bool { return leftKnobLabelRightMargin() < rightKnobLabelLeftMargin() && canAnimateCenter } private func shouldMoveLabelAway() -> Bool { return leftKnobLabelRightMargin() >= rightKnobLabelLeftMargin() && canAnimateMoveAway } private func leftKnobLabelRightMargin() -> CGFloat { return leftKnob.center.x + leftKnob.components.knobLabel.label.frame.width/2 } private func rightKnobLabelLeftMargin() -> CGFloat { return rightKnob.center.x - rightKnob.components.knobLabel.label.frame.width/2 } }
mit
108ee59f104dce4d1e41c634dc229494
32.855556
102
0.639646
4.581955
false
false
false
false
Ramshandilya/Swift-Notes
Swift-Notes.playground/Pages/14. Initialization.xcplaygroundpage/Contents.swift
1
13149
//: # Swift Foundation //: ---- //: ## Initialization //: Initialization is the process of preparing an instance of a class, structure, or enumeration for use. /*: Consider the following class class User { var name: String var age: Int } */ //: The above code will throw an error saying that the class has no initializers. Classes and Structures must set its stored properties to an initial value by the time its instance is created. //One way to shut off the error is to actually set initial values for the properties. class User { var name: String = "" var age: Int = 0 } //: ### Initializer //: Swift provides a default initializer for any structure or base class that provides default values for all of its properties and does not provide at least one initializer itself. The default initializer simply creates a new instance with all of its properties set to their default values. let someUser = User() //Calls default Initializer someUser.name someUser.age //Memberwise Initializers for Structure Types //: Structure types automatically receive a memberwise initializer if they do not define any of their own custom initializers. Unlike a default initializer, the structure receives a memberwise initializer even if it has stored properties that do not have default values. struct BirthDate { var date: Int var month: Int var year: Int = 1980 init(){ date = 1 month = 1 } //Initializer Delegation init(year: Int) { self.init() self.year = year } } var dateOfBirth = BirthDate() dateOfBirth.year dateOfBirth = BirthDate(year: 1995) dateOfBirth.year //: Structures provide memberwise initializer by default. But Classes in Swift don't provide default initializers. //In many cases, the default initializer is not very helpful class Human { let name: String var age: Int init (name: String, age: Int){ self.name = name //assigning to a constant property self.age = age } func greeting () { print("Hello, \(name)") } } //: ## 📖 //: If you define a custom initializer for a value type, you will no longer have access to the default initializer (or the memberwise initializer, if it is a structure) for that type. //:The following code will throw an error /*: let nicePerson = Human() //Error */ let somePerson = Human(name: "Bran", age: 7) //somePerson.name = "" //ERROR. Cant change constant property somePerson.age = 8 //: ### Class Inheritance and Initialization // Some Theory 😩 /*: Value types (structures and enumerations) do not support inheritance, and so their initializer delegation process is relatively simple, because they can only delegate to another initializer that they provide themselves. Classes, however, can inherit from other classes. Since all of a class’s stored properties—including any properties the class inherits from its superclass—must be assigned an initial value during initialization. This means that classes have additional responsibilities for ensuring that all stored properties they inherit are assigned a suitable value during initialization. */ /*: Swift provides two kind of initializers to ensure all the stored properties are set to an initial Value. 1. ***Designated Initializers*** - * Are primary initializers * Initializes all properties introduced by that class and calls an appropriate superclass initializer to continue the initialization process up the superclass chain. * Every class must have at least one designated initializer. 2. ***Convenience Initializers*** - * Are secondary and supporting initializers for a class. * Can call the designated initializer or another convenience initializer of the same class. * Not mandatory */ //Syntax /*: //Designated Initializer init(parameters){ //statements } //Convenience Initializer convenience init(parameters){ //statements } */ /*: ### Initializer Delegation for Class Types Swift applies three rules for delegation calls between initializer calls. 1. A designated initializer must call a designated initializer from its immediate superclass. 2. A convenience initializer must call another initializer from the *same* class. 3. A convenience initializer must ultimately call a designated initializer. */ //: ![Initializer Delegation](initializerDelegation01.png "Initializer Delegation") //: ---- //: ![Initializer Delegation](initializerDelegation02.png "Initializer Delegation") /*: * Designated initializers must always delegate up. * Convenience initializers must always delegate across. */ //: ### Two phase initialization /*: Class initialization in Swift is a two-phase process. * First, each stored property is assigned an initial value. * Then each class is given the opportunity to customize its stored properties further before the new instance is considered ready for use. Hence, * It prevents property values being accessed before it is initialized * And prevents property values from being set to a different value by another initializer unexpectedly. */ //: ### Safety checks to ensure two-phase initialization /*: * A designated initializer must ensure that all of the properties introduced by its class are initialized before it delegates up to a superclass initializer. * A designated initializer must delegate up to a superclass initializer before assigning a value to an inherited property. * A convenience initializer must delegate to another initializer before assigning a value to any property (including properties defined by the same class). * An initializer cannot call any instance methods, read the values of any instance properties, or refer to self as a value until after the first phase of initialization is complete. */ //Enough talk. Let's code class Person { let name: String var age: Int init (name: String, age: Int){ self.name = name self.age = age } convenience init(name: String){ self.init(name: name, age: 0) } convenience init() { self.init(name: "[Unnamed]") } } let hodor = Person(name: "Hodor") hodor.name hodor.age let facelessGod = Person() facelessGod.name facelessGod.age class RoyalPerson: Person { var title: String = "" init (name: String, title: String) { self.title = title super.init(name: name, age: 0) } override convenience init(name: String, age: Int) { self.init(name: name, title: "Lord") self.age = age } } let kingRobert = RoyalPerson(name: "Robert", title: "King") kingRobert.name kingRobert.age kingRobert.title let jonAryyn = RoyalPerson(name: "Jon") jonAryyn.name jonAryyn.title jonAryyn.age //: ### Automatic Initializer Inheritance //: Subclasses do not inherit their superclass initializers by default. However, superclass initializers are automatically inherited if certain conditions are met. /*: * If your subclass doesn’t define any designated initializers, it automatically inherits all of its superclass designated initializers. * If your subclass provides an implementation of all of its superclass designated initializers—either by inheriting them as per rule 1, or by providing a custom implementation as part of its definition—then it automatically inherits all of the superclass convenience initializers. */ //: ## 📖 //: `RoyalPerson` has it's own designated initializer. Hence it won't inherit the initializers from its superClass. To inherit, it had to override the designated initializer of its superclass. class Knight: RoyalPerson { var combatSkills: Int = 0 } let hound = Knight(name: "Sandor", title: "Ser") hound.name hound.title //: ![Initializer Delegation](InitializerDelegation03.png "Initializer Delegation") //: ## Failable Initializers //: It is sometimes useful to define a class, structure, or enumeration for which initialization can fail. This failure might be triggered by invalid initialization parameter values, the absence of a required external resource, or some other condition that prevents initialization from succeeding. //: To cope with such initialization failures, we define ***failable initializers***. We define by adding a `?` after `init` like `init?`. Return `nil` to indicate failure. struct PositiveInteger{ var integerValue: Int init?(integer: Int){ if integer < 0 { return nil } integerValue = integer } init(number: Int){ integerValue = number } } let someNumber = PositiveInteger(integer:23) //will be of type Optional PositiveInteger someNumber?.integerValue let negativeNumber = PositiveInteger(number: -2) negativeNumber.integerValue //: 📖 //: You cannot define a failable and a nonfailable initializer with the same parameter types and names. //Failable initializers for enumerations enum Boolean { case Yes, No init?(_ boolString: String){ switch boolString{ case "Y": self = .Yes case "N": self = .No default: return nil } } } let amIAwesome = Boolean("Y") let isThisSessionTooLong = Boolean("N") let yawn = Boolean("Z") //Failable initializers for enumerations with Raw Values enum YesOrNo: Character { case Yes = "Y" case No = "N" } let foo = YesOrNo(rawValue: "Y") let bar = YesOrNo(rawValue: "X") //: ### Failable Initializers for Classes //: For classes, a failable initializer can trigger an initialization failure only after all stored properties introduced by that class have been set to an initial value and any initializer delegation has taken place. class Place { var name: String! //Note the Implicitly unwrapped optional String init (){ name = "[Unnamed]" } init?(name: String) { self.name = name if name == "#" { return nil } } } let somePlace = Place(name: "Westeros") somePlace?.name //Propagation of initialization Failure class Kingdom: Place { var population: Int! init?(name: String, population: Int){ self.population = population super.init(name: name) if population < 1 { return nil } } convenience init?(population: Int){ self.init() self.population = population } override init() { self.population = 1 super.init() } } let kingdomOfNorth = Kingdom(name: "Winterfell", population: 800) let someKingdom = Kingdom(name: "#", population: 900) let anotherKingdom = Kingdom(name: "Dorne", population: 0) let winterFell = Kingdom(population: 200) //: 📖 //: Failable initializer must always perform initializer delegation before triggering an initialization failure. A failable initializer can also delegate to a nonfailable initializer. //: ### Overriding Failable Initializers //: You can override a superclass failable initializer in a subclass, just like any other initializer. //: Alternatively, you can override a superclass failable initializer with a subclass non-failable initializer. This enables you to define a subclass for which initialization cannot fail, even though initialization of the superclass is allowed to fail. But remember, a nonfailable initializer can never delegate to a failable initializer. //: You cannot override a non-failable initializer with a failable initializer. // Let's say all southern kingdoms have a min population of 500 class SouthernKingdom: Kingdom { override init(name: String, population: Int){ super.init() if self.population < 500 { self.population = 500 } if name.isEmpty { self.name = "Southern Kingdom" } else { self.name = name } } } let dorne = SouthernKingdom(name: "Dorne", population: 44) //Result is not an optional dorne.name dorne.population //: ## Required Initializers //: Write the `required` modifier before the definition of a class initializer to indicate that every subclass of the class must implement that initializer. You must also write the required modifier before every subclass implementation of a `required` initializer, to indicate that the initializer requirement applies to further subclasses in the chain. class ClassA { required init (){ } func someMethod(){ } } class ClassB: ClassA { //Subclass init should also have required modifier. NO need to write override. required init () { } } //: ### Setting a Default Property value with a closure or function let someArray = ["HI"] class Westeros { var kingdoms: [String] = { var array = someArray return array }() var kingdoms2: [String] = { var array = ["Reach", "Stormlands"] return array }() var greeting: String = { return "Hello" }() } let continent = Westeros() continent.kingdoms continent.kingdoms2 continent.greeting //: ## Finally! 😪 //: ---- //: [Next](@next)
mit
6f7815921f311251115f05db4f3d4428
29.08945
374
0.705694
4.559958
false
false
false
false
S7Vyto/SVCalendar
SVCalendar/SVCalendar/Calendar/Controllers/Navigation/SVCalendarNavigationView.swift
1
2528
// // SVCalendarNavigationView.swift // SVCalendarView // // Created by Sam on 19/11/2016. // Copyright © 2016 Semyon Vyatkin. All rights reserved. // import UIKit public enum SVCalendarNavigationDirection { case reduce, increase, none } class SVCalendarNavigationView: UIView { @IBOutlet weak var reduceButton: UIButton! @IBOutlet weak var increaseButton: UIButton! @IBOutlet weak var dateTitle: UILabel! static var identifier: String { return NSStringFromClass(SVCalendarNavigationView.self).replacingOccurrences(of: SVCalendarConstants.bundleIdentifier, with: "") } fileprivate weak var delegate: SVCalendarNavigationDelegate? var style: SVStyleProtocol? { didSet { if dateTitle != nil { dateTitle.textColor = self.style?.text.normalColor dateTitle.font = self.style?.text.font } } } var title: String? { didSet { if dateTitle != nil { dateTitle.text = title } } } // MARK: - Object LifeCycle static func navigation(delegate: SVCalendarNavigationDelegate?, style: SVStyleProtocol, title: String?) -> SVCalendarNavigationView { let nib = UINib(nibName: SVCalendarNavigationView.identifier, bundle: SVCalendarConstants.bundle!) let view = nib.instantiate(withOwner: nil, options: nil).first as! SVCalendarNavigationView view.delegate = delegate view.style = style view.title = title return view } override func awakeFromNib() { super.awakeFromNib() self.configApperance() } deinit { self.clearData() } // MARK: - Config Appearance fileprivate func configApperance() { self.translatesAutoresizingMaskIntoConstraints = false self.backgroundColor = self.style?.background.normalColor } // MARK: - Navigation Methods fileprivate func clearData() { self.style = nil self.title = nil self.delegate = nil } func updateNavigationDate(_ date: String?) { self.title = date } // MARK: - Navigation Delegates @IBAction func didChangeNavigationDate(_ sender: UIButton) { guard let date = self.delegate?.didChangeNavigationDate(direction: sender.tag == 0 ? .reduce : .increase), date != "" else { return } self.title = date } }
apache-2.0
1d681d65d96a7c6534e9c98db055b99c
27.715909
137
0.616937
5.033865
false
false
false
false
RikkiGibson/Corvallis-Bus-iOS
CorvallisBus/ServiceAlert.swift
1
940
import Foundation struct ServiceAlert { var title: String var publishDate: Date var link: String /// Uniquely identifies the service alert. /// Currently a concatenation of the link and publish date. var id: String static let dateFormatter: DateFormatter = { let formatter = DateFormatter() formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ" return formatter }() static func fromDictionary(_ data: [String : AnyObject]) -> ServiceAlert? { guard let title = data["title"] as? String, let link = data["link"] as? String, let publishDateString = data["publishDate"] as? String, let publishDate = dateFormatter.date(from: publishDateString) else { return nil } return ServiceAlert(title: title, publishDate: publishDate, link: link, id: link + " " + publishDateString) } }
mit
3e44f2f6c797d5be3cd00322d7670e05
31.413793
115
0.612766
4.820513
false
true
false
false
setoelkahfi/JomloTableView
Example/JomloTableView/View Controllers/NotJomloSimpleTableViewController.swift
1
4562
// // NotJomloSimpleTableViewController.swift // JomloTableView // // Created by SDMobile on 4/17/17. // Copyright © 2017 CocoaPods. All rights reserved. // import UIKit import TwitterKit class NotJomloSimpleTableViewController: UIViewController { @IBOutlet var tableView: UITableView! var tweets = [Tweet]() let client = TWTRAPIClient() var loginButton: TWTRLogInButton! override func viewDidLoad() { super.viewDidLoad() // tableView.isHidden = true loginButton = TWTRLogInButton { (session, error) in if let session = session { print("Signed as: \(session.userName)") self.loadTweets() } else { print("Error: \(error?.localizedDescription)") } } loginButton.center = view.center view.addSubview(loginButton) } internal func loadTweets() { let searchEndPoint = "https://api.twitter.com/1.1/search/tweets.json" let params = ["q" : "jomlo"] var clientError: NSError? let request = client.urlRequest(withMethod: "GET", url: searchEndPoint, parameters: params, error: &clientError) client.sendTwitterRequest(request) { (response, data, connectionError) in if let data = data { self.populate(data: data) } if let error = connectionError { print("Error: \(error.localizedDescription)") } } } internal func populate(data: Data) { do { if let json = try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any] { // print("json: \(json)") if let statuses = json["statuses"] as? [Any] { // print("statuses: \(statuses)") for status in statuses { print("status: \(status)") let status = status as! [String: Any] // print("\(status["text"])") let user = status["user"] as! [String: Any] let tweet = Tweet(screenName: user["screen_name"] as! String, name: user["name"] as! String, text: status["text"] as! String) // profile_image_url_https tweets.append(tweet) } DispatchQueue.main.async { self.tableView.isHidden = false self.loginButton.removeFromSuperview() self.tableView.reloadData() } } } } catch let jsonError as NSError { print("json error: \(jsonError.localizedDescription)") } } } extension NotJomloSimpleTableViewController: UITableViewDelegate { func numberOfSections(in tableView: UITableView) -> Int { return 1 } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 88 } func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat { return 88 } } extension NotJomloSimpleTableViewController: UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return tweets.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { var cell = tableView.dequeueReusableCell(withIdentifier: "SimpleCell") as? SimpleCell if cell == nil { let nib = UINib(nibName: "SimpleCell", bundle: nil) tableView.register(nib, forCellReuseIdentifier: "SimpleCell") cell = tableView.dequeueReusableCell(withIdentifier: "SimpleCell") as? SimpleCell } cell?.textLabel?.text = "@\(tweets[indexPath.row].screenName!) \(tweets[indexPath.row].name!)" cell?.subTitleLabel.text = tweets[indexPath.row].text! return cell! } } class Tweet { var screenName: String! var name: String! var text: String! init(screenName: String, name: String, text: String) { self.screenName = screenName self.name = name self.text = text } }
mit
f86c7b7b3e99ce83a3f78ac56fb74bf3
31.119718
149
0.540452
5.242529
false
false
false
false
koscida/Kos_AMAD_Spring2015
Spring_16/IGNORE_work/projects/Girl_Game/Girl_Game/GameCharacterCreationScene.swift
2
18468
// // GameCharacterCreationScene.swift // Girl_Game // // Created by Brittany Kos on 4/6/16. // Copyright © 2016 Kode Studios. All rights reserved. // import UIKit import SpriteKit class GameCharacterCreationScene: SKScene { // frame things var frameWidth: CGFloat = 0; var frameHeight: CGFloat = 0; var frameCenterWidth: CGFloat = 0; var frameCenterHeight: CGFloat = 0; let frameBorder: CGFloat = 20 let ratioWidthFromHeight: CGFloat = (1328/2400) let ratioHeightFromWidth: CGFloat = (2400/1328) // views let BODY_OPTION = 1; let ARMOR_OPTION = 2; let WEAPON_OPTION = 3; var optionState = 0 let optionView = SKNode() let displayView = SKNode() let detailBodyView = SKNode() let detailArmorView = SKNode() let detailWeaponView = SKNode() var currentDetailView = SKNode(); // view sizes var optionWidth: CGFloat = 0 var optionHeight: CGFloat = 0 var optionMargin: CGFloat = 0 var optionStartX: CGFloat = 0 var optionStartY: CGFloat = 0 var detailWidth: CGFloat = 0 var detailHeight: CGFloat = 0 var detailMargin: CGFloat = 0 var detailDisplayWidth: CGFloat = 0 var detailDisplayHeight: CGFloat = 0 var detailDisplayStartX: CGFloat = 0 var detailDisplayStartY: CGFloat = 0 var detailOptionsWidth: CGFloat = 0 var detailOptionsHeight: CGFloat = 0 var detailOptionsStartX: CGFloat = 0 var detailOptionsStartY: CGFloat = 0 // display things var selectedBodySprite = CreationOptionCharacterSprite() var selectedArmorSprite = CreationOptionCharacterSprite() var selectedWeaponSprite = CreationOptionCharacterSprite() // body things var bodySelectedIndex = 0; var bodySpritesArray = [CreationOptionCharacterSprite]() var bodyImageNames = [ "sil_african", "sil_indian", "sil_native", "sil_pacificislander", "sil_latina", "sil_asian", "sil_middleeastern", "sil_white"] // armor things var armorSelectedIndex = 0; var armorSpritesArray = [CreationOptionCharacterSprite]() var armorImageNames = [ "sil_armor_archer_trans", "sil_armor_healer_trans", "sil_armor_warrior_trans" ] // weapon things var weaponSelectedIndex = 0; var weaponSpritesArray = [CreationOptionCharacterSprite]() var weaponImageNames: [String] = [ ] override func didMoveToView(view: SKView) { //print("in GameCharacterCreationScene") frameWidth = CGRectGetWidth(frame) frameCenterWidth = frameWidth / 2 frameHeight = CGRectGetHeight(frame) frameCenterHeight = frameHeight / 2 //print("frameWidth: \(frameWidth) frameCenterWidth: \(frameCenterWidth)") //print("frameHeight: \(frameHeight) frameCenterHeight: \(frameCenterHeight)") optionWidth = (frameWidth/4) optionHeight = frameHeight optionMargin = 20 optionStartX = optionMargin optionStartY = optionMargin detailWidth = frameWidth - optionWidth detailHeight = frameHeight detailMargin = 30 detailOptionsWidth = detailWidth detailOptionsHeight = (frameHeight/3) detailOptionsStartX = optionWidth + detailMargin detailOptionsStartY = detailMargin detailDisplayWidth = detailWidth detailDisplayHeight = frameHeight - detailOptionsHeight detailDisplayStartX = detailOptionsStartX detailDisplayStartY = detailOptionsHeight + detailMargin // option view createAndLoadOptionsView() // display view createAndLoadDisplayView() // detail views loadBodyView() currentDetailView = detailBodyView self.addChild(currentDetailView) loadArmorView() loadWeaponView() } override init(size: CGSize) { super.init(size: size) } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } /////////////////////////////////////// // Scene loaders // /////////////////////////////////////// func createAndLoadOptionsView() { //print("in GameCharacterCreationScene - loadOptionsView") let numberOfOptionButtons: CGFloat = 5 let optionButtonBackgroundWidth = optionWidth-(frameBorder*2) let optionButtonBackgroundHeight = (frameHeight-((numberOfOptionButtons+1)*frameBorder)) / numberOfOptionButtons let optionButton1Y = (frameBorder*1) + (optionButtonBackgroundHeight*0) // bottom most let optionButton2Y = (frameBorder*2) + (optionButtonBackgroundHeight*1) let optionButton3Y = (frameBorder*3) + (optionButtonBackgroundHeight*2) let optionButton4Y = (frameBorder*4) + (optionButtonBackgroundHeight*3) let optionButton5Y = (frameBorder*5) + (optionButtonBackgroundHeight*4) // top most // background let optionBackground = SKShapeNode(rect: CGRect(x: 0, y: 0, width: optionWidth, height: frameHeight)) optionBackground.fillColor = greyMediumColor optionView.addChild(optionBackground) // detail backaground let detailBackground = SKShapeNode(rect: CGRect(x: optionWidth, y: 0, width: frameWidth-optionWidth, height: frameHeight)) detailBackground.fillColor = UIColor.whiteColor() optionView.addChild(detailBackground) // body let r1 = CGRect(x: frameBorder, y: optionButton5Y, width: optionButtonBackgroundWidth, height: optionButtonBackgroundHeight) optionView.addChild(createSKShapeNodeRect(name: "bodyButton", rect: r1, fillColor: pinkColor)) optionView.addChild(createSKLabelNodeAdj(name: "bodyButtonLabel", text: "Body", x: optionWidth/2, y: optionButton5Y+(optionButtonBackgroundHeight/2), width: optionButtonBackgroundWidth, height: optionButtonBackgroundHeight, fontColor: UIColor.whiteColor())) // armor let r2 = CGRect(x: frameBorder, y: optionButton4Y, width: optionButtonBackgroundWidth, height: optionButtonBackgroundHeight) optionView.addChild(createSKShapeNodeRect(name: "armorButton", rect: r2, fillColor: pinkColor)) optionView.addChild(createSKLabelNodeAdj(name: "armorButtonLabel", text: "Armor", x: optionWidth/2, y: optionButton4Y+(optionButtonBackgroundHeight/2), width: optionButtonBackgroundWidth, height: optionButtonBackgroundHeight, fontColor: UIColor.whiteColor())) // weapon let r3 = CGRect(x: frameBorder, y: optionButton3Y, width: optionButtonBackgroundWidth, height: optionButtonBackgroundHeight) optionView.addChild(createSKShapeNodeRect(name: "weaponButton", rect: r3, fillColor: pinkColor)) optionView.addChild(createSKLabelNodeAdj(name: "weaponButtonLabel", text: "Weapon", x: optionWidth/2, y: optionButton3Y+(optionButtonBackgroundHeight/2), width: optionButtonBackgroundWidth, height: optionButtonBackgroundHeight, fontColor: UIColor.whiteColor())) // random let r4 = CGRect(x: frameBorder, y: optionButton2Y, width: optionButtonBackgroundWidth, height: optionButtonBackgroundHeight) optionView.addChild(createSKShapeNodeRect(name: "randomButton", rect: r4, fillColor: pinkLightColor)) optionView.addChild(createSKLabelNodeAdj(name: "randomButtonLabel", text: "Random", x: optionWidth/2, y: optionButton2Y+(optionButtonBackgroundHeight/2), width: optionButtonBackgroundWidth, height: optionButtonBackgroundHeight, fontColor: UIColor.whiteColor())) // save let r5 = CGRect(x: frameBorder, y: optionButton1Y, width: optionButtonBackgroundWidth, height: optionButtonBackgroundHeight) optionView.addChild(createSKShapeNodeRect(name: "saveButton", rect: r5, fillColor: tealColor)) optionView.addChild(createSKLabelNodeAdj(name: "saveButtonLabel", text: "Save", x: optionWidth/2, y: optionButton1Y+(optionButtonBackgroundHeight/2), width: optionButtonBackgroundWidth, height: optionButtonBackgroundHeight, fontColor: UIColor.blackColor())) self.addChild(optionView) } func createAndLoadDisplayView() { let displaySelectedHeight: CGFloat = detailDisplayHeight - (2*detailMargin) let displaySelectedWidth: CGFloat = displaySelectedHeight * (1328/2400) let displaySelectedX: CGFloat = detailDisplayStartX + (displaySelectedWidth/2) let displaySelectedY: CGFloat = detailDisplayStartY + (displaySelectedHeight/2) // display body selectedBodySprite = CreationOptionCharacterSprite(name: "bodyDetailSprite", imageName: bodyImageNames[0], x: displaySelectedX, y: displaySelectedY, width: displaySelectedWidth, height: displaySelectedHeight, select: false) let tmpNode1 = selectedBodySprite.getNode() tmpNode1.zPosition = 1 displayView.addChild(tmpNode1) // display armor selectedArmorSprite = CreationOptionCharacterSprite(name: "armorDetailSprite", imageName: armorImageNames[0], x: displaySelectedX, y: displaySelectedY, width: displaySelectedWidth, height: displaySelectedHeight, select: false) let tmpNode2 = selectedArmorSprite.getNode() tmpNode2.zPosition = 2 displayView.addChild(tmpNode2) // display weapon //TODO self.addChild(displayView) } func loadBodyView() { loadGenericView(detailView: detailBodyView, imagesNamesArray: bodyImageNames, spritesArray: &bodySpritesArray, optionNamePrefix: "bodyOptionSprite") } func loadArmorView() { loadGenericView(detailView: detailArmorView, imagesNamesArray: armorImageNames, spritesArray: &armorSpritesArray, optionNamePrefix: "armorOptionSprite") } func loadWeaponView() { loadGenericView(detailView: detailWeaponView, imagesNamesArray: weaponImageNames, spritesArray: &weaponSpritesArray, optionNamePrefix: "weaponOptionSprite") } func loadGenericView(detailView detailView: SKNode, imagesNamesArray: [String], inout spritesArray: [CreationOptionCharacterSprite], optionNamePrefix: String) { let detailStartX = optionWidth + detailMargin let detailStartY = detailMargin // detail (body) options let numOptions: CGFloat = CGFloat(imagesNamesArray.count) // compute width and height // set w & h var singleOptionHeight = detailOptionsHeight - (2*detailMargin) var singleOptionWidth: CGFloat = singleOptionHeight * ratioWidthFromHeight // compute total width let allOptionsTotalWidth = ((singleOptionWidth+detailMargin) * numOptions) + detailMargin // test fit if allOptionsTotalWidth > detailWidth { // recompute w & h singleOptionWidth = ( detailWidth-((numOptions+1)*detailMargin) ) / numOptions singleOptionHeight = singleOptionWidth * ratioHeightFromWidth } var singleOptionSpriteX: CGFloat = detailStartX + (singleOptionWidth/2) let singleOptionSpriteY: CGFloat = detailStartY + (singleOptionHeight/2) for var i = 0; i<Int(numOptions); i++ { let singleSprite_stub = CreationOptionCharacterSprite(name: "\(optionNamePrefix)_\(i)", imageName: imagesNamesArray[i], x: singleOptionSpriteX, y: singleOptionSpriteY, width: singleOptionWidth, height: singleOptionHeight, select: (i == 0)) spritesArray.append(singleSprite_stub) detailView.addChild(singleSprite_stub.getNode()) singleOptionSpriteX += (detailMargin+singleOptionWidth) } } func changeOptionDetailView(newOptionState: Int) { optionState = newOptionState currentDetailView.removeFromParent() switch(optionState) { case BODY_OPTION: currentDetailView = detailBodyView case ARMOR_OPTION: currentDetailView = detailArmorView case WEAPON_OPTION: currentDetailView = detailWeaponView default: return; } self.addChild(currentDetailView) } func selectBodyOption(optionSelectedNew: Int) { selectGenericOption(optionSelectedNew, spritesArray: bodySpritesArray, spritesNamesArray: bodyImageNames, selectedIndex: bodySelectedIndex, selectedSprite: selectedBodySprite) bodySelectedIndex = optionSelectedNew } func selectArmorOption(optionSelectedNew: Int) { selectGenericOption(optionSelectedNew, spritesArray: armorSpritesArray, spritesNamesArray: armorImageNames, selectedIndex: armorSelectedIndex, selectedSprite: selectedArmorSprite) armorSelectedIndex = optionSelectedNew } func selectWeaponOption(optionSelectedNew: Int) { selectGenericOption(optionSelectedNew, spritesArray: weaponSpritesArray, spritesNamesArray: weaponImageNames, selectedIndex: weaponSelectedIndex, selectedSprite: selectedWeaponSprite) weaponSelectedIndex = optionSelectedNew } func selectGenericOption(optionSelectedNew: Int, spritesArray: [CreationOptionCharacterSprite], spritesNamesArray: [String], selectedIndex: Int, selectedSprite: CreationOptionCharacterSprite) { // remove last select spritesArray[selectedIndex].removeSelectedBox() // add current select spritesArray[optionSelectedNew].addSelectedBox() // change displayed sprite selectedSprite.changeImage(imageName: spritesNamesArray[optionSelectedNew]) } ////////////////////////////////////////// // Helper Functions // ////////////////////////////////////////// func stateChangeNext(newState: Int) { } //////////////////////////////////// // Game Logic // //////////////////////////////////// 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 = self.nodeAtPoint(location) //print("x: \(location.x)") //print("y: \(location.y)") if let name = touchedNode.name { // switching between options if name == "bodyButton" || name == "bodyButtonLabel" { //print("bodyButton or bodyButtonLabel") changeOptionDetailView(BODY_OPTION) } else if name == "armorButton" || name == "armorButtonLabel" { //print("armorButton or armorButtonLabel") changeOptionDetailView(ARMOR_OPTION) } else if name == "weaponButton" || name == "weaponButtonLabel" { //print("weaponButton or weaponButtonLabel") changeOptionDetailView(WEAPON_OPTION) } else if name == "randomButton" || name == "randomButtonLabel" { //print("randomButton or randomButtonLabel") changeOptionDetailView(BODY_OPTION) let bodySelectedIndexNew = Int(arc4random_uniform(UInt32(bodySpritesArray.count))) //print("bodySelectedIndexNew: \(bodySelectedIndexNew)") selectBodyOption(bodySelectedIndexNew) let armorSelectedIndexNew = Int(arc4random_uniform(UInt32(armorSpritesArray.count))) //print("armorSelectedIndexNew: \(armorSelectedIndexNew)") selectArmorOption(armorSelectedIndexNew) let weaponSelectedIndexNew = Int(arc4random_uniform(UInt32(weaponSpritesArray.count))) //print("weaponSelectedIndexNew: \(weaponSelectedIndexNew)") //selectWeaponOption(weaponSelectedIndexNew) } else if name == "saveButton" || name == "saveButtonLabel" { //print("saveButton or saveButtonLabel") let transition = SKTransition.flipVerticalWithDuration(1.0) let game = GameLevel1Scene(size:frame.size, bodyFileName: bodyImageNames[bodySelectedIndex], armorFileName: armorImageNames[armorSelectedIndex], weaponFileName: "") view!.presentScene(game, transition: transition) } // switching between body options for(var i: Int = 0; i<bodyImageNames.count; i++) { if name == "bodyOptionSprite_\(i)" { //print("bodyOptionSprite_\(i)") selectBodyOption(i) } } // switching between armor options for(var i: Int = 0; i<armorImageNames.count; i++) { if name == "armorOptionSprite_\(i)" { //print("armorOptionSprite_\(i)") selectArmorOption(i) } } // switching between weapon options for(var i: Int = 0; i<weaponImageNames.count; i++) { if name == "weaponOptionSprite_\(i)" { //print("weaponOptionSprite_\(i)") selectWeaponOption(i) } } } } } override func update(currentTime: CFTimeInterval) { /* Called before each frame is rendered */ } }
gpl-3.0
6cfbc3e3b52ebb2546b17af74a0178e0
39.233115
269
0.6197
5.169933
false
false
false
false
huangboju/Moots
UICollectionViewLayout/Blueprints-master/Sources/macOS/Extensions/BlueprintLayout+macOS.swift
1
3462
import Cocoa extension BlueprintLayout { open override func layoutAttributesForSupplementaryView(ofKind elementKind: NSCollectionView.SupplementaryElementKind, at indexPath: IndexPath) -> LayoutAttributes? { if indexPathIsOutOfBounds(indexPath, for: cachedSupplementaryAttributesBySection) { return nil } let sectionAttributes = cachedSupplementaryAttributesBySection[indexPath.section] var layoutAttributesResult: LayoutAttributes? = nil switch elementKind { case NSCollectionView.elementKindSectionHeader: layoutAttributesResult = sectionAttributes.filter({ $0.representedElementCategory == .supplementaryView }).first case NSCollectionView.elementKindSectionFooter: layoutAttributesResult = sectionAttributes.filter({ $0.representedElementCategory == .supplementaryView }).last default: return nil } return layoutAttributesResult } open override func finalizeLayoutTransition() { super.finalizeLayoutTransition() collectionView?.enclosingScrollView?.layout() macOSWorkaroundSetNewContentSize() } /// On macOS, collection views that don't have an initial size won't /// try and invalidate its layout attributes when updates happen if the /// collection views size is zero. To work around this issue, /// the collection will get half a pixel and an alpha value that is not /// visible to the user. That way it can respond to updates and invalidate /// properly. If a hidden collection view gets a new content size /// it will restore the alpha value to 1.0, but only if the alpha value /// is equal to the workaround value. func macOSWorkaroundCreateCache() { let alphaValue: CGFloat = 0.0001 if contentSize.height == 0 && collectionView?.alphaValue != 0.0 { contentSize.height = super.collectionViewContentSize.height collectionView?.alphaValue = alphaValue } else if collectionView?.alphaValue == alphaValue { collectionView?.alphaValue = 1.0 } collectionView?.frame.size.height = contentSize.height } /// When transitioning between layouts macOS does not set the /// proper size to the document view of the scroll view. /// To work around this, the collection views window will /// temporarily be resized and then restored. This will /// trigger the document view getting the new size. func macOSWorkaroundSetNewContentSize() { if let window = collectionView?.window { CATransaction.begin() CATransaction.setDisableActions(true) CATransaction.setAnimationDuration(0.0) let originalFrame = window.frame var frame = originalFrame frame.origin.y = frame.origin.y - 0.025 frame.size.height = frame.size.height + 0.025 frame.size.width = frame.size.width + 0.025 window.setFrame(frame, display: false) CATransaction.commit() DispatchQueue.main.asyncAfter(deadline: .now() + 0.045) { window.setFrame(originalFrame, display: false) } } } func configureSupplementaryWidth(_ view: NSView) { supplementaryWidth = view.frame.width } @objc func contentViewBoundsDidChange(_ notification: NSNotification) { guard let clipView = notification.object as? NSClipView, clipView == collectionView?.enclosingScrollView else { return } collectionView?.enclosingScrollView?.layout() configureSupplementaryWidth(clipView) } }
mit
7653b93965599378d7f1a76eb7bd7659
39.729412
120
0.721837
5.174888
false
false
false
false
tianyc1019/LSPhotoPicker
LSPhotoPicker/LSPhotoPicker/LSPhotoPicker/LSPhotoPicker/view/LSPhotoCollectionViewCell.swift
1
3921
// // LSPhotoCollectionViewCell.swift // LSPhotoPicker // // Created by John_LS on 2017/2/8. // Copyright © 2017年 John_LS. All rights reserved. // import UIKit import Photos protocol LSPhotoCollectionViewCellDelegate: class { func ls_eventSelectNumberChange(number: Int); } class LSPhotoCollectionViewCell: UICollectionViewCell { @IBOutlet weak var thumbnail: UIImageView! @IBOutlet weak var imageSelect: UIImageView! @IBOutlet weak var selectButton: UIButton! weak var delegate: LSPhotoCollectionViewController? weak var eventDelegate: LSPhotoCollectionViewCellDelegate? var representedAssetIdentifier: String? var model : PHAsset? override func awakeFromNib() { super.awakeFromNib() self.thumbnail.contentMode = .scaleAspectFill self.thumbnail.clipsToBounds = true } func ls_updateSelected(select:Bool){ self.selectButton.isSelected = select self.imageSelect.isHidden = !select if select { self.selectButton.setImage(nil, for: UIControlState.normal) } else { self.selectButton.setImage(UIImage(named: "img_unselect.png"), for: UIControlState.normal) } } @IBAction func eventImageSelect(sender: UIButton) { if sender.isSelected { sender.isSelected = false self.imageSelect.isHidden = true sender.setImage(UIImage(named: "img_unselect.png"), for: UIControlState.normal) if delegate != nil { if let index = LSPhoto.instance.selectedPhoto.index(of: self.model!) { LSPhoto.instance.selectedPhoto.remove(at: index) } if self.eventDelegate != nil { self.eventDelegate!.ls_eventSelectNumberChange(number: LSPhoto.instance.selectedPhoto.count) } } } else { if delegate != nil { if LSPhoto.instance.selectedPhoto.count >= LSPhotoPickerController.photoMaxSelectedNum - LSPhotoPickerController.alreadySelectedPhotoNum { self.ls_showSelectErrorDialog() ; return; } else { LSPhoto.instance.selectedPhoto.append(self.model!) if self.eventDelegate != nil { self.eventDelegate!.ls_eventSelectNumberChange(number: LSPhoto.instance.selectedPhoto.count) } } } sender.isSelected = true self.imageSelect.isHidden = false sender.setImage(nil, for: UIControlState.normal) self.imageSelect.transform = CGAffineTransform(scaleX: 0.8, y: 0.8) UIView.animate(withDuration: 0.4, delay: 0, usingSpringWithDamping: 0.4, initialSpringVelocity: 6, options: [UIViewAnimationOptions.curveEaseIn], animations: { () -> Void in self.imageSelect.transform = CGAffineTransform(scaleX: 1.0, y: 1.0) }, completion: nil) } } private func ls_showSelectErrorDialog() { if self.delegate != nil { let less = LSPhotoPickerController.photoMaxSelectedNum - LSPhotoPickerController.alreadySelectedPhotoNum let range = LSPhotoPickerConfig.ErrorImageMaxSelect.range(of:"#") var error = LSPhotoPickerConfig.ErrorImageMaxSelect error.replaceSubrange(range!, with: String(less)) let alert = UIAlertController.init(title: nil, message: error, preferredStyle: UIAlertControllerStyle.alert) let confirmAction = UIAlertAction(title: LSPhotoPickerConfig.ButtonConfirmTitle, style: .default, handler: nil) alert.addAction(confirmAction) self.delegate?.present(alert, animated: true, completion: nil) } } }
mit
81973d7ccc0856d0731553cd0d665f95
39.391753
185
0.622767
5.042471
false
false
false
false
mightydeveloper/swift
test/NameBinding/reference-dependencies-members.swift
20
2972
// RUN: rm -rf %t && mkdir %t // RUN: cp %s %t/main.swift // RUN: %target-swift-frontend -parse -primary-file %t/main.swift %S/Inputs/reference-dependencies-members-helper.swift -emit-reference-dependencies-path - > %t.swiftdeps // RUN: FileCheck -check-prefix=PROVIDES-NOMINAL %s < %t.swiftdeps // RUN: FileCheck -check-prefix=PROVIDES-NOMINAL-NEGATIVE %s < %t.swiftdeps // RUN: FileCheck -check-prefix=PROVIDES-MEMBER %s < %t.swiftdeps // RUN: FileCheck -check-prefix=PROVIDES-MEMBER-NEGATIVE %s < %t.swiftdeps // RUN: FileCheck -check-prefix=DEPENDS-NOMINAL %s < %t.swiftdeps // RUN: FileCheck -check-prefix=DEPENDS-NOMINAL-NEGATIVE %s < %t.swiftdeps // RUN: FileCheck -check-prefix=DEPENDS-MEMBER %s < %t.swiftdeps // RUN: FileCheck -check-prefix=DEPENDS-MEMBER-NEGATIVE %s < %t.swiftdeps // PROVIDES-NOMINAL-LABEL: {{^provides-nominal:$}} // PROVIDES-NOMINAL-NEGATIVE-LABEL: {{^provides-nominal:$}} // PROVIDES-MEMBER-LABEL: {{^provides-member:$}} // PROVIDES-MEMBER-NEGATIVE-LABEL: {{^provides-member:$}} // DEPENDS-NOMINAL-LABEL: {{^depends-nominal:$}} // DEPENDS-NOMINAL-NEGATIVE-LABEL: {{^depends-nominal:$}} // DEPENDS-MEMBER-LABEL: {{^depends-member:$}} // DEPENDS-MEMBER-NEGATIVE-LABEL: {{^depends-member:$}} // PROVIDES-NOMINAL-DAG: 4Base" class Base { // PROVIDES-MEMBER-DAG: - ["{{.+}}4Base", ""] // PROVIDES-MEMBER-NEGATIVE-NOT: - ["{{.+}}4Base", "{{.+}}"] func foo() {} } // PROVIDES-NOMINAL-DAG: 3Sub" // DEPENDS-NOMINAL-DAG: 9OtherBase" class Sub : OtherBase { // PROVIDES-MEMBER-DAG: - ["{{.+}}3Sub", ""] // PROVIDES-MEMBER-NEGATIVE-NOT: - ["{{.+}}3Sub", "{{.+}}"] // DEPENDS-MEMBER-DAG: - ["{{.+}}9OtherBase", ""] // DEPENDS-MEMBER-DAG: - ["{{.+}}9OtherBase", "foo"] // DEPENDS-MEMBER-DAG: - ["{{.+}}9OtherBase", "init"] func foo() {} } // PROVIDES-NOMINAL-DAG: 9SomeProto" // PROVIDES-MEMBER-DAG: - ["{{.+}}9SomeProto", ""] protocol SomeProto {} // PROVIDES-NOMINAL-DAG: 10OtherClass" // PROVIDES-MEMBER-DAG: - ["{{.+}}10OtherClass", ""] // DEPENDS-NOMINAL-DAG: 10OtherClass" // DEPENDS-NOMINAL-DAG: 9SomeProto" // DEPENDS-MEMBER-DAG: - ["{{.+}}9SomeProto", ""] // DEPENDS-MEMBER-DAG: - ["{{.+}}10OtherClass", "deinit"] extension OtherClass : SomeProto {} // PROVIDES-NOMINAL-NEGATIVE-NOT: 11OtherStruct"{{$}} // DEPENDS-NOMINAL-DAG: 11OtherStruct" extension OtherStruct { // PROVIDES-MEMBER-DAG: - ["{{.+}}11OtherStruct", ""] // PROVIDES-MEMBER-DAG: - ["{{.+}}11OtherStruct", "foo"] // PROVIDES-MEMBER-DAG: - ["{{.+}}11OtherStruct", "bar"] // PROVIDES-MEMBER-NEGATIVE-NOT: "baz" // DEPENDS-MEMBER-DAG: - ["{{.+}}11OtherStruct", "foo"] // DEPENDS-MEMBER-DAG: - ["{{.+}}11OtherStruct", "bar"] // DEPENDS-MEMBER-DAG: - !private ["{{.+}}11OtherStruct", "baz"] // DEPENDS-MEMBER-NEGATIVE-NOT: - ["{{.+}}11OtherStruct", ""] func foo() {} var bar: () { return () } private func baz() {} } // PROVIDES-NOMINAL-NEGATIVE-LABEL: {{^depends-nominal:$}} // PROVIDES-MEMBER-NEGATIVE-LABEL: {{^depends-member:$}}
apache-2.0
df7e91e7542adba2fbd6635b41549aa6
40.859155
170
0.64502
3.459837
false
false
false
false
rlisle/ParticleIoT
iOS/Patriot/Patriot/Models/DevicesDataManager.swift
1
2297
// // DevicesDataManager.swift // Patriot // // Created by Ron Lisle on 5/31/18. // Copyright © 2018 Ron Lisle. All rights reserved. // import UIKit class DevicesDataManager { var devices: [ Device ] = [] let hardware: HwManager weak var delegate: DeviceNotifying? init(hardware: HwManager) { print("DevicesDataManager init") self.hardware = hardware devices.append(Device(name: "office", percent: 0)) refresh(devices: hardware.devices) } func isDeviceOn(at: Int) -> Bool { return devices[at].percent > 0 } func toggleDevice(at: Int) { let isOn = isDeviceOn(at: at) print("toggleDevice to \(isOn ? 0 : 100)") setDevice(at: at, percent: isOn ? 0 : 100) } func setDevice(at: Int, percent: Int) { print("DM set device at: \(at) to \(percent)") devices[at].percent = percent let name = devices[at].name // if mqtt.isConnected { // mqtt.sendCommand(device: name, percent: percent) // } else { hardware.sendCommand(device: name, percent: percent) { (error) in if let error = error { print("Send command error: \(error)") } } // } } } //MARK: Helper Methods extension DevicesDataManager { func refresh(devices: [DeviceInfo]) { self.devices = [] for device in devices { let name = device.name let percent = device.percent self.devices.append(Device(name: name, percent: percent)) } delegate?.deviceListChanged() } } extension DevicesDataManager: DeviceNotifying { func deviceListChanged() { print("DevicesDataManager deviceListChanged") let list = hardware.devices refresh(devices: list) } func deviceChanged(name: String, percent: Int) { print("DeviceDataManager: DeviceChanged: \(name)") if let index = devices.firstIndex(where: {$0.name == name}) { print(" index of device = \(index)") devices[index].percent = percent } delegate?.deviceChanged(name: name, percent: percent) } }
mit
c3af59f2de44cd8e8fb08746f69bc0ef
22.428571
77
0.558798
4.212844
false
false
false
false
svachmic/ios-url-remote
URLRemote/Classes/ViewModel/CategoryTableViewModel.swift
1
1128
// // CategoryTableViewModel.swift // URLRemote // // Created by Michal Švácha on 14/07/2017. // Copyright © 2017 Svacha, Michal. All rights reserved. // import Foundation import Bond import ReactiveKit /// View Model of the Category Table View Controller. Handles logic of category selection. class CategoryTableViewModel { let initialSelection = Observable<Int>(0) let userSelection = Observable<Int>(0) let contents = MutableObservableArray<Category>([]) let signal = PublishSubject<Int, NoError>() let bag = DisposeBag() init() { initialSelection.bind(to: userSelection).dispose(in: bag) } /// Validates and saves user's selection in the table view. /// /// - Parameter index: Selected index by the user. func selected(_ index: Int) { if let category = contents.array[safe: index], !category.isFull() { self.userSelection.value = index } } /// Sends out signal with the selection to the observers before the view controller gets dismissed. func done() { signal.next(userSelection.value) } }
apache-2.0
427d445aa9fc8909500c2d5385a133bf
27.846154
103
0.664889
4.482072
false
false
false
false
LeeMinglu/LSWeiboSwift
LSWeiboSwift/LSWeiboSwift/Classes/Tools/NetWork/LSWeiBoCommon.swift
1
1103
// // LSWeiBoCommon.swift // LSWeiboSwift // // Created by 李明禄 on 2017/10/11. // Copyright © 2017年 SocererGroup. All rights reserved. // import Foundation // MARK: -----应用程序信息------ //应用程序ID let AppKey = "3749979107" //应用程序加密信息 let AppSecret = "7c6caa278636b325243e07f976bdf72e" //回调URI--登录程序跳转的URI,参数以get形式进行拼接 let RedirectURL = "https://www.baidu.com" // MARK: -----全局通知定义----- //登陆通知 let LSUserShouldeLoginNotification = "LSUserShouldeLoginNotification" //用户登陆成功通知 let LSUSERLoginSuccessNotification = "LSUSERLoginSuccessNotification" //MARK:-----配图视图信息----- //外部间距 let LSStatusPictureViewOutterMargin = CGFloat(12) //图片的内部间距 let LSStatusPictureViewInnerMargin = CGFloat(3) //图片视图的宽度 let LSStatusPictureViewWidth = UIScreen.main.bounds.width - 2 * LSStatusPictureViewOutterMargin //图片视图内每个图片的宽度 let LSStatusPictureViewItemWidth = (LSStatusPictureViewWidth - 2 * LSStatusPictureViewInnerMargin) / 3
apache-2.0
e08aeb3d724fa23f75c064fc5147118e
23.052632
102
0.761488
3.077441
false
false
false
false
abarisain/skugga
Apple/iOS/Skugga/View Controllers/RemoteFileListViewController.swift
1
9257
// // RemoteFileListViewController.swift // Skugga // // Created by Arnaud Barisain Monrose on 12/02/2015. // Copyright (c) 2015 NamelessDev. All rights reserved. // import UIKit import DateToolsSwift import UpdAPI import Photos @objc @objcMembers class RemoteFileListViewController : UITableViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate, UIViewControllerPreviewingDelegate { fileprivate var files = [RemoteFile]() override func viewDidLoad() { super.viewDidLoad() if "" == Configuration.endpoint { performSegue(withIdentifier: "settings", sender: self) } else { RemoteFileDatabaseHelper.refreshFromServer() } if #available(iOS 9, *) { if traitCollection.forceTouchCapability == .available { /* Register for `UIViewControllerPreviewingDelegate` to enable "Peek" and "Pop". The view controller will be automatically unregistered when it is deallocated. */ registerForPreviewing(with: self, sourceView: view) } } } override func viewWillAppear(_ animated: Bool) { NotificationCenter.default.addObserver(self, selector: #selector(RemoteFileListViewController.refreshData), name: NSNotification.Name(rawValue: RemoteFilesChangedNotification), object: nil) NotificationCenter.default.addObserver(self, selector: #selector(RemoteFileListViewController.dataRefreshFailed), name: NSNotification.Name(rawValue: RemoteFilesRefreshFailureNotification), object: nil) NotificationCenter.default.addObserver(self, selector: #selector(RemoteFileListViewController.uploadShortcut), name: NSNotification.Name(rawValue: UploadActionNotification), object: nil) refreshData() if let app = UIApplication.shared.delegate as? AppDelegate , app.doUploadAction { app.doUploadAction = false uploadShortcut() } } override func viewWillDisappear(_ animated: Bool) { NotificationCenter.default.removeObserver(self) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @objc func uploadShortcut() { uploadAction(self) } @IBAction func uploadAction(_ sender: AnyObject) { //FIXME : Implement iOS 8's document provider let imagePicker = FixedStatusBarImagePickerController() imagePicker.delegate = self imagePicker.sourceType = .photoLibrary //FIXME : Add popover support for iPads present(imagePicker, animated: true, completion: nil) } @objc func refreshData() { DispatchQueue.main.async { self.files = RemoteFileDatabaseHelper.cachedFiles self.tableView.reloadData() self.refreshControl?.endRefreshing() } } @objc func dataRefreshFailed() { DispatchQueue.main.async { self.refreshControl?.endRefreshing() } } fileprivate func uploadImage(_ image: UIImage, data: Data, filename: String) { let storyboard = UIStoryboard(name: "Main", bundle: nil) let uploadNavigationController = storyboard.instantiateViewController(withIdentifier: "UploadScene") as! UINavigationController let uploadController = uploadNavigationController.viewControllers[0] as! UploadViewController uploadController.targetImage = image uploadController.targetData = data uploadController.targetFilename = filename present(uploadNavigationController, animated: true) { () -> Void in uploadController.startUpload() } } @IBAction func refreshControlPulled(_ sender: AnyObject) { RemoteFileDatabaseHelper.refreshFromServer() } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "FileDetails" { let detailsViewController = segue.destination as! FileDetailsViewController detailsViewController.remoteFile = files[(tableView.indexPathForSelectedRow as NSIndexPath?)?.row ?? 0] } } // MARK : Table delegate/datasource Methods override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return files.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "FileCell") as! RemoteFileTableViewCell cell.update(files[(indexPath as NSIndexPath).row]) return cell } override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool { return true } override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) { if editingStyle == .delete { FileListClient(configuration: Configuration.updApiConfiguration).deleteFile(files[(indexPath as NSIndexPath).row], success: { () -> () in self.files.remove(at: (indexPath as NSIndexPath).row) self.tableView.beginUpdates() self.tableView.deleteRows(at: [indexPath], with: .automatic) self.tableView.endUpdates() RemoteFileDatabaseHelper.refreshFromServer() }, failure: { (error: NSError) -> () in let alert = UIAlertController(title: "Error", message: "Couldn't delete file : \(error) \(error.userInfo)", preferredStyle: .alert) alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.cancel, handler: nil)) self.present(alert, animated: true, completion: nil) }); } } // MARK : UIImagePickerController Methods func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String: Any]) { let image = info[UIImagePickerControllerOriginalImage] as! UIImage picker.dismiss(animated: true) { () -> Void in if let asset = info[UIImagePickerControllerPHAsset] as? PHAsset { let filename = asset.value(forKey: "filename") as? String ?? "iOS Upload" self.uploadImage(image, data: UIImageJPEGRepresentation(image, 1)!, filename: filename) } else { let alert = UIAlertController(title: "Error", message: "Couldn't upload image", preferredStyle: .alert) alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.cancel, handler: nil)) self.present(alert, animated: true, completion: nil) } } } // MARK : UIViewControllerPreviewingDelegate @available(iOS 9.0, *) func previewingContext(_ previewingContext: UIViewControllerPreviewing, viewControllerForLocation location: CGPoint) -> UIViewController? { // Obtain the index path and the cell that was pressed. guard let indexPath = tableView.indexPathForRow(at: location), let cell = tableView.cellForRow(at: indexPath) else { return nil } guard let detailViewController = storyboard?.instantiateViewController(withIdentifier: "FileDetailsViewController") as? FileDetailsViewController else { return nil } previewingContext.sourceRect = cell.frame detailViewController.remoteFile = files[indexPath.row] return detailViewController } @available(iOS 9.0, *) func previewingContext(_ previewingContext: UIViewControllerPreviewing, commit viewControllerToCommit: UIViewController) { show(viewControllerToCommit, sender: self) } } class RemoteFileTableViewCell : UITableViewCell { @IBOutlet weak var filenameLabel: UILabel! @IBOutlet weak var dateLabel: UILabel! @IBOutlet weak var fileImageView: UIImageView! func update(_ remoteFile : RemoteFile) { filenameLabel.text = remoteFile.filename dateLabel.text = remoteFile.uploadDate.timeAgoSinceNow var url = remoteFile.absoluteURL(baseURL: Configuration.endpoint) if let baseURL = url { var urlComponents = URLComponents(url: baseURL, resolvingAgainstBaseURL: false) urlComponents?.queryItems = [ URLQueryItem(name: "w", value: "0"), URLQueryItem(name: "h", value: "96"), ] url = urlComponents?.url } fileImageView.sd_setImage(with: url) } } class FixedStatusBarImagePickerController : UIImagePickerController { override var prefersStatusBarHidden : Bool { return false } override var childViewControllerForStatusBarHidden : UIViewController? { return nil } }
apache-2.0
090389a88f908d94e7dd5e25eaebb6bd
36.477733
210
0.64697
5.600121
false
false
false
false
EZ-NET/ESSwim
Sources/State/Existence.swift
1
3711
// // Existence.swift // ESSwim // // Created by Tomohiro Kumagai on H27/06/10. // // public protocol ExistenceDeterminationable { var isExists:Bool { get } var isEmpty:Bool { get } } extension ExistenceDeterminationable { public var isExists: Bool { return !isEmpty } } // MARK: Type Implementation extension String : ExistenceDeterminationable { } extension Array : ExistenceDeterminationable { } extension Dictionary : ExistenceDeterminationable { } extension Set : ExistenceDeterminationable { } extension CollectionOfOne : ExistenceDeterminationable { } extension ContiguousArray : ExistenceDeterminationable { } extension LazyCollection : ExistenceDeterminationable { } extension EmptyCollection : ExistenceDeterminationable { public var isExists: Bool { return false } public var isEmpty: Bool { return true } } extension FlattenCollection : ExistenceDeterminationable { } extension ReverseCollection : ExistenceDeterminationable { } extension Optional : ExistenceDeterminationable { public var isExists:Bool { switch self { case .Some: return true case .None: return false } } public var isEmpty:Bool { switch self { case .Some: return false case .None: return true } } } // MARK: - Function public func existAll<T:ExistenceDeterminationable>(states:T...) -> Bool { return states.existAll } public func existAny<T:ExistenceDeterminationable>(states:T...) -> Bool { return states.existAny } public func emptyAll<T:ExistenceDeterminationable>(states:T...) -> Bool { return states.emptyAll } public func emptyAny<T:ExistenceDeterminationable>(states:T...) -> Bool { return states.emptyAny } // MARK: - Extension extension SequenceType where Generator.Element : ExistenceDeterminationable { public var existAll:Bool { return meetsAllOf(self) { $0.isExists } } public var existAny:Bool { return meetsAnyOf(self) { $0.isExists } } public var emptyAll:Bool { return meetsAllOf(self) { $0.isEmpty } } public var emptyAny:Bool { return meetsAnyOf(self) { $0.isEmpty } } } // MARK: Deprecated @available(*, unavailable, message="access the 'isEmpty' method on the ExistenceDeterminationable") @noreturn public func isNotExists<T>(state:Optional<T>) -> Bool {} @available(*, unavailable, message="access the 'isExists' method on the ExistenceDeterminationable") @noreturn public func isExists<T>(state:Optional<T>) -> Bool {} @available(*, unavailable, renamed="emptyAll") @noreturn public func notExistAll<T>(states:Optional<T>...) -> Bool {} @available(*, unavailable, renamed="emptyAny") @noreturn public func notExistAny<T>(states:Optional<T>...) -> Bool {} @available(*, unavailable, message="access the 'existAll' property on the SequenceType") @noreturn public func existAll<T>(states:[Optional<T>]) -> Bool {} @available(*, unavailable, message="access the 'existAny' property on the SequenceType") @noreturn public func existAny<T>(states:[Optional<T>]) -> Bool {} @available(*, unavailable, message="access the 'emptyAll' property on the SequenceType") @noreturn public func notExistAll<T>(states:[Optional<T>]) -> Bool {} @available(*, unavailable, message="access the 'emptyAny' property on the SequenceType") @noreturn public func notExistAny<T>(states:[Optional<T>]) -> Bool {} extension SequenceType where Generator.Element : ExistenceDeterminationable { @available(*, unavailable, renamed="emptyAll") public var notExistAll:Bool { return meetsAllOf(self) { $0.isEmpty } } @available(*, unavailable, renamed="emptyAny") public var notExistAny:Bool { return meetsAnyOf(self) { $0.isEmpty } } }
mit
29d58f51e9ce878f20ca12fbd2db8906
18.84492
100
0.718135
3.670623
false
false
false
false
ashfurrow/eidolon
Kiosk/App/BidderDetailsRetrieval.swift
2
3258
import UIKit import RxSwift import SVProgressHUD import Action extension UIViewController { func promptForBidderDetailsRetrieval(provider: Networking) -> Observable<Void> { return Observable.deferred { () -> Observable<Void> in let alertController = self.emailPromptAlertController(provider: provider) self.present(alertController, animated: true) { } return .empty() } } func retrieveBidderDetails(provider: Networking, email: String) -> Observable<Void> { return Observable.just(email) .take(1) .do(onNext: { _ in SVProgressHUD.show() }) .flatMap { email -> Observable<Void> in let endpoint = ArtsyAPI.bidderDetailsNotification(auctionID: appDelegate().appViewController.sale.value.id, identifier: email) return provider.request(endpoint).filterSuccessfulStatusCodes().map(void) } .throttle(1, scheduler: MainScheduler.instance) .do(onNext: { _ in SVProgressHUD.dismiss() self.present(UIAlertController.successfulBidderDetailsAlertController(), animated: true, completion: nil) }, onError: { _ in SVProgressHUD.dismiss() self.present(UIAlertController.failedBidderDetailsAlertController(), animated: true, completion: nil) }) } func emailPromptAlertController(provider: Networking) -> UIAlertController { let alertController = UIAlertController(title: "Send Bidder Details", message: "Enter your email address or phone number registered with Artsy and we will send your bidder number and PIN.", preferredStyle: .alert) var ok = UIAlertAction.Action("OK", style: .default) let action = CocoaAction { _ -> Observable<Void> in let text = (alertController.textFields?.first)?.text ?? "" return self.retrieveBidderDetails(provider: provider, email: text) } ok.rx.action = action let cancel = UIAlertAction.Action("Cancel", style: .cancel) alertController.addTextField(configurationHandler: nil) alertController.addAction(ok) alertController.addAction(cancel) return alertController } } extension UIAlertController { class func successfulBidderDetailsAlertController() -> UIAlertController { let alertController = self.init(title: "Your details have been sent", message: nil, preferredStyle: .alert) alertController.addAction(UIAlertAction.Action("OK", style: .default)) return alertController } class func failedBidderDetailsAlertController() -> UIAlertController { let alertController = self.init(title: "Incorrect Email", message: "Email was not recognized. You may not be registered to bid yet.", preferredStyle: .alert) alertController.addAction(UIAlertAction.Action("Cancel", style: .cancel)) var retryAction = UIAlertAction.Action("Retry", style: .default) retryAction.rx.action = appDelegate().requestBidderDetailsCommand() alertController.addAction(retryAction) return alertController } }
mit
e4bf97923411555351f6542106467167
41.311688
221
0.659607
5.457286
false
false
false
false
thefirstnikhil/hydrateapp
Hydrate/Models/HydrationManager.swift
1
1708
// // HydrationManager.swift // Hydrate // // Created by Nikhil Kalra on 9/2/14. // Copyright (c) 2014 Nikhil Kalra. All rights reserved. // import UIKit private let consumptionName = "Consumption" let waterGoalKey = "HydrationWaterGoal" let waterNotificationsKey = "HydrationNotificationKey" let waterNotificationIntervalsKey = "HydrationWaterNotificationIntervalsKey" class HydrationManager: NSObject { var consumptions = [Consumption]() let persistenceHelper = PersistenceHelper() /* SINGLETON */ class var sharedInstance: HydrationManager { struct Singleton { static let instance = HydrationManager() } return Singleton.instance } override init() { let tempConsump = persistenceHelper.listConsumption() for res in tempConsump { consumptions.append(res) } } func addConsumption(time: NSDate, quantity: NSNumber) { var dict = Dictionary<String, AnyObject>() dict["time"] = time dict["quantity"] = quantity let consTuple = persistenceHelper.saveConsumption(time, quantity: quantity) if (consTuple.success) { consumptions.append(consTuple.consumption!) } } func removeConsumption(consumption: Consumption) { let time = consumption.time var found: Int? for var i = 0; i < consumptions.count; i++ { if consumptions[i] == consumption { found = i } } if (persistenceHelper.removeConsumption(time)) { consumptions.removeAtIndex(found!) } } }
mit
6e4304f24015a8b04e8603a0a20b3868
24.878788
83
0.605972
4.335025
false
false
false
false
2016321/CycleScrollView
CycleScrollView/CycleScrollViewCollectionView.swift
1
1745
// // CycleScrollViewCollectionView.swift // BingoCycleScrollViewDemo // // Created by 王昱斌 on 17/4/17. // Copyright © 2017年 Qtin. All rights reserved. // import UIKit class CycleScrollViewCollectionView: UICollectionView { fileprivate var cycleScrollView: CycleScrollView? { return self.superview?.superview as? CycleScrollView } override var contentInset: UIEdgeInsets { set { super.contentInset = .zero if (newValue.top > 0) { let contentOffset = CGPoint(x:self.contentOffset.x, y:self.contentOffset.y+newValue.top); self.contentOffset = contentOffset } } get { return super.contentInset } } override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) { super.init(frame: frame, collectionViewLayout: layout) self.commonInit() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) self.commonInit() } } extension CycleScrollViewCollectionView{ fileprivate func commonInit() { self.contentInset = .zero self.decelerationRate = UIScrollViewDecelerationRateFast self.showsVerticalScrollIndicator = false self.showsHorizontalScrollIndicator = false self.isPagingEnabled = true //MARK: - iOS10中关闭预加载,因为是动态改变cell大小,一定要关闭,一定要关闭,一定要关闭! if #available(iOS 10.0, *) { self.isPrefetchingEnabled = false } #if !os(tvOS) self.scrollsToTop = false self.isPagingEnabled = false #endif } }
apache-2.0
f1692efadda54b34b16060491a995a87
26.311475
105
0.62545
4.843023
false
false
false
false
abertelrud/swift-package-manager
Sources/PackageDescription/Context.swift
2
1207
//===----------------------------------------------------------------------===// // // This source file is part of the Swift open source project // // Copyright (c) 2018 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 // //===----------------------------------------------------------------------===// /// The context information for a Swift package. /// /// The context encapsulates states that are known when Swift Package Manager interprets the package manifest, /// for example the location in the file system where the current package resides. @available(_PackageDescription, introduced: 5.6) public struct Context { private static let model = try! ContextModel.decode() /// The directory that contains `Package.swift`. public static var packageDirectory : String { model.packageDirectory } /// Snapshot of the system environment variables. public static var environment : [String : String] { model.environment } private init() { } }
apache-2.0
9c1976574dab0c6f2e4011f20c92195e
35.575758
110
0.619718
5.270742
false
false
false
false
aiwalle/LiveProject
LiveProject/Test/ViewController.swift
1
3541
// // ViewController.swift // LiveProject // // Created by liang on 2017/7/25. // Copyright © 2017年 liang. All rights reserved. // import UIKit private let kViewControllerCellID = "kViewControllerCellID" class ViewController: UIViewController { fileprivate var itemCount = 15 fileprivate lazy var collectionView : UICollectionView = { let layout = LJWaterFallLayout() layout.sectionInset = UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10) layout.minimumInteritemSpacing = 10 layout.minimumLineSpacing = 10 layout.cols = 2 layout.dataSource = self layout.scrollDirection = .vertical let collectionView = UICollectionView(frame: self.view.bounds, collectionViewLayout:layout ) collectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: kViewControllerCellID) collectionView.dataSource = self collectionView.delegate = self return collectionView }() override func viewDidLoad() { super.viewDidLoad() // setupPageView() view.addSubview(collectionView) } fileprivate func setupPageView() { automaticallyAdjustsScrollViewInsets = false let pageFrame = CGRect(x: 0, y: 64, width: view.bounds.width, height: view.bounds.height - 64) // let titles = ["推荐", "游戏推荐", "娱乐推", "天天"] let titles = ["推荐", "游戏推荐", "娱乐推", "哈哈哈哈哈荐","呵呵呵", "科技推", "娱乐推荐推荐"] var childVcs = [UIViewController]() for _ in 0..<titles.count { let vc = UIViewController() vc.view.backgroundColor = UIColor.getRandomColor() childVcs.append(vc) } var style = LJPageStyle() style.isShowBottomLine = true style.isShowCoverView = true style.isScrollEnable = true style.isNeedScale = true let pageView = LJPageView(frame: pageFrame, titles: titles, style: style, childVcs: childVcs, parentVc: self) view.addSubview(pageView) } } extension ViewController : UICollectionViewDataSource { func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return itemCount } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: kViewControllerCellID, for: indexPath) cell.backgroundColor = UIColor.getRandomColor() return cell } } extension ViewController : UICollectionViewDelegate { func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { self.navigationController?.pushViewController(ViewController(), animated: true) } func scrollViewDidScroll(_ scrollView: UIScrollView) { if scrollView.contentOffset.y > scrollView.contentSize.height - scrollView.bounds.height { itemCount += 30 collectionView.reloadData() } } } extension ViewController : LJWaterFallLayoutDataSource { func waterFallLayout(_ layout: LJWaterFallLayout, itemIndex: Int) -> CGFloat { // let screenW = UIScreen.main.bounds.width // return itemIndex % 2 == 0 ? screenW * 2 / 3 : screenW * 0.5 return CGFloat(arc4random_uniform(150) + 80) } }
mit
e79546c81db7cdb9fb341eaa8978a777
31.971429
121
0.65569
5.113737
false
false
false
false
dflax/amazeballs
Legacy Versions/Swift 3.x Version/AmazeBalls/GameViewController.swift
1
3864
// // GameViewController.swift // Amazeballs // // Created by Daniel Flax on 5/18/15. // Copyright (c) 2015 Daniel Flax. All rights reserved. // // The MIT License (MIT) // // 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 SpriteKit class GameViewController: UIViewController, SettingsDelegateProtocol { var scene: BallScene! override func viewDidLoad() { super.viewDidLoad() let skView = self.view as! SKView scene = BallScene(size: skView.bounds.size) scene.scaleMode = .aspectFit skView.presentScene(scene) skView.showsFPS = true skView.showsNodeCount = true skView.ignoresSiblingOrder = true scene.scaleMode = .resizeFill // Present the main scene for the game skView.presentScene(scene) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } // Update the physics settings, when the view appears - after Settings are changed override func viewWillAppear(_ animated: Bool) { self.scene.updateWorldPhysicsSettings() } // Prepare for segues override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Leveraging a Storyboard segue to bring up the settings view, must set the delegate correctly if (segue.identifier == "settingsSegue") { // set the destination of the segue (the settingsView) delegate to myself let settingsView = segue.destination as! SettingsViewController settingsView.delegate = self } } //MARK: - Settings Delegate Protocol Methods // When the user taps save, the delegate calls this method, sending back all of the data values from the settings panel func settingsViewController(_ viewController: SettingsViewController, gravitySetting: Float, bouncySetting: Float, boundingWallSetting: Bool, accelerometerSetting: Bool, activeBall: Int) { // Ceate a handle for the Standard User Defaults let userDefaults = UserDefaults.standard let cgFloatGrav = gravitySetting * -40.0 // Store values for the various settings in User Defaults userDefaults.setValue(gravitySetting, forKey:"gravityValue") userDefaults.setValue(bouncySetting, forKey:"bouncyness") userDefaults.setValue(boundingWallSetting, forKey:"boundingWallSetting") userDefaults.setValue(accelerometerSetting, forKey:"accelerometerSetting") userDefaults.setValue(activeBall, forKey:"activeBall") userDefaults.synchronize() // With the new physics now stored in NSUserDefaults, update the Physics for the scene scene.updateWorldPhysicsSettings() // Now dismiss the modal view controller self.dismiss(animated: true, completion: nil) } // If the user cancels the settings view, simply dismiss the modal view controller for settings func settingsViewController(_ viewController: SettingsViewController, cancelled: Bool) { self.dismiss(animated: true, completion: nil) } }
mit
f1ef8e2d790d17cab3da554bf6a91800
35.8
189
0.762681
4.461894
false
false
false
false
cubixlabs/GIST-Framework
GISTFramework/Classes/Controls/AnimatedTextInput/AnimatedTextInput.swift
1
30660
import UIKit @objc public protocol AnimatedTextInputDelegate: class { @objc optional func animatedTextInputDidBeginEditing(animatedTextInput: AnimatedTextInput) @objc optional func animatedTextInputDidEndEditing(animatedTextInput: AnimatedTextInput) @objc optional func animatedTextInputDidChange(animatedTextInput: AnimatedTextInput) @objc optional func animatedTextInput(animatedTextInput: AnimatedTextInput, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool @objc optional func animatedTextInputShouldBeginEditing(animatedTextInput: AnimatedTextInput) -> Bool @objc optional func animatedTextInputShouldEndEditing(animatedTextInput: AnimatedTextInput) -> Bool @objc optional func animatedTextInputShouldReturn(animatedTextInput: AnimatedTextInput) -> Bool } open class AnimatedTextInput: UIControl, BaseView, TextInputDelegate { //MARK: - Properties /// The String to display when the textfield is not editing and the input is not empty. @IBInspectable open var title:String? { didSet { } } //P.E. private var _placeholder:String? = "Placeholder"; @IBInspectable open var placeholder:String? { set { if let key:String = newValue , key.hasPrefix("#") == true { _placeholder = SyncedText.text(forKey: key); } else { _placeholder = newValue; } placeholderLayer.string = _placeholder } get { return _placeholder; } } @IBInspectable open var multilined:Bool = false { didSet { self.type = (multilined) ? .multiline:.standard; } } /// Max Character Count Limit for the text field. @IBInspectable open var maxCharLimit: Int = 255; /// Background color key from Sync Engine. @IBInspectable open var bgColorStyle:String? = nil { didSet { self.backgroundColor = SyncedColors.color(forKey: bgColorStyle); } } /// Width of View Border. @IBInspectable open var border:Int = 0 { didSet { if let borderCStyle:String = borderColorStyle { self.addBorder(SyncedColors.color(forKey: borderCStyle), width: border) } } } /// Border color key from Sync Engine. @IBInspectable open var borderColorStyle:String? = nil { didSet { if let borderCStyle:String = borderColorStyle { self.addBorder(SyncedColors.color(forKey: borderCStyle), width: border) } } } /// Corner Radius for View. @IBInspectable open var cornerRadius:Int = 0 { didSet { self.addRoundedCorners(GISTUtility.convertToRatio(CGFloat(cornerRadius), sizedForIPad: iStyle.sizeForIPad)); } } /// Flag for making circle/rounded view. @IBInspectable open var rounded:Bool = false { didSet { if rounded { self.addRoundedCorners(); } } } /// Flag for Drop Shadow. @IBInspectable open var hasDropShadow:Bool = false { didSet { if (hasDropShadow) { self.addDropShadow(); } else { // TO HANDLER } } } @IBInspectable var autoCapitalization: String { set { self.autocapitalization = UITextAutocapitalizationType.textAutocapitalizationType(for: newValue); } get { return "\(self.autocapitalization)"; } } @IBInspectable var autoCorrection: String { set { self.autocorrection = UITextAutocorrectionType.textAutocorrectionType(for: newValue); } get { return "\(self.autocorrection)"; } } @IBInspectable var keyboard: String { set { self.keyboardType = UIKeyboardType.keyboardType(for: newValue); } get { return "\(self.keyboardType)"; } } @IBInspectable var returnKey: String { set { self.returnKeyType = UIReturnKeyType.returnKeyType(for: newValue); } get { return "\(self.returnKeyType)"; } } open var rightViewMode: UITextField.ViewMode = .never { didSet { if let animatedTextField:AnimatedTextField = self.textInput as? AnimatedTextField { animatedTextField.rightViewMode = rightViewMode; } } } /// Parameter key for service - Default Value is nil @IBInspectable open var paramKey:String?; typealias AnimatedTextInputType = AnimatedTextInputFieldConfigurator.AnimatedTextInputType private var _tapAction: (() -> Void)? open weak var delegate: AnimatedTextInputDelegate? open fileprivate(set) var isActive = false var type: AnimatedTextInputType = .standard { didSet { configureType() } } open var autocapitalization: UITextAutocapitalizationType { get { return self.textInput.autocapitalization; } set { self.textInput.autocapitalization = newValue; } } open var autocorrection: UITextAutocorrectionType { get { return self.textInput.autocorrection; } set { self.textInput.autocorrection = newValue; } } open var keyboardType: UIKeyboardType { get { return self.textInput.keyboardType; } set { self.textInput.keyboardType = newValue; } } open var keyboardAppearance: UIKeyboardAppearance { get { return textInput.currentKeyboardAppearance } set { textInput.currentKeyboardAppearance = newValue } } open var returnKeyType: UIReturnKeyType = .default { didSet { textInput.changeReturnKeyType(with: returnKeyType) } } open var clearButtonMode: UITextField.ViewMode = .whileEditing { didSet { textInput.changeClearButtonMode(with: clearButtonMode) } } // Some letters like 'g' or 'á' were not rendered properly, the frame need to be about 20% higher than the font size open var frameHeightCorrectionFactor : Double = 1.2 { didSet { layoutPlaceholderLayer() } } open var placeholderAlignment: CATextLayer.Alignment = .natural { didSet { placeholderLayer.alignmentMode = CATextLayerAlignmentMode(rawValue: String(describing: placeholderAlignment)) } } //External GIST Style open var style: AnimatedTextInputStyle? { didSet { //Externel Style self.iStyle = InternalAnimatedTextInputStyle(style); } } //Internal Style var iStyle: InternalAnimatedTextInputStyle = InternalAnimatedTextInputStyle(nil) { didSet { configureStyle() } } open var text: String? { get { return textInput.currentText } set { if !textInput.view.isFirstResponder { (newValue != nil && !newValue!.isEmpty) ? configurePlaceholderAsInactiveHint() : configurePlaceholderAsDefault() } textInput.currentText = newValue } } open var selectedTextRange: UITextRange? { get { return textInput.currentSelectedTextRange } set { textInput.currentSelectedTextRange = newValue } } open var beginningOfDocument: UITextPosition? { get { return textInput.currentBeginningOfDocument } } open var font: UIFont? { get { return textInput.font } set { textAttributes = [NSAttributedString.Key.font: newValue as Any] } } open var textColor: UIColor? { get { return textInput.textColor } set { textAttributes = [NSAttributedString.Key.foregroundColor: newValue as Any] } } open var lineSpacing: CGFloat? { get { guard let paragraph = textAttributes?[NSAttributedString.Key.paragraphStyle] as? NSParagraphStyle else { return nil } return paragraph.lineSpacing } set { guard let spacing = newValue else { return } let paragraphStyle = textAttributes?[NSAttributedString.Key.paragraphStyle] as? NSMutableParagraphStyle ?? NSMutableParagraphStyle() paragraphStyle.lineSpacing = spacing textAttributes = [NSAttributedString.Key.paragraphStyle: paragraphStyle] } } @IBInspectable open var isSecureTextEntry: Bool { get { return self.textInput.isSecureTextEntry; } set { self.textInput.isSecureTextEntry = newValue; } } open var textAlignment: NSTextAlignment? { get { guard let paragraph = textInput.textAttributes?[NSAttributedString.Key.paragraphStyle] as? NSParagraphStyle else { return nil } return paragraph.alignment } set { guard let alignment = newValue else { return } let paragraphStyle = textAttributes?[NSAttributedString.Key.paragraphStyle] as? NSMutableParagraphStyle ?? NSMutableParagraphStyle() paragraphStyle.alignment = alignment textAttributes = [NSAttributedString.Key.paragraphStyle: paragraphStyle] } } open var tailIndent: CGFloat? { get { guard let paragraph = textAttributes?[NSAttributedString.Key.paragraphStyle] as? NSParagraphStyle else { return nil } return paragraph.tailIndent } set { guard let indent = newValue else { return } let paragraphStyle = textAttributes?[NSAttributedString.Key.paragraphStyle] as? NSMutableParagraphStyle ?? NSMutableParagraphStyle() paragraphStyle.tailIndent = indent textAttributes = [NSAttributedString.Key.paragraphStyle: paragraphStyle] } } open var headIndent: CGFloat? { get { guard let paragraph = textAttributes?[NSAttributedString.Key.paragraphStyle] as? NSParagraphStyle else { return nil } return paragraph.headIndent } set { guard let indent = newValue else { return } let paragraphStyle = textAttributes?[NSAttributedString.Key.paragraphStyle] as? NSMutableParagraphStyle ?? NSMutableParagraphStyle() paragraphStyle.headIndent = indent textAttributes = [NSAttributedString.Key.paragraphStyle: paragraphStyle] } } open var textAttributes: [NSAttributedString.Key: Any]? { didSet { guard var textInputAttributes = textInput.textAttributes else { textInput.textAttributes = textAttributes return } guard textAttributes != nil else { textInput.textAttributes = nil return } textInput.textAttributes = textInputAttributes.merge(dict: textAttributes!) } } private var _inputAccessoryView: UIView? open override var inputAccessoryView: UIView? { set { _inputAccessoryView = newValue } get { return _inputAccessoryView } } open var contentInset: UIEdgeInsets? { didSet { guard let insets = contentInset else { return } textInput.contentInset = insets } } open override var isUserInteractionEnabled: Bool { didSet { textInput.isUserInteractionEnabled = self.isUserInteractionEnabled; } } fileprivate let lineView = AnimatedLine() fileprivate let placeholderLayer = CATextLayer() fileprivate let counterLabel = UILabel() fileprivate let lineWidth: CGFloat = GIST_CONFIG.seperatorWidth; fileprivate let counterLabelRightMargin: CGFloat = 15 fileprivate let counterLabelTopMargin: CGFloat = 5 fileprivate var isResigningResponder = false fileprivate var isPlaceholderAsHint = false fileprivate var hasCounterLabel = false internal var textInput: TextInput! fileprivate var lineToBottomConstraint: NSLayoutConstraint! fileprivate var textInputTrailingConstraint: NSLayoutConstraint! fileprivate var disclosureViewWidthConstraint: NSLayoutConstraint! fileprivate var disclosureView: UIView? fileprivate var placeholderErrorText: String? fileprivate var placeholderPosition: CGPoint { let hintPosition = CGPoint( x: placeholderAlignment != .natural ? 0 : iStyle.leftMargin, y: iStyle.yHintPositionOffset ) let defaultPosition = CGPoint( x: placeholderAlignment != .natural ? 0 : iStyle.leftMargin, y: iStyle.topMargin + iStyle.yPlaceholderPositionOffset ) return isPlaceholderAsHint ? hintPosition : defaultPosition } public override init(frame: CGRect) { super.init(frame: frame) setupCommonElements() } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setupCommonElements() } override open var intrinsicContentSize: CGSize { let normalHeight = textInput.view.intrinsicContentSize.height return CGSize(width: UIView.noIntrinsicMetric, height: normalHeight + iStyle.topMargin + iStyle.bottomMargin) } open override func updateConstraints() { addLineViewConstraints() addTextInputConstraints() addCharacterCounterConstraints() super.updateConstraints() } open override func layoutSubviews() { super.layoutSubviews() layoutPlaceholderLayer() if rounded { self.addRoundedCorners(); } if (hasDropShadow) { self.addDropShadow(); } } fileprivate func layoutPlaceholderLayer() { // Some letters like 'g' or 'á' were not rendered properly, the frame need to be about 20% higher than the font size let frameHeightCorrectionFactor: CGFloat = 1.2 placeholderLayer.frame = CGRect(origin: placeholderPosition, size: CGSize(width: bounds.width, height: iStyle.textInputFont.pointSize * frameHeightCorrectionFactor)) } // mark: Configuration fileprivate func addLineViewConstraints() { removeConstraints(constraints) pinLeading(toLeadingOf: lineView, constant: iStyle.leftMargin) pinTrailing(toTrailingOf: lineView, constant: iStyle.rightMargin) lineView.setHeight(to: lineWidth) let constant = hasCounterLabel ? -counterLabel.intrinsicContentSize.height - counterLabelTopMargin : 0 lineToBottomConstraint = pinBottom(toBottomOf: lineView, constant: constant) } fileprivate func addTextInputConstraints() { pinLeading(toLeadingOf: textInput.view, constant: iStyle.leftMargin) if disclosureView == nil { textInputTrailingConstraint = pinTrailing(toTrailingOf: textInput.view, constant: iStyle.rightMargin) } pinTop(toTopOf: textInput.view, constant: iStyle.topMargin) textInput.view.pinBottom(toTopOf: lineView, constant: iStyle.bottomMargin) } fileprivate func setupCommonElements() { addLine() addPlaceHolder() addTapGestureRecognizer() addTextInput() } fileprivate func addLine() { lineView.defaultColor = iStyle.lineInactiveColor lineView.translatesAutoresizingMaskIntoConstraints = false addSubview(lineView) } fileprivate func addPlaceHolder() { placeholderLayer.masksToBounds = false placeholderLayer.string = placeholder placeholderLayer.foregroundColor = iStyle.inactiveColor.cgColor placeholderLayer.fontSize = iStyle.textInputFont.pointSize placeholderLayer.font = iStyle.textInputFont placeholderLayer.contentsScale = UIScreen.main.scale placeholderLayer.backgroundColor = UIColor.clear.cgColor layoutPlaceholderLayer() layer.addSublayer(placeholderLayer) } fileprivate func addTapGestureRecognizer() { let tap = UITapGestureRecognizer(target: self, action: #selector(viewWasTapped)) addGestureRecognizer(tap) } fileprivate func addTextInput() { textInput = AnimatedTextInputFieldConfigurator.configure(with: type) textInput.textInputDelegate = self textInput.view.tintColor = iStyle.activeColor textInput.textColor = iStyle.textInputFontColor textInput.font = iStyle.textInputFont textInput.view.translatesAutoresizingMaskIntoConstraints = false addSubview(textInput.view) invalidateIntrinsicContentSize() } fileprivate func updateCounter() { guard let counterText = counterLabel.text else { return } let components = counterText.components(separatedBy: "/") let characters = text?.count ?? 0 counterLabel.text = "\(characters)/\(components[1])" } // mark: States and animations fileprivate func configurePlaceholderAsActiveHint() { isPlaceholderAsHint = true configurePlaceholderWith(iStyle.titleFont, fontSize: iStyle.placeholderMinFontSize, foregroundColor: iStyle.titleFontColor.cgColor, text: self.title ?? self.placeholder) lineView.fillLine(with: iStyle.activeColor) } fileprivate func configurePlaceholderAsInactiveHint() { isPlaceholderAsHint = true configurePlaceholderWith(iStyle.titleFont, fontSize: iStyle.placeholderMinFontSize, foregroundColor: iStyle.titleFontColor.cgColor, text: self.title ?? self.placeholder) lineView.animateToInitialState() } fileprivate func configurePlaceholderAsDefault() { isPlaceholderAsHint = false configurePlaceholderWith(iStyle.textInputFont, fontSize: iStyle.textInputFont.pointSize, foregroundColor: iStyle.inactiveColor.cgColor, text: placeholder) lineView.animateToInitialState() } fileprivate func configurePlaceholderAsErrorHint() { isPlaceholderAsHint = true configurePlaceholderWith(iStyle.titleFont, fontSize: iStyle.placeholderMinFontSize, foregroundColor: iStyle.errorColor.cgColor, text: placeholderErrorText) lineView.fillLine(with: iStyle.errorColor) } fileprivate func configurePlaceholderWith(_ font:UIFont, fontSize: CGFloat, foregroundColor: CGColor, text: String?) { placeholderLayer.fontSize = fontSize placeholderLayer.font = font; placeholderLayer.foregroundColor = foregroundColor placeholderLayer.string = text layoutPlaceholderLayer() } fileprivate func animatePlaceholder(to applyConfiguration: () -> Void) { let duration = 0.2 let function = CAMediaTimingFunction(controlPoints: 0.3, 0.0, 0.5, 0.95) transactionAnimation(with: duration, timingFuncion: function, animations: applyConfiguration) } // mark: Behaviours public func onTap(action: @escaping () -> Void) { _tapAction = action; } //F.E. @objc fileprivate func viewWasTapped(sender: UIGestureRecognizer) { if let tapAction = _tapAction { tapAction() } else { becomeFirstResponder() } } fileprivate func styleDidChange() { lineView.defaultColor = iStyle.lineInactiveColor placeholderLayer.foregroundColor = iStyle.inactiveColor.cgColor let fontSize = iStyle.textInputFont.pointSize placeholderLayer.fontSize = fontSize placeholderLayer.font = iStyle.textInputFont textInput.view.tintColor = iStyle.activeColor textInput.textColor = iStyle.textInputFontColor textInput.font = iStyle.textInputFont invalidateIntrinsicContentSize() layoutIfNeeded() } @discardableResult override open func becomeFirstResponder() -> Bool { isActive = true let firstResponder = textInput.view.becomeFirstResponder() counterLabel.textColor = iStyle.activeColor placeholderErrorText = nil animatePlaceholder(to: configurePlaceholderAsActiveHint) return firstResponder } override open var isFirstResponder: Bool { return textInput.view.isFirstResponder } @discardableResult override open func resignFirstResponder() -> Bool { guard !isResigningResponder else { return true } isActive = false isResigningResponder = true let resignFirstResponder = textInput.view.resignFirstResponder() isResigningResponder = false counterLabel.textColor = iStyle.inactiveColor if let textInputError = textInput as? TextInputError { textInputError.removeErrorHintMessage() } // If the placeholder is showing an error we want to keep this state. Otherwise revert to inactive state. if placeholderErrorText == nil { animateToInactiveState() } return resignFirstResponder } fileprivate func animateToInactiveState() { guard let text = textInput.currentText, !text.isEmpty else { animatePlaceholder(to: configurePlaceholderAsDefault) return } animatePlaceholder(to: configurePlaceholderAsInactiveHint) } override open var canResignFirstResponder: Bool { return textInput.view.canResignFirstResponder } override open var canBecomeFirstResponder: Bool { guard !isResigningResponder else { return false } if let disclosureView = disclosureView, disclosureView.isFirstResponder { return false } return textInput.view.canBecomeFirstResponder } open func show(error errorMessage: String, placeholderText: String? = nil) { placeholderErrorText = errorMessage if let textInput = textInput as? TextInputError { textInput.configureErrorState(with: placeholderText) } animatePlaceholder(to: configurePlaceholderAsErrorHint) } open func clearError() { placeholderErrorText = nil if let textInputError = textInput as? TextInputError { textInputError.removeErrorHintMessage() } if isActive { animatePlaceholder(to: configurePlaceholderAsActiveHint) } else { animateToInactiveState() } } fileprivate func configureType() { textInput.view.removeFromSuperview() addTextInput() } open func applyStyle() { self.configureStyle(); } //F.E. fileprivate func configureStyle() { styleDidChange() if isActive { configurePlaceholderAsActiveHint() } else { isPlaceholderAsHint ? configurePlaceholderAsInactiveHint() : configurePlaceholderAsDefault() } } open func showCharacterCounterLabel(with maximum: Int? = nil) { hasCounterLabel = true let characters = text?.count ?? 0 if let maximumValue = maximum { counterLabel.text = "\(characters)/\(maximumValue)" } else { counterLabel.text = "\(characters)" } counterLabel.textColor = isActive ? iStyle.activeColor : iStyle.inactiveColor counterLabel.font = iStyle.counterLabelFont counterLabel.translatesAutoresizingMaskIntoConstraints = false addSubview(counterLabel) invalidateIntrinsicContentSize() } fileprivate func addCharacterCounterConstraints() { guard hasCounterLabel else { return } lineToBottomConstraint.constant = -counterLabel.intrinsicContentSize.height - counterLabelTopMargin lineView.pinBottom(toTopOf: counterLabel, constant: counterLabelTopMargin) pinTrailing(toTrailingOf: counterLabel, constant: counterLabelRightMargin) } open func removeCharacterCounterLabel() { hasCounterLabel = false counterLabel.removeConstraints(counterLabel.constraints) counterLabel.removeFromSuperview() lineToBottomConstraint.constant = 0 invalidateIntrinsicContentSize() } open func addDisclosureView(disclosureView: UIView) { if let constraint = textInputTrailingConstraint { removeConstraint(constraint) } self.disclosureView?.removeFromSuperview() self.disclosureView = disclosureView addSubview(disclosureView) textInputTrailingConstraint = textInput.view.pinTrailing(toLeadingOf: disclosureView, constant: 0) disclosureView.alignHorizontalAxis(toSameAxisOfView: textInput.view) disclosureView.pinBottom(toBottomOf: self, constant: 12) disclosureView.pinTrailing(toTrailingOf: self, constant: 16) } open func removeDisclosureView() { guard disclosureView != nil else { return } disclosureView?.removeFromSuperview() disclosureView = nil textInput.view.removeConstraint(textInputTrailingConstraint) textInputTrailingConstraint = pinTrailing(toTrailingOf: textInput.view, constant: iStyle.rightMargin) } open func position(from: UITextPosition, offset: Int) -> UITextPosition? { return textInput.currentPosition(from: from, offset: offset) } //MARK: - Methods open func textInputDidBeginEditing(textInput: TextInput) { becomeFirstResponder() delegate?.animatedTextInputDidBeginEditing?(animatedTextInput: self) } open func textInputDidEndEditing(textInput: TextInput) { resignFirstResponder() delegate?.animatedTextInputDidEndEditing?(animatedTextInput: self) } open func textInputDidChange(textInput: TextInput) { updateCounter() delegate?.animatedTextInputDidChange?(animatedTextInput: self) } open func textInput(textInput: TextInput, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool { let rtn:Bool = delegate?.animatedTextInput?(animatedTextInput: self, shouldChangeCharactersIn: range, replacementString: string) ?? true; //IF CHARACTERS-LIMIT <= ZERO, MEANS NO RESTRICTIONS ARE APPLIED if (self.maxCharLimit <= 0 || rtn == false || string == "") { return rtn; } guard let text = textInput.currentText else { return true } let newLength = text.utf16.count + string.utf16.count - range.length return (newLength <= self.maxCharLimit) // Bool } open func textInputShouldBeginEditing(textInput: TextInput) -> Bool { return delegate?.animatedTextInputShouldBeginEditing?(animatedTextInput: self) ?? true } open func textInputShouldEndEditing(textInput: TextInput) -> Bool { return delegate?.animatedTextInputShouldEndEditing?(animatedTextInput: self) ?? true } open func textInputShouldReturn(textInput: TextInput) -> Bool { return delegate?.animatedTextInputShouldReturn?(animatedTextInput: self) ?? true } open func add(disclosureButton button: UIButton, action: @escaping (() -> Void)) { if let animatedTextField:AnimatedTextField = self.textInput as? AnimatedTextField { animatedTextField.add(disclosureButton: button, action: action); } } } public protocol TextInput { var view: UIView { get } var currentText: String? { get set } var font: UIFont? { get set } var textColor: UIColor? { get set } var textAttributes: [NSAttributedString.Key: Any]? { get set } var textInputDelegate: TextInputDelegate? { get set } var currentSelectedTextRange: UITextRange? { get set } var currentBeginningOfDocument: UITextPosition? { get } var currentKeyboardAppearance: UIKeyboardAppearance { get set } var contentInset: UIEdgeInsets { get set } var autocorrection: UITextAutocorrectionType {get set} var autocapitalization: UITextAutocapitalizationType {get set} func configureInputView(newInputView: UIView) func changeReturnKeyType(with newReturnKeyType: UIReturnKeyType) func currentPosition(from: UITextPosition, offset: Int) -> UITextPosition? func changeClearButtonMode(with newClearButtonMode: UITextField.ViewMode) var keyboardType: UIKeyboardType { get set } // default is UIKeyboardTypeDefault var enablesReturnKeyAutomatically: Bool { get set } // default is NO (when YES, will automatically disable return key when text widget has zero-length contents, and will automatically enable when text widget has non-zero-length contents) var isSecureTextEntry: Bool { get set } // default is NO var isUserInteractionEnabled: Bool { get set } func updateData(_ data: Any?); } public extension TextInput where Self: UIView { var view: UIView { return self } } public protocol TextInputDelegate: class { func textInputDidBeginEditing(textInput: TextInput) func textInputDidEndEditing(textInput: TextInput) func textInputDidChange(textInput: TextInput) func textInput(textInput: TextInput, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool func textInputShouldBeginEditing(textInput: TextInput) -> Bool func textInputShouldEndEditing(textInput: TextInput) -> Bool func textInputShouldReturn(textInput: TextInput) -> Bool } public protocol TextInputError { func configureErrorState(with message: String?) func removeErrorHintMessage() } public extension CATextLayer { /// Describes how individual lines of text are aligned within the layer. /// /// - natural: Natural alignment. /// - left: Left alignment. /// - right: Right alignment. /// - center: Center alignment. /// - justified: Justified alignment. enum Alignment { case natural case left case right case center case justified } } fileprivate extension Dictionary { mutating func merge(dict: [Key: Value]) -> Dictionary { for (key, value) in dict { self[key] = value } return self } }
agpl-3.0
ed71d23db47f7ed4dc32e67b9de67c32
34.566125
241
0.65699
5.551974
false
false
false
false
BlueBiteLLC/Eddystone
Example/Eddystone/ExampleViewController.swift
2
2749
// // ExampleViewController.swift // Eddystone // // Created by Tanner Nelson on 07/24/2015. // Copyright (c) 2015 Tanner Nelson. All rights reserved. // import UIKit import Eddystone class ExampleViewController: UIViewController { //MARK: Interface @IBOutlet weak var mainTableView: UITableView! //MARK: Properties var urls = Eddystone.Scanner.nearbyUrls var previousUrls: [Eddystone.Url] = [] //MARK: Lifecycle override func viewDidLoad() { super.viewDidLoad() Eddystone.logging = true Eddystone.Scanner.start(self) self.mainTableView.rowHeight = UITableViewAutomaticDimension self.mainTableView.estimatedRowHeight = 100 } } extension ExampleViewController: Eddystone.ScannerDelegate { func eddystoneNearbyDidChange() { self.previousUrls = self.urls self.urls = Eddystone.Scanner.nearbyUrls self.mainTableView.switchDataSourceFrom(self.previousUrls, to: self.urls, withAnimation: .top) } } extension ExampleViewController: UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.urls.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "ExampleTableViewCell") as! ExampleTableViewCell let url = self.urls[indexPath.row] cell.mainLabel.text = url.url.absoluteString if let battery = url.battery, let temp = url.temperature, let advCount = url.advertisementCount, let onTime = url.onTime { cell.detailLabel.text = "Battery: \(battery)% \nTemp: \(temp)˚C \nPackets Sent: \(advCount) \nUptime: \(onTime.readable)" } else { cell.detailLabel.text = "No telemetry data" } switch url.signalStrength { case .excellent: cell.signalStrengthView.signal = .excellent case .veryGood: cell.signalStrengthView.signal = .veryGood case .good: cell.signalStrengthView.signal = .good case .low: cell.signalStrengthView.signal = .low case .veryLow: cell.signalStrengthView.signal = .veryLow case .noSignal: cell.signalStrengthView.signal = .noSignal default: cell.signalStrengthView.signal = .unknown } return cell } } extension ExampleViewController: UITableViewDelegate { func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: true) } }
mit
dc47b4519f44bedba6316b5d35094b75
29.197802
137
0.654294
4.88968
false
false
false
false
hardikamal/actor-platform
actor-apps/app-ios/Actor/Core/Providers/Storage/FMDBList.swift
40
14357
// // Copyright (c) 2015 Actor LLC. <https://actor.im> // import Foundation class FMDBList : NSObject, DKListStorageDisplayEx { var db :FMDatabase? = nil; var isTableChecked: Bool = false; let databasePath: String; let tableName: String; let queryCreate: String; let queryCreateIndex: String; let queryCreateFilter: String; let queryCount: String; let queryEmpty: String let queryAdd: String; let queryItem: String; let queryDelete: String; let queryDeleteAll: String; let queryForwardFirst: String; let queryForwardMore: String; let queryForwardFilterFirst: String; let queryForwardFilterMore: String; let queryBackwardFirst: String; let queryBackwardMore: String; let queryBackwardFilterFirst: String; let queryBackwardFilterMore: String; let queryCenterBackward: String; let queryCenterForward: String; init (databasePath: String, tableName: String){ self.databasePath = databasePath self.tableName = tableName; self.queryCreate = "CREATE TABLE IF NOT EXISTS " + tableName + " (" + // "\"ID\" INTEGER NOT NULL," + // 0: id "\"SORT_KEY\" INTEGER NOT NULL," + // 1: sortKey "\"QUERY\" TEXT," + // 2: query "\"BYTES\" BLOB NOT NULL," + // 3: bytes "PRIMARY KEY(\"ID\"));"; self.queryCreateIndex = "CREATE INDEX IF NOT EXISTS IDX_ID_SORT ON " + tableName + " (\"SORT_KEY\");" self.queryCreateFilter = "CREATE INDEX IF NOT EXISTS IDX_ID_QUERY_SORT ON " + tableName + " (\"QUERY\", \"SORT_KEY\");" self.queryCount = "SELECT COUNT(*) FROM " + tableName + ";"; self.queryEmpty = "EXISTS (SELECT * FROM " + tableName + ");" self.queryAdd = "REPLACE INTO " + tableName + " (\"ID\",\"QUERY\",\"SORT_KEY\",\"BYTES\") VALUES (?,?,?,?)"; self.queryItem = "SELECT \"ID\",\"QUERY\",\"SORT_KEY\",\"BYTES\" FROM " + tableName + " WHERE \"ID\" = ?;"; self.queryDeleteAll = "DELETE FROM " + tableName + ";"; self.queryDelete = "DELETE FROM " + tableName + " WHERE \"ID\"= ?;"; self.queryForwardFirst = "SELECT \"ID\", \"QUERY\",\"SORT_KEY\", \"BYTES\" FROM " + tableName + " ORDER BY SORT_KEY DESC LIMIT ?"; self.queryForwardMore = "SELECT \"ID\", \"QUERY\",\"SORT_KEY\", \"BYTES\" FROM " + tableName + " WHERE \"SORT_KEY\" < ? ORDER BY SORT_KEY DESC LIMIT ?"; self.queryBackwardFirst = "SELECT \"ID\", \"QUERY\",\"SORT_KEY\", \"BYTES\" FROM " + tableName + " ORDER BY SORT_KEY ASC LIMIT ?"; self.queryBackwardMore = "SELECT \"ID\", \"QUERY\",\"SORT_KEY\", \"BYTES\" FROM " + tableName + " WHERE \"SORT_KEY\" > ? ORDER BY SORT_KEY ASC LIMIT ?"; self.queryCenterForward = queryForwardMore self.queryCenterBackward = "SELECT \"ID\", \"QUERY\",\"SORT_KEY\", \"BYTES\" FROM " + tableName + " WHERE \"SORT_KEY\" >= ? ORDER BY SORT_KEY ASC LIMIT ?"; self.queryForwardFilterFirst = "SELECT \"ID\", \"QUERY\",\"SORT_KEY\", \"BYTES\" FROM " + tableName + " WHERE \"QUERY\" LIKE ? OR \"QUERY\" LIKE ? ORDER BY SORT_KEY DESC LIMIT ?"; self.queryForwardFilterMore = "SELECT \"ID\", \"QUERY\",\"SORT_KEY\", \"BYTES\" FROM " + tableName + " WHERE (\"QUERY\" LIKE ? OR \"QUERY\" LIKE ?) AND \"SORT_KEY\" < ? ORDER BY SORT_KEY DESC LIMIT ?"; self.queryBackwardFilterFirst = "SELECT \"ID\", \"QUERY\",\"SORT_KEY\", \"BYTES\" FROM " + tableName + " WHERE \"QUERY\" LIKE ? OR \"QUERY\" LIKE ? ORDER BY SORT_KEY ASC LIMIT ?"; self.queryBackwardFilterMore = "SELECT \"ID\", \"QUERY\",\"SORT_KEY\", \"BYTES\" FROM " + tableName + " WHERE (\"QUERY\" LIKE ? OR \"QUERY\" LIKE ?) AND \"SORT_KEY\" > ? ORDER BY SORT_KEY ASC LIMIT ?"; } func checkTable() { if (isTableChecked) { return } isTableChecked = true; self.db = FMDatabase(path: databasePath) self.db!.open() if (!db!.tableExists(tableName)) { db!.executeUpdate(queryCreate) db!.executeUpdate(queryCreateIndex) db!.executeUpdate(queryCreateFilter) } } func updateOrAddWithValue(valueContainer: DKListEngineRecord!) { checkTable(); var start = NSDate() // db!.beginTransaction() db!.executeUpdate(queryAdd, withArgumentsInArray: [valueContainer.getKey().toNSNumber(), valueContainer.dbQuery(), valueContainer.getOrder().toNSNumber(), valueContainer.getData().toNSData()]) // db!.commit() log("updateOrAddWithValue \(tableName): \(valueContainer.getData().length()) in \(Int((NSDate().timeIntervalSinceDate(start)*1000)))") } func updateOrAddWithList(items: JavaUtilList!) { checkTable(); db!.beginTransaction() for i in 0..<items.size() { let record = items.getWithInt(i) as! DKListEngineRecord; db!.executeUpdate(queryAdd, record.getKey().toNSNumber(), record.dbQuery(), record.getOrder().toNSNumber(), record.getData().toNSData()) } db!.commit() } func deleteWithKey(key: jlong) { checkTable(); db!.beginTransaction() db!.executeUpdate(queryDelete, key.toNSNumber()); db!.commit() } func deleteWithKeys(keys: IOSLongArray!) { checkTable(); db!.beginTransaction() for i in 0..<keys.length() { var k = keys.longAtIndex(UInt(i)); db!.executeUpdate(queryDelete, k.toNSNumber()); } db!.commit() } func getCount() -> jint { checkTable(); var result = db!.executeQuery(queryCount) if (result == nil) { return 0; } if (result!.next()) { var res = jint(result!.intForColumnIndex(0)) result?.close() return res } else { result?.close() } return 0; } func isEmpty() -> Bool { checkTable(); var result = db!.executeQuery(queryEmpty) if (result == nil) { return false; } if (result!.next()) { var res = result!.intForColumnIndex(0) result?.close() return res > 0 } else { result?.close() } return false; } func clear() { checkTable(); db!.beginTransaction() db!.executeUpdate(queryDeleteAll); db!.commit() } func loadItemWithKey(key: jlong) -> DKListEngineRecord! { checkTable(); var result = db!.executeQuery(queryItem, key.toNSNumber()); if (result == nil) { return nil } if (result!.next()) { var query: AnyObject! = result!.objectForColumnName("QUERY"); if (query is NSNull){ query = nil } var res = DKListEngineRecord(key: jlong(result!.longLongIntForColumn("ID")), withOrder: jlong(result!.longLongIntForColumn("SORT_KEY")), withQuery: query as! String?, withData: result!.dataForColumn("BYTES").toJavaBytes()) result?.close() return res; } else { result?.close() return nil } } func loadForwardWithSortKey(sortingKey: JavaLangLong!, withLimit limit: jint) -> JavaUtilList! { var startTime = NSDate().timeIntervalSinceReferenceDate checkTable(); var result : FMResultSet? = nil; if (sortingKey == nil) { result = db!.executeQuery(queryForwardFirst, limit.toNSNumber()); } else { result = db!.executeQuery(queryForwardMore, sortingKey!.toNSNumber(), limit.toNSNumber()); } if (result == nil) { NSLog(db!.lastErrorMessage()) return nil } var endTime1 = NSDate().timeIntervalSinceReferenceDate // println("Forward query1 \(tableName): \((endTime1 - startTime).time)") startTime = NSDate().timeIntervalSinceReferenceDate var res: JavaUtilArrayList = JavaUtilArrayList(); var queryIndex = result!.columnIndexForName("QUERY") var idIndex = result!.columnIndexForName("ID") var sortKeyIndex = result!.columnIndexForName("SORT_KEY") var bytesIndex = result!.columnIndexForName("BYTES") var dataSize = 0 var rowCount = 0 while(result!.next()) { var key = jlong(result!.longLongIntForColumnIndex(idIndex)) var order = jlong(result!.longLongIntForColumnIndex(sortKeyIndex)) var query: AnyObject! = result!.objectForColumnIndex(queryIndex) if (query is NSNull) { query = nil } var data = result!.dataForColumnIndex(bytesIndex).toJavaBytes() dataSize += Int(data.length()) rowCount++ var record = DKListEngineRecord(key: key, withOrder: order, withQuery: query as! String?, withData: data) res.addWithId(record) } result!.close() var endTime2 = NSDate().timeIntervalSinceReferenceDate // println("Forward query2 \(tableName): \((endTime2 - startTime).time), size = \(dataSize), rows = \(rowCount)") return res; } func loadForwardWithQuery(query: String!, withSortKey sortingKey: JavaLangLong!, withLimit limit: jint) -> JavaUtilList! { checkTable(); var result : FMResultSet? = nil; if (sortingKey == nil) { result = db!.executeQuery(queryForwardFilterFirst, query + "%", "% " + query + "%", limit.toNSNumber()); } else { result = db!.executeQuery(queryForwardFilterMore, query + "%", "% " + query + "%", sortingKey!.toNSNumber(), limit.toNSNumber()); } if (result == nil) { NSLog(db!.lastErrorMessage()) return nil } var res: JavaUtilArrayList = JavaUtilArrayList(); while(result!.next()) { var query: AnyObject! = result!.objectForColumnName("QUERY"); if (query is NSNull) { query = nil } var record = DKListEngineRecord(key: jlong(result!.longLongIntForColumn("ID")), withOrder: jlong(result!.longLongIntForColumn("SORT_KEY")), withQuery: query as! String?, withData: result!.dataForColumn("BYTES").toJavaBytes()) res.addWithId(record) } result!.close() return res; } func loadBackwardWithSortKey(sortingKey: JavaLangLong!, withLimit limit: jint) -> JavaUtilList! { checkTable(); var result : FMResultSet? = nil; if (sortingKey == nil) { result = db!.executeQuery(queryBackwardFirst, limit.toNSNumber()); } else { result = db!.executeQuery(queryBackwardMore, sortingKey!.toNSNumber(), limit.toNSNumber()); } if (result == nil) { NSLog(db!.lastErrorMessage()) return nil } var res: JavaUtilArrayList = JavaUtilArrayList(); while(result!.next()) { var query: AnyObject! = result!.objectForColumnName("QUERY"); if (query is NSNull) { query = nil } var record = DKListEngineRecord(key: jlong(result!.longLongIntForColumn("ID")), withOrder: jlong(result!.longLongIntForColumn("SORT_KEY")), withQuery: query as! String?, withData: result!.dataForColumn("BYTES").toJavaBytes()) res.addWithId(record) } result!.close() return res; } func loadBackwardWithQuery(query: String!, withSortKey sortingKey: JavaLangLong!, withLimit limit: jint) -> JavaUtilList! { checkTable(); var result : FMResultSet? = nil; if (sortingKey == nil) { result = db!.executeQuery(queryBackwardFilterFirst, query + "%", "% " + query + "%", limit.toNSNumber()); } else { result = db!.executeQuery(queryBackwardFilterMore, query + "%", "% " + query + "%", sortingKey!.toNSNumber(), limit.toNSNumber()); } if (result == nil) { NSLog(db!.lastErrorMessage()) return nil } var res: JavaUtilArrayList = JavaUtilArrayList(); while(result!.next()) { var query: AnyObject! = result!.objectForColumnName("QUERY"); if (query is NSNull) { query = nil } var record = DKListEngineRecord(key: jlong(result!.longLongIntForColumn("ID")), withOrder: jlong(result!.longLongIntForColumn("SORT_KEY")), withQuery: query as! String?, withData: result!.dataForColumn("BYTES").toJavaBytes()) res.addWithId(record) } result!.close() return res; } func loadCenterWithSortKey(centerSortKey: JavaLangLong!, withLimit limit: jint) -> JavaUtilList! { checkTable(); var res: JavaUtilArrayList = JavaUtilArrayList(); res.addAllWithJavaUtilCollection(loadSlise(db!.executeQuery(queryCenterBackward, centerSortKey.toNSNumber(), limit.toNSNumber()))) res.addAllWithJavaUtilCollection(loadSlise(db!.executeQuery(queryCenterForward, centerSortKey.toNSNumber(), limit.toNSNumber()))) return res } func loadSlise(result: FMResultSet?) -> JavaUtilList! { if (result == nil) { NSLog(db!.lastErrorMessage()) return nil } var res: JavaUtilArrayList = JavaUtilArrayList(); while(result!.next()) { var query: AnyObject! = result!.objectForColumnName("QUERY"); if (query is NSNull) { query = nil } var record = DKListEngineRecord(key: jlong(result!.longLongIntForColumn("ID")), withOrder: jlong(result!.longLongIntForColumn("SORT_KEY")), withQuery: query as! String?, withData: result!.dataForColumn("BYTES").toJavaBytes()) res.addWithId(record) } result!.close() return res; } }
mit
54a50287434db2d2e6f46856f4d59430
38.229508
237
0.568642
4.876698
false
false
false
false
BarTabs/bartabs
ios-application/Bar Tabs/MenuItemViewController.swift
1
4919
// // typeViewController.swift // Bar Tabs // // Created by Dexstrum on 3/2/17. // Copyright © 2017 muhlenberg. All rights reserved. /* This view controller gets all of the items inside the subcategory (i.e. Sam Adams) and displays them in a table view. */ import UIKit import Alamofire import SwiftyJSON var _type: String? class MenuItemViewController: UIViewController, UITableViewDataSource, UITableViewDelegate { var menu : JSON? var type: String { return _type ?? "" } var effect: UIVisualEffect! @IBOutlet var tableView: UITableView! override func viewDidLoad() { super.viewDidLoad() self.navigationItem.title = type self.automaticallyAdjustsScrollViewInsets = false tableView.delegate = self tableView.dataSource = self fetchData() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) self.navigationController?.navigationBar.titleTextAttributes = [NSForegroundColorAttributeName:UIColor.white] } override func viewWillDisappear(_ animated: Bool) { self.navigationController?.navigationBar.titleTextAttributes = [NSForegroundColorAttributeName:UIColor.black] self.navigationController?.navigationBar.isHidden = false } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "orderSegue" { let destSeg = segue.destination as! OrderViewController destSeg.item = sender as? JSON } else if segue.identifier == "popUpSegue" { let destSeg = segue.destination as! popUpViewController destSeg.item = sender as? JSON } } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { let count = (self.menu?["menuItems"].count) ?? 0 return count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! MenuItemTableViewCell if (self.menu != nil) { let jsonVar : JSON = self.menu! let name = jsonVar["menuItems"][indexPath.row]["name"].stringValue let description = jsonVar["menuitems"][indexPath.row]["description"].stringValue print(description) let price = jsonVar["menuItems"][indexPath.row]["price"].doubleValue cell.title.text = name cell.subtitle.text = description cell.price.text = String(format:"$%.02f", price) } return cell } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let jsonVar : JSON = self.menu! let item = jsonVar["menuItems"][indexPath.row] performSegue(withIdentifier: "orderSegue", sender: item) } func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool { return true } func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) { if (editingStyle == UITableViewCellEditingStyle.delete) { // showActivityIndicatory(uiView: self.view) let jsonVar : JSON = self.menu! let objectID = jsonVar["menuItems"][indexPath.row]["objectID"].int64Value deleteRecord(objectID: objectID) } } func tableView(_ tableView: UITableView, accessoryButtonTappedForRowWith indexPath: IndexPath) { let jsonVar : JSON = self.menu! let item = jsonVar["menuItems"][indexPath.row] performSegue(withIdentifier: "popUpSegue", sender: item) } func fetchData() { let service = "menu/getmenu" let parameters: Parameters = [ "barID" : 4, "category" : _category ?? "-1" , "type" : type ] let dataService = DataService(view: self) dataService.fetchData(service: service, parameters: parameters, completion: {(response: JSON) -> Void in self.menu = response self.tableView.reloadData() }) } func deleteRecord(objectID: Int64) { let service = "menu/deletemenuitem" let parameters: Parameters = [ "objectID" : objectID ] let dataService = DataService(view: self) dataService.post(service: service, parameters: parameters, completion: {(response: JSON) -> Void in self.fetchData() }) } }
gpl-3.0
764c5ac79a5c1f5cae5a7096bce0afdc
32.455782
127
0.618951
5.171399
false
false
false
false
devgabrielcoman/woodhouse
Pod/Classes/Services/DataService.swift
1
7520
// // ServiceProtocol.swift // Pods // // Created by Gabriel Coman on 23/02/2016. // // import UIKit import Dollar import Alamofire import IDZSwiftCommonCrypto /** * Auth Type enum */ enum AuthMethod { case NONE case SIMPLE case OAUTH } /** * Protocol for Authentication portion of each service */ protocol AuthProtocol { func method() -> AuthMethod func query() -> [String:AnyObject]? func header() -> [String:AnyObject]? func body() -> [String:AnyObject]? } /** * Normal function that each API service must respect */ protocol ServiceProtocol { func apiurl() -> String func method() -> String func query() -> [String:AnyObject]? func header() -> [String:AnyObject]? func body() -> [String:AnyObject]? func process(JSON: AnyObject) -> AnyObject } /** * Class that implements the ServiceProtocol */ class DataService: NSObject { /** * delegate variable for the Data Service class */ public var serviceDelegate: ServiceProtocol? = nil public var authDelgate: AuthProtocol? = nil /** * override init */ override init() { super.init() } /** The main public function of the Data Service */ func execute(callback: (AnyObject) -> Void) { guard let serviceDelegate = serviceDelegate else { return } guard let authDelgate = authDelgate else { return } // 1. the three vars for the request var url = serviceDelegate.apiurl() var query: [String:AnyObject] = [:] var header: [String:AnyObject] = [:] var body: [String:AnyObject] = [:] var authQuery: [String:AnyObject] = [:] var authHeader:[String:AnyObject] = [:] var authBody:[String:AnyObject] = [:] // 2. get additional data if let q = serviceDelegate.query() { query = q } if let h = serviceDelegate.header() { header = h } if let b = serviceDelegate.body() { body = b } // 3. get auth data if let q = authDelgate.query() { authQuery = q } if let h = authDelgate.header() { authHeader = h } if let b = authDelgate.body() { authBody = b } // 4. sum data if (authDelgate.method() == .SIMPLE) { sumParameters(into: &query, from: authQuery) } else if (authDelgate.method() == .OAUTH){ sumParametersOAuth(into: &query, auth: authQuery, url: url) } sumParameters(into: &header, from: authHeader) sumParameters(into: &body, from: authBody) // 5. form the request var finalUrl = url + flattenQuery(query) let finalBody = serializeBody(body) let URL = NSURL(string: finalUrl)! let req = NSMutableURLRequest(URL: URL) req.HTTPMethod = serviceDelegate.method() req.HTTPBody = finalBody for key in header.keys { if let value = header[key]! as? String { req.setValue(value, forHTTPHeaderField: key) } } // 6. start the request Alamofire.request(req).responseJSON { response in switch response.result { case .Success(let JSON): let result = serviceDelegate.process(JSON) callback(result) case .Failure(let error): print("Request failed with error: \(error)") } } } /** This function flattens out a GET query - parameter query: a dictionary containing the Query elements - returns: a optional query string in the form name1=param1&name2=param2 ... */ private func flattenQuery(query:[String:AnyObject]) -> String { var queryArray:[String] = [] for key in query.keys { if let value = query[key] { queryArray.append("\(key)=\(value)") } } if queryArray.count >= 1 { return "?" + queryArray.joinWithSeparator("&") } return "" } /** Function that serializes a set of POST parameters - parameter parameters: a dictionary containing all POST parameters - returns: an optional NSData value */ private func serializeBody(body:[String:AnyObject]) -> NSData? { if body.count == 0 { return nil } var data: NSData do { data = try NSJSONSerialization.dataWithJSONObject(body, options: NSJSONWritingOptions.PrettyPrinted) } catch { return nil } return data } /** Adds to a referenced "into" dictionary the keys from another "from" dictionary - parameter i: the reference "into" dictionary - parameter f: the "from" dictionary */ private func sumParameters(inout into i: [String:AnyObject], from f: [String:AnyObject]){ for key in f.keys { i[key] = f[key] } } /** Adds OAuth 1.0a type parameters to the query parameters already existing - parameter query: a reference to the existing query params that need to be ammended - parameter auth: auth parameters - parameter url: the base url (needed for the OAuth 1.0a algorithm) */ private func sumParametersOAuth(inout into query: [String:AnyObject], auth: [String:AnyObject], url: String) { // form variables let oauthUrl = url let method = serviceDelegate!.method() let consumerKey = auth["oauth_consumer_key"] as! String let token = auth["oauth_token"] as! String let consumerSecret = auth["oauth_consumer_secret"] as! String let tokenSecret = auth["oauth_token_secret"] as! String // prepare data query["oauth_signature_method"] = "HMAC-SHA1" query["oauth_version"] = "1.0" query["oauth_consumer_key"] = consumerKey query["oauth_token"] = token query["oauth_nonce"] = String.createUUID(6) query["oauth_timestamp"] = "\((NSInteger)(NSDate().timeIntervalSince1970))" // do the magick! let sortedKeysAndValues = (query as? [String:String])!.sort { $0.0 < $1.0 } var encoded: [String] = [] for val:(String, String) in sortedKeysAndValues { encoded.append("\(val.0.percentEscape())=\(val.1.percentEscape())") } let parameterString = encoded.joinWithSeparator("&") let signatureBaseString = "\(method)&\(oauthUrl.percentEscape())&\(parameterString.percentEscape())" let signingKey = "\(consumerSecret.percentEscape())&\(tokenSecret.percentEscape())" // new HMAC let sha1DigestArr = HMAC(algorithm:.SHA1, key:signingKey).update(signatureBaseString)?.final() var sha1DigestStr = "" for hma in sha1DigestArr! { let str = NSString(format: "%02X", hma) sha1DigestStr += str as String } let sha1Digest = sha1DigestStr.dataFromHexadecimalString() let base64Encoded = sha1Digest!.base64EncodedDataWithOptions(NSDataBase64EncodingOptions.Encoding64CharacterLineLength) let signature = (NSString(data: base64Encoded, encoding: NSUTF8StringEncoding) as! String) // add the signature to the dictionary query["oauth_signature"] = signature } }
gpl-3.0
7c939a77e69ba84c15109da5a26ba19c
30.864407
127
0.582846
4.574209
false
false
false
false
wangyuanou/Coastline
Coastline/Structure/String+Path.swift
1
3070
// // String+Path.swift // Coastline // // Created by 王渊鸥 on 2016/9/24. // Copyright © 2016年 王渊鸥. All rights reserved. // import Foundation public extension String { // Home路径 public static var homePath: String { get { return NSHomeDirectory() } } // 文档路径 public static var documentsPath: String { get { return homePath + "/Documents" } } // 库路径 public static var libraryPath: String { get { return homePath + "/Library" } } // Bundle路径 public static var bundlePath: String { get { return Bundle().bundlePath } } // 寻找某个项目下的子项目 public func pathsIn() -> [String] { let filePath = URL(fileURLWithPath: self) if let itor = FileManager.default.enumerator(at: filePath, includingPropertiesForKeys: nil, options: [.skipsHiddenFiles, .skipsSubdirectoryDescendants], errorHandler: nil) { return itor.allObjects.map{ ($0 as! URL).relativePath } } return [] } // 寻找某个项目下递归寻找的所有子项目 public func pathsDeepIn() -> [String] { let filePath = URL(fileURLWithPath: self) if let itor = FileManager.default.enumerator(at: filePath, includingPropertiesForKeys: nil, options: [.skipsHiddenFiles], errorHandler: nil) { return itor.allObjects.map{ ($0 as! URL).relativePath } } return [] } // 寻找某个项目下所有的文件 public func filesIn() -> [String] { return pathsIn().filter{ $0.isFile == true } } // 寻找某个项目下所有的目录 public func dirsIn() -> [String] { return pathsIn().filter{ $0.isDir == true } } // 递归寻找某个项目下所有的文件 public func filesDeepIn() -> [String] { return pathsDeepIn().filter{ $0.isFile == true } } // 递归寻找某个项目下所有的目录 public func dirsDeepIn() -> [String] { return pathsDeepIn().filter{ $0.isDir == true } } // 判断此项目是否为文件 public var isFile: Bool? { get { if let attr = try? FileManager.default.attributesOfItem(atPath: self) { if let type:String = attr.val(FileAttributeKey.type.rawValue) { return type == FileAttributeType.typeRegular.rawValue } } return nil } } // 判断此项目是否为目录 public var isDir: Bool? { get { if let attr = try? FileManager.default.attributesOfItem(atPath: self) { if let type:String = attr.val(FileAttributeKey.type.rawValue) { return type == FileAttributeType.typeDirectory.rawValue } } return nil } } // 创建目录 public func createDir() -> Bool { return ((try? FileManager.default.createDirectory(atPath: self, withIntermediateDirectories: true, attributes: nil)) != nil) } // 删除项目 public func removePath() -> Bool { return ((try? FileManager.default.removeItem(atPath: self)) != nil) } }
mit
2a774f7cb0c0d88f7a694cb0b39f4b9b
24.844037
126
0.611644
3.547859
false
false
false
false
crazypoo/PTools
Pods/CryptoSwift/Sources/CryptoSwift/SHA2.swift
2
13168
// // CryptoSwift // // Copyright (C) 2014-2022 Marcin Krzyżanowski <[email protected]> // This software is provided 'as-is', without any express or implied warranty. // // In no event will the authors be held liable for any damages arising from the use of this software. // // Permission is granted to anyone to use this software for any purpose,including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: // // - The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation is required. // - Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. // - This notice may not be removed or altered from any source or binary distribution. // // TODO: generic for process32/64 (UInt32/UInt64) // public final class SHA2: DigestType { @usableFromInline let variant: Variant @usableFromInline let size: Int @usableFromInline let blockSize: Int @usableFromInline let digestLength: Int private let k: Array<UInt64> @usableFromInline var accumulated = Array<UInt8>() @usableFromInline var processedBytesTotalCount: Int = 0 @usableFromInline var accumulatedHash32 = Array<UInt32>() @usableFromInline var accumulatedHash64 = Array<UInt64>() @frozen public enum Variant: RawRepresentable { case sha224, sha256, sha384, sha512 public var digestLength: Int { self.rawValue / 8 } public var blockSize: Int { switch self { case .sha224, .sha256: return 64 case .sha384, .sha512: return 128 } } public typealias RawValue = Int public var rawValue: RawValue { switch self { case .sha224: return 224 case .sha256: return 256 case .sha384: return 384 case .sha512: return 512 } } public init?(rawValue: RawValue) { switch rawValue { case 224: self = .sha224 case 256: self = .sha256 case 384: self = .sha384 case 512: self = .sha512 default: return nil } } @usableFromInline var h: Array<UInt64> { switch self { case .sha224: return [0xc1059ed8, 0x367cd507, 0x3070dd17, 0xf70e5939, 0xffc00b31, 0x68581511, 0x64f98fa7, 0xbefa4fa4] case .sha256: return [0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19] case .sha384: return [0xcbbb9d5dc1059ed8, 0x629a292a367cd507, 0x9159015a3070dd17, 0x152fecd8f70e5939, 0x67332667ffc00b31, 0x8eb44a8768581511, 0xdb0c2e0d64f98fa7, 0x47b5481dbefa4fa4] case .sha512: return [0x6a09e667f3bcc908, 0xbb67ae8584caa73b, 0x3c6ef372fe94f82b, 0xa54ff53a5f1d36f1, 0x510e527fade682d1, 0x9b05688c2b3e6c1f, 0x1f83d9abfb41bd6b, 0x5be0cd19137e2179] } } @usableFromInline var finalLength: Int { switch self { case .sha224: return 7 case .sha384: return 6 default: return Int.max } } } public init(variant: SHA2.Variant) { self.variant = variant switch self.variant { case .sha224, .sha256: self.accumulatedHash32 = variant.h.map { UInt32($0) } // FIXME: UInt64 for process64 self.blockSize = variant.blockSize self.size = variant.rawValue self.digestLength = variant.digestLength self.k = [ 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2 ] case .sha384, .sha512: self.accumulatedHash64 = variant.h self.blockSize = variant.blockSize self.size = variant.rawValue self.digestLength = variant.digestLength self.k = [ 0x428a2f98d728ae22, 0x7137449123ef65cd, 0xb5c0fbcfec4d3b2f, 0xe9b5dba58189dbbc, 0x3956c25bf348b538, 0x59f111f1b605d019, 0x923f82a4af194f9b, 0xab1c5ed5da6d8118, 0xd807aa98a3030242, 0x12835b0145706fbe, 0x243185be4ee4b28c, 0x550c7dc3d5ffb4e2, 0x72be5d74f27b896f, 0x80deb1fe3b1696b1, 0x9bdc06a725c71235, 0xc19bf174cf692694, 0xe49b69c19ef14ad2, 0xefbe4786384f25e3, 0x0fc19dc68b8cd5b5, 0x240ca1cc77ac9c65, 0x2de92c6f592b0275, 0x4a7484aa6ea6e483, 0x5cb0a9dcbd41fbd4, 0x76f988da831153b5, 0x983e5152ee66dfab, 0xa831c66d2db43210, 0xb00327c898fb213f, 0xbf597fc7beef0ee4, 0xc6e00bf33da88fc2, 0xd5a79147930aa725, 0x06ca6351e003826f, 0x142929670a0e6e70, 0x27b70a8546d22ffc, 0x2e1b21385c26c926, 0x4d2c6dfc5ac42aed, 0x53380d139d95b3df, 0x650a73548baf63de, 0x766a0abb3c77b2a8, 0x81c2c92e47edaee6, 0x92722c851482353b, 0xa2bfe8a14cf10364, 0xa81a664bbc423001, 0xc24b8b70d0f89791, 0xc76c51a30654be30, 0xd192e819d6ef5218, 0xd69906245565a910, 0xf40e35855771202a, 0x106aa07032bbd1b8, 0x19a4c116b8d2d0c8, 0x1e376c085141ab53, 0x2748774cdf8eeb99, 0x34b0bcb5e19b48a8, 0x391c0cb3c5c95a63, 0x4ed8aa4ae3418acb, 0x5b9cca4f7763e373, 0x682e6ff3d6b2b8a3, 0x748f82ee5defb2fc, 0x78a5636f43172f60, 0x84c87814a1f0ab72, 0x8cc702081a6439ec, 0x90befffa23631e28, 0xa4506cebde82bde9, 0xbef9a3f7b2c67915, 0xc67178f2e372532b, 0xca273eceea26619c, 0xd186b8c721c0c207, 0xeada7dd6cde0eb1e, 0xf57d4f7fee6ed178, 0x06f067aa72176fba, 0x0a637dc5a2c898a6, 0x113f9804bef90dae, 0x1b710b35131c471b, 0x28db77f523047d84, 0x32caab7b40c72493, 0x3c9ebe0a15c9bebc, 0x431d67c49c100d4c, 0x4cc5d4becb3e42b6, 0x597f299cfc657e2a, 0x5fcb6fab3ad6faec, 0x6c44198c4a475817 ] } } @inlinable public func calculate(for bytes: Array<UInt8>) -> Array<UInt8> { do { return try update(withBytes: bytes.slice, isLast: true) } catch { return [] } } @usableFromInline func process64(block chunk: ArraySlice<UInt8>, currentHash hh: inout Array<UInt64>) { // break chunk into sixteen 64-bit words M[j], 0 ≤ j ≤ 15, big-endian // Extend the sixteen 64-bit words into eighty 64-bit words: let M = UnsafeMutablePointer<UInt64>.allocate(capacity: self.k.count) M.initialize(repeating: 0, count: self.k.count) defer { M.deinitialize(count: self.k.count) M.deallocate() } for x in 0..<self.k.count { switch x { case 0...15: let start = chunk.startIndex.advanced(by: x * 8) // * MemoryLayout<UInt64>.size M[x] = UInt64(bytes: chunk, fromIndex: start) default: let s0 = rotateRight(M[x - 15], by: 1) ^ rotateRight(M[x - 15], by: 8) ^ (M[x - 15] >> 7) let s1 = rotateRight(M[x - 2], by: 19) ^ rotateRight(M[x - 2], by: 61) ^ (M[x - 2] >> 6) M[x] = M[x - 16] &+ s0 &+ M[x - 7] &+ s1 } } var A = hh[0] var B = hh[1] var C = hh[2] var D = hh[3] var E = hh[4] var F = hh[5] var G = hh[6] var H = hh[7] // Main loop for j in 0..<self.k.count { let s0 = rotateRight(A, by: 28) ^ rotateRight(A, by: 34) ^ rotateRight(A, by: 39) let maj = (A & B) ^ (A & C) ^ (B & C) let t2 = s0 &+ maj let s1 = rotateRight(E, by: 14) ^ rotateRight(E, by: 18) ^ rotateRight(E, by: 41) let ch = (E & F) ^ ((~E) & G) let t1 = H &+ s1 &+ ch &+ self.k[j] &+ UInt64(M[j]) H = G G = F F = E E = D &+ t1 D = C C = B B = A A = t1 &+ t2 } hh[0] = (hh[0] &+ A) hh[1] = (hh[1] &+ B) hh[2] = (hh[2] &+ C) hh[3] = (hh[3] &+ D) hh[4] = (hh[4] &+ E) hh[5] = (hh[5] &+ F) hh[6] = (hh[6] &+ G) hh[7] = (hh[7] &+ H) } // mutating currentHash in place is way faster than returning new result @usableFromInline func process32(block chunk: ArraySlice<UInt8>, currentHash hh: inout Array<UInt32>) { // break chunk into sixteen 32-bit words M[j], 0 ≤ j ≤ 15, big-endian // Extend the sixteen 32-bit words into sixty-four 32-bit words: let M = UnsafeMutablePointer<UInt32>.allocate(capacity: self.k.count) M.initialize(repeating: 0, count: self.k.count) defer { M.deinitialize(count: self.k.count) M.deallocate() } for x in 0..<self.k.count { switch x { case 0...15: let start = chunk.startIndex.advanced(by: x * 4) // * MemoryLayout<UInt32>.size M[x] = UInt32(bytes: chunk, fromIndex: start) default: let s0 = rotateRight(M[x - 15], by: 7) ^ rotateRight(M[x - 15], by: 18) ^ (M[x - 15] >> 3) let s1 = rotateRight(M[x - 2], by: 17) ^ rotateRight(M[x - 2], by: 19) ^ (M[x - 2] >> 10) M[x] = M[x - 16] &+ s0 &+ M[x - 7] &+ s1 } } var A = hh[0] var B = hh[1] var C = hh[2] var D = hh[3] var E = hh[4] var F = hh[5] var G = hh[6] var H = hh[7] // Main loop for j in 0..<self.k.count { let s0 = rotateRight(A, by: 2) ^ rotateRight(A, by: 13) ^ rotateRight(A, by: 22) let maj = (A & B) ^ (A & C) ^ (B & C) let t2 = s0 &+ maj let s1 = rotateRight(E, by: 6) ^ rotateRight(E, by: 11) ^ rotateRight(E, by: 25) let ch = (E & F) ^ ((~E) & G) let t1 = H &+ s1 &+ ch &+ UInt32(self.k[j]) &+ M[j] H = G G = F F = E E = D &+ t1 D = C C = B B = A A = t1 &+ t2 } hh[0] = hh[0] &+ A hh[1] = hh[1] &+ B hh[2] = hh[2] &+ C hh[3] = hh[3] &+ D hh[4] = hh[4] &+ E hh[5] = hh[5] &+ F hh[6] = hh[6] &+ G hh[7] = hh[7] &+ H } } extension SHA2: Updatable { @inlinable public func update(withBytes bytes: ArraySlice<UInt8>, isLast: Bool = false) throws -> Array<UInt8> { self.accumulated += bytes if isLast { let lengthInBits = (processedBytesTotalCount + self.accumulated.count) * 8 let lengthBytes = lengthInBits.bytes(totalBytes: self.blockSize / 8) // A 64-bit/128-bit representation of b. blockSize fit by accident. // Step 1. Append padding bitPadding(to: &self.accumulated, blockSize: self.blockSize, allowance: self.blockSize / 8) // Step 2. Append Length a 64-bit representation of lengthInBits self.accumulated += lengthBytes } var processedBytes = 0 for chunk in self.accumulated.batched(by: self.blockSize) { if isLast || (self.accumulated.count - processedBytes) >= self.blockSize { switch self.variant { case .sha224, .sha256: self.process32(block: chunk, currentHash: &self.accumulatedHash32) case .sha384, .sha512: self.process64(block: chunk, currentHash: &self.accumulatedHash64) } processedBytes += chunk.count } } self.accumulated.removeFirst(processedBytes) self.processedBytesTotalCount += processedBytes // output current hash var result = Array<UInt8>(repeating: 0, count: variant.digestLength) switch self.variant { case .sha224, .sha256: var pos = 0 for idx in 0..<self.accumulatedHash32.count where idx < self.variant.finalLength { let h = accumulatedHash32[idx] result[pos + 0] = UInt8((h >> 24) & 0xff) result[pos + 1] = UInt8((h >> 16) & 0xff) result[pos + 2] = UInt8((h >> 8) & 0xff) result[pos + 3] = UInt8(h & 0xff) pos += 4 } case .sha384, .sha512: var pos = 0 for idx in 0..<self.accumulatedHash64.count where idx < self.variant.finalLength { let h = accumulatedHash64[idx] result[pos + 0] = UInt8((h >> 56) & 0xff) result[pos + 1] = UInt8((h >> 48) & 0xff) result[pos + 2] = UInt8((h >> 40) & 0xff) result[pos + 3] = UInt8((h >> 32) & 0xff) result[pos + 4] = UInt8((h >> 24) & 0xff) result[pos + 5] = UInt8((h >> 16) & 0xff) result[pos + 6] = UInt8((h >> 8) & 0xff) result[pos + 7] = UInt8(h & 0xff) pos += 8 } } // reset hash value for instance if isLast { switch self.variant { case .sha224, .sha256: self.accumulatedHash32 = self.variant.h.lazy.map { UInt32($0) } // FIXME: UInt64 for process64 case .sha384, .sha512: self.accumulatedHash64 = self.variant.h } } return result } }
mit
2e60e8a6deb892887a1219a148dc1413
34.758152
217
0.620412
2.833549
false
false
false
false
HTWDD/HTWDresden-iOS
HTWDD/Components/Canteen/ViewModels/MealsViewModel.swift
1
1430
// // MealsViewModel.swift // HTWDD // // Created by Mustafa Karademir on 27.09.19. // Copyright © 2019 HTW Dresden. All rights reserved. // import Foundation import RxSwift // MARK: - Items enum Meals { case header(model: MealHeader) case meal(model: Meal) } // MARK: - VM class MealsViewModel { private let data: CanteenDetail init(data: CanteenDetail) { self.data = data } func load() -> Observable<[Meals]> { return Observable.deferred { var result: [Meals] = [] let categoriesSet = self.data.meals.reduce(into: Set<String>(), { categories, meal in categories.insert(meal.category) }) Array(categoriesSet.sorted()).forEach { category in let meals = self.data.meals.filter { $0.category == category } let mealsCount = meals.count result.append(.header(model: MealHeader(header: category, subheader: mealsCount > 1 ? R.string.localizable.canteenMealCountPlural(mealsCount) : R.string.localizable.canteenMealCount(mealsCount)))) meals.forEach { meal in result.append(.meal(model: meal)) } } return .just(result) } .observeOn(SerialDispatchQueueScheduler(qos: .background)) .catchErrorJustReturn([Meals]()) } }
gpl-2.0
062ec5bb129dd28bb9e3a05c588680ff
28.163265
212
0.578726
4.410494
false
false
false
false
devios1/Gravity
Plugins/Default.swift
1
7291
// // Default.swift // Gravity // // Created by Logan Murray on 2016-02-15. // Copyright © 2016 Logan Murray. All rights reserved. // import Foundation // do we really need/want this class? maybe rename? @available(iOS 9.0, *) extension Gravity { @objc public class Default: GravityPlugin { // private static let keywords = ["id", "zIndex", "gravity"] // add more? move? // TODO: these should ideally be blocked at the same location they are used (e.g. zIndex and gravity in Layout, id should be blocked in the kernel. var defaultValues = [GravityNode: [String: AnyObject?]]() // when should we purge this? // deprecated // public override var recognizedAttributes: [String]? { // get { // return nil // all attributes // } // } static var swizzleToken: dispatch_once_t = 0 // we should abstract this to a function in core that just swaps two selectors on a class like swizzle(UIView.self, selector1, selector2) public override class func initialize() { dispatch_once(&swizzleToken) { // method swizzling: let loadView_orig = class_getInstanceMethod(UIViewController.self, #selector(UIViewController.loadView)) let loadView_swiz = class_getInstanceMethod(UIViewController.self, #selector(UIViewController.grav_loadView)) if class_addMethod(UIViewController.self, #selector(UIViewController.loadView), method_getImplementation(loadView_swiz), method_getTypeEncoding(loadView_swiz)) { class_replaceMethod(UIViewController.self, #selector(UIViewController.grav_loadView), method_getImplementation(loadView_orig), method_getTypeEncoding(loadView_orig)); } else { method_exchangeImplementations(loadView_orig, loadView_swiz); } } } public override func instantiateView(node: GravityNode) -> UIView? { var type: AnyClass? = NSClassFromString(node.nodeName) if type == nil { // couldn't find type; try Swift style naming if let appName = NSBundle.mainBundle().objectForInfoDictionaryKey("CFBundleName") as? String { type = NSClassFromString("\(appName).\(node.nodeName)") } } if let type = type as? GravityElement.Type where type.instantiateView != nil { return type.instantiateView!(node) } else if let type = type as? UIView.Type { // var view: UIView // tryBlock { let view = type.init() view.translatesAutoresizingMaskIntoConstraints = false // do we need this? i think so // TODO: should we set clipsToBounds for views by default? // } return view // TODO: determine if the instance is an instance of UIView or UIViewController and handle the latter by embedding a view controller } else if let type = type as? UIViewController.Type { let vc = type.init() vc.gravityNode = node node.controller = vc // this might be a problem since node.view is not set at this point (dispatch_async?) // FIXME: there is a design issue here: accessing vc.view calls viewDidLoad on the vc; we should think of a way to avoid doing this until the very end, which may involve wrapping it in an extra view, or swizzling viewDidLoad return UIView() // this will be bound to the node; is a plain UIView enough? //node._view = vc.view // let container = UIView() // container.addSu } return nil } public override func selectAttribute(node: GravityNode, attribute: String, inout value: GravityNode?) -> GravityResult { value = node.attributes[attribute] // good? return .Handled } // this is really a singleton; should we provide a better way for this to be overridden? // we should turn this into processValue() public override func handleAttribute(node: GravityNode, attribute: String?, value: GravityNode?) -> GravityResult { // guard let node = value.parentNode else { // return .NotHandled // } guard let attribute = attribute else { return .NotHandled } // NSLog("KeyPath \(attribute) converted var objectValue: AnyObject? if value != nil { objectValue = value!.objectValue tryBlock { if self.defaultValues[node] == nil { self.defaultValues[node] = [String: AnyObject?]() } if self.defaultValues[node]![attribute] == nil { // only store the default value the first time (so it is deterministic) let defaultValue = node.view.valueForKeyPath(attribute) self.defaultValues[node]![attribute] = defaultValue } } } else { if let nodeIndex = defaultValues[node] { if let defaultValue = nodeIndex[attribute] { NSLog("Default value found for attribute \(attribute): \(defaultValue)") objectValue = defaultValue } } } if let objectValue = objectValue { if tryBlock({ NSLog("Setting property \(attribute) to value: \(objectValue)") node.view.setValue(objectValue, forKeyPath: attribute) }) != nil { NSLog("Warning: Key path '\(attribute)' not found on object \(node.view).") return .NotHandled } } else { return .NotHandled } return .Handled } // public override func postprocessValue(node: GravityNode, attribute: String, value: GravityNode) -> GravityResult { // // TODO: if value is a node, check property type on target and potentially convert into a view (view controller?) // // var propertyType: String? = nil // // // this is string.endsWith in swift. :| lovely. // if attribute.lowercaseString.rangeOfString("color", options:NSStringCompareOptions.BackwardsSearch)?.endIndex == attribute.endIndex { // propertyType = "UIColor" // bit of a hack because UIView.backgroundColor doesn't seem to know its property class via inspection :/ // } // // if propertyType == nil { //// NSLog("Looking up property for \(node.view.dynamicType) . \(attribute)") // // is there a better/safer way to do this reliably? // let property = class_getProperty(NSClassFromString("\(node.view.dynamicType)"), attribute) // if property != nil { // if let components = String.fromCString(property_getAttributes(property))?.componentsSeparatedByString("\"") { // if components.count >= 2 { // propertyType = components[1] //// NSLog("propertyType: \(propertyType!)") // } // } // } // } // // var convertedValue: AnyObject? = value.stringValue // // if let propertyType = propertyType { // convertedValue = value.convert(propertyType) //// if let converter = Conversion.converters[propertyType!] { //// var newOutput: AnyObject? = output //// if converter(input: input, output: &newOutput) == .Handled { //// output = newOutput! // this feels ugly //// return .Handled //// } //// } // } // //// NSLog("KeyPath \(attribute) converted // // if tryBlock({ // node.view.setValue(convertedValue, forKeyPath: attribute) // }) != nil { // NSLog("Warning: Key path '\(attribute)' not found on object \(node.view).") // } // } // public override func postprocessElement(node: GravityNode) -> GravityResult { // } } } @available(iOS 9.0, *) extension UIViewController { public func grav_loadView() { if self.gravityNode != nil { self.view = self.gravityNode?.view // TODO: make sure this works for all levels of embedded VCs } if !self.isViewLoaded() { grav_loadView() } } }
mit
1c2dfd216697c731ab99d86b8aee0bae
36.19898
228
0.676955
3.861229
false
false
false
false
woshishui1243/QRCode_Swift
QRCodeDemo/QRCodeDemo/QRCodeViewController.swift
1
678
// // QRCodeViewController.swift // QRCodeDemo // // Created by dayu on 15/7/1. // Copyright (c) 2015年 dayu. All rights reserved. // import UIKit import QRCode class QRCodeViewController: UIViewController { @IBOutlet weak var qrCodeView: UIImageView! let qrCode = QRCode() override func viewDidLoad() { super.viewDidLoad() let icon = UIImage(named: "avatar") let color = CIColor(color: UIColor.blackColor()) let backColor = CIColor(color: UIColor.whiteColor()) qrCodeView.image = qrCode.generateQRCode("http://www.baidu.com", icon: icon, iconScale: 0.2, color: color!, backColor: backColor!) } }
mit
0a5d1a11970e775a4b38f402b398aa87
23.142857
138
0.656805
4.121951
false
false
false
false
relayr/apple-sdk
Sources/common/services/API/APIProjects.swift
1
13032
import Foundation import Result import ReactiveSwift import Utils internal extension API { /// Project entity as represented on the relayr API platform. struct Project: JSONable { let identifier: String var name: String? var description: String? var oauthSecret: String? var oauthRedirectURI: String? var publisherIdentifier: String? } /// Authorization of a project to use the data of a specific user. struct AuthorizationProjectUser { let projectIdentifier: String let projectName: String let userIdentifier: String } } // HTTP APIs for project related endpoints. internal extension API { /// Request information about all projects hosted in the relayr cloud. /// /// If a project dictionary is malformed or missing properties, the project is ignored. /// - returns: Signal sending a project per event. func projects() -> SignalProducer<API.Project,API.Error> { let url = Addresses.build(withHostURL: urls.root, relativeURL: "apps") return self.sessionForRequests.requestJSON(withAbsoluteURL: url, method: .Get, expectedCodes: [200]).flatMap(.latest) { (json : [[String:Any]]) in SignalProducer<API.Project,API.Error>(json) { try? Project(fromJSON: $0) } } } /// Creates a new project on the relayr cloud for the publisher given as `publisherID`. /// /// For the creation of the project to be successful, the publisher given must be owned by the user owning this API instance. /// - parameter name: The given name of the project. /// - parameter description: A brief description of what the project does. /// - parameter publisherID: The publisher that will own the created project. /// - parameter oauthRedirectURI: The redirection address to use on OAuth authorization. /// - returns: Signal returning the created project on the value event. func createProject(withName name: String, description: String?, publisherID: String, oauthRedirectURI: String) -> SignalProducer<API.Project,API.Error> { let url = Addresses.build(withHostURL: urls.root, relativeURL: "apps") let body = API.Project(withIdentifier: "", name: name, description: description, uri: oauthRedirectURI, publisher: publisherID).jsonNoID return self.sessionForRequests.requestJSON(withAbsoluteURL: url, method: .Post, token: token, contentType: .JSON, body: body, expectedCodes: [201]).attemptMap { (json : [String:Any]) in Result { try API.Project(fromJSON: json) } } } /// Requests information about the project where the user is currently logged into. /// - returns: Signal returning the project on the value event. func currentProjectInfo() -> SignalProducer<API.Project,API.Error> { let url = Addresses.build(withHostURL: urls.root, relativeURL: "oauth2/app-info") return self.sessionForRequests.requestJSON(withAbsoluteURL: url, method: .Get, token: token, expectedCodes: [200]).attemptMap { (json : [String:Any]) in Result { try API.Project(fromJSON: json) } } } /// Requests information about the project identified by the `projectID`. /// /// There are two projectInfo calls, one that doesn't require a token, another that does (this one). /// - parameter projectID: relayr unique identifier for the given project. func projectInfo(withID projectID: String) -> SignalProducer<API.Project,API.Error> { let url = Addresses.build(withHostURL: urls.root, relativeURL: "apps/\(projectID)") return self.sessionForRequests.requestJSON(withAbsoluteURL: url, method: .Get, token: token, expectedCodes: [200]).attemptMap { (json : [String:Any]) in Result { try API.Project(fromJSON: json) } } } /// Requests extended inforamtion about the project identified by the given `projectID`. /// /// Your user's publisher needs to own the project being queried to get information successfully. /// - parameter projectID: relayr unique identifier for the given project. func projectInfoExtended(withID projectID: String) -> SignalProducer<API.Project,API.Error> { let url = Addresses.build(withHostURL: urls.root, relativeURL: "apps/\(projectID)/extended") return self.sessionForRequests.requestJSON(withAbsoluteURL: url, method: .Get, token: token, expectedCodes: [200]).attemptMap { (json : [String:Any]) in Result { try API.Project(fromJSON: json) } } } /// Updates the project with the arguments passed. /// /// If none arguments are given, no HTTP call is performed and an error is returned. /// - parameter name: Modify the project's name. /// - parameter description: Modify the project's description. /// - parameter uri: Modify the project's redirect URI. func setProjectInfo(withID projectID: String, name: String? = nil, description: String? = nil, oauthRedirectURI uri: String? = nil) -> SignalProducer<API.Project,API.Error> { let url = Addresses.build(withHostURL: urls.root, relativeURL: "apps/\(projectID)") let body = API.Project(withIdentifier: "", name: name, description: description, uri: uri).jsonNoID guard !body.isEmpty else { return SignalProducer(error: .insufficientInformation) } return self.sessionForRequests.requestJSON(withAbsoluteURL: url, method: .Patch, token: token, contentType: .JSON, body: body, expectedCodes: [200]).attemptMap { (json : [String:Any]) in Result { try API.Project(fromJSON: json) } } } /// Deletes a project own by the user's publisher. /// - parameter projectID: The project targeted to be deleted. func deleteProject(withID projectID: String) -> SignalProducer<(),API.Error> { let url = Addresses.build(withHostURL: urls.root, relativeURL: "apps/\(projectID)") return self.sessionForRequests.request(withAbsoluteURL: url, method: .Delete, token: token, expectedCodes: [204,404]).map { _ in () } } } internal extension API { /// Retrieves a list of projects owned by the given publisher. /// /// If a project is malformed, the project is ignored and not send as a value event. /// - parameter publisherID: Publisher entity being target for information. /// - returns: Signal returning a project per event. func projectsFromPublisher(withID publisherID: String) -> SignalProducer<API.Project,API.Error> { let url = Addresses.build(withHostURL: urls.root, relativeURL: "publishers/\(publisherID)/apps") return self.sessionForRequests.requestJSON(withAbsoluteURL: url, method: .Get, token: self.token, expectedCodes: [200]).flatMap(.latest) { (json: [[String:Any]]) in SignalProducer<API.Project,API.Error>(json) { try? API.Project(fromJSON: $0) } } } /// Retrieves a list of projects owned by the specified publisher with its extended information. /// - parameter publisherID: Publisher entity being target for information. /// - returns: Signal returning a project per event. func projectsExtendedFromPublisher(withID publisherID: String) -> SignalProducer<API.Project,API.Error> { let url = Addresses.build(withHostURL: urls.root, relativeURL: "publishers/\(publisherID)/apps/extended") return self.sessionForRequests.requestJSON(withAbsoluteURL: url, method: .Get, token: token, expectedCodes: [200]).flatMap(.latest) { (json: [[String:Any]]) in SignalProducer<API.Project,API.Error>(json) { try? API.Project(fromJSON: $0) } } } } internal extension API { /// An authorization request is sent for a project to use the data of a specific user. /// - parameter projectID: The project that request authorization. /// - parameter userID: The user being targeted. func authorizeProject(withID projectID: String, toUseDataFromUserWithID userID: String) -> SignalProducer<(),API.Error> { let url = Addresses.build(withHostURL: urls.root, relativeURL: "users/\(userID)/apps/\(projectID)") return self.sessionForRequests.request(withAbsoluteURL: url, method: .Post, token: token, expectedCodes: [200]).map { _ in () } } /// Retrieves a list of projects that are authorized to use the data of the specified user. /// - parameter userID: The user being targeted. func authorizedProjectsToUseDataFromUser(withID userID: String) -> SignalProducer<API.AuthorizationProjectUser,API.Error> { let url = Addresses.build(withHostURL: urls.root, relativeURL: "users/\(userID)/apps") return self.sessionForRequests.requestJSON(withAbsoluteURL: url, method: .Get, token: token, expectedCodes: [200]).flatMap(.latest) { (json: [[String:Any]]) in SignalProducer<API.AuthorizationProjectUser,API.Error>(json) { try? API.AuthorizationProjectUser(fromJSON: $0) } } } /// Retrieves the information of a specific authorization project. /// - parameter projectID: The project being targeted for information. /// - parameter userID: The user being targeted for information. func authorizedProjectInfo(withID projectID: String, usingDataFromUserWithID userID: String) -> SignalProducer<API.AuthorizationProjectUser,API.Error> { let url = Addresses.build(withHostURL: urls.root, relativeURL: "users/\(userID)/apps/\(projectID)") return self.sessionForRequests.requestJSON(withAbsoluteURL: url, method: .Get, token: token, expectedCodes: [200]).attemptMap { (json : [String:Any]) in Result { try API.AuthorizationProjectUser(fromJSON: json) } } } /// Unauthorize a proejct for using the data of a specific user. /// - parameter projectID: The project being targeted for information. /// - parameter userID: The user being targeted for information. func unauthorizeProject(withID projectID: String, fromUsingDataOfUserWithID userID: String) -> SignalProducer<(),API.Error> { let url = Addresses.build(withHostURL: urls.root, relativeURL: "users/\(userID)/apps/\(projectID)") return self.sessionForRequests.request(withAbsoluteURL: url, method: .Delete, token: token, expectedCodes: [204,404]).map { _ in () } } } extension API.Project { typealias JSONType = [String:Any] init(fromJSON json: JSONType) throws { guard let identifier = (json[Keys.identifier]) as? String else { throw API.Error.invalidResponseBody(body: json) } self.identifier = identifier self.name = json[Keys.name] as? String self.description = json[Keys.description] as? String self.oauthSecret = json[Keys.secret] as? String self.oauthRedirectURI = json[Keys.uri] as? String self.publisherIdentifier = json[Keys.publisher] as? String } var json: JSONType { var result: JSONType = [Keys.identifier : self.identifier] if let name = self.name { result[Keys.name] = name } if let description = self.description { result[Keys.description] = description } if let oauthSecret = self.oauthSecret { result[Keys.secret] = oauthSecret } if let redirectURI = self.oauthRedirectURI { result[Keys.uri] = redirectURI } if let publisher = self.publisherIdentifier { result[Keys.publisher] = publisher } return result } fileprivate var jsonNoID: JSONType { var result = self.json let _ = result.removeValue(forKey: Keys.identifier) return result } fileprivate init(withIdentifier identifier: String, name: String?=nil, description: String?=nil, secret: String?=nil, uri: String?=nil, publisher: String?=nil) { self.identifier = identifier self.name = name self.description = description self.oauthSecret = secret self.oauthRedirectURI = uri self.publisherIdentifier = publisher } private struct Keys { static let identifier = "id" static let name = "name" static let description = "description" static let secret = "clientSecret" static let uri = "redirectUri" static let publisher = "publisher" } } extension API.AuthorizationProjectUser { fileprivate typealias JSONType = [String:Any] fileprivate init(fromJSON json: JSONType) throws { guard let projectID = json[Keys.app] as? String, let projectName = json[Keys.name] as? String, let userID = json[Keys.owner] as? String else { throw API.Error.invalidResponseBody(body: json) } self.projectIdentifier = projectID self.projectName = projectName self.userIdentifier = userID } private struct Keys { static let name = "name" static let app = "app" static let owner = "owner" } }
mit
c8813662316b5ae26408866ed73ba9f6
49.123077
188
0.677563
4.470669
false
false
false
false
imobilize/Molib
Molib/Classes/Networking/AlamofireNetworkRequestService.swift
1
6057
import Foundation import Alamofire class AlamofireNetworkRequestService: NetworkRequestService { init() { } func enqueueNetworkRequest(request: NetworkRequest) -> NetworkOperation? { let alamoFireRequestOperation = AlamofireNetworkOperation(networkRequest: request) alamoFireRequestOperation.performRequest() return alamoFireRequestOperation } func enqueueNetworkUploadRequest(request: NetworkUploadRequest) -> NetworkUploadOperation? { let alamorFireUploadOperation = AlamofireNetworkUploadOperation(networkRequest: request) alamorFireUploadOperation.performRequest() return alamorFireUploadOperation } func enqueueNetworkDownloadRequest(request: NetworkDownloadRequest) -> NetworkDownloadOperation? { let alamorFireDownloadOperation = AlamofireNetworkDownloadOperation(networkRequest: request) alamorFireDownloadOperation.performRequest() return alamorFireDownloadOperation } func cancelAllOperations() { AF.cancelAllRequests() } } class AlamofireNetworkOperation: NetworkOperation { private let networkRequest: NetworkRequest private var alamoFireRequest: DataRequest? init(networkRequest: NetworkRequest) { self.networkRequest = networkRequest } func performRequest() { alamoFireRequest = AF.request(networkRequest.urlRequest) alamoFireRequest?.validate().responseData { [weak self](networkResponse) -> Void in debugPrint("Request response for URL: \(String(describing: self?.networkRequest.urlRequest.url))") self?.networkRequest.handleResponse(dataOptional: networkResponse.data, errorOptional: networkResponse.error) } } func cancel() { alamoFireRequest?.cancel() } } class AlamofireNetworkUploadOperation : NetworkUploadOperation { private let networkRequest: NetworkUploadRequest private var alamoFireRequest: UploadRequest? init(networkRequest: NetworkUploadRequest) { self.networkRequest = networkRequest } func performRequest() { alamoFireRequest = AF.upload(networkRequest.fileURL, with: networkRequest.urlRequest) alamoFireRequest?.validate().responseData { [weak self](networkResponse) -> Void in debugPrint("Download request response for URL: \(String(describing: self?.networkRequest.urlRequest.url))") self?.networkRequest.handleResponse(dataOptional: networkResponse.data, errorOptional: networkResponse.error) } } func registerProgressUpdate(progressUpdate: @escaping ProgressUpdate) { alamoFireRequest?.downloadProgress(closure: { (progress: Progress) in var downloadProgress: Float = 0 if let fileTotal = progress.fileTotalCount, let fileCompleted = progress.fileCompletedCount { downloadProgress = Float(fileTotal)/Float(fileCompleted) } progressUpdate(downloadProgress) }) } func pause() { alamoFireRequest?.suspend() } func resume() { alamoFireRequest?.resume() } func cancel() { alamoFireRequest?.cancel() } } class AlamofireNetworkDownloadOperation: NetworkDownloadOperation { private let networkRequest: NetworkDownloadRequest private var alamoFireRequest: DownloadRequest? init(networkRequest: NetworkDownloadRequest) { self.networkRequest = networkRequest } func performRequest() { alamoFireRequest = AF.download(networkRequest.urlRequest, to: { (url, response) -> (destinationURL: URL, options: DownloadRequest.Options) in return (self.networkRequest.downloadLocationURL, Alamofire.DownloadRequest.Options.removePreviousFile) }) alamoFireRequest?.validate().responseData { [weak self](networkResponse) -> Void in debugPrint("Request response for URL: \(String(describing: self?.networkRequest.urlRequest.url))") self?.networkRequest.handleResponse(dataOptional: networkResponse.value, errorOptional: networkResponse.error) } } func registerProgressUpdate(progressUpdate: @escaping ProgressUpdate) { alamoFireRequest?.downloadProgress(closure: { (progress: Progress) in var downloadProgress: Float = 0 if let fileTotal = progress.fileTotalCount, let fileCompleted = progress.fileCompletedCount { downloadProgress = Float(fileTotal)/Float(fileCompleted) } progressUpdate(downloadProgress) }) } func pause() { alamoFireRequest?.suspend() } func resume() { alamoFireRequest?.resume() } func cancel() { alamoFireRequest?.cancel() } } extension NetworkDownloadOperation { func handleResponse<T>(networkResponse: AFDataResponse<T>, completion: DataResponseCompletion) { debugPrint(networkResponse) var errorOptional: Error? = nil switch networkResponse.result { case .success: break case .failure(let error): if let response = networkResponse.response { let errorMessage = NSLocalizedString("The service is currently unable to satisfy your request. Please try again later", comment: "Bad service response text") let userInfo: [String: Any] = ["response": response, NSUnderlyingErrorKey: error] errorOptional = NSError(domain: "RequestOperation", code: response.statusCode, userInfo: userInfo) } else { let errorMessage = NSLocalizedString("The service is currently unavailable. Please try again later", comment: "Service unavailable text") let userInfo: [String: Any] = [NSUnderlyingErrorKey: error, NSLocalizedDescriptionKey: errorMessage] errorOptional = NSError(domain: "RequestOperation", code: 101, userInfo: userInfo) } } completion(networkResponse.data, errorOptional) } }
apache-2.0
9866bfa34fc911b87cd3253547740129
28.691176
173
0.692257
5.364925
false
false
false
false
cemolcay/CEMKit-Swift
CEMKit-Swift/CEMKit/UIKit/CEMKit+UILabel.swift
1
9164
// // CEMKit+UILabel.swift // // // Created by Cem Olcay on 12/08/15. // // import UIKit private var UILabelAttributedStringArray: UInt8 = 0 extension UILabel { var attributedStrings: [NSAttributedString]? { get { return objc_getAssociatedObject(self, &UILabelAttributedStringArray) as? [NSAttributedString] } set (value) { objc_setAssociatedObject(self, &UILabelAttributedStringArray, value,objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC) } } func addAttributedString ( text: String, color: UIColor, font: UIFont) { let att = NSAttributedString (text: text, color: color, font: font) self.addAttributedString(att) } func addAttributedString (attributedString: NSAttributedString) { var att: NSMutableAttributedString? if let a = self.attributedText { att = NSMutableAttributedString (attributedString: a) att?.appendAttributedString(attributedString) } else { att = NSMutableAttributedString (attributedString: attributedString) attributedStrings = [] } attributedStrings?.append(attributedString) self.attributedText = NSAttributedString (attributedString: att!) } func updateAttributedStringAtIndex ( index: Int, attributedString: NSAttributedString) { if let _ = attributedStrings?[index] { attributedStrings?.removeAtIndex(index) attributedStrings?.insert(attributedString, atIndex: index) let updated = NSMutableAttributedString () for att in attributedStrings! { updated.appendAttributedString(att) } self.attributedText = NSAttributedString (attributedString: updated) } } func updateAttributedStringAtIndex ( index: Int, newText: String) { if let att = attributedStrings?[index] { let newAtt = NSMutableAttributedString (string: newText) att.enumerateAttributesInRange(NSMakeRange(0, att.string.characters.count-1), options: NSAttributedStringEnumerationOptions.LongestEffectiveRangeNotRequired, usingBlock: { (attribute, range, stop) -> Void in for (key, value) in attribute { newAtt.addAttribute(key , value: value, range: range) } } ) updateAttributedStringAtIndex(index, attributedString: newAtt) } } func getEstimatedSize ( width: CGFloat = CGFloat.max, height: CGFloat = CGFloat.max) -> CGSize { return sizeThatFits(CGSize(width: width, height: height)) } func getEstimatedHeight () -> CGFloat { return sizeThatFits(CGSize(width: w, height: CGFloat.max)).height } func getEstimatedWidth () -> CGFloat { return sizeThatFits(CGSize(width: CGFloat.max, height: h)).width } func fitHeight () { self.h = getEstimatedHeight() } func fitWidth () { self.w = getEstimatedWidth() } func fitSize () { self.fitWidth() self.fitHeight() sizeToFit() } // Text, TextColor, TextAlignment, Font convenience init ( frame: CGRect, text: String, textColor: UIColor, textAlignment: NSTextAlignment, font: UIFont) { self.init(frame: frame) self.text = text self.textColor = textColor self.textAlignment = textAlignment self.font = font self.numberOfLines = 0 } convenience init ( x: CGFloat, y: CGFloat, width: CGFloat, height: CGFloat, text: String, textColor: UIColor, textAlignment: NSTextAlignment, font: UIFont) { self.init(frame: CGRect (x: x, y: y, width: width, height: height)) self.text = text self.textColor = textColor self.textAlignment = textAlignment self.font = font self.numberOfLines = 0 } convenience init ( x: CGFloat, y: CGFloat, width: CGFloat, text: String, textColor: UIColor, textAlignment: NSTextAlignment, font: UIFont) { self.init(frame: CGRect (x: x, y: y, width: width, height: 10.0)) self.text = text self.textColor = textColor self.textAlignment = textAlignment self.font = font self.numberOfLines = 0 self.fitHeight() } convenience init ( x: CGFloat, y: CGFloat, width: CGFloat, padding: CGFloat, text: String, textColor: UIColor, textAlignment: NSTextAlignment, font: UIFont) { self.init(frame: CGRect (x: x, y: y, width: width, height: 10.0)) self.text = text self.textColor = textColor self.textAlignment = textAlignment self.font = font self.numberOfLines = 0 self.h = self.getEstimatedHeight() + 2*padding } convenience init ( x: CGFloat, y: CGFloat, height: CGFloat, text: String, textColor: UIColor, textAlignment: NSTextAlignment, font: UIFont) { self.init(frame: CGRect (x: x, y: y, width: 10.0, height: height)) self.text = text self.textColor = textColor self.textAlignment = textAlignment self.font = font self.numberOfLines = 0 self.fitSize() } // AttributedText convenience init ( frame: CGRect, attributedText: NSAttributedString, textAlignment: NSTextAlignment) { self.init(frame: frame) self.attributedText = attributedText self.textAlignment = textAlignment self.numberOfLines = 0 } convenience init ( x: CGFloat, y: CGFloat, width: CGFloat, height: CGFloat, attributedText: NSAttributedString, textAlignment: NSTextAlignment) { self.init(frame: CGRect (x: x, y: y, width: width, height: height)) self.attributedText = attributedText self.textAlignment = textAlignment self.numberOfLines = 0 } convenience init ( x: CGFloat, y: CGFloat, width: CGFloat, attributedText: NSAttributedString, textAlignment: NSTextAlignment) { self.init(frame: CGRect (x: x, y: y, width: width, height: 10.0)) self.attributedText = attributedText self.textAlignment = textAlignment self.numberOfLines = 0 self.fitHeight() } convenience init ( x: CGFloat, y: CGFloat, width: CGFloat, padding: CGFloat, attributedText: NSAttributedString, textAlignment: NSTextAlignment) { self.init(frame: CGRect (x: x, y: y, width: width, height: 10.0)) self.attributedText = attributedText self.textAlignment = textAlignment self.numberOfLines = 0 self.fitHeight() self.h += padding*2 } convenience init ( x: CGFloat, y: CGFloat, attributedText: NSAttributedString, textAlignment: NSTextAlignment) { self.init(frame: CGRect (x: x, y: y, width: 10.0, height: 10.0)) self.attributedText = attributedText self.textAlignment = textAlignment self.numberOfLines = 0 self.fitSize() } convenience init ( x: CGFloat, y: CGFloat, padding: CGFloat, attributedText: NSAttributedString, textAlignment: NSTextAlignment) { self.init(frame: CGRect (x: x, y: y, width: 10.0, height: 10.0)) self.attributedText = attributedText self.textAlignment = textAlignment self.numberOfLines = 0 self.fitSize() self.h += padding*2 } convenience init ( x: CGFloat, y: CGFloat, height: CGFloat, attributedText: NSAttributedString, textAlignment: NSTextAlignment) { self.init(frame: CGRect (x: x, y: y, width: 10.0, height: height)) self.attributedText = attributedText self.textAlignment = textAlignment self.numberOfLines = 0 self.fitWidth() } }
mit
8aa8f9f8f1d8aaf5f91cb5ad4c7ee891
28.184713
137
0.541467
5.400118
false
false
false
false
Ucself/JGCache
JGCache/Classes/JGFileManager.swift
1
2534
// // JGFileManager.swift // JGCache // // Created by 李保君 on 2017/11/1. // Copyright © 2017年 JGCache. All rights reserved. // import UIKit class JGFileManager: NSObject { /// 获取缓存的文件路径 /// /// - Parameters: /// - isCreateNewFile: 是否创建新文件覆盖 /// - cacheName: 缓存文件名 /// - pathURL: 缓存文件路径,默认在document 下 /// - Returns: 返回URL /// - Throws: 是否有异常返回 class func cacheDirectory(isCreateNewFile:Bool, cacheName:String, pathURL:URL = JGFileManager.documentDirectory()) throws -> URL { //获取UUID let uuid:String = UIDevice.current.identifierForVendor?.uuidString ?? "" //文件夹路径 let urlFolder:URL = pathURL.appendingPathComponent("\(uuid)_JGCache", isDirectory: true) if !FileManager.default.fileExists(atPath: urlFolder.path){ try FileManager.default.createDirectory(at: urlFolder, withIntermediateDirectories: true, attributes: nil) } //文件路径 let urlFile:URL = urlFolder.appendingPathComponent("\(cacheName)_Data", isDirectory: false) if isCreateNewFile && !FileManager.default.fileExists(atPath: urlFile.path) { let attr: [FileAttributeKey: Any] = [FileAttributeKey(rawValue: FileAttributeKey.protectionKey.rawValue): FileProtectionType.complete] let ret = FileManager.default.createFile(atPath: urlFile.path, contents: nil, attributes: attr) if ret { return urlFile } else { throw NSError.init(domain: "com.JGCache.error", code: 10001, userInfo: [NSLocalizedDescriptionKey: "file create fail."]) } } return urlFile } //MARK: Directory URL /// document URL /// /// - Returns: document URL class func documentDirectory() -> URL { let URL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first! return URL } /// library URL /// /// - Returns: library URL class func libraryDirectory() -> URL { let URL = FileManager.default.urls(for: .libraryDirectory, in: .userDomainMask).first! return URL } /// caches URL /// /// - Returns: caches URL class func cachesDirectory() -> URL { let URL = FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask).first! return URL } }
mit
72bbf69291fe6fbef7a98c90169257a0
34.544118
146
0.612329
4.500931
false
false
false
false
rduan8/Aerial
Aerial/Source/Controllers/PreferencesWindowController.swift
1
15769
// // PreferencesWindowController.swift // Aerial // // Created by John Coates on 10/23/15. // Copyright © 2015 John Coates. All rights reserved. // import Cocoa import AVKit import AVFoundation import ScreenSaver class TimeOfDay { let title:String; var videos:[AerialVideo] = [AerialVideo]() init(title:String) { self.title = title; } } class City { var night:TimeOfDay = TimeOfDay(title: "night"); var day:TimeOfDay = TimeOfDay(title: "day"); let name:String; init(name:String) { self.name = name; } func addVideoForTimeOfDay(timeOfDay:String, video:AerialVideo) { if timeOfDay.lowercaseString == "night" { video.arrayPosition = night.videos.count; night.videos.append(video); } else { video.arrayPosition = day.videos.count; day.videos.append(video); } } } @objc(PreferencesWindowController) class PreferencesWindowController: NSWindowController, NSOutlineViewDataSource, NSOutlineViewDelegate { @IBOutlet var outlineView:NSOutlineView? @IBOutlet var playerView:AVPlayerView! @IBOutlet var differentAerialCheckbox:NSButton! @IBOutlet var projectPageLink:NSButton! @IBOutlet var cacheLocation:NSPathControl! var player:AVPlayer = AVPlayer() let defaults:NSUserDefaults = ScreenSaverDefaults(forModuleWithName: "com.JohnCoates.Aerial")! as ScreenSaverDefaults var videos:[AerialVideo]? // cities -> time of day -> videos var cities = [City](); static var loadedJSON:Bool = false; override func awakeFromNib() { super.awakeFromNib() if let previewPlayer = AerialView.previewPlayer { self.player = previewPlayer; } outlineView?.floatsGroupRows = false; loadJSON(); playerView.player = player; playerView.controlsStyle = .None; if #available(OSX 10.10, *) { playerView.videoGravity = AVLayerVideoGravityResizeAspectFill }; defaults.synchronize(); if (defaults.boolForKey("differentDisplays")) { differentAerialCheckbox.state = NSOnState; } // blue link let color = NSColor(calibratedRed:0.18, green:0.39, blue:0.76, alpha:1); let coloredTitle = NSMutableAttributedString(attributedString: projectPageLink.attributedTitle); let titleRange = NSMakeRange(0, coloredTitle.length); coloredTitle.addAttribute(NSForegroundColorAttributeName, value: color, range: titleRange); projectPageLink.attributedTitle = coloredTitle; if let cacheDirectory = VideoCache.cacheDirectory { cacheLocation.URL = NSURL(fileURLWithPath: cacheDirectory as String) } } required init?(coder decoder: NSCoder) { super.init(coder: decoder) } override init(window: NSWindow?) { super.init(window: window) } override func windowDidLoad() { super.windowDidLoad() } @IBAction func cacheAerialsAsTheyPlayClick(button:NSButton!) { debugLog("cache aerials as they play: \(button.state)"); if button.state == NSOnState { defaults.setBool(false, forKey: "disableCache"); } else { defaults.setBool(true, forKey: "disableCache"); } defaults.synchronize(); } @IBAction func userSetCacheLocation(button:NSButton?) { let openPanel = NSOpenPanel() openPanel.canChooseDirectories = true; openPanel.canChooseFiles = false openPanel.canCreateDirectories = true openPanel.allowsMultipleSelection = false openPanel.title = "Choose Aerial Cache Directory" openPanel.prompt = "Choose" openPanel.directoryURL = cacheLocation.URL openPanel.beginWithCompletionHandler { (result:Int) -> Void in if result == NSFileHandlingPanelOKButton { if openPanel.URLs.count > 0 { let cacheDirectory = openPanel.URLs[0]; self.defaults.setObject(cacheDirectory.path, forKey: "cacheDirectory"); self.defaults.synchronize() self.cacheLocation.URL = cacheDirectory } } } } @IBAction func resetCacheLocation(button:NSButton?) { defaults.removeObjectForKey("cacheDirectory"); defaults.synchronize() if let cacheDirectory = VideoCache.cacheDirectory { cacheLocation.URL = NSURL(fileURLWithPath: cacheDirectory as String) } } @IBAction func outlineViewSettingsClick(button:NSButton) { let menu = NSMenu() menu.insertItemWithTitle("Uncheck All", action: "outlineViewUncheckAll:", keyEquivalent: "", atIndex: 0); menu.insertItemWithTitle("Check All", action: "outlineViewCheckAll:", keyEquivalent: "", atIndex: 1); let event = NSApp.currentEvent; NSMenu.popUpContextMenu(menu, withEvent: event!, forView: button); } func outlineViewUncheckAll(button:NSButton) { setChecked(false); } func outlineViewCheckAll(button:NSButton) { setChecked(true); } func setChecked(checked:Bool) { guard let videos = videos else { return; } for video in videos { self.defaults.setBool(checked, forKey: video.id); } self.defaults.synchronize(); outlineView!.reloadData() } @IBAction func differentAerialsOnEachDisplayCheckClick(button:NSButton?) { let state = differentAerialCheckbox.state; let onState:Bool = state == NSOnState; defaults.setBool(onState, forKey: "differentDisplays"); defaults.synchronize(); debugLog("set differentDisplays to \(onState)"); } @IBAction func pageProjectClick(button:NSButton?) { NSWorkspace.sharedWorkspace().openURL(NSURL(string: "http://github.com/JohnCoates/Aerial")!); } func loadJSON() { if (PreferencesWindowController.loadedJSON) { return; } PreferencesWindowController.loadedJSON = true; let completionHandler = { (data:NSData?, response:NSURLResponse?, error:NSError?) -> Void in guard let data = data else { return; } var videos = [AerialVideo](); var cities = [String:City](); do { let batches = try NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.AllowFragments) as! Array<NSDictionary>; for batch:NSDictionary in batches { let assets = batch["assets"] as! Array<NSDictionary>; for item in assets { let url = item["url"] as! String; let name = item["accessibilityLabel"] as! String; let timeOfDay = item["timeOfDay"] as! String; let id = item["id"] as! String; let type = item["type"] as! String; if (type != "video") { continue; } // check if city name has dictionary if cities.keys.contains(name) == false { cities[name] = City(name: name); } let city:City = cities[name]!; let video = AerialVideo(id: id, name: name, type: type, timeOfDay: timeOfDay, url: url); city.addVideoForTimeOfDay(timeOfDay, video: video); videos.append(video) // debugLog("id: \(id), name: \(name), time of day: \(timeOfDay), url: \(url)"); } } self.videos = videos; // sort cities by name let unsortedCities = cities.values; let sortedCities = unsortedCities.sort { $0.name < $1.name }; self.cities = sortedCities; dispatch_async(dispatch_get_main_queue(), { () -> Void in self.outlineView?.reloadData(); self.outlineView?.expandItem(nil, expandChildren: true); }) // debugLog("reloading outline view\(self.outlineView)"); } catch { NSLog("Aerial: Error retrieving content listing."); return; } }; let url = NSURL(string: "http://a1.phobos.apple.com/us/r1000/000/Features/atv/AutumnResources/videos/entries.json"); let task = NSURLSession.sharedSession().dataTaskWithURL(url!, completionHandler:completionHandler); task.resume(); } @IBAction func close(sender: AnyObject?) { NSApp.mainWindow?.endSheet(window!); } // MARK: - Outline View Delegate & Data Source func outlineView(outlineView: NSOutlineView, numberOfChildrenOfItem item: AnyObject?) -> Int { if item == nil { return cities.count; } switch item { case is TimeOfDay: let timeOfDay = item as! TimeOfDay; return timeOfDay.videos.count; case is City: let city = item as! City; var count = 0; if city.night.videos.count > 0 { count++; } if city.day.videos.count > 0 { count++; } return count; default: return 0; } } func outlineView(outlineView: NSOutlineView, isItemExpandable item: AnyObject) -> Bool { switch item { case is TimeOfDay: return true; case is City: // cities return true; default: return false; } } func outlineView(outlineView: NSOutlineView, child index: Int, ofItem item: AnyObject?) -> AnyObject { if item == nil { return cities[index]; } switch item { case is City: let city = item as! City; if (index == 0 && city.day.videos.count > 0) { return city.day; } else { return city.night; } case is TimeOfDay: let timeOfDay = item as! TimeOfDay; return timeOfDay.videos[index]; default: return false; } } func outlineView(outlineView: NSOutlineView, objectValueForTableColumn tableColumn: NSTableColumn?, byItem item: AnyObject?) -> AnyObject? { switch item { case is City: let city = item as! City; return city.name; case is TimeOfDay: let timeOfDay = item as! TimeOfDay; return timeOfDay.title; default: return "untitled"; } } func outlineView(outlineView: NSOutlineView, shouldEditTableColumn tableColumn: NSTableColumn?, item: AnyObject) -> Bool { return false; } func outlineView(outlineView: NSOutlineView, dataCellForTableColumn tableColumn: NSTableColumn?, item: AnyObject) -> NSCell? { let row = outlineView.rowForItem(item); return tableColumn!.dataCellForRow(row) as? NSCell; } func outlineView(outlineView: NSOutlineView, isGroupItem item: AnyObject) -> Bool { switch item { case is TimeOfDay: return true; case is City: return true; default: return false; } } func outlineView(outlineView: NSOutlineView, viewForTableColumn tableColumn: NSTableColumn?, item: AnyObject) -> NSView? { switch item { case is City: let city = item as! City; let view = outlineView.makeViewWithIdentifier("HeaderCell", owner: self) as? NSTableCellView view?.textField?.stringValue = city.name; return view; case is TimeOfDay: let view = outlineView.makeViewWithIdentifier("DataCell", owner: self) as? NSTableCellView let timeOfDay = item as! TimeOfDay; view?.textField?.stringValue = timeOfDay.title.capitalizedString; let bundle = NSBundle(forClass: PreferencesWindowController.self); let imagePath = bundle.pathForResource("icon-\(timeOfDay.title)", ofType:"pdf"); let image = NSImage(contentsOfFile: imagePath!); view?.imageView?.image = image; return view; case is AerialVideo: let view = outlineView.makeViewWithIdentifier("CheckCell", owner: self) as? CheckCellView let video = item as! AerialVideo; let number = video.arrayPosition + 1; let numberFormatter = NSNumberFormatter(); numberFormatter.numberStyle = NSNumberFormatterStyle.SpellOutStyle; let numberString = numberFormatter.stringFromNumber(number); view?.textField?.stringValue = numberString!.capitalizedString; let settingValue = defaults.objectForKey(video.id); if let settingValue = settingValue as? NSNumber { if settingValue.boolValue == false { view?.checkButton.state = NSOffState; } else { view?.checkButton.state = NSOnState; } } else { view?.checkButton.state = NSOnState; } view?.onCheck = { (checked:Bool) in self.defaults.setBool(checked, forKey: video.id); self.defaults.synchronize(); }; return view; default: return nil; } } func outlineView(outlineView: NSOutlineView, shouldSelectItem item: AnyObject) -> Bool { switch item { case is AerialVideo: player = AVPlayer() playerView.player = player; let video = item as! AerialVideo; let asset = CachedOrCachingAsset(video.url); // let asset = AVAsset(URL: video.url); let item = AVPlayerItem(asset: asset); player.replaceCurrentItemWithPlayerItem(item); player.play(); return true; case is TimeOfDay: return false; default: return false; } } func outlineView(outlineView: NSOutlineView, heightOfRowByItem item: AnyObject) -> CGFloat { switch item { case is AerialVideo: return 18; case is TimeOfDay: return 18; case is City: return 18; default: return 0; } } }
mit
309e7490552f34f0229bdd4fac1f6023
32.056604
149
0.541159
5.51136
false
false
false
false
rithms/lolesports-kit
Data/Series.swift
1
1307
// // Series.swift // eSportsKitProject // // Created by Taylor Caldwell on 7/8/15. // Copyright (c) 2015 Rithms. All rights reserved. // import Foundation struct Series { var labelPublic: String? // Name of series suitable for public consumption var season: String? // Season this series is in var label: String? // Name of the series for administrative purposes var id: String? // Unique numeric identifier for this series var url: String? // URL to this series's page var tournaments: [String]? // IDs of the tournaments belonging to this series init(data: AnyObject) { labelPublic = data[LolEsportsClient.JSONKeys.LabelPublic] as? String season = data[LolEsportsClient.JSONKeys.Season] as? String label = data[LolEsportsClient.JSONKeys.Label] as? String id = data[LolEsportsClient.JSONKeys.Id] as? String url = data[LolEsportsClient.JSONKeys.URL] as? String tournaments = data[LolEsportsClient.JSONKeys.Tournaments] as? [String] } static func seriesFromResults(results: [AnyObject]) -> [Series] { var series = [Series]() for value in results { series.append(Series(data: value)) } return series } }
mit
7140f7cb99a2183611ac5663437fe7c1
30.142857
82
0.641928
3.960606
false
false
false
false
theddnc/iService
iService/ServiceRealm.swift
1
14925
// // ServiceRealm.swift // iPromise // // Created by jzaczek on 30.10.2015. // Copyright © 2015 jzaczek. All rights reserved. // import Foundation import iPromise /** **TODO:** add possibility to list all services in this realm - for debugging (?) A ServiceRealm is an entry point for shared configuration of Services. After creating and configuring a realm, Services can be registered for it, and configuration provided will be used for every request. For example, if an API protects some of its services with APIKey authentication and some are publicly available, two realms can be created: - first for publicly available services, e.g. ```ServiceRealm.getDefault()``` - second one for services hidden behind APIKey, with appropriate headers set ``` ServiceRealm.get("www.example.com/hidden").addHeaders( ["Authentication": "ApiKey (...)"] ) ``` This class supports chained calls. All overriding functions return ServiceRealms. Supported configuration options: - CRUD method - HTTP method map - for APIs that do not conform to the default (or the most sane) CRUD - HTTP mapping - HTTP headers - CRUD method specific HTTP headers - for APIs that use some weird and 'legacy' interfaces which make use of HTTP headers */ public class ServiceRealm { /// Type representing a map of CRUD methods and their corresponding HTTP methods public typealias CRUDMap = [Service.CRUDMethod: Service.HTTPMethod] /// Type representing a dictionary of HTTP headers public typealias HTTPHeaderDictionary = [String: String] /** Contains default CRUD method - HTTP method map: ``` [ .CREATE: .POST, .RETRIEVE: .GET, .UPDATE: .PUT, .DESTROY: .DELETE, ] ``` */ static public let defaultCRUDMap: CRUDMap = [ .CREATE: .POST, .RETRIEVE: .GET, .UPDATE: .PUT, .DESTROY: .DELETE ] /** Contains default CRUD specific headers dictionary: ``` [ .CREATE: [:], .RETRIEVE: [:], .UPDATE: [:], .DESTROY: [:] ] ``` */ static public let defaultCRUDSpecificHeaders: [Service.CRUDMethod: HTTPHeaderDictionary] = [ .CREATE: [:], .RETRIEVE: [:], .UPDATE: [:], .DESTROY: [:] ] /// Array of user defined ServiceRealms static private var realms: [String: ServiceRealm] = [:] /// Default realm with default configuration. All services use this configuration, unless /// registered for a different realm. static private var defaultRealm: ServiceRealm = ServiceRealm() /// Dictionary of HTTP headers to add to every request coming out of this realm private var _headers: HTTPHeaderDictionary /// Global cache policy for this realm private var _cachePolicy: NSURLRequestCachePolicy /// Map of CRUD methods and their corresponding HTTP headers private var _crudSpecificHeaders: [Service.CRUDMethod: HTTPHeaderDictionary] /// Map of CRUD methods and their corresponding cache policies private var _crudSpecificCachePolicies: [Service.CRUDMethod: NSURLRequestCachePolicy] /// CRUD method - HTTP method map private var _crudMethodMap: CRUDMap /// Identifier for this realm private var _id: String = NSUUID().UUIDString /// User-defined key for this realm private var _key: String = "" /// Contains unique id for this realm, read only /// **TODO:** is this necessary? public var id: String { get { return "KEY: \(_key), ID: \(_id)\n" } } /// Contains HTTPHeaders for this realm, read only public var HTTPHeaders: HTTPHeaderDictionary { get { return _headers } } /// Contains map of CRUD methods and their corresponding HTTP headers, read only public var CRUDSpecificHTTPHeaders: [Service.CRUDMethod: HTTPHeaderDictionary] { get { return _crudSpecificHeaders } } /// Contains CRUD method - HTTP method map, read only public var CRUDMethodMap: CRUDMap { get { return _crudMethodMap } } /// Contains global cache policy public var CachePolicy: NSURLRequestCachePolicy { get { return _cachePolicy } } ///Contains map of CRUD methods and their corresponding cache policies public var CRUDSpecificCachePolicies: [Service.CRUDMethod: NSURLRequestCachePolicy] { get { return _crudSpecificCachePolicies } } /// Creates a default realm private init() { _headers = [:] _crudSpecificHeaders = ServiceRealm.defaultCRUDSpecificHeaders _crudMethodMap = ServiceRealm.defaultCRUDMap _cachePolicy = NSURLRequestCachePolicy.ReloadIgnoringLocalCacheData _crudSpecificCachePolicies = [:] } /** Creates a fully configured request for a given CRUD method and URL Injects headers, cache policy and uses apropriate HTTP method. - parameter method: ```Service.CRUDMethod``` - parameter url: ```NSURL``` of the request - returns: ```NSMutableURLRequest``` */ public func configuredRequestForMethod(method: Service.CRUDMethod, andURL url: NSURL) -> NSMutableURLRequest { let cachePolicy = self.cachePolicyForMethod(method) let request = NSMutableURLRequest(URL: url, cachePolicy: cachePolicy, timeoutInterval: 60.0) // set all http headers for this crud method to this request request.allHTTPHeaderFields = self.allHTTPHeadersForMethod(method) // use correct http method for this request request.HTTPMethod = (self.CRUDMethodMap[method] ?? ServiceRealm.defaultCRUDMap[method]!).rawValue return request } /** Overrides default CRUD method - HTTP method map with passed argument - parameter map: A dictionary of type ```[Service.CRUDMethod: Service.HTTPMethod]``` - returns: This ```ServiceRealm``` */ public func overrideCrudMap(map: CRUDMap) -> ServiceRealm { self._crudMethodMap = map return self } /** Overrides CRUD method with HTTP method passed as the argument. - parameter method: CRUD method to override. See ```Service.CRUDMethod``` - parameter httpMethod: HTTP method to override. See ```Service.HTTPMethod``` - returns: This ```ServiceRealm``` */ public func overrideCrudMethod(method: Service.CRUDMethod, withHTTPMethod httpMethod: Service.HTTPMethod) -> ServiceRealm { self._crudMethodMap.updateValue(httpMethod, forKey: method) return self } /** Adds a single header value to HTTP header dictionary - parameter header: HTTP header field name - parameter value: Value of the HTTP header field - returns: This ```ServiceRealm``` */ public func addHeader(header: String, withValue value: String) -> ServiceRealm { self._headers.updateValue(value, forKey: header) return self } /** Adds multiple headers to HTTP header dictionary. If a header from ```headers``` parameter is already defined, its value is set to a corresponding value from ```headers```. - parameter headers: Dictionary of headers to be merged with internal HTTP header dictionary - returns: This ```ServiceRealm``` */ public func addHeaders(headers: HTTPHeaderDictionary) -> ServiceRealm { for (key, value) in headers { self._headers.updateValue(value, forKey: key) } return self } /** Adds a single header value to HTTP header dictionary for a specific CRUD method - parameter header: HTTP header field name - parameter value: Value of the HTTP header field - parameter method: See ```Service.CRUDMethod``` - returns: This ```ServiceRealm``` */ public func addHeader(header: String, withValue value: String, specificForCRUDMethod crudMethod: Service.CRUDMethod) -> ServiceRealm { self._crudSpecificHeaders[crudMethod]?.updateValue(value, forKey: header) return self } /** Adds multiple headers to HTTP header dictionary for a specific CRUD method. If a header from ```headers``` parameter is already defined, its value is set to a corresponding value from ```headers```. - parameter headers: Dictionary of headers to be merged with internal HTTP header dictionary - parameter method: See ```Service.CRUDMethod``` - returns: This ```ServiceRealm``` */ public func addHeaders(headers: HTTPHeaderDictionary, specificForCRUDMethod crudMethod: Service.CRUDMethod) -> ServiceRealm { for (key, value) in headers { self._crudSpecificHeaders[crudMethod]?.updateValue(value, forKey: key) } return self } /** Removes headers with their values from the configuration. - parameter headers: An ```Array``` of ```String``` keys representing headers to be removed. - returns: This ```ServiceRealm``` */ public func cleanHeaders(headers: [String]) -> ServiceRealm { for header in headers { self._headers.removeValueForKey(header) } return self } /** Removes headers with their values from the configuration for a specified CRUD method. - parameter headers: An ```Array``` of ```String``` keys representing headers to be removed. - parameter method: ```Service.CRUDMethod``` - returns: This ```ServiceRealm``` */ public func cleanHeaders(headers: [String], forCRUDMethod method: Service.CRUDMethod) -> ServiceRealm { for header in headers { self._crudSpecificHeaders[method]?.removeValueForKey(header) } return self } /** Overrides global cache policy. Policies for CRUD methods can be overriden separately and have higher priority. - parameter cachePolicy: ```NSURLRequestCachePolicy``` to be set as default - returns: This ```ServiceRealm``` */ public func overrideGlobalCachePolicy(cachePolicy: NSURLRequestCachePolicy) -> ServiceRealm { self._cachePolicy = cachePolicy return self } /** Overrides CRUD method specific cache policy. This policy has a higher priority than the global policy. - parameter cachePolicy: ```NSURLRequestCachePolicy``` to be set for this method - parameter method: See: ```Service.CRUDMethod``` - returns: This ```ServiceRealm``` */ public func overrideCachePolicy(cachePolicy: NSURLRequestCachePolicy, forCrudMethod method: Service.CRUDMethod) -> ServiceRealm { self._crudSpecificCachePolicies.updateValue(cachePolicy, forKey: method) return self } /** Register a service in this ```ServiceRealm```. Registering in a service realm provides an entry point for configuration. - parameter service: ```Service``` to be registered for this configuration - returns: This ```ServiceRealm``` */ public func register(service: Service) -> ServiceRealm { service.registerForRealm(self) return self } /** Returns a cache policy for requested CRUD method. If none is specified, returns the global cache policy. - parameter method: ```Service.CRUDMethod``` - returns: A ```NSURLRequestCachePolicy``` for specified method. */ public func cachePolicyForMethod(method: Service.CRUDMethod) -> NSURLRequestCachePolicy { if self.CRUDSpecificCachePolicies.keys.contains(method) { return self.CRUDSpecificCachePolicies[method]! } return self.CachePolicy } /** Returns all headers for a requested CRUD method. Merges CRUD specific headers with global headers. - parameter method: ```Service.CRUDMethod``` - returns: A ```HTTPHeaderDictionary``` */ public func allHTTPHeadersForMethod(method: Service.CRUDMethod) -> HTTPHeaderDictionary { var headers = self.HTTPHeaders; for (key, value) in self.CRUDSpecificHTTPHeaders[method] ?? [:] { headers.updateValue(value, forKey: key) } return headers } /** Provides a copy of this ServiceRealm. Used for overriding configuration. **NOTDE:** Realm returned by this method will not be accesible using ```.get(key)``` - returns: Cloned ```ServiceRealm``` */ internal func clone() -> ServiceRealm { let newRealm = ServiceRealm() newRealm._cachePolicy = self._cachePolicy newRealm._crudMethodMap = self._crudMethodMap newRealm._crudSpecificCachePolicies = self._crudSpecificCachePolicies newRealm._crudSpecificHeaders = self._crudSpecificHeaders newRealm._headers = self._headers newRealm._id = NSUUID().UUIDString newRealm._key = self._key return newRealm } /** Returns a realm for a given key. If no realm corresponds to that key, a new default one is created and returned. - parameter key: A key for which the realm is registered. - returns: A ```ServiceRealm``` for the given key. */ public class func get(key: String) -> ServiceRealm { if !realms.keys.contains(key) { let realm = ServiceRealm() realm._key = key realms[key] = realm } return realms[key]! } public class func destroy(key: String) -> Void { if realms.keys.contains(key) { realms.removeValueForKey(key) } } /** Returns a default realm. All services use this realm, unless they are registered for a different one. **NOTE:** Overriding any configuration of this realm will influence all services which were not explicitly registered for another realm. This may be considered an easy way of changing global configuration of outgoing requests. - returns: Default ```ServiceRealm``` */ public class func getDefault() -> ServiceRealm { return defaultRealm } /** Registers a service for a realm at a given key. Equivalent to ```ServiceRealm.get(key).register(service)``` call. - parameter service: Service to be registered - parameter key: Key of the realm to register the service for */ public class func registerService(service: Service, forRealmAtKey key: String) { ServiceRealm.get(key).register(service) } }
mit
e7af7913981598e63ee304760972e431
31.94702
138
0.641182
4.90276
false
false
false
false
CoderST/DYZB
DYZB/DYZB/Class/Profile/Controller/LocationSubViewController.swift
1
3326
// // LocationSubViewController.swift // DYZB // // Created by xiudou on 2017/7/13. // Copyright © 2017年 xiudo. All rights reserved. // import UIKit import SVProgressHUD class LocationSubViewController: UIViewController { /// 省会model var locationModel : LocationModel = LocationModel() fileprivate lazy var locationSubVM : LocationSubVM = LocationSubVM() fileprivate lazy var collectionView : STCollectionView = STCollectionView() override func viewDidLoad() { super.viewDidLoad() setupUI() } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) SVProgressHUD.dismiss() } deinit { debugLog("LocationSubViewController -- 销毁") } } extension LocationSubViewController { func setupUI(){ view.addSubview(collectionView) collectionView.frame = view.bounds collectionView.dataSource = self collectionView.delegate = self } } extension LocationSubViewController : STCollectionViewDataSource{ func collectionViewTitleInRow(_ collectionView: STCollectionView, _ indexPath: IndexPath) -> String { let model = locationModel.city[indexPath.item] return model.name } func collectionView(_ stCollectionView: STCollectionView, numberOfItemsInSection section: Int) -> Int { return locationModel.city.count } func isHiddenArrowImageView(_ collectionView: STCollectionView, _ indexPath: IndexPath) -> Bool { // 没有下级页面 全部隐藏 return true } } extension LocationSubViewController : STCollectionViewDelegate { func stCollection(_ stCollectionView: STCollectionView, didSelectItemAt indexPath: IndexPath) { let locationSubModel = locationModel.city[indexPath.item] // let city = model.name /** http://capi.douyucdn.cn/api/v1/set_userinfo_custom?aid=ios&client_sys=ios&time=1499930940&auth=3d4bf3c09cfd003962eb3394dffb3617 location 蚌埠 13,12 */ let proID = locationModel.code // 省会ID let cityID = locationSubModel.code // 市区ID var ID : String = "" if locationModel.city.count > 0{ ID = String(format: "%d,%d",proID,cityID) }else{ ID = "\(proID)" } locationSubVM.upLoadLocationDatas(ID, { notificationCenter.post(name: Notification.Name(rawValue: sNotificationName_ReLoadProfileInforData), object: nil, userInfo: nil) self.popAction() }, { (message) in SVProgressHUD.showInfo(withStatus: message) }) { } } fileprivate func popAction(){ // 在请求回调成功里pop到个人信息(ProfileInforViewController)指定控制器 for i in 0..<(navigationController?.viewControllers.count)! { if self.navigationController?.viewControllers[i].isKind(of: ProfileInforViewController.self) == true { _ = navigationController?.popToViewController(navigationController?.viewControllers[i] as! ProfileInforViewController, animated: true) break } } } }
mit
7e74471442547171ee4f31476e8538d8
29.345794
150
0.636588
4.824666
false
false
false
false
tejen/codepath-instagram
Instagram/Instagram/HomeViewController.swift
1
8831
// // HomeViewController.swift // Instagram // // Created by Tejen Hasmukh Patel on 3/10/16. // Copyright © 2016 Tejen. All rights reserved. // import UIKit import Parse class HomeViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, UIGestureRecognizerDelegate, UIScrollViewDelegate { @IBOutlet weak var tableView: UITableView! var posts: [Post]?; var inspectPostComments: Post?; var isMoreDataLoading = false; var refreshControl: UIRefreshControl!; var loadingMoreView: InfiniteScrollActivityView?; override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. tableView.delegate = self; tableView.dataSource = self; tableView.rowHeight = UITableViewAutomaticDimension; tableView.estimatedRowHeight = 160.0; let logoImage = UIImage(named: "Logo-Instagram-Transparent-Bordered")! let imageView = UIImageView(image: logoImage); imageView.frame.size.height = (navigationController?.navigationBar.frame.size.height)! - 10; imageView.contentMode = .ScaleAspectFit; navigationItem.titleView = imageView; // Set up Infinite Scroll loading indicator let frame = CGRectMake(0, tableView.contentSize.height, tableView.bounds.size.width, InfiniteScrollActivityView.defaultHeight); loadingMoreView = InfiniteScrollActivityView(frame: frame); loadingMoreView!.hidden = true; tableView.addSubview(loadingMoreView!); var insets = tableView.contentInset; insets.bottom += InfiniteScrollActivityView.defaultHeight; tableView.contentInset = insets refreshControl = UIRefreshControl(); refreshControl.addTarget(self, action: "onRefresh", forControlEvents: UIControlEvents.ValueChanged); tableView.insertSubview(refreshControl, atIndex: 0); } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated); if((posts == nil) && (User.currentUser() != nil)) { reloadTable(); } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func reloadTable(append: Bool = false) { var completion: PFQueryArrayResultBlock = { (posts: [PFObject]?, error: NSError?) -> Void in self.posts = posts as? [Post]; // Update flag self.isMoreDataLoading = false // Stop the loading indicator self.loadingMoreView!.stopAnimating() self.tableView.reloadData(); } if(append) { completion = { (posts: [PFObject]?, error: NSError?) -> Void in for post in posts! { self.posts?.append(post as! Post); } // Update flag self.isMoreDataLoading = false // Stop the loading indicator self.loadingMoreView!.stopAnimating() if(posts?.count > 0) { // if there's even anything new to show, self.tableView.reloadData(); // then show it! } } } var offset = 0; if((append == true) && (posts != nil)) { offset = posts!.count; } Post.fetchPosts(offset, completion: completion); } func numberOfSectionsInTableView(tableView: UITableView) -> Int { return posts?.count ?? 0; } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 1; } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("PostCell") as! PostCell; cell.post = posts![indexPath.section]; cell.tableViewController1 = self; cell.indexPathSection = indexPath.section; // buffer next cell if(posts!.count - 1 >= indexPath.section + 1){ posts![indexPath.section + 1].buffer(); } // buffer next cell if(posts!.count - 1 >= indexPath.section + 2){ posts![indexPath.section + 2].buffer(); } return cell; } func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { let headerView = UIView(frame: CGRect(x: 0, y: 0, width: UIScreen.mainScreen().bounds.width, height: 50)); headerView.backgroundColor = UIColor(white: 1, alpha: 0.97); let profileView = UIImageView(frame: CGRect(x: 10, y: 10, width: 30, height: 30)); profileView.clipsToBounds = true; profileView.layer.cornerRadius = 15; profileView.layer.borderColor = UIColor(white: 0.7, alpha: 0.8).CGColor profileView.layer.borderWidth = 1; let ageView = UILabel(frame: CGRect(x: UIScreen.mainScreen().bounds.width - 60, y: 11, width: 50, height: 30)); // usernameView.center = CGPointMake(100, 25); ageView.textAlignment = NSTextAlignment.Right; ageView.font = UIFont.systemFontOfSize(12.0); ageView.textColor = UIColor(white: 0.75, alpha: 1.0); let usernameView = UILabel(frame: CGRect(x: 50, y: 10, width: 150, height: 30)); // usernameView.center = CGPointMake(100, 25); usernameView.textAlignment = NSTextAlignment.Left; usernameView.font = UIFont.systemFontOfSize(14.0, weight: UIFontWeightMedium); usernameView.textColor = UIColor(red: 0.247, green: 0.4471, blue: 0.608, alpha: 1.0); if let posts = posts { profileView.setImageWithURL( posts[section].author!.profilePicURL! ); usernameView.text = posts[section].author?.username; ageView.text = Post.timeSince(posts[section].createdAt!); } let tap = UITapGestureRecognizer(target: self, action: Selector("onTappedUsername:")); tap.delegate = self; usernameView.userInteractionEnabled = true; usernameView.addGestureRecognizer(tap); headerView.addSubview(profileView); headerView.addSubview(ageView); headerView.addSubview(usernameView); return headerView; } func onTappedUsername(sender: UITapGestureRecognizer) { let authorUsernameLabel = sender.view as! UILabel; authorUsernameLabel.textColor = UIColor.lightGrayColor(); let pVc = storyboard!.instantiateViewControllerWithIdentifier("ProfileTableViewController") as! ProfileTableViewController; pVc.user = User.getUserByUsername(authorUsernameLabel.text!); navigationController?.pushViewController(pVc, animated: true); } func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return 50; } func onRefresh() { reloadTable(); delay(2, closure: { self.refreshControl.endRefreshing(); }) } func scrollViewDidScroll(scrollView: UIScrollView) { if(posts?.count < 5) { return; } if (!isMoreDataLoading) { // Calculate the position of one screen length before the bottom of the results let scrollViewContentHeight = tableView.contentSize.height let scrollOffsetThreshold = scrollViewContentHeight - tableView.bounds.size.height // When the user has scrolled past the threshold, start requesting if(scrollView.contentOffset.y > scrollOffsetThreshold && tableView.dragging) { isMoreDataLoading = true // Update position of loadingMoreView, and start loading indicator let frame = CGRectMake(0, tableView.contentSize.height, tableView.bounds.size.width, InfiniteScrollActivityView.defaultHeight) loadingMoreView?.frame = frame loadingMoreView!.startAnimating() delay(1.0, closure: { () -> () in self.reloadTable(true); }); } } } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if(segue.identifier == "toComments") { let vc = segue.destinationViewController as! CommentsTableViewController; vc.post = inspectPostComments; vc.parentCell = sender as! PostCell; } } }
apache-2.0
548cd4e22b6f6f7b40faefb22af7369b
37.225108
142
0.607814
5.303303
false
false
false
false
kickstarter/ios-ksapi
KsApi/ServerConfig.swift
1
1901
/** A type that knows the location of a Kickstarter API and web server. */ public protocol ServerConfigType { var apiBaseUrl: URL { get } var webBaseUrl: URL { get } var apiClientAuth: ClientAuthType { get } var basicHTTPAuth: BasicHTTPAuthType? { get } } public func == (lhs: ServerConfigType, rhs: ServerConfigType) -> Bool { return type(of: lhs) == type(of: rhs) && lhs.apiBaseUrl == rhs.apiBaseUrl && lhs.webBaseUrl == rhs.webBaseUrl && lhs.apiClientAuth == rhs.apiClientAuth && lhs.basicHTTPAuth == rhs.basicHTTPAuth } public struct ServerConfig: ServerConfigType { public let apiBaseUrl: URL public let webBaseUrl: URL public let apiClientAuth: ClientAuthType public let basicHTTPAuth: BasicHTTPAuthType? public static let production: ServerConfigType = ServerConfig( apiBaseUrl: URL(string: "https://\(Secrets.Api.Endpoint.production)")!, webBaseUrl: URL(string: "https://\(Secrets.WebEndpoint.production)")!, apiClientAuth: ClientAuth.production, basicHTTPAuth: nil ) public static let staging: ServerConfigType = ServerConfig( apiBaseUrl: URL(string: "https://\(Secrets.Api.Endpoint.staging)")!, webBaseUrl: URL(string: "https://\(Secrets.WebEndpoint.staging)")!, apiClientAuth: ClientAuth.development, basicHTTPAuth: BasicHTTPAuth.development ) public static let local: ServerConfigType = ServerConfig( apiBaseUrl: URL(string: "http://api.ksr.dev")!, webBaseUrl: URL(string: "http://ksr.dev")!, apiClientAuth: ClientAuth.development, basicHTTPAuth: BasicHTTPAuth.development ) public init(apiBaseUrl: URL, webBaseUrl: URL, apiClientAuth: ClientAuthType, basicHTTPAuth: BasicHTTPAuthType?) { self.apiBaseUrl = apiBaseUrl self.webBaseUrl = webBaseUrl self.apiClientAuth = apiClientAuth self.basicHTTPAuth = basicHTTPAuth } }
apache-2.0
d211370c01f877aaf6c41a77411dbdc8
32.350877
75
0.7091
4.150655
false
true
false
false
koba-uy/chivia-app-ios
src/Pods/Alamofire/Source/Notifications.swift
111
2653
// // Notifications.swift // // Copyright (c) 2014-2017 Alamofire Software Foundation (http://alamofire.org/) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import Foundation extension Notification.Name { /// Used as a namespace for all `URLSessionTask` related notifications. public struct Task { /// Posted when a `URLSessionTask` is resumed. The notification `object` contains the resumed `URLSessionTask`. public static let DidResume = Notification.Name(rawValue: "org.alamofire.notification.name.task.didResume") /// Posted when a `URLSessionTask` is suspended. The notification `object` contains the suspended `URLSessionTask`. public static let DidSuspend = Notification.Name(rawValue: "org.alamofire.notification.name.task.didSuspend") /// Posted when a `URLSessionTask` is cancelled. The notification `object` contains the cancelled `URLSessionTask`. public static let DidCancel = Notification.Name(rawValue: "org.alamofire.notification.name.task.didCancel") /// Posted when a `URLSessionTask` is completed. The notification `object` contains the completed `URLSessionTask`. public static let DidComplete = Notification.Name(rawValue: "org.alamofire.notification.name.task.didComplete") } } // MARK: - extension Notification { /// Used as a namespace for all `Notification` user info dictionary keys. public struct Key { /// User info dictionary key representing the `URLSessionTask` associated with the notification. public static let Task = "org.alamofire.notification.key.task" } }
lgpl-3.0
76f33cec230ff34756bd97d41fcb24a5
50.019231
123
0.740671
4.638112
false
false
false
false
ChenYilong/CYLTabBarController
Example-Swift/View/CYLPlusButtonSubclass.swift
1
2917
// // CYLPlusButtonSubclass.swift // // v1.16.0 Created by 微博@iOS程序犭袁 ( http://weibo.com/luohanchenyilong/ ) on 10/20/15. // Copyright © 2018 https://github.com/ChenYilong . All rights reserved. // import UIKit import CYLTabBarController class CYLPlusButtonSubclass: CYLPlusButton,CYLPlusButtonSubclassing { static func plusButton() -> Any! { let button = CYLPlusButtonSubclass() button.setImage(UIImage(named: "post_normal"), for: .normal) button.titleLabel?.textAlignment = .center button.titleLabel?.font = UIFont.systemFont(ofSize: 10) button.setTitle("发布", for: .normal) button.setTitleColor(UIColor.gray, for: .normal) button.setTitle("选中", for: .selected) button.setTitleColor(UIColor.blue, for: .selected) button.adjustsImageWhenHighlighted = false button.sizeToFit() // button.addTarget(self, action: #selector(testClick(sender:)), for: .touchUpInside) return button } // @objc static func testClick(sender: UIButton){ // print("testClick") // } static func indexOfPlusButtonInTabBar() -> UInt { return 2 } static func multiplier(ofTabBarHeight tabBarHeight: CGFloat) -> CGFloat { return 0.3 } static func constantOfPlusButtonCenterYOffset(forTabBarHeight tabBarHeight: CGFloat) -> CGFloat { return -10 } static func plusChildViewController() -> UIViewController! { let vc = PublishViewController() let nav = UINavigationController(rootViewController: vc) return nav } static func shouldSelectPlusChildViewController() -> Bool { return true } override func layoutSubviews() { super.layoutSubviews() // tabbar UI layout setup let imageViewEdgeWidth:CGFloat = self.bounds.size.width * 0.7 let imageViewEdgeHeight:CGFloat = imageViewEdgeWidth * 0.9 let centerOfView = self.bounds.size.width * 0.5 let labelLineHeight = self.titleLabel!.font.lineHeight let verticalMargin = (self.bounds.size.height - labelLineHeight - imageViewEdgeHeight ) * 0.5 let centerOfImageView = verticalMargin + imageViewEdgeHeight * 0.5 let centerOfTitleLabel = imageViewEdgeHeight + verticalMargin * 2 + labelLineHeight * 0.5 + 10 //imageView position layout self.imageView!.bounds = CGRect(x:0, y:0, width:imageViewEdgeWidth, height:imageViewEdgeHeight) self.imageView!.center = CGPoint(x:centerOfView, y:centerOfImageView) //title position layout self.titleLabel!.bounds = CGRect(x:0, y:0, width:self.bounds.size.width,height:labelLineHeight) self.titleLabel!.center = CGPoint(x:centerOfView, y:centerOfTitleLabel) } }
mit
2e590f2e88412d1a327251993369da5f
32.674419
103
0.649171
4.434916
false
false
false
false
jdspoone/Recipinator
RecipeBook/AppDelegate.swift
1
1138
/* Written by Jeff Spooner */ import UIKit import CoreData @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // Instantiate the main window window = UIWindow(frame: UIScreen.main.bounds) // Create a CoreDataController and get the managed object context let coreDataController = CoreDataController() let managedObjectContext = coreDataController.getManagedObjectContext() // Embed the recipe table view controller in a navigation view controller, and set that as the root view controller let navigationViewController = UINavigationController(rootViewController: SearchViewController(context: managedObjectContext)) navigationViewController.navigationBar.isTranslucent = false self.window!.rootViewController = navigationViewController // Make the window key and visible window!.makeKeyAndVisible() return true } }
mit
884b8ccf52e72fda4060cd73e8f3accd
28.947368
142
0.733743
6.287293
false
false
false
false
Zi0P4tch0/CollectionViewLayoutToLayoutTransitions
CollectionViewLayoutToLayoutTransitions/ViewController.swift
1
4740
/////////////////////////////////////////////////////////////////////////////////// // Copyright (c) 2015-2019 Matteo Pacini // // // // 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 class ViewController : UICollectionViewController { //MARK: Properties //Cell class name, without Swift module fileprivate let cellIdentifier = NSStringFromSwiftClass(CollectionViewCell.self)! //MARK: UIViewController override func viewDidLoad() { super.viewDidLoad() self.setup() } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) } override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) { //This is necessary for the layout to honor "itemsPerRow" self.collectionViewLayout.invalidateLayout() } //MARK: Setup fileprivate func setup() { //Background color (as per screenshot) self.collectionView!.backgroundColor = UIColor(red: 0.85, green: 0.85, blue: 0.85, alpha: 1) //Title (random) self.navigationItem.title = "Whatever" //Register cell nib let nib = UINib(nibName: "CollectionViewCell", bundle: Bundle.main) self.collectionView!.register(nib, forCellWithReuseIdentifier: cellIdentifier) //If we're on the normal layout, we add a bar button item, //whose action pushes a copy of this view controller with the expanded //layout. if let _ = self.collectionViewLayout as? CollectionViewFlowLayout { let bbi = UIBarButtonItem(title: "Change Layout", style: UIBarButtonItem.Style.plain, target: self, action: #selector(ViewController.changeLayout)) self.navigationItem.setLeftBarButton(bbi, animated: false) } } //MARK: UICollectionViewDataSource override func collectionView( _ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return 27 //Random } override func collectionView( _ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell( withReuseIdentifier: self.cellIdentifier, for: indexPath) as! CollectionViewCell return cell } //MARK: Change Layout @objc func changeLayout() { let nextVC = ViewController(collectionViewLayout : CollectionViewExpandedFlowLayout()) //This performs some kind of witchcraft underneath. nextVC.useLayoutToLayoutNavigationTransitions = true self.navigationController?.pushViewController(nextVC, animated: true) } }
mit
10805658d562b8eb7ffccd7b36b12e55
35.461538
112
0.547046
6.220472
false
false
false
false
kujenga/CoreDataIssue
Entity/Persistence.swift
1
1855
// // Persistence.swift // Entity // // Created by Aaron Taylor on 3/27/15. // Copyright (c) 2015 Aaron Taylor. All rights reserved. // import Foundation import Cocoa import CoreData struct Persistence { // handles unwrapping passed in MOC, or returns the default AppDelegate MOC private static func validateMOC(mocIn: NSManagedObjectContext?) -> NSManagedObjectContext { if let moc = mocIn { return moc } else { let appDel = NSApplication.sharedApplication().delegate as AppDelegate return appDel.managedObjectContext! } } private static func saveMOC(moc: NSManagedObjectContext, funcName: String) { var err = NSErrorPointer() moc.save(err) if err != nil { NSLog("%@: Error saving Managed Object Context: %@", funcName, err.memory!) } } static func createFile(mocIn: NSManagedObjectContext?, name: NSString) { let moc = self.validateMOC(mocIn) let newEntity: AnyObject = NSEntityDescription.insertNewObjectForEntityForName("File", inManagedObjectContext: moc) let newFile = newEntity as File newFile.name = name self.saveMOC(moc, funcName: __FUNCTION__) } static func getAllFiles(mocIn: NSManagedObjectContext?) -> [File]? { let moc = self.validateMOC(mocIn) var fetchRequest = NSFetchRequest(entityName: "File") var err = NSErrorPointer() let results = moc.executeFetchRequest(fetchRequest, error: err) if err != nil { NSLog("%@ fetch request error: %@", __FUNCTION__, err.memory!) return nil } if let r = results { if r.count > 0 { return r as? [File] } } return nil } }
mit
daa9f8046afb8d88e0a504e853d97556
29.42623
123
0.596765
5.013514
false
false
false
false
NemProject/NEMiOSApp
NEMWallet/Application/Settings/SettingsAddServerViewController.swift
1
5184
// // SettingsAddServerViewController.swift // // This file is covered by the LICENSE file in the root of this project. // Copyright (c) 2016 NEM // import UIKit /// The view controller that lets the user add a new server. final class SettingsAddServerViewController: UITableViewController { // MARK: - View Controller Outlets @IBOutlet weak var protocolTypeTextField: UITextField! @IBOutlet weak var addressTextField: UITextField! @IBOutlet weak var portTextField: UITextField! // MARK: - View Controller Lifecycle override func viewDidLoad() { super.viewDidLoad() updateViewControllerAppearance() } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { switch indexPath.row { case 0: protocolTypeTextField.becomeFirstResponder() case 1: addressTextField.becomeFirstResponder() case 2: portTextField.becomeFirstResponder() default: break } } // MARK: - View Controller Helper Methods /// Updates the appearance (coloring, titles) of the view controller. fileprivate func updateViewControllerAppearance() { title = "ADD_SERVER".localized() protocolTypeTextField.placeholder = "http" addressTextField.placeholder = "10.10.100.1" portTextField.placeholder = "7890" protocolTypeTextField.text = "http" portTextField.text = "7890" } /** Shows an alert view controller with the provided alert message. - Parameter message: The message that should get shown. - Parameter completion: An optional action that should get performed on completion. */ fileprivate func showAlert(withMessage message: String, completion: ((Void) -> Void)? = nil) { let alert = UIAlertController(title: "INFO".localized(), message: message, preferredStyle: UIAlertControllerStyle.alert) alert.addAction(UIAlertAction(title: "OK".localized(), style: UIAlertActionStyle.default, handler: { (action) -> Void in alert.dismiss(animated: true, completion: nil) completion?() })) present(alert, animated: true, completion: nil) } // MARK: - View Controller Outlet Actions @IBAction func cancel(_ sender: UIBarButtonItem) { performSegue(withIdentifier: "unwindToServerViewController", sender: nil) } @IBAction func save(_ sender: UIBarButtonItem) { guard protocolTypeTextField.text != nil else { showAlert(withMessage: NSLocalizedString("FIELDS_EMPTY_ERROR", comment: "Description")) return } guard addressTextField.text != nil else { showAlert(withMessage: NSLocalizedString("FIELDS_EMPTY_ERROR", comment: "Description")) return } guard portTextField.text != nil else { showAlert(withMessage: NSLocalizedString("FIELDS_EMPTY_ERROR", comment: "Description")) return } guard protocolTypeTextField.text! != "" && addressTextField.text! != "" && portTextField.text! != "" else { showAlert(withMessage: NSLocalizedString("FIELDS_EMPTY_ERROR", comment: "Description")) return } guard protocolTypeTextField.text!.lowercased() == "http" || protocolTypeTextField.text!.lowercased() == "https" else { showAlert(withMessage: NSLocalizedString("SERVER_PROTOCOL_NOT_AVAILABLE", comment: "Description")) return } let protocolType = protocolTypeTextField.text! let address = addressTextField.text! let port = portTextField.text! do { let _ = try SettingsManager.sharedInstance.validateServerExistence(forServerWithAddress: address) SettingsManager.sharedInstance.create(server: address, withProtocolType: protocolType, andPort: port, completion: { [unowned self] (result) in switch result { case .success: self.performSegue(withIdentifier: "unwindToServerViewController", sender: nil) case .failure: self.showAlert(withMessage: "Couldn't create server") } }) } catch ServerAdditionValidation.serverAlreadyPresent(let serverAddress) { showAlert(withMessage: "Server with address \(serverAddress) already exists") } catch { return } } @IBAction func textFieldDidEndOnExit(_ sender: UITextField) { switch sender { case protocolTypeTextField: addressTextField.becomeFirstResponder() case addressTextField: portTextField.becomeFirstResponder() case portTextField: portTextField.endEditing(true) default: break } } }
mit
75711c197c70ff0a2b996d39c4488d71
34.027027
154
0.60706
5.69045
false
false
false
false
theniceboy/SBGestureTableView
SBGestureTableView/SBGestureTableViewCell.swift
1
8937
// // SBGestureTableViewCell.swift // SBGestureTableView-Swift // // Created by Ben Nichols on 10/3/14. // Copyright (c) 2014 Stickbuilt. All rights reserved. // import UIKit class SBGestureTableViewCell: UITableViewCell, UIGestureRecognizerDelegate { var actionIconsFollowSliding = true var actionIconsMargin: CGFloat = 20.0 var actionNormalColor = UIColor(white: 0.85, alpha: 1) var leftSideView = SBGestureTableViewCellSideView() var rightSideView = SBGestureTableViewCellSideView() var firstLeftAction: SBGestureTableViewCellAction? { didSet { if (firstLeftAction?.fraction == 0) { firstLeftAction?.fraction = 0.3 } } } var secondLeftAction: SBGestureTableViewCellAction? { didSet { if (secondLeftAction?.fraction == 0) { secondLeftAction?.fraction = 0.7 } } } var firstRightAction: SBGestureTableViewCellAction? { didSet { if (firstRightAction?.fraction == 0) { firstRightAction?.fraction = 0.3 } } } var secondRightAction: SBGestureTableViewCellAction? { didSet { if (secondRightAction?.fraction == 0) { secondRightAction?.fraction = 0.7 } } } var currentAction: SBGestureTableViewCellAction? override var center: CGPoint { get { return super.center } set { super.center = newValue updateSideViews() } } override var frame: CGRect { get { return super.frame } set { super.frame = newValue updateSideViews() } } private var gestureTableView: SBGestureTableView! private let panGestureRecognizer = UIPanGestureRecognizer() func setup() { panGestureRecognizer.addTarget(self, action: "slideCell:") panGestureRecognizer.delegate = self addGestureRecognizer(panGestureRecognizer) } required init(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setup() } override init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) setup() } override func didMoveToSuperview() { gestureTableView = superview?.superview as? SBGestureTableView } func percentageOffsetFromCenter() -> (Double) { let diff = fabs(frame.size.width/2 - center.x); return Double(diff / frame.size.width); } func percentageOffsetFromEnd() -> (Double) { let diff = fabs(frame.size.width/2 - center.x); return Double((frame.size.width - diff) / frame.size.width); } override func gestureRecognizer(gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWithGestureRecognizer otherGestureRecognizer: UIGestureRecognizer) -> Bool { return false } override func gestureRecognizerShouldBegin(gestureRecognizer: UIGestureRecognizer) -> Bool { if gestureRecognizer.isKindOfClass(UIPanGestureRecognizer) { let panGestureRecognizer = gestureRecognizer as! UIPanGestureRecognizer let velocity = panGestureRecognizer.velocityInView(self) let horizontalLocation = panGestureRecognizer.locationInView(self).x if fabs(velocity.x) > fabs(velocity.y) && horizontalLocation > CGFloat(gestureTableView.edgeSlidingMargin) && horizontalLocation < frame.size.width - CGFloat(gestureTableView.edgeSlidingMargin) && gestureTableView.isEnabled { return true; } } else if gestureRecognizer.isKindOfClass(UILongPressGestureRecognizer) { if gestureTableView.didMoveCellFromIndexPathToIndexPathBlock == nil { return true; } } return false; } func actionForCurrentPosition() -> SBGestureTableViewCellAction? { let fraction = fabs(frame.origin.x/frame.size.width) if frame.origin.x > 0 { if secondLeftAction != nil && fraction > secondLeftAction!.fraction { return secondLeftAction! } else if firstLeftAction != nil && fraction > firstLeftAction!.fraction { return firstLeftAction! } } else if frame.origin.x < 0 { if secondRightAction != nil && fraction > secondRightAction!.fraction { return secondRightAction! } else if firstRightAction != nil && fraction > firstRightAction!.fraction { return firstRightAction! } } return nil } func performChanges() { let action = actionForCurrentPosition() if let action = action { if frame.origin.x > 0 { leftSideView.backgroundColor = action.color leftSideView.iconImageView.image = action.icon } else if frame.origin.x < 0 { rightSideView.backgroundColor = action.color rightSideView.iconImageView.image = action.icon } } else { if frame.origin.x > 0 { leftSideView.backgroundColor = actionNormalColor leftSideView.iconImageView.image = firstLeftAction!.icon } else if frame.origin.x < 0 { rightSideView.backgroundColor = actionNormalColor rightSideView.iconImageView.image = firstRightAction!.icon } } if let image = leftSideView.iconImageView.image { leftSideView.iconImageView.alpha = frame.origin.x / (actionIconsMargin*2 + image.size.width) } if let image = rightSideView.iconImageView.image { rightSideView.iconImageView.alpha = -(frame.origin.x / (actionIconsMargin*2 + image.size.width)) } if currentAction != action { action?.didHighlightBlock?(gestureTableView, self) currentAction?.didUnhighlightBlock?(gestureTableView, self) currentAction = action } } func hasAnyLeftAction() -> Bool { return firstLeftAction != nil || secondLeftAction != nil } func hasAnyRightAction() -> Bool { return firstRightAction != nil || secondRightAction != nil } func setupSideViews() { leftSideView.iconImageView.contentMode = actionIconsFollowSliding ? UIViewContentMode.Right : UIViewContentMode.Left rightSideView.iconImageView.contentMode = actionIconsFollowSliding ? UIViewContentMode.Left : UIViewContentMode.Right superview?.insertSubview(leftSideView, atIndex: 0) superview?.insertSubview(rightSideView, atIndex: 0) } func slideCell(panGestureRecognizer: UIPanGestureRecognizer) { if !hasAnyLeftAction() || !hasAnyRightAction() { return } var horizontalTranslation = panGestureRecognizer.translationInView(self).x if panGestureRecognizer.state == UIGestureRecognizerState.Began { setupSideViews() } else if panGestureRecognizer.state == UIGestureRecognizerState.Changed { if (!hasAnyLeftAction() && frame.size.width/2 + horizontalTranslation > frame.size.width/2) || (!hasAnyRightAction() && frame.size.width/2 + horizontalTranslation < frame.size.width/2) { horizontalTranslation = 0 } performChanges() center = CGPointMake(frame.size.width/2 + horizontalTranslation, center.y) } else if panGestureRecognizer.state == UIGestureRecognizerState.Ended { if (currentAction == nil && frame.origin.x != 0) || !gestureTableView.isEnabled { gestureTableView.cellReplacingBlock?(gestureTableView, self) } else { currentAction?.didTriggerBlock(gestureTableView, self) } currentAction = nil } } func updateSideViews() { leftSideView.frame = CGRectMake(0, frame.origin.y, frame.origin.x, frame.size.height) if let image = leftSideView.iconImageView.image { leftSideView.iconImageView.frame = CGRectMake(actionIconsMargin, 0, max(image.size.width, leftSideView.frame.size.width - actionIconsMargin*2), leftSideView.frame.size.height) } rightSideView.frame = CGRectMake(frame.origin.x + frame.size.width, frame.origin.y, frame.size.width - (frame.origin.x + frame.size.width), frame.size.height) if let image = rightSideView.iconImageView.image { rightSideView.iconImageView.frame = CGRectMake(rightSideView.frame.size.width - actionIconsMargin, 0, min(-image.size.width, actionIconsMargin*2 - rightSideView.frame.size.width), rightSideView.frame.size.height) } } }
mit
5f9fdc25375ab5775a321cca42a09f68
38.901786
224
0.631532
5.074957
false
false
false
false
lightsprint09/LADVSwift
LADVSwift/Athelt+JSONDecodeable.swift
1
686
// // Athelte+JSONDecodeable.swift // Leichatletik // // Created by Lukas Schmidt on 28.01.17. // Copyright © 2017 freiraum. All rights reserved. // import Foundation extension Athlete: JSONCodable { public init(object: JSONObject) throws { let decoder = JSONDecoder(object: object) id = try decoder.decode("id") athletnumber = try decoder.decode("athletnumber") firstname = try decoder.decode("forename") lastname = try decoder.decode("surname") gender = Gender(string: try decoder.decode("sex"))! yearOfBirth = try decoder.decode("birthyear") allClubs = [try? Club(object: object)].compactMap { $0 } } }
mit
35610a941f8d46f3ecdad64fa48d5a0c
28.782609
64
0.654015
3.959538
false
false
false
false
sevenapps/SVNiOSBootstraper
SVNBootstraper/Reachable.swift
1
1354
// // Reachable.swift // SwiftApp // // Created by Aaron bikis on 8/25/16. // Copyright © 2016 Aaron bikis. All rights reserved. // import UIKit public struct ReachableErrorAlert: SVNAlert { public var title: String = "Your internet seems to be unreachable" public var message: String = "Please check your connection and try again." } public protocol Reachable: Alertable {} extension Reachable where Self: UIViewController { /** Tests the user's internet connection - callback: isReachable *Bool* returns when the user's internet connection is ascertained */ func testConnection(_ callback:@escaping (_ isReachable:Bool) ->()){ let reachability = Reachability()! reachability.whenReachable = { reachability in // this is called on a background thread, but UI updates must // be on the main thread, like this: DispatchQueue.main.async { callback(true) } } reachability.whenUnreachable = { reachability in // this is called on a background thread, but UI updates must // be on the main thread, like this: DispatchQueue.main.async { self.show(alertWithType: ReachableErrorAlert(), withCompletionHandler: nil) callback(false) } } do { try reachability.startNotifier() } catch { callback(false) } } }
apache-2.0
686bb08ab77d70adf9a37f153a3a2ae2
26.06
92
0.671101
4.480132
false
false
false
false
joshdholtz/Few.swift
FewCore/RealizedElement.swift
1
3364
// // RealizedElement.swift // Few // // Created by Josh Abernathy on 2/13/15. // Copyright (c) 2015 Josh Abernathy. All rights reserved. // import Foundation internal func indexOfObject<T: AnyObject>(array: [T], element: T) -> Int? { for (i, e) in enumerate(array) { if element === e { return i } } return nil } public class RealizedElement { public var element: Element public let view: ViewType? public weak var parent: RealizedElement? internal var children: [RealizedElement] = [] private var layoutFrame: CGRect private var needsLayout = true public init(element: Element, view: ViewType?, parent: RealizedElement?) { self.element = element self.view = view self.parent = parent layoutFrame = element.frame } public func addRealizedChild(child: RealizedElement, index: Int?) { if let index = index { children.insert(child, atIndex: index) } else { children.append(child) } addRealizedViewForChild(child) } public func addRealizedViewForChild(child: RealizedElement) { if child.view == nil { child.element.elementDidRealize(child) return } let viewParent = child.findViewParent() viewParent?.view?.addSubview(child.view!) child.element.elementDidRealize(child) } private func findViewParent() -> RealizedElement? { var currentParent: RealizedElement? = parent while let p = currentParent { if p.view != nil { return p } currentParent = p.parent } return nil } public func remove() { for child in children { child.remove() } view?.removeFromSuperview() element.derealize() parent?.removeRealizedChild(self) parent = nil } private final func removeRealizedChild(child: RealizedElement) { if let index = indexOfObject(children, child) { children.removeAtIndex(index) } } public final func markNeedsLayout() { needsLayout = true if let parent = parent where !parent.needsLayout { parent.markNeedsLayout() } } private final func layoutIfNeeded(maxWidth: CGFloat) { if !needsLayout { return } let node = element.assembleLayoutNode() let layout = node.layout(maxWidth: maxWidth) applyLayout(layout, offset: CGPointZero) } internal func realizedElementForElement(element: Element) -> RealizedElement? { for child in children { if child.element === element { return child } } return nil } internal func layoutFromRoot() { if let root = findRoot() { if root.element.isRendering && root !== self { return } root.layoutIfNeeded(root.element.frame.size.width) } else { layoutIfNeeded(element.frame.size.width) } } internal final func findRoot() -> RealizedElement? { if element.isRoot { return self } else { return parent?.findRoot() } } private final func applyLayout(layout: Layout, offset: CGPoint) { var transformedFrame = layout.frame transformedFrame.origin.x += offset.x transformedFrame.origin.y += offset.y layoutFrame = transformedFrame let childOffset: CGPoint if let view = view { // If we have a view then children won't need to be offset at all. childOffset = CGPointZero view.frame = layoutFrame.integerRect } else { childOffset = layoutFrame.origin } for (child, layout) in Zip2(children, layout.children) { child.applyLayout(layout, offset: childOffset) } element.elementDidLayout(self) needsLayout = false } }
mit
02192b87048df774cb30201971c805e2
20.986928
80
0.706005
3.48601
false
false
false
false
sundusk/Dazzle-light
QwQ/QwQ/Tools/XMToastView.swift
1
4371
// // XMToastView.swift // XMSwift // // Created by mifit on 16/9/19. // Copyright © 2016年 Mifit. All rights reserved. // import UIKit let kXMToastView_fontSize :CGFloat = 14.0 let kXMToastView_width = 200 let kMax_ConstrainedSize = CGSize(width: 200, height:100) class XMToastView: UIView { private var bgColor :CGColor? private var infoShow :NSString? private var fontSize :CGSize? /* // Only override draw() if you perform custom drawing. // An empty implementation adversely affects performance during animation. override func draw(_ rect: CGRect) { // Drawing code } */ private init(frame: CGRect, bgColor: CGColor, info: String) { let viewRect = CGRect(x: 0, y: 0, width: frame.size.width*1.2, height: frame.size.height*1.2) super.init(frame: viewRect) self.backgroundColor = UIColor.clear self.bgColor = bgColor infoShow = info as NSString? fontSize = frame.size } required init?(coder aDecoder: NSCoder) { //fatalError("init(coder:) has not been implemented") super.init(coder: aDecoder) } override func draw(_ rect: CGRect) { let context = UIGraphicsGetCurrentContext() context!.setAlpha(0.8) self.addRoundRectToPath(context: context!, rect: rect, width: 4.0, height: 4.0) context!.setFillColor(bgColor!) context!.fillPath() context!.setAlpha(1.0) context!.setShadow(offset: CGSize(width: 0, height: -1), blur: 1, color: UIColor.white.cgColor) context!.setFillColor(UIColor.black.cgColor) let x = (rect.size.width - (fontSize?.width)!) / 2.0 let y = (rect.size.height - (fontSize?.height)!) / 2.0 let r = CGRect(x: x, y: y, width: fontSize!.width, height: fontSize!.height) let attrs = [NSFontAttributeName:UIFont.systemFont(ofSize: kXMToastView_fontSize),NSBaselineOffsetAttributeName:1] as [String : Any] infoShow?.draw(with: r, options: .usesLineFragmentOrigin, attributes: attrs, context: nil) } //MARK: - public class func showInfo(info: String, bgColor color: UIColor,inView view: UIView,vertical height: Float) { let h = height < 0 ? 0 : height > 1 ? 1 : height; let temInfo :NSString = info as NSString let attributes = [NSFontAttributeName:UIFont.systemFont(ofSize: kXMToastView_fontSize)] var frame = temInfo.boundingRect(with: kMax_ConstrainedSize, options: .truncatesLastVisibleLine, attributes:attributes , context: nil) frame.origin = CGPoint(x: 0, y: 0) let alert = XMToastView(frame: frame, bgColor: color.cgColor, info: info) alert.center = CGPoint(x: view.center.x, y: view.frame.size.height*CGFloat(h)) alert.alpha = 0; view .addSubview(alert) UIView.animate(withDuration: 0.4) { alert.alpha = 1.0 } alert.perform(#selector(fadeAway), with: nil, afterDelay: 1.5) } //MARK: - private private func addRoundRectToPath(context: CGContext, rect: CGRect, width: Float, height: Float) { if width == 0 || height == 0 { context.addRect(rect) return } var fw :CGFloat = 0.0 var fh :CGFloat = 0.0 context.saveGState() context.translateBy(x: rect.minX, y: rect.minY) context.scaleBy(x: CGFloat(width), y: CGFloat(height)) fw = rect.width / CGFloat(width) fh = rect.height / CGFloat(height) context.move(to: CGPoint(x: fw, y: fh/2)) context.addArc(tangent1End: CGPoint(x: fw, y:fh), tangent2End: CGPoint(x: fw/2, y:fh), radius: 1) context.addArc(tangent1End: CGPoint(x: 0, y:fh), tangent2End: CGPoint(x: 0, y:fh/2), radius: 1) context.addArc(tangent1End: CGPoint(x: 0, y:0), tangent2End: CGPoint(x: fw/2, y:0), radius: 1) context.addArc(tangent1End: CGPoint(x: fw, y:0), tangent2End: CGPoint(x: fw, y:fh/2), radius: 1) context.closePath() context.restoreGState() } func fadeAway() { UIView.animate(withDuration: 1.5) { self.alpha = 0 } self.perform(#selector(removeAway), with: nil, afterDelay: 1.5) } func removeAway() { self.removeFromSuperview() } }
mit
37f4691e8feff1a6e30248a5f75d54bc
36.655172
142
0.617445
3.788378
false
false
false
false
sigmonky/hearthechanges
iHearChangesSwift/MidiManager.swift
1
4951
// // MidiGenerator.swift // iHearChangesSwift // // Created by Randy Weinstein on 6/30/17. // Copyright © 2017 fakeancient. All rights reserved. // import Foundation import MIKMIDI import AVFoundation class MidiManager { var loopRange:Int = 0 var newLoopRange = 0 var trackNumbers = [Int]() let synthesizer = MIKMIDISynthesizer() var sequence = MIKMIDISequence() var sequencer = MIKMIDISequencer() func renderProgressionToMidi(piano:Player, bass:Player) { for aChord in piano.performance { let firstChord = (aChord as! NSArray) as Array let beat = firstChord[0] let notesInChord = (firstChord[1] as! NSArray) as Array let duration = firstChord[2] print("starting beat for chord \(beat)") print("chord notes \(notesInChord)") print("chord duration \(duration)") } for aChord in bass.performance { let firstChord = (aChord as! NSArray) as Array let beat = firstChord[0] let notesInChord = (firstChord[1] as! NSArray) as Array let duration = firstChord[2] print(beat) print(notesInChord) print(duration) } sequencer.tempo = 120.0 let endTimeStamp = Float(bass.performance.count) * 4.0 loopRange = bass.performance.count * 4 newLoopRange = loopRange sequencer.setLoopStartTimeStamp(0.0, endTimeStamp: MusicTimeStamp(endTimeStamp)) sequencer.shouldLoop = true for track in sequence.tracks { sequence.removeTrack(track) } sequencer.sequence = sequence buildMidiTrack(forVoice: 0, withInstrument: 18,thePerformer:bass) buildMidiTrack(forVoice: 0, withInstrument: 18,thePerformer:piano) buildMidiTrack(forVoice: 1, withInstrument: 32,thePerformer:piano) buildMidiTrack(forVoice: 2, withInstrument: 70,thePerformer:piano) buildMidiTrack(forVoice: 3, withInstrument: 70,thePerformer:piano) sequence.tracks[0].isMuted = true if let trackNumber = addTrackWithSoundFont("rhodes_73", presetID: 0) , trackNumber > -1 { let track = sequence.tracks[trackNumber] var timeStamp = 0.0 for _ in 0..<bass.performance.count { let note = MIKMIDINoteEvent(timeStamp: timeStamp,note:0,velocity:0,duration:4.0,channel:0) track.addEvents([note]) timeStamp += 4.0 } } } func buildMidiTrack(forVoice:Int, withInstrument:Int, thePerformer:Player) { if let trackNumber = addTrackWithSoundFont("rhodes_73", presetID: UInt8(withInstrument) ) , trackNumber > -1 { trackNumbers.append(trackNumber) let track = sequence.tracks[trackNumber] for aChord in thePerformer.performance { let firstChord = (aChord as! NSArray) as Array let beat = firstChord[0] as! MusicTimeStamp let notesInChord = (firstChord[1] as! NSArray) as Array let duration = firstChord[2] as! Float32 if forVoice < notesInChord.count { if let midiNoteNumber:UInt8 = notesInChord[forVoice].uint8Value { let newNote = MIKMIDINoteEvent(timeStamp: beat, note:midiNoteNumber, velocity:127, duration:duration, channel:0) track.addEvents([newNote]) } } } } } func addTrackWithSoundFont(_ soundFontFile:String, presetID:UInt8)-> Int? { var trackNumber:Int? = -1 do { let _ = try sequence.addTrack() let track = sequence.tracks[sequence.tracks.count - 1] let trackSynth = sequencer.builtinSynthesizer(for: track) if let soundfont = Bundle.main.url(forResource: soundFontFile, withExtension: "sf2") { do { try trackSynth?.loadSoundfontFromFile(at: soundfont) trackNumber = sequence.tracks.count - 1 } catch { } } } catch { } return trackNumber } }
mit
bd9455081274da8c8446d0020f64c4ba
31.142857
116
0.510707
4.920477
false
false
false
false
Stamates/30-Days-of-Swift
src/Day 6 - While Loops.playground/section-1.swift
2
1080
// Playground - noun: a place where people can play import UIKit var str = "Hello, playground" var someTrueThing = true someTrueThing == true var someInt = 10 while someInt < 20 { // run some code someInt++ // println("hello") } someInt var numLoops = 0 runTheLoop: while someInt < 10 { numLoops++ someInt += 3 // println(someInt) switch numLoops { case 0...100: println(someInt) if someInt % 2 == 0 { println("\(someInt) is even") continue runTheLoop } else if someInt % 5 == 0 { println("\(someInt) is divisible by 5") // break runTheLoop } case 101...1000: println("something else") default: println("this is the default") } } var abc = 3 while abc < 1000000000 { println("\(abc)") abc = abc * abc * abc } var theList = ["abc", "Justin", "jack", "john", "abby", "jill"] theList.count while theList.count < 10 { theList.append("Another Name") } theList println(theList[0..<4]) println(theList[0...3])
apache-2.0
cf9c820c6a286375c0668d9f84a809ec
14.211268
63
0.57037
3.564356
false
false
false
false
tus/TUSKit
Tests/TUSKitTests/TUSClient/TUSClientInternalTests.swift
1
3611
// // TUSClientInternalTests.swift // // // Created by Tjeerd in ‘t Veen on 01/10/2021. // import XCTest @testable import TUSKit // These tests are for when you want internal access for testing. Please prefer to use TUSClientTests for closer to real-world testing. final class TUSClientInternalTests: XCTestCase { var client: TUSClient! var tusDelegate: TUSMockDelegate! var relativeStoragePath: URL! var fullStoragePath: URL! var data: Data! var files: Files! override func setUp() { super.setUp() do { relativeStoragePath = URL(string: "TUSTEST")! let docDir = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0] fullStoragePath = docDir.appendingPathComponent(relativeStoragePath.absoluteString) files = try Files(storageDirectory: fullStoragePath) clearDirectory(dir: fullStoragePath) data = Data("abcdef".utf8) client = makeClient(storagePath: relativeStoragePath) tusDelegate = TUSMockDelegate() client.delegate = tusDelegate } catch { XCTFail("Could not instantiate Files \(error)") } MockURLProtocol.reset() } override func tearDown() { super.tearDown() MockURLProtocol.reset() clearDirectory(dir: fullStoragePath) let cacheDir = FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask)[0] clearDirectory(dir: cacheDir) do { try client.reset() } catch { // Some dirs may not exist, that's fine. We can ignore the error. } } @discardableResult private func storeFiles() throws -> UploadMetadata { let id = UUID() let path = try files.store(data: data, id: id) return UploadMetadata(id: id, filePath: path, uploadURL: URL(string: "io.tus")!, size: data.count, customHeaders: [:], mimeType: nil) } func testClientDoesNotDeleteUploadedFilesOnStartup() throws { var contents = try FileManager.default.contentsOfDirectory(at: fullStoragePath, includingPropertiesForKeys: nil) XCTAssert(contents.isEmpty) try storeFiles() contents = try FileManager.default.contentsOfDirectory(at: fullStoragePath, includingPropertiesForKeys: nil) XCTAssertFalse(contents.isEmpty) client = makeClient(storagePath: fullStoragePath) contents = try FileManager.default.contentsOfDirectory(at: fullStoragePath, includingPropertiesForKeys: nil) XCTAssertFalse(contents.isEmpty, "Expected client to NOT clear unfinished uploaded metadata") } func testClientDeletesUploadedFilesOnStartup() throws { var contents = try FileManager.default.contentsOfDirectory(at: fullStoragePath, includingPropertiesForKeys: nil) XCTAssert(contents.isEmpty) let finishedMetadata = try storeFiles() finishedMetadata.uploadedRange = 0..<data.count try files.encodeAndStore(metaData: finishedMetadata) contents = try FileManager.default.contentsOfDirectory(at: fullStoragePath, includingPropertiesForKeys: nil) XCTAssertFalse(contents.isEmpty) client = makeClient(storagePath: fullStoragePath) contents = try FileManager.default.contentsOfDirectory(at: fullStoragePath, includingPropertiesForKeys: nil) XCTAssert(contents.isEmpty, "Expected client to clear finished uploaded metadata") } }
mit
d7b08acbc621f850bda42dde25b3061c
38.228261
159
0.665558
5.260933
false
true
false
false
manavgabhawala/MGDocIt
MGDocIt/MGDocIt.swift
1
14407
// // MGDocItExtension.swift // MGDocIt // // Created by Manav Gabhawala on 14/08/15. // Copyright © 2015 Manav Gabhawala. All rights reserved. // import Foundation import Carbon.HIToolbox extension MGDocIt { /// Call this function when the text's storage has changed. This function handles accepting a trigger and then determines which sub handler to invoke based on the language /// /// - Parameter file: This is a parameter of type `NSURL`. The file that is currently open in the editor. This is used to determine the sub handler to call for the language. /// - Parameter textStorage: This is a parameter of type `NSTextView`. The TextView whose storage was changed. /// func handleStorageChange(file: NSURL, textStorage: NSTextView) { if mainMonitor == nil { mainMonitor = NSEvent.addLocalMonitorForEventsMatchingMask(NSEventMask.KeyDownMask, handler: { (event) -> NSEvent? in let trigger = MGDocItSetting.triggerString let triggerChar = trigger.substringFromIndex(trigger.endIndex.predecessor()).utf8.first!.value if event.type == .KeyDown && self.keyCodeForChar(Int8(triggerChar)) == event.keyCode { self.lastCharTyped = true } else { self.lastCharTyped = false } return event }) } guard lastCharTyped else { return } guard let currentLine = textStorage.textResultOfCurrentLine() else { // No current line return } currentLine.string.trimWhitespaceOnLeft() let trigger = MGDocItSetting.triggerString let triggerLength = trigger.characters.count guard currentLine.string.characters.count >= triggerLength else { return } guard currentLine.string == trigger else { // No trigger was entered. return } let cursorPos = textStorage.currentCursorLocation() - triggerLength let textStorageStr = textStorage.textStorage!.string let str = textStorageStr.stringByRemovingRange(textStorageStr.startIndex.advancedBy(cursorPos), end: textStorageStr.startIndex.advancedBy(cursorPos + triggerLength)) // TODO: Add playground support if file.pathExtension == "swift" { handleSwiftStorageChange(textStorage, parsedString: str, cursorPosition: cursorPos) } else { handleNonSwiftStorageChange(textStorage, parsedString: str, cursorPosition: cursorPos) } } /// A sub handler that handles changes for swift source code changes. It communicates with SourceKit to get the AST. /// /// - Parameter textStorage: This is a parameter of type `NSTextView`. The storage who was changed. This parameter is used to pass to the `pasteHeaderDocFor:` function. /// - Parameter str: This is a parameter of type `String`. The string which is swift source code that should be parsed. /// - Parameter cursorPos: This is a parameter of type `Int`. The current position of the cursor offset for the removal of the newly inserted trigger. /// /// func handleSwiftStorageChange(textStorage: NSTextView, parsedString str: String, cursorPosition cursorPos: Int) { dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), { guard self.lock.tryLock() else { return } defer { self.lock.unlock() } let fileToParse = File(contents: str) let response = Request.EditorOpen(fileToParse).send() guard let structure = findAllSubstructures(response, withCursorPosition: cursorPos) else { // Ignore non documentable kinds. return } if let attributes = SwiftDocKey.getAttributes(structure) { for attribute in attributes { guard let attr = SwiftDocKey.getAttribute(attribute as? XPCDictionary) else { print("Unknown attribute found: \(attribute)") continue } guard attr != SwiftDeclarationKind.HeaderDocs else { return } } } let map = SyntaxMap(sourceKitResponse: response) guard let nextTokenIndex = map.tokens.binarySearch({ $0.offset }, compareTo: cursorPos) else { return } let nextToken = map.tokens[nextTokenIndex] guard nextToken.type != .DocComment && nextToken.type != .DocCommentField else { return } if nextTokenIndex > 1 { let previousTokenType = map.tokens[nextTokenIndex - 1].type guard previousTokenType != .DocComment && previousTokenType != .DocCommentField else { return } } let startInd = str.startIndex.advancedBy(nextToken.offset) let nextWord = str.substringWithRange(Range<String.Index>(start: startInd, end: startInd.advancedBy(nextToken.length))) // Since import statements don't show up in the AST. guard nextWord != "import" else { return } guard let type = createSwiftType(SwiftDocKey.getKind(structure)) else { return } let doc = type.init(dict: structure, map: map, stringDelegate: { let startLoc = str.startIndex.advancedBy($0 - 1) let range = Range<String.Index>(start: startLoc, end: startLoc.advancedBy($1)) let str = str.substringWithRange(range) return str }) let indentString = self.calculateIndentString(fromString: str, withOffset: Int(SwiftDocKey.getOffset(structure)!)) self.pasteHeaderDocFor(doc, intoTextStorage: textStorage, withIndentation: indentString) }) } /// A sub handler that handles changes for any non-swift source code changes like C, C++ and ObjC. It communicates with clang and the llvm to get the AST. /// /// - Parameter textStorage: This is a parameter of type `NSTextView`. The storage who was changed. This parameter is used to pass to the `pasteHeaderDocFor:` function. /// - Parameter str: This is a parameter of type `String`. The string which is C, C++ or ObjC source code that should be parsed. /// - Parameter cursorPos: This is a parameter of type `Int`. The current position of the cursor offset for the removal of the newly inserted trigger. func handleNonSwiftStorageChange(textStorage: NSTextView, parsedString str: String, cursorPosition cursorPos: Int) { dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), { guard self.lock.tryLock() else { return } defer { self.lock.unlock() } let clangIndex = clang_createIndex(0, 1) let opts = ["-x", "objective-c"].map { ($0 as NSString).UTF8String } let directory = NSURL(fileURLWithPath: NSTemporaryDirectory()) let manager = NSFileManager() var fileName = NSUUID().UUIDString while manager.fileExistsAtPath(directory.URLByAppendingPathComponent(fileName).path!) { fileName = NSUUID().UUIDString } do { try str.writeToURL(directory.URLByAppendingPathComponent(fileName), atomically: true, encoding: NSUTF8StringEncoding) } catch { return } defer { do { try manager.removeItemAtURL(directory.URLByAppendingPathComponent(fileName)) } catch { } } let unit = clang_parseTranslationUnit(clangIndex, (directory.URLByAppendingPathComponent(fileName).path! as NSString).UTF8String, opts, Int32(opts.count), nil, 0, CXTranslationUnit_None.rawValue) var selectedCursor : CXCursor? var topCursor = clang_getTranslationUnitCursor(unit) clang_visitChildrenWithBlock(topCursor) { cursor, parent in guard Bool(Int(clang_Location_isFromMainFile(clang_getCursorLocation(cursor)))) else { return CXChildVisit_Continue } guard Bool(Int(clang_equalCursors(parent, topCursor))) else { return CXChildVisit_Break } var startOffset : UInt32 = 0 var endOffset: UInt32 = 0 let extents = clang_getCursorExtent(cursor) clang_getSpellingLocation(clang_getRangeStart(extents), nil, nil, nil, &startOffset) clang_getSpellingLocation(clang_getRangeEnd(extents), nil, nil, nil, &endOffset) let start = Int(startOffset) let end = Int(endOffset) print(String(clang_getCursorSpelling(cursor))) guard end > cursorPos else { return CXChildVisit_Continue } guard start >= cursorPos else { topCursor = cursor let range = Range<String.Index>(start: str.startIndex.advancedBy(start - 1), end: str.startIndex.advancedBy(end)) print(str.substringWithRange(range)) print(String(clang_getCursorSpelling(cursor))) return CXChildVisit_Recurse } selectedCursor = cursor return CXChildVisit_Break } guard var selected = selectedCursor else { print("No selected cursor") return } print(String(clang_getCursorSpelling(selected))) let language = clang_getCursorLanguage(selected) if language.rawValue != CXLanguage_ObjC.rawValue && language.rawValue != CXLanguage_Invalid.rawValue { let opt = CXLanguage_C.rawValue == language.rawValue ? "c" : "c++" let newOpt = ["-x", opt].map { ($0 as NSString).UTF8String } let unit = clang_parseTranslationUnit(clangIndex, (directory.URLByAppendingPathComponent(fileName).path! as NSString).UTF8String, newOpt, Int32(newOpt.count), nil, 0, CXTranslationUnit_None.rawValue) let oldSelected = selected selected = clang_getCursor(unit, clang_getCursorLocation(selected)) if clang_getCursorKind(selected).rawValue == CXCursor_UnexposedDecl.rawValue { selected = oldSelected } } var isCommented = false let kind = clang_getCursorKind(selected) clang_visitChildrenWithBlock(selected, { (child, _) -> CXChildVisitResult in guard clang_getCursorKind(child).rawValue == kind.rawValue else { return CXChildVisit_Recurse } guard clang_Comment_getKind(clang_Cursor_getParsedComment(selected)).rawValue == CXComment_Null.rawValue else { isCommented = true return CXChildVisit_Break } return CXChildVisit_Recurse }) let comment = clang_Cursor_getParsedComment(selected) if clang_Comment_getKind(comment).rawValue != CXComment_Null.rawValue { isCommented = true } guard !isCommented else { return } print(String(clang_getCursorSpelling(selected))) // By only using the type we are saving on creating the tokens spuriously. guard let type = createCXType(kind) else { return } let tu = clang_Cursor_getTranslationUnit(selected) let tokens = self.tokenizeTranslationUnit(tu, withRange: clang_getCursorExtent(selected)) var cursorOff : UInt32 = 0 clang_getSpellingLocation(clang_getCursorLocation(selected), nil, nil, nil, &cursorOff) let doc = type.init(cursor: selected, tokens: tokens, translationUnit: tu) let indentString = self.calculateIndentString(fromString: str, withOffset: Int(cursorOff)) self.pasteHeaderDocFor(doc, intoTextStorage: textStorage, withIndentation: indentString) }) } /// This function handles calculating an indent string for any source code. /// /// - Parameter str: This is a parameter of type `String`. The string from which we need to calculate the indentation. This is the entire source code representation. /// - Parameter offset: This is a parameter of type `Int`. The offset is the structure which is being documented's absolute offset in the file. /// /// - Returns: The indent string. This string will either be empty or full of ` ` and `\t` characters. No characters not in the `NSCharacterSet.whitespaceCharacterSet()` will be included. @warn_unused_result func calculateIndentString(fromString str: String, withOffset offset: Int) -> String { let structOffset = str.startIndex.advancedBy(offset) let indentPoint = str.rangeOfCharacterFromSet(NSCharacterSet.newlineCharacterSet(), options: NSStringCompareOptions.BackwardsSearch, range: Range<String.Index>(start: str.startIndex, end: structOffset)) let fullIndentString = str.substringWithRange(Range<String.Index>(start: indentPoint?.endIndex ?? structOffset, end: structOffset)) var endIndex = fullIndentString.startIndex for char in fullIndentString.unicodeScalars { guard NSCharacterSet.whitespaceCharacterSet().longCharacterIsMember(char.value) else { break } endIndex = endIndex.successor() } return fullIndentString.substringWithRange(Range<String.Index>(start: fullIndentString.startIndex, end: endIndex)) } /// Paste's the header documentation into the text storage with the indentation and handles everything from deleting the trigger string, getting the header doc and pasting it in, resetting the pasteboard and then tabbing into the first tokenized field if one exists. /// /// - Parameter document: This is a parameter of type `DocumentType`. The document type using which the documentation string can be calculated. /// - Parameter textStorage: This is a parameter of type `NSTextView`. The text view into which to paste the string and then tab into the first tokenizable field. /// - Parameter indentString: This is a parameter of type `String`. The indentation that should be applied to every line before pasting it in. This is calcualated by the document by using the `documentationWithIndentation:` method. func pasteHeaderDocFor(document: DocumentType, intoTextStorage textStorage: NSTextView, withIndentation indentString: String) { dispatch_sync(dispatch_get_main_queue(), { let pasteboard = NSPasteboard.generalPasteboard() let oldData = pasteboard.stringForType(NSPasteboardTypeString) pasteboard.declareTypes([NSPasteboardTypeString], owner: nil) let docString = document.documentationWithIndentation(indentString) pasteboard.setString(docString, forType: NSPasteboardTypeString) KeyboardSimulator.defaultSimulator().beginKeyboardEvents() self.eventMonitor = NSEvent.addLocalMonitorForEventsMatchingMask(NSEventMask.KeyUpMask, handler: { (event) -> NSEvent? in if event.type == .KeyUp && event.keyCode == UInt16(kVK_Delete) { NSEvent.removeMonitor(self.eventMonitor!) self.eventMonitor = nil let oldCursor = textStorage.currentCursorLocation() self.performPasteAction() pasteboard.setString(oldData ?? "", forType: NSPasteboardTypeString) if docString.rangeOfString("<#") != nil { textStorage.selectedRange = NSRange(location: oldCursor, length: 0) KeyboardSimulator.defaultSimulator().sendKeyCode(kVK_Tab) } KeyboardSimulator.defaultSimulator().endKeyboardEvents() } return event }) KeyboardSimulator.defaultSimulator().sendKeyCode(kVK_Delete, withModifierCommand: true, alt: false, shift: false, control: false) }) } }
mit
cadf516fa76d962fe2acc4dad79de166
35.846547
267
0.723518
3.949013
false
false
false
false
josve05a/wikipedia-ios
Wikipedia/Code/GlobalUserInfoFetcher.swift
2
1685
import Foundation enum GlobalUserInfoFetcherError: Error { case cannotExtractMergedGroups case unableToFindEditCount } class GlobalUserInfoFetcher: Fetcher { func fetchEditCount(guiUser: String, siteURL: URL, completion: @escaping ((Result<Int, Error>) -> Void)) { let parameters = [ "action": "query", "meta": "globaluserinfo", "guiuser": guiUser, "guiprop": "groups|merged|unattached", "format": "json" ] performMediaWikiAPIGET(for: siteURL, with: parameters, cancellationKey: nil) { (result, response, error) in if let error = error { completion(.failure(error)) return } guard let query = result?["query"] as? [String : Any], let userinfo = query["globaluserinfo"] as? [String : Any], let merged = userinfo["merged"] as? [[String: Any]] else { completion(.failure(GlobalUserInfoFetcherError.cannotExtractMergedGroups)) return } for dict in merged { if let responseURLString = dict["url"] as? String, let responseURL = URL(string: responseURLString), siteURL == responseURL, let editCount = dict["editcount"] as? Int { completion(.success(editCount)) return } } completion(.failure(GlobalUserInfoFetcherError.unableToFindEditCount)) } } }
mit
31e5aaca25fad34348015189950e2128
32.7
115
0.511573
5.435484
false
false
false
false
noxytrux/SwiftGeom
Quaternion.swift
1
7410
// // Quaternion.swift // SwiftGeom // // Created by Marcin Pędzimąż on 23.10.2014. // Copyright (c) 2014 Marcin Pedzimaz. All rights reserved. // import UIKit struct Quaternion { var x : Float32 = 0 var y : Float32 = 0 var z : Float32 = 0 var w : Float32 = 0 init() { x = 0 y = 0 z = 0 w = 0 } init(value: Float32) { x = value y = value z = value w = value } init(x:Float32, y:Float32, z:Float32, w:Float32) { self.x = x self.y = y self.z = z self.w = w } init(other: Quaternion) { x = other.x y = other.y z = other.z w = other.w } init(vector: Vector3, w _w: Float32) { x = vector.x y = vector.y z = vector.z w = _w } init(angle: Float32, axis: Vector3) { fromAngleAxis(angle, axis: axis) } } extension Quaternion: Printable { var description: String { return "[\(x),\(y),\(z),\(w)]" } } extension Quaternion { func isFinite() -> Bool { return x.isFinite && y.isFinite && z.isFinite && w.isFinite } mutating func fromAngleAxis(angle: Float32, axis: Vector3 ) { x = axis.x; y = axis.y; z = axis.z; let length = 1.0 / sqrt( x*x + y*y + z*z ) x = x * length; y = y * length; z = z * length; let half = degToRad(angle * 0.5); w = cos(half); let sin_theta_over_two = sin(half); x = x * sin_theta_over_two; y = y * sin_theta_over_two; z = z * sin_theta_over_two; } mutating func invert() { x = -x y = -y z = -z } mutating func negate() { x = -x y = -y z = -z w = -w } mutating func zero() { x = 0 y = 0 z = 0 w = 1 } func isIdentityRotation() -> Bool { return x==0 && y==0 && z==0 && fabsf(w)==1; } func magnitude() -> Float32 { return sqrtf( x*x + y*y + z*z + w*w) } func magnitudeSquared() -> Float32 { return x*x + y*y + z*z + w*w } func getAngle() -> Float32 { return acos(w) * 2.0; } func getAngle(q:Quaternion) -> Float32 { return acos( dot(q) ) * 2.0; } func dot(v:Quaternion) -> Float32 { return x * v.x + y * v.y + z * v.z + w * v.w; } mutating func normalize() { let mag = magnitude(); if mag > 0 { let lenght = 1.0 / mag; x *= lenght; y *= lenght; z *= lenght; w *= lenght; } } mutating func conjugate() { x = -x; y = -y; z = -z; } mutating func set(other: Quaternion) { x = other.x y = other.y z = other.z w = other.w } mutating func slerp(t:Float32, left:Quaternion, right:Quaternion) { let quatEpsilon: Float32 = 1.0e-8 self.set(left) var cosine: Float32 = x * right.x + y * right.y + z * right.z + w * right.w var sign: Float32 = 1.0 if cosine < 0 { cosine = -cosine sign = -1.0 } var sinus: Float32 = 1.0 - cosine*cosine if sinus >= quatEpsilon*quatEpsilon { sinus = sqrt(sinus) var angle = atan2(sinus, cosine) var i_sin_angle = 1 / sinus var lower_weight = sin(angle*(1-t)) * i_sin_angle var upper_weight = sin(angle * t) * i_sin_angle * sign w = (w * (lower_weight)) + (right.w * (upper_weight)) x = (x * (lower_weight)) + (right.x * (upper_weight)) y = (y * (lower_weight)) + (right.y * (upper_weight)) z = (z * (lower_weight)) + (right.z * (upper_weight)) } } mutating func rotate(inout v: Vector3) { var myInverse = Quaternion() myInverse.x = -x myInverse.y = -y myInverse.z = -z myInverse.w = w //v = ((*this) * v) ^ myInverse; var left = self * v v.x = left.w * myInverse.x + myInverse.w * left.x + left.y * myInverse.z - myInverse.y*left.z v.y = left.w * myInverse.y + myInverse.w * left.y + left.z * myInverse.x - myInverse.z*left.x v.z = left.w * myInverse.z + myInverse.w * left.z + left.x * myInverse.y - myInverse.x*left.y } func inverseRotate(inout v: Vector3) { var myInverse = Quaternion() myInverse.x = -x; myInverse.y = -y; myInverse.z = -z; myInverse.w = w; //v = (myInverse * v) ^ (*this); var left = myInverse * v v.x = left.w*x + w*left.x + left.y*z - y*left.z v.y = left.w*y + w*left.y + left.z*x - z*left.x v.z = left.w*z + w*left.z + left.x*y - x*left.y } func rot(v: Vector3) -> Vector3 { var qv = Vector3(x: x,y: y,z: z) var crossDot = (qv.cross(v)) * w + qv * (qv.dot(v)) return (v * (w*w - 0.5) + crossDot) * 2.0 } func invRot(v: Vector3) -> Vector3 { var qv = Vector3(x: x,y: y,z: z) var crossDot = (qv.cross(v)) * w + qv * (qv.dot(v)) return (v * (w*w - 0.5) - crossDot) * 2.0 } func transform(v: Vector3, p: Vector3) -> Vector3 { return rot(v) + p } func invTransform(v: Vector3, p: Vector3) -> Vector3 { return invRot(v - p) } } func * (left: Quaternion, right : Quaternion) -> Quaternion { var a:Float32, b:Float32, c:Float32, d:Float32 a = -left.x*right.x - left.y*right.y - left.z * right.z b = left.w*right.x + left.y*right.z - right.y * left.z c = left.w*right.y + left.z*right.x - right.z * left.x d = left.w*right.z + left.x*right.y - right.x * left.y return Quaternion(x: a, y: b, z: c, w: d) } func * (left: Quaternion, right : Vector3) -> Quaternion { var a:Float32, b:Float32, c:Float32, d:Float32 a = -left.x*right.x - left.y*right.y - left.z * right.z; b = left.w*right.x + left.y*right.z - right.y * left.z; c = left.w*right.y + left.z*right.x - right.z * left.x; d = left.w*right.z + left.x*right.y - right.x * left.y; return Quaternion(x: a, y: b, z: c, w: d) } func * (left: Quaternion, right : Float32) -> Quaternion { return Quaternion(x: left.x * right, y: left.y * right, z: left.z * right, w: left.w * right); } func + (left: Quaternion, right : Quaternion) -> Quaternion { return Quaternion(x: left.x + right.x, y: left.y + right.y, z: left.z + right.z, w: left.w + right.w); } func - (left: Quaternion, right : Quaternion) -> Quaternion { return Quaternion(x: left.x - right.x, y: left.y - right.y, z: left.z - right.z, w: left.w - right.w); }
mit
c04f2d0f2bdd57a66b05f965185c667d
21.790769
106
0.451735
3.24726
false
false
false
false
kaushaldeo/Olympics
Olympics/Views/KDMedalView.swift
1
2723
// // KDMedalView.swift // Olympics // // Created by Kaushal Deo on 8/6/16. // Copyright © 2016 Scorpion Inc. All rights reserved. // import UIKit class KDMedalView: UITableViewHeaderFooterView { @IBOutlet weak var brozeLabel: UILabel! @IBOutlet weak var silverLabel: UILabel! @IBOutlet weak var goldLabel: UILabel! @IBOutlet weak var nameLabel: UILabel! @IBOutlet weak var rankLabel: UILabel! @IBOutlet weak var iconView: UIImageView! var tapHandler : ((KDMedalView)->Void)? = nil // Only override drawRect: if you perform custom drawing. // An empty implementation adversely affects performance during animation. override func drawRect(rect: CGRect) { // Drawing code var bezierPath = UIBezierPath(rect: rect) UIColor.cellBackgroundColor().setFill() bezierPath.fill() bezierPath = UIBezierPath() bezierPath.moveToPoint(CGPoint(x: 0, y: CGRectGetHeight(rect))) bezierPath.addLineToPoint(CGPoint(x: CGRectGetWidth(rect), y: CGRectGetHeight(rect))) bezierPath.lineWidth = 0.25 UIColor.sepratorColor().setStroke() bezierPath.strokeWithBlendMode(.Exclusion, alpha: 1.0) } override func awakeFromNib() { super.awakeFromNib() // Initialization code var color = UIColor(red: 218, green: 181, blue: 10) self.goldLabel.layer.borderColor = color.CGColor self.goldLabel.layer.borderWidth = 1.0 self.goldLabel.textAlignment = .Center self.goldLabel.layer.masksToBounds = true self.goldLabel.layer.cornerRadius = 15.0 self.goldLabel.textColor = color color = UIColor.silverColor() self.silverLabel.layer.borderColor = color.CGColor self.silverLabel.layer.borderWidth = 1.0 self.silverLabel.textAlignment = .Center self.silverLabel.layer.masksToBounds = true self.silverLabel.layer.cornerRadius = 15.0 self.silverLabel.textColor = color color = UIColor(red: 232, green: 147, blue: 114) self.brozeLabel.layer.borderColor = color.CGColor self.brozeLabel.layer.borderWidth = 1.0 self.brozeLabel.textAlignment = .Center self.brozeLabel.layer.masksToBounds = true self.brozeLabel.layer.cornerRadius = 15.0 self.brozeLabel.textColor = color self.addGestureRecognizer(UITapGestureRecognizer(target: self, action: Selector("tapped:"))) } func tapped(gesture: UITapGestureRecognizer) { debugPrint(gesture.state.rawValue) if let block = self.tapHandler { block(self) } } }
apache-2.0
bafffac1f35df491498c0e8acd8e9eb2
33.455696
100
0.652829
4.54424
false
false
false
false
adrfer/swift
test/1_stdlib/CollectionDiagnostics.swift
1
15553
// RUN: %target-parse-verify-swift import StdlibUnittest // Also import modules which are used by StdlibUnittest internally. This // workaround is needed to link all required libraries in case we compile // StdlibUnittest with -sil-serialize-all. import SwiftPrivate #if _runtime(_ObjC) import ObjectiveC #endif // // Check that CollectionType.SubSequence is constrained to CollectionType. // // expected-error@+2 {{type 'CollectionWithBadSubSequence' does not conform to protocol 'SequenceType'}} // expected-error@+1 {{type 'CollectionWithBadSubSequence' does not conform to protocol 'CollectionType'}} struct CollectionWithBadSubSequence : CollectionType { var startIndex: MinimalForwardIndex { fatalError("unreachable") } var endIndex: MinimalForwardIndex { fatalError("unreachable") } subscript(i: MinimalForwardIndex) -> OpaqueValue<Int> { fatalError("unreachable") } // expected-note@+2 {{possibly intended match 'SubSequence' (aka 'OpaqueValue<Int8>') does not conform to 'Indexable'}} // expected-note@+1 {{possibly intended match}} typealias SubSequence = OpaqueValue<Int8> } func useCollectionTypeSubSequenceIndex< C : CollectionType where C.SubSequence.Index : BidirectionalIndexType >(c: C) {} func useCollectionTypeSubSequenceGeneratorElement< C : CollectionType where C.SubSequence.Generator.Element == C.Generator.Element >(c: C) {} func sortResultIgnored< S : SequenceType, MC : MutableCollectionType where S.Generator.Element : Comparable, MC.Generator.Element : Comparable >( sequence: S, mutableCollection: MC, array: [Int] ) { var sequence = sequence // expected-warning {{was never mutated; consider changing to 'let' constant}} var mutableCollection = mutableCollection // expected-warning {{was never mutated; consider changing to 'let' constant}} var array = array // expected-warning {{was never mutated; consider changing to 'let' constant}} sequence.sort() // expected-warning {{result of call to 'sort()' is unused}} sequence.sort { $0 < $1 } // expected-warning {{result of call to 'sort' is unused}} mutableCollection.sort() // expected-warning {{result of call to non-mutating function 'sort()' is unused; use 'sortInPlace()' to mutate in-place}} {{21-25=sortInPlace}} mutableCollection.sort { $0 < $1 } // expected-warning {{result of call to non-mutating function 'sort' is unused; use 'sortInPlace' to mutate in-place}} {{21-25=sortInPlace}} array.sort() // expected-warning {{result of call to non-mutating function 'sort()' is unused; use 'sortInPlace()' to mutate in-place}} {{9-13=sortInPlace}} array.sort { $0 < $1 } // expected-warning {{result of call to non-mutating function 'sort' is unused; use 'sortInPlace' to mutate in-place}} {{9-13=sortInPlace}} } struct GoodForwardIndex1 : ForwardIndexType { func successor() -> GoodForwardIndex1 { fatalError("not implemented") } } func == (lhs: GoodForwardIndex1, rhs: GoodForwardIndex1) -> Bool { fatalError("not implemented") } struct GoodForwardIndex2 : ForwardIndexType { func successor() -> GoodForwardIndex2 { fatalError("not implemented") } typealias Distance = Int32 } func == (lhs: GoodForwardIndex2, rhs: GoodForwardIndex2) -> Bool { fatalError("not implemented") } struct GoodBidirectionalIndex1 : BidirectionalIndexType { func successor() -> GoodBidirectionalIndex1 { fatalError("not implemented") } func predecessor() -> GoodBidirectionalIndex1 { fatalError("not implemented") } } func == (lhs: GoodBidirectionalIndex1, rhs: GoodBidirectionalIndex1) -> Bool { fatalError("not implemented") } struct GoodBidirectionalIndex2 : BidirectionalIndexType { func successor() -> GoodBidirectionalIndex2 { fatalError("not implemented") } func predecessor() -> GoodBidirectionalIndex2 { fatalError("not implemented") } typealias Distance = Int32 } func == (lhs: GoodBidirectionalIndex2, rhs: GoodBidirectionalIndex2) -> Bool { fatalError("not implemented") } // expected-error@+1 {{type 'BadBidirectionalIndex1' does not conform to protocol 'BidirectionalIndexType'}} struct BadBidirectionalIndex1 : BidirectionalIndexType { func successor() -> BadBidirectionalIndex1 { fatalError("not implemented") } // Missing 'predecessor()'. } func == (lhs: BadBidirectionalIndex1, rhs: BadBidirectionalIndex1) -> Bool { fatalError("not implemented") } struct GoodRandomAccessIndex1 : RandomAccessIndexType { func successor() -> GoodRandomAccessIndex1 { fatalError("not implemented") } func predecessor() -> GoodRandomAccessIndex1 { fatalError("not implemented") } func distanceTo(other: GoodRandomAccessIndex1) -> Int { fatalError("not implemented") } func advancedBy(n: Int) -> GoodRandomAccessIndex1 { fatalError("not implemented") } } func == (lhs: GoodRandomAccessIndex1, rhs: GoodRandomAccessIndex1) -> Bool { fatalError("not implemented") } struct GoodRandomAccessIndex2 : RandomAccessIndexType { func successor() -> GoodRandomAccessIndex2 { fatalError("not implemented") } func predecessor() -> GoodRandomAccessIndex2 { fatalError("not implemented") } func distanceTo(other: GoodRandomAccessIndex2) -> Int32 { fatalError("not implemented") } func advancedBy(n: Int32) -> GoodRandomAccessIndex2 { fatalError("not implemented") } typealias Distance = Int32 } func == (lhs: GoodRandomAccessIndex2, rhs: GoodRandomAccessIndex2) -> Bool { fatalError("not implemented") } // expected-error@+2 {{type 'BadRandomAccessIndex1' does not conform to protocol 'RandomAccessIndexType'}} // expected-error@+1 * {{}} // There are a lot of other errors we don't care about. struct BadRandomAccessIndex1 : RandomAccessIndexType { func successor() -> BadRandomAccessIndex1 { fatalError("not implemented") } func predecessor() -> BadRandomAccessIndex1 { fatalError("not implemented") } } func == (lhs: BadRandomAccessIndex1, rhs: BadRandomAccessIndex1) -> Bool { fatalError("not implemented") } // expected-error@+2 {{type 'BadRandomAccessIndex2' does not conform to protocol 'RandomAccessIndexType'}} // expected-error@+1 * {{}} // There are a lot of other errors we don't care about. struct BadRandomAccessIndex2 : RandomAccessIndexType { func successor() -> BadRandomAccessIndex2 { fatalError("not implemented") } func predecessor() -> BadRandomAccessIndex2 { fatalError("not implemented") } func distanceTo(other: GoodRandomAccessIndex1) -> Int { fatalError("not implemented") } } func == (lhs: BadRandomAccessIndex2, rhs: BadRandomAccessIndex2) -> Bool { fatalError("not implemented") } // expected-error@+2 {{type 'BadRandomAccessIndex3' does not conform to protocol 'RandomAccessIndexType'}} // expected-error@+1 * {{}} // There are a lot of other errors we don't care about. struct BadRandomAccessIndex3 : RandomAccessIndexType { func successor() -> BadRandomAccessIndex3 { fatalError("not implemented") } func predecessor() -> BadRandomAccessIndex3 { fatalError("not implemented") } func advancedBy(n: Int) -> GoodRandomAccessIndex1 { fatalError("not implemented") } } func == (lhs: BadRandomAccessIndex3, rhs: BadRandomAccessIndex3) -> Bool { fatalError("not implemented") } extension Array { func foo(element: T) {} // expected-error {{'T' has been renamed to 'Element'}} {{21-22=Element}} } extension ArraySlice { func foo(element: T) {} // expected-error {{'T' has been renamed to 'Element'}} {{21-22=Element}} } extension ContiguousArray { func foo(element: T) {} // expected-error {{'T' has been renamed to 'Element'}} {{21-22=Element}} } extension Set { func foo(element: T) {} // expected-error {{'T' has been renamed to 'Element'}} {{21-22=Element}} } extension SetGenerator { func foo(element: T) {} // expected-error {{'T' has been renamed to 'Element'}} {{21-22=Element}} } extension SetIndex { func foo(element: T) {} // expected-error {{'T' has been renamed to 'Element'}} {{21-22=Element}} } extension Repeat { func foo(element: T) {} // expected-error {{'T' has been renamed to 'Element'}} {{21-22=Element}} } extension GeneratorOfOne { func foo(element: T) {} // expected-error {{'T' has been renamed to 'Element'}} {{21-22=Element}} } extension CollectionOfOne { func foo(element: T) {} // expected-error {{'T' has been renamed to 'Element'}} {{21-22=Element}} } extension EmptyGenerator { func foo(element: T) {} // expected-error {{'T' has been renamed to 'Element'}} {{21-22=Element}} } extension EmptyCollection { func foo(element: T) {} // expected-error {{'T' has been renamed to 'Element'}} {{21-22=Element}} } extension UnsafeBufferPointerGenerator { func foo(element: T) {} // expected-error {{'T' has been renamed to 'Element'}} {{21-22=Element}} } extension UnsafeBufferPointer { func foo(element: T) {} // expected-error {{'T' has been renamed to 'Element'}} {{21-22=Element}} } extension UnsafeMutableBufferPointer { func foo(element: T) {} // expected-error {{'T' has been renamed to 'Element'}} {{21-22=Element}} } extension Range { func foo(element: T) {} // expected-error {{'T' has been renamed to 'Element'}} {{21-22=Element}} } extension RangeGenerator { func foo(element: T) {} // expected-error {{'T' has been renamed to 'Element'}} {{21-22=Element}} } extension StrideToGenerator { func foo(element: T) {} // expected-error {{'T' has been renamed to 'Element'}} {{21-22=Element}} } extension StrideTo { func foo(element: T) {} // expected-error {{'T' has been renamed to 'Element'}} {{21-22=Element}} } extension StrideThroughGenerator { func foo(element: T) {} // expected-error {{'T' has been renamed to 'Element'}} {{21-22=Element}} } extension StrideThrough { func foo(element: T) {} // expected-error {{'T' has been renamed to 'Element'}} {{21-22=Element}} } extension AnyGenerator { func foo(element: T) {} // expected-error {{'T' has been renamed to 'Element'}} {{21-22=Element}} } extension AnySequence { func foo(element: T) {} // expected-error {{'T' has been renamed to 'Element'}} {{21-22=Element}} } extension AnyForwardCollection { func foo(element: T) {} // expected-error {{'T' has been renamed to 'Element'}} {{21-22=Element}} } extension AnyBidirectionalCollection { func foo(element: T) {} // expected-error {{'T' has been renamed to 'Element'}} {{21-22=Element}} } extension AnyRandomAccessCollection { func foo(element: T) {} // expected-error {{'T' has been renamed to 'Element'}} {{21-22=Element}} } extension FilterSequenceView {} // expected-error {{'FilterSequenceView' has been renamed to 'FilterSequence'}} {{11-29=FilterSequence}} extension FilterCollectionViewIndex {} // expected-error {{'FilterCollectionViewIndex' has been renamed to 'FilterCollectionIndex'}} {{11-36=FilterCollectionIndex}} extension FilterCollectionView {} // expected-error {{'FilterCollectionView' has been renamed to 'FilterCollection'}} {{11-31=FilterCollection}} extension LazyMapGenerator { func foo(element: T) {} // expected-error {{'T' has been renamed to 'Element'}} {{21-22=Element}} } extension LazyMapSequence { func foo(element: T) {} // expected-error {{'T' has been renamed to 'Element'}} {{21-22=Element}} } extension LazyMapCollection { func foo(element: T) {} // expected-error {{'T' has been renamed to 'Element'}} {{21-22=Element}} } extension MapSequenceGenerator {} // expected-error {{'MapSequenceGenerator' has been renamed to 'LazyMapGenerator'}} {{11-31=LazyMapGenerator}} extension MapSequenceView {} // expected-error {{'MapSequenceView' has been renamed to 'LazyMapSequence'}} {{11-26=LazyMapSequence}} extension MapCollectionView {} // expected-error {{'MapCollectionView' has been renamed to 'LazyMapCollection'}} {{11-28=LazyMapCollection}} extension LazySequence { func foo(base: S) {} // expected-error {{'S' has been renamed to 'Base'}} {{18-19=Base}} func bar() { _ = self.array } // expected-error {{please construct an Array from your lazy sequence}} } extension LazyCollection { func foo(base: S) {} // expected-error {{'S' has been renamed to 'Base'}} {{18-19=Base}} } func foo<T>(_:LazyForwardCollection<T>) // expected-error {{'LazyForwardCollection' has been renamed to 'LazyCollection'}} {{15-36=LazyCollection}} func foo<T>(_:LazyBidirectionalCollection<T>) // expected-error {{'LazyBidirectionalCollection' has been renamed to 'LazyCollection'}} {{15-42=LazyCollection}} func foo<T>(_:LazyRandomAccessCollection<T>) // expected-error {{'LazyRandomAccessCollection' has been renamed to 'LazyCollection'}} {{15-41=LazyCollection}} extension ReverseIndex { func foo(base: I) {} // expected-error {{'I' has been renamed to 'Base'}} {{18-19=Base}} } extension ReverseRandomAccessIndex { func foo(base: I) {} // expected-error {{'I' has been renamed to 'Base'}} {{18-19=Base}} } extension ReverseCollection { func foo(base: T) {} // expected-error {{'T' has been renamed to 'Base'}} {{18-19=Base}} } extension ReverseRandomAccessCollection { func foo(base: T) {} // expected-error {{'T' has been renamed to 'Base'}} {{18-19=Base}} } extension BidirectionalReverseView {} // expected-error {{'BidirectionalReverseView' has been renamed to 'ReverseCollection'}} {{11-35=ReverseCollection}} extension RandomAccessReverseView {} // expected-error {{'RandomAccessReverseView' has been renamed to 'ReverseRandomAccessCollection'}} {{11-34=ReverseRandomAccessCollection}} extension GeneratorSequence { func foo(base: G) {} // expected-error {{'G' has been renamed to 'Base'}} {{18-19=Base}} } extension ZipGenerator2 {} // expected-error {{'ZipGenerator2' has been renamed to 'Zip2Generator'}} {{11-24=Zip2Generator}} extension Zip2 {} // expected-error {{'Zip2' has been renamed to 'Zip2Sequence'}} {{11-15=Zip2Sequence}} extension UnsafePointer { func foo(memory: T) {} // expected-error {{'T' has been renamed to 'Memory'}} {{20-21=Memory}} } extension UnsafeMutablePointer { func foo(memory: T) {} // expected-error {{'T' has been renamed to 'Memory'}} {{20-21=Memory}} } extension HalfOpenInterval { func foo(bound: T) {} // expected-error {{'T' has been renamed to 'Bound'}} {{19-20=Bound}} } extension ClosedInterval { func foo(bound: T) {} // expected-error {{'T' has been renamed to 'Bound'}} {{19-20=Bound}} } extension Unmanaged { func foo(instance: T) {} // expected-error {{'T' has been renamed to 'Instance'}} {{22-23=Instance}} } struct MyCollection : Sliceable {} // expected-error {{'Sliceable' has been renamed to 'CollectionType'}} {{23-32=CollectionType}} protocol MyProtocol : Sliceable {} // expected-error {{'Sliceable' has been renamed to 'CollectionType'}} {{23-32=CollectionType}} func processCollection<E : Sliceable>(e: E) {} // expected-error {{'Sliceable' has been renamed to 'CollectionType'}} {{28-37=CollectionType}} func renamedRangeReplaceableCollectionTypeMethods(c: DefaultedForwardRangeReplaceableCollection<Int>) { var c = c c.extend([ 10 ]) // expected-error {{'extend' has been renamed to 'appendContentsOf'}} {{5-11=appendContentsOf}} c.splice([ 10 ], atIndex: c.startIndex) // expected-error {{'splice(_:atIndex:)' has been renamed to 'insertContentsOf'}} {{5-11=insertContentsOf}} } func renamedAnyGenerator<G : GeneratorType>(g: G) { _ = anyGenerator(g) // expected-warning {{'anyGenerator' is deprecated: renamed to 'AnyGenerator'}} expected-note {{use 'AnyGenerator' instead}} _ = anyGenerator { 1 } // expected-warning {{'anyGenerator' is deprecated: renamed to 'AnyGenerator'}} expected-note {{use 'AnyGenerator' instead}} }
apache-2.0
d9c54e487ecc61a5658de6e39aa5de63
39.608355
177
0.713431
4.065081
false
false
false
false
XSega/Words
Words/MeaningsManager.swift
1
2233
// // MeaningsManager.swift // Words // // Created by Sergey Ilyushin on 28/07/2017. // Copyright © 2017 Sergey Ilyushin. All rights reserved. // import Foundation protocol IMeaningsManagerOutput: class { func onFetchMeaningsSuccess(meanings: [Meaning]) func onFetchMeaningsFailure(message: String) } protocol IMeaningsManager: class { func fetchMeanings(count: Int) } class MeaningsManager: IMeaningsManager { var apiDataManager: IAPIDataManager! var localDataManager: ILocalDataManager! weak var interactor: IMeaningsManagerOutput! func fetchMeanings(count: Int) { guard var ids = localDataManager.fetchMeaningIds(count: count) else { return self.interactor.onFetchMeaningsFailure(message: "Error loading user meanign ids") } // Fetch from local storage let localMeanings = localDataManager.fetchMeanings(identifiers: ids) if let meanings = localMeanings, meanings.count == count { DispatchQueue.main.async { self.interactor.onFetchMeaningsSuccess(meanings: meanings) } return } if let meanings = localMeanings { print(ids) let fetchedIds = meanings.map({$0.identifier}) ids = ids.filter {!fetchedIds.contains($0) } print(ids) } // Request from server let succesHandler = {[unowned self] (meanings: [Meaning]) in self.localDataManager.saveMeanings(meanings) DispatchQueue.main.async { if let local = localMeanings { self.interactor.onFetchMeaningsSuccess(meanings: local + meanings) } else { self.interactor.onFetchMeaningsSuccess(meanings: meanings) } } } let errorHandler = {[unowned self] (error: Error) in DispatchQueue.main.async { self.interactor.onFetchMeaningsFailure(message: "Error loading meanings") } } apiDataManager.requestMeanings(identifiers:ids, completionHandler: succesHandler, errorHandler: errorHandler) } }
mit
e8bc461ada37bcada27211dc6df2175f
31.347826
117
0.616935
4.759062
false
false
false
false
didi/DoraemonKit
iOS/Swift/DoKitSwiftDemo/DoKitSwiftDemo/Util/DoraemonDemoDefine.swift
1
1558
// // DoraemonDefine.swift // DoKitSwiftDemo // // Created by didi on 2020/5/13. // Copyright © 2020 didi. All rights reserved. // import Foundation import UIKit let kDoKitScreenWidth:CGFloat = UIScreen.main.bounds.size.width let kDoKitScreenHeight:CGFloat = UIScreen.main.bounds.size.height let kDoKitOrientationPortrait:Bool = UIApplication.shared.statusBarOrientation.isPortrait let kIphoneNavBarHeight:CGFloat = kDoKitIsIphoneXSeries() ? 88 : 64 let kIphoneStatusBarHeight:CGFloat = kDoKitIsIphoneXSeries() ? 44 : 20 let kIphoneSafeBottomAreaHeight:CGFloat = kDoKitIsIphoneXSeries() ? 34 : 0 let kIphoneTopSensorHeight:CGFloat = kDoKitIsIphoneXSeries() ? 32 : 0 func kDoKitSizeFrom750(_ x: CGFloat) -> CGFloat { return x*kDoKitScreenWidth/750 } func kDoKitkSizeFrom750_Landscape(_ x: CGFloat) -> CGFloat { if kDoKitOrientationPortrait { return kDoKitSizeFrom750(x) }else{ return x*kDoKitScreenHeight/750 } } func kDoKitIsIphoneXSeries() -> Bool{ var iPhoneXSeries = false if UIDevice.current.userInterfaceIdiom != .phone { return iPhoneXSeries } if #available(iOS 11.0, *) { let mainWindow = getKeyWindow() if let mainWindow = mainWindow { if mainWindow.safeAreaInsets.bottom > 0 { iPhoneXSeries = true } } } return iPhoneXSeries } func getKeyWindow() -> UIWindow? { let keyWindow: UIWindow? = UIApplication.shared.delegate?.window ?? UIApplication.shared.windows.first return keyWindow }
apache-2.0
9cd7194e31cdf17ccd56e4365e320a4f
26.315789
106
0.703276
3.873134
false
false
false
false
LoveZYForever/HXWeiboPhotoPicker
Pods/HXPHPicker/Sources/HXPHPicker/Camera/Controller/CameraResultViewController.swift
1
6547
// // CameraResultViewController.swift // HXPHPicker // // Created by Slience on 2021/8/31. // import UIKit import AVFoundation class CameraResultViewController: UIViewController { enum ResultType { case photo case video } weak var delegate: CameraResultViewControllerDelegate? let type: ResultType let color: UIColor var image: UIImage? init(image: UIImage, tintColor: UIColor) { self.type = .photo self.image = image self.color = tintColor super.init(nibName: nil, bundle: nil) } var videoURL: URL? init(videoURL: URL, tintColor: UIColor) { self.type = .video self.videoURL = videoURL self.color = tintColor super.init(nibName: nil, bundle: nil) } lazy var topMaskLayer: CAGradientLayer = { let layer = PhotoTools.getGradientShadowLayer(true) return layer }() lazy var imageView: UIImageView = { let view = UIImageView(image: image) view.clipsToBounds = true view.contentMode = .scaleAspectFill return view }() lazy var playerView: CameraResultVideoView = { let view = CameraResultVideoView() if let videoURL = videoURL { view.avAsset = AVAsset(url: videoURL) } return view }() lazy var doneButton: UIButton = { let button = UIButton(type: .system) button.setTitle("完成".localized, for: .normal) button.titleLabel?.font = UIFont.mediumPingFang(ofSize: 16) button.layer.cornerRadius = 3 button.layer.masksToBounds = true button.addTarget(self, action: #selector(didDoneButtonClick(button:)), for: .touchUpInside) button.backgroundColor = color button.setTitleColor(.white, for: .normal) return button }() @objc func didDoneButtonClick(button: UIButton) { delegate?.cameraResultViewController(didDone: self) } override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = .black if type == .photo { view.addSubview(imageView) }else { view.addSubview(playerView) } view.addSubview(doneButton) view.layer.addSublayer(topMaskLayer) view.addGestureRecognizer( UITapGestureRecognizer( target: self, action: #selector(didViewClick) ) ) } @objc func didViewClick() { if doneButton.alpha == 1 { navigationController?.setNavigationBarHidden(true, animated: true) UIView.animate(withDuration: 0.25) { self.doneButton.alpha = 0 } }else { navigationController?.setNavigationBarHidden(false, animated: true) UIView.animate(withDuration: 0.25) { self.doneButton.alpha = 1 } } } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() let rect: CGRect if UIDevice.isPad || !UIDevice.isPortrait { if UIDevice.isPad { rect = view.bounds }else { let size = CGSize(width: view.height * 16 / 9, height: view.height) rect = CGRect( x: (view.width - size.width) * 0.5, y: (view.height - size.height) * 0.5, width: size.width, height: size.height ) } }else { let size = CGSize(width: view.width, height: view.width / 9 * 16) rect = CGRect( x: (view.width - size.width) * 0.5, y: (view.height - size.height) * 0.5, width: size.width, height: size.height ) } if type == .photo { imageView.frame = rect }else { playerView.frame = rect } var doneWidth = (doneButton.currentTitle?.width( ofFont: doneButton.titleLabel!.font, maxHeight: 33) ?? 0) + 20 if doneWidth < 60 { doneWidth = 60 } doneButton.width = doneWidth doneButton.height = 33 doneButton.x = view.width - doneWidth - 12 - UIDevice.rightMargin doneButton.centerY = view.height - UIDevice.bottomMargin - 25 if let nav = navigationController { topMaskLayer.frame = CGRect( x: 0, y: 0, width: view.width, height: nav.navigationBar.frame.maxY + 10 ) } } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) guard let nav = navigationController else { return } let navHeight = nav.navigationBar.frame.maxY nav.navigationBar.setBackgroundImage( UIImage.image( for: .clear, havingSize: CGSize(width: view.width, height: navHeight) ), for: .default ) nav.navigationBar.shadowImage = UIImage() } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) navigationController?.setNavigationBarHidden(false, animated: true) } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } } class CameraResultVideoView: VideoPlayerView { override var avAsset: AVAsset? { didSet { configAsset() } } func configAsset() { if let avAsset = avAsset { try? AVAudioSession.sharedInstance().setCategory(.soloAmbient) let playerItem = AVPlayerItem(asset: avAsset) player.replaceCurrentItem(with: playerItem) playerLayer.player = player player.play() NotificationCenter.default.addObserver( self, selector: #selector(playerItemDidPlayToEndTimeNotification(notifi:)), name: NSNotification.Name.AVPlayerItemDidPlayToEndTime, object: player.currentItem ) } } @objc func playerItemDidPlayToEndTimeNotification(notifi: Notification) { player.seek(to: .zero, toleranceBefore: .zero, toleranceAfter: .zero) player.play() } deinit { NotificationCenter.default.removeObserver(self) } }
mit
b853aab8d8764a4612df78f8f7877a5a
30.456731
99
0.561516
4.998472
false
false
false
false
karavakis/simply_counted
simply_counted/EditClientViewController.swift
1
16165
// // EditClientViewController.swift // simply_counted // // Created by Jennifer Karavakis on 8/30/16. // Copyright © 2017 Jennifer Karavakis. All rights reserved. // import UIKit class EditClientViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, UIPopoverPresentationControllerDelegate, UIPickerViewDataSource, UIPickerViewDelegate { @IBOutlet weak var numPassesLeftLabel: UILabel! @IBOutlet weak var numTotalCheckInsLabel: UILabel! @IBOutlet weak var numTotalPassesLabel: UILabel! @IBOutlet weak var priceTotalAmountPaidLabel: UILabel! @IBOutlet weak var activitiesTableView: UITableView! @IBOutlet weak var addPassButton: UIButton! @IBOutlet weak var notesTextView: UITextView! var dateTextField = UITextField(); var checkInButton: UIBarButtonItem! var checkInDatePicker = UIDatePicker() var passPickerView = UIPickerView() var passesLeftTextField = UITextField(); var client:Client? = nil //passed in from last view func reloadActivitiesTable() -> Void { activitiesTableView.reloadData() populateClientInfo() } override func viewDidLoad() { if let client = self.client { //Set header self.navigationItem.title = client.name reloadActivitiesTable() } super.viewDidLoad() setupBorders() setupPickerView() setupDatePicker() setupBarButtonItems() addKeyboardNotifications() } /*****************/ /* Setup Borders */ /*****************/ func setupBorders() { //Notes self.notesTextView.layer.borderColor = UIColor.gray.cgColor self.notesTextView.layer.borderWidth = 1.0; self.notesTextView.layer.cornerRadius = 8; } /************************/ /* Populate Client Info */ /************************/ func populateClientInfo() { if let client : Client = client { // self.automaticallyAdjustsScrollViewInsets = false //TODO: not sure if we should remove this, default value is true notesTextView.text = client.notes numPassesLeftLabel.text = String(client.passes) numTotalCheckInsLabel.text = String(client.totalCheckIns) numTotalPassesLabel.text = String(client.totalPasses) priceTotalAmountPaidLabel.text = "$" + String(describing: client.totalPrice) } } /*******************/ /* Load Table View */ /*******************/ func numberOfSections(in tableView: UITableView) -> Int { return 1 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if let client : Client = client { return client.activities.count } return 0 } public func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { return "Activities" } public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { var cell : SimpleLabelTableViewCell cell = tableView.dequeueReusableCell(withIdentifier: "CheckInCell") as! SimpleLabelTableViewCell if let client : Client = client { // Price and Pass Count var price = "" var passText = "" if let passActivity = client.activities[indexPath.row] as? PassActivity { cell = tableView.dequeueReusableCell(withIdentifier: "PassCell") as! SimpleLabelTableViewCell let passesString = passActivity.passesAdded == 1 ? " Pass" : " Passes" passText = String(passActivity.passesAdded) + passesString price = "$" + passActivity.price cell.label3.text = price cell.label2.text = passText } //Date let dateFormatter = DateFormatter() dateFormatter.dateFormat = "E, MMM d, yyyy" let dateText = dateFormatter.string(from: client.activities[indexPath.row].date) cell.label.text = dateText } return cell } internal func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool { return true } func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) { if editingStyle == UITableViewCell.EditingStyle.delete { if let client = client { func deleteSuccess() { client.removeActivity(activityIndex: indexPath.row) populateClientInfo() tableView.deleteRows(at: [indexPath], with: UITableView.RowAnimation.automatic) } func errorHandler(_ error: NSError) { print("Error: \(error) \(error.userInfo)") } client.activities[indexPath.row].deleteRecord(deleteSuccess, errorHandler: errorHandler) } } } /************/ /* Check-In */ /************/ func setupBarButtonItems() { checkInButton = UIBarButtonItem(title: "Past Check-In", style: .plain, target: self, action: #selector(EditClientViewController.checkInClicked)) self.navigationItem.rightBarButtonItem = checkInButton } @objc func checkInClicked() { if let client = client { if (client.passes <= 0) { let noPassesAlert = UIAlertController(title: "Warning", message: "Client has no passes remaining.", preferredStyle: UIAlertController.Style.alert) noPassesAlert.addAction(UIAlertAction(title: "Cancel", style: .default, handler: { (action: UIAlertAction!) in })) noPassesAlert.addAction(UIAlertAction(title: "Check-in", style: .default, handler: { (action: UIAlertAction!) in self.dateTextField.becomeFirstResponder() })) present(noPassesAlert, animated: true, completion: nil) } else { self.dateTextField.becomeFirstResponder() } } } @objc func checkInDoneClicked() { client!.checkIn(checkInDatePicker.date) _ = navigationController?.popViewController(animated: true) _ = navigationController?.popViewController(animated: true) } @objc func checkInCancelClicked() { dateTextField.resignFirstResponder() } /*********************/ /* Setup Date Picker */ /*********************/ func setupDatePicker() { let today = Date() checkInDatePicker.datePickerMode = UIDatePicker.Mode.date checkInDatePicker.setDate(today, animated: false) checkInDatePicker.maximumDate = today self.view.addSubview(dateTextField) let cancelButton = UIBarButtonItem(barButtonSystemItem: UIBarButtonItem.SystemItem.cancel, target: self, action: #selector(EditClientViewController.checkInCancelClicked)) let flexSpace = UIBarButtonItem(barButtonSystemItem: UIBarButtonItem.SystemItem.flexibleSpace, target: self, action: nil) let doneButton = UIBarButtonItem(title: "Check-In", style: .plain, target: self, action: #selector(EditClientViewController.checkInDoneClicked)) let titleLabel = UILabel(frame: CGRect(x: 0, y: 0, width: 200, height: 40)) titleLabel.text = "Pick Check-In Date" titleLabel.textAlignment = NSTextAlignment.center let title = UIBarButtonItem(customView: titleLabel) let pickerToolbar = UIToolbar(frame: CGRect(x: 0, y: self.view.frame.size.height, width: self.view.frame.size.width, height: 40.0)) pickerToolbar.setItems([cancelButton, flexSpace, title, flexSpace, doneButton], animated: true) dateTextField.isHidden = true dateTextField.inputView = checkInDatePicker dateTextField.inputAccessoryView = pickerToolbar } /************/ /* Add Pass */ /************/ @IBAction func addPassClicked(_ sender: AnyObject) { performSegue(withIdentifier: "AddPassClicked", sender: self) } func passAddedHandler() { reloadActivitiesTable() populateClientInfo() } /**********************/ /* Update Passes Left */ /**********************/ @IBAction func updatePassesLeftClicked(_ sender: AnyObject) { passesLeftTextField.text = numPassesLeftLabel.text passPickerView.selectRow(Int(passesLeftTextField.text!)!+999, inComponent: 0, animated: false) passesLeftTextField.becomeFirstResponder() } func setupPickerView() { passPickerView.delegate = self self.view.addSubview(passesLeftTextField) passesLeftTextField.inputView = passPickerView passesLeftTextField.isHidden = true let cancelButton = UIBarButtonItem(barButtonSystemItem: UIBarButtonItem.SystemItem.cancel, target: self, action: #selector(EditClientViewController.cancelClicked)) let flexSpace = UIBarButtonItem(barButtonSystemItem: UIBarButtonItem.SystemItem.flexibleSpace, target: self, action: nil) let doneButton = UIBarButtonItem(barButtonSystemItem: UIBarButtonItem.SystemItem.done, target: self, action: #selector(EditClientViewController.doneClicked)) let titleLabel = UILabel(frame: CGRect(x: 0, y: 0, width: 200, height: 40)) titleLabel.text = "Update Passes Left" titleLabel.textAlignment = NSTextAlignment.center let title = UIBarButtonItem(customView: titleLabel) let pickerToolbar = UIToolbar(frame: CGRect(x: 0, y: self.view.frame.size.height/6, width: self.view.frame.size.width, height: 40.0)) pickerToolbar.setItems([cancelButton, flexSpace, title, flexSpace, doneButton], animated: true) passesLeftTextField.inputAccessoryView = pickerToolbar passesLeftTextField.text = "0" } @objc func cancelClicked() { passesLeftTextField.resignFirstResponder() } @objc func doneClicked() { passesLeftTextField.resignFirstResponder() if let passes = passesLeftTextField.text { if let passNumber = Int(passes) { if let client = client { var newPassNumber = passNumber-999 newPassNumber = newPassNumber >= 999 || newPassNumber <= -999 ? 0 : newPassNumber passPickerView.selectRow(newPassNumber+999, inComponent: 0, animated: false) client.updatePassesLeft(newPassNumber, successHandler: populateClientInfo) //Add note let dateFormatter = DateFormatter() dateFormatter.dateStyle = .short dateFormatter.timeStyle = .short var noteString = dateFormatter.string(from: Date()) + ": Manually updated passes left from " noteString = noteString + numPassesLeftLabel.text! + " to " noteString = noteString + String(newPassNumber) + "\n" + notesTextView.text notesTextView.text = noteString saveNote() } } } } func numberOfComponents(in: UIPickerView) -> Int { return 1 } func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int { return 1999 } func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? { return String(row-999) } func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) { passesLeftTextField.text = String(row) } /*************/ /* Save Note */ /*************/ func saveNote() { if let client = client { client.updateNotes(notesTextView.text) } } /***********************/ /* Keyboard moves view */ /***********************/ let MOVE_VIEW_ANIMATE_TIME : TimeInterval = 10 @IBOutlet weak var topConstraint: NSLayoutConstraint! @IBOutlet weak var topConstraint2: NSLayoutConstraint! @IBOutlet weak var topConstraint3: NSLayoutConstraint! @IBOutlet weak var topConstraint4: NSLayoutConstraint! @IBOutlet weak var bottomConstraint: NSLayoutConstraint! var originalTopConstraint : CGFloat! var originalTopConstraint2 : CGFloat! var originalTopConstraint3 : CGFloat! var originalTopConstraint4 : CGFloat! var originalBottomConstraint : CGFloat! func setOriginalConstraints() { self.originalTopConstraint = self.topConstraint.constant self.originalTopConstraint2 = self.topConstraint2.constant self.originalTopConstraint3 = self.topConstraint3.constant self.originalTopConstraint4 = self.topConstraint4.constant self.originalBottomConstraint = self.bottomConstraint.constant } func addKeyboardNotifications() { setOriginalConstraints() self.hideKeyboardWhenTappedAround() NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardWillShow(notification:)), name: UIResponder.keyboardWillShowNotification, object: self.view.window) NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardWillHide(notification:)), name: UIResponder.keyboardWillHideNotification, object: self.view.window) } //TODO pull into a new class so we can just import the class at the top instead of duplicating @objc func keyboardWillShow(notification:Notification) { resetConstraints() let info = notification.userInfo! let keyboardFrame: CGRect = (info[UIResponder.keyboardFrameEndUserInfoKey] as! NSValue).cgRectValue if( notesTextView.isFirstResponder ) { UIView.animate(withDuration: MOVE_VIEW_ANIMATE_TIME, animations: { () -> Void in let shift = (self.notesTextView.frame.maxY - keyboardFrame.minY) > 0 ? self.notesTextView.frame.maxY - keyboardFrame.minY + 8 : 0 self.bottomConstraint.constant += shift self.topConstraint.constant -= shift self.topConstraint2.constant -= shift self.topConstraint3.constant -= shift self.topConstraint4.constant -= shift }) } } @objc func keyboardWillHide(notification:Notification) { resetConstraints() if( notesTextView.isFirstResponder ) { saveNote() } } func resetConstraints() { if (self.originalTopConstraint) != nil { UIView.animate(withDuration: MOVE_VIEW_ANIMATE_TIME, animations: { () -> Void in self.topConstraint.constant = self.originalTopConstraint self.topConstraint2.constant = self.originalTopConstraint2 self.topConstraint3.constant = self.originalTopConstraint3 self.topConstraint4.constant = self.originalTopConstraint4 self.bottomConstraint.constant = self.originalBottomConstraint }) } } func removeKeyboardNotifications() { NotificationCenter.default.removeObserver(self) } /**********/ /* Segues */ /**********/ override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if (segue.identifier == "AddPassClicked") { let popoverViewController = segue.destination as! AddPassViewController popoverViewController.modalPresentationStyle = UIModalPresentationStyle.popover popoverViewController.popoverPresentationController!.delegate = self popoverViewController.client = client popoverViewController.passAddedHandler = passAddedHandler fixIOS9PopOverAnchor(segue) } } func adaptivePresentationStyle(for controller: UIPresentationController, traitCollection: UITraitCollection) -> UIModalPresentationStyle { return .none } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
apache-2.0
a0ce02f496972fc8f6a41ac22b3185ee
39.009901
185
0.642786
5.270297
false
false
false
false
TalkingBibles/Talking-Bible-iOS
TalkingBible/ZHLogger.swift
1
5096
//// //// Copyright 2015 Talking Bibles International //// //// 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 // //// Public //var logLevel = defaultDebugLevel //var ZHLogShowDateTime: Bool = true //var ZHLogShowLogLevel: Bool = true //var ZHLogShowFileName: Bool = true //var ZHLogShowLineNumber: Bool = true //var ZHLogShowFunctionName: Bool = true // //enum ZHLogLevel: Int { // case All = 0 // case Verbose = 10 // case Debug = 20 // case Info = 30 // case Warning = 40 // case Error = 50 // case Off = 60 // static func logLevelString(logLevel: ZHLogLevel) -> String { // switch logLevel { // case .Verbose: return "Verbose" // case .Info: return "Info" // case .Debug: return "Debug" // case .Warning: return "Warning" // case .Error: return "Error" // default: // assertionFailure("Invalid level to get string") // return "Invalid" // } // } //} // //// Be sure to set the "DEBUG" symbol. //// Set it in the "Swift Compiler - Custom Flags" section, "Other Swift Flags" line. You add the DEBUG symbol with the -D DEBUG entry. //#if DEBUG_VERSION // let defaultDebugLevel = ZHLogLevel.All // #else //let defaultDebugLevel = ZHLogLevel.Warning //#endif // //var _ZHLogDateFormatter: NSDateFormatter? //var ZHLogDateFormatter: NSDateFormatter { // if _ZHLogDateFormatter == nil { // _ZHLogDateFormatter = NSDateFormatter() // _ZHLogDateFormatter!.locale = NSLocale(localeIdentifier: "en_US_POSIX") //24H // _ZHLogDateFormatter!.dateFormat = "y-MM-dd HH:mm:ss.SSS" // } // return _ZHLogDateFormatter! //} // //// Default //#if DEBUG_VERSION // var ZHLogFunc: (format: String) -> Void = print // var ZHLogUsingNSLog: Bool = false // #else //var ZHLogFunc: (format: String, args: CVarArgType...) -> Void = NSLog //var ZHLogUsingNSLog: Bool = true //#endif // //func logVerbose(logText: String = "", // file: String = __FILE__, // line: UInt = __LINE__, // function: String = __FUNCTION__, // args: CVarArgType...) //{ // if ZHLogLevel.Verbose.rawValue >= logLevel.rawValue { // log(.Verbose, file: file, function: function, line: line, format: logText, args: getVaList(args)) // } //} // //func log.info(logText: String = "", // file: String = __FILE__, // line: UInt = __LINE__, // function: String = __FUNCTION__, // args: CVarArgType...) //{ // if ZHLogLevel.Info.rawValue >= logLevel.rawValue { // log(.Info, file: file, function: function, line: line, format: logText, args: getVaList(args)) // } //} // //func log.debug(logText: String = "", // file: String = __FILE__, // line: UInt = __LINE__, // function: String = __FUNCTION__, // args: CVarArgType...) //{ // if ZHLogLevel.Debug.rawValue >= logLevel.rawValue { // log(.Debug, file: file, function: function, line: line, format: logText, args: getVaList(args)) // } //} // //func log.warning(logText: String = "", // file: String = __FILE__, // line: UInt = __LINE__, // function: String = __FUNCTION__, // args: CVarArgType...) //{ // if ZHLogLevel.Warning.rawValue >= logLevel.rawValue { // log(.Warning, file: file, function: function, line: line, format: logText, args: getVaList(args)) // } //} // //func log.error(logText: String = "", // file: String = __FILE__, // line: UInt = __LINE__, // function: String = __FUNCTION__, // args: CVarArgType...) //{ // if ZHLogLevel.Error.rawValue >= logLevel.rawValue { // log(.Error, file: file, function: function, line: line, format: logText, args: getVaList(args)) // } //} // //private func log(level: ZHLogLevel, file: String = __FILE__, var function: String = __FUNCTION__, line: UInt = __LINE__, format: String, args: CVaListPointer) { // let time: String = ZHLogShowDateTime ? (ZHLogUsingNSLog ? "" : "\(ZHLogDateFormatter.stringFromDate(NSDate())) ") : "" // let level: String = ZHLogShowLogLevel ? "[\(ZHLogLevel.logLevelString(level))] " : "" // var fileLine: String = "" // if ZHLogShowFileName { // fileLine += "[" + file.lastPathComponent // if ZHLogShowLineNumber { // fileLine += ":\(line)" // } // fileLine += "] " // } // if !ZHLogShowFunctionName { function = "" } // let message = NSString(format: format, arguments: args) as String // let logText = "\(time)\(level)\(fileLine)\(function): \(message)" // // ZHLogFunc(format: logText) //}
apache-2.0
df5ac8d6e622a829323fa111e43dacb5
33.673469
162
0.610871
3.591261
false
false
false
false
leosimas/ios_KerbalCampaigns
Kerbal Campaigns/Models/Bean/Campaign.swift
1
844
// // Campaign.swift // Kerbal Campaigns // // Created by SSA on 15/09/17. // Copyright © 2017 Simas Team. All rights reserved. // import RealmSwift class Campaign : Object { dynamic var id = "" dynamic var completed : Bool = false dynamic var name = "" dynamic var difficulty = "" dynamic var introduction = "" dynamic var length = "" dynamic var difficultyNumber = 1 dynamic var difficultyText = "" let missions = List<Mission>() override static func primaryKey() -> String? { return "id" } func currentProgress() -> Int { var completed = 0 for mission in missions { if (mission.completed) { completed += 1 } } return Int(Float(completed) / Float(missions.count) * 100) } }
apache-2.0
129791dbc25b9b80adaf0d60b1875ad9
21.184211
66
0.56465
4.390625
false
false
false
false
ByteriX/BxTextField
memory-leak-tester/helpers/ParsedTraceToStatistics.swift
1
5423
import Foundation import Darwin // Structures /////////////////////////////////////////////////////////////////////// struct Plist { let filename: String let dict: NSDictionary } struct Leak { let name: String let description: String let debugDescription: String let displayAddress: String let isCycle: Bool let isRootLeak: Bool let allocationTimestamp: Int let count: Int let size: Int let bundleName: String? var id: String { var text = name.isEmpty ? "unknown" : name if let bundleName = bundleName, !bundleName.isEmpty { text.append(" (\(bundleName))") } return text } init?(dict: NSDictionary) { guard let name = dict["name"] as? String, let description = dict["description"] as? String, let debugDescription = dict["debugDescription"] as? String, let displayAddress = dict["displayAddress"] as? String, let isCycle = dict["isCycle"] as? Bool, let isRootLeak = dict["isRootLeak"] as? Bool, let allocationTimestamp = dict["allocationTimestamp"] as? Int, let count = dict["count"] as? Int, let size = dict["size"] as? Int else { return nil } self.name = name self.description = description self.debugDescription = debugDescription self.displayAddress = displayAddress self.isCycle = isCycle self.isRootLeak = isRootLeak self.allocationTimestamp = allocationTimestamp self.count = count self.size = size self.bundleName = description .components(separatedBy: " ") .filter { !$0.isEmpty && $0 != name && !$0.contains("DVT_") && !$0.contains("0x") } .joined(separator: " ") } } struct Report { let createdAt: Date let leaks: [Leak] init?(plist: Plist) { let filenameComponents = plist.filename.components(separatedBy: "-") let dateFormatter = DateFormatter() dateFormatter.dateFormat = "yyyyMMddHHmmss" guard filenameComponents.count == 3, let createdAt = dateFormatter.date(from: filenameComponents[1]), let leaksRaw = plist.dict["com.apple.xray.instrument-type.homeleaks"] as? [NSDictionary] else { return nil } self.createdAt = createdAt self.leaks = leaksRaw.compactMap { leakRaw in let leak = Leak(dict: leakRaw) return leak } } } class Statistics { var leaksCountByName: [String: Int] init() { leaksCountByName = [:] } func analyze(report: Report) { for leak in report.leaks { leaksCountByName[leak.id] = (leaksCountByName[leak.id] ?? 0) + leak.count } } func printInfo() { if leaksCountByName.count == 0 { print("No leaks.") } else { print("Found leaks:") let sortedLeaks = leaksCountByName.enumerated().sorted(by: { $0.1.value >= $1.1.value }).map { $1 } for (key, value) in sortedLeaks { print(" \(value)x \(key)") } } } func save(to url: URL) { let out = [ "leaksCountByName": leaksCountByName ] let dict = NSDictionary(dictionary: out) try! dict.write(to: url) } } // Helpers /////////////////////////////////////////////////////////////////////// func print(error: String) { fputs("Error: \(error)\n", stderr) } func fullPathFromCurrentDirectory(for path: String) -> URL? { let currentDirectoryURL = URL(fileURLWithPath: FileManager.default.currentDirectoryPath) return URL(fileURLWithPath: path, relativeTo: currentDirectoryURL) } func loadPlists(from directoryURL: URL) throws -> [Plist] { let fileManager = FileManager.default let plistsFiles = try fileManager.contentsOfDirectory(at: directoryURL, includingPropertiesForKeys: nil, options: [.skipsHiddenFiles]) let plists = plistsFiles.compactMap { plistFile -> Plist? in guard let dict = NSDictionary(contentsOf: plistFile) else { return nil } return Plist(filename: plistFile.lastPathComponent, dict: dict) } let sortedPlists = plists.sorted(by: { $0.filename < $1.filename }) return sortedPlists } // Parse arguments /////////////////////////////////////////////////////////////////////// guard CommandLine.arguments.count == 3 else { print("usage: ParsedTraceToStatistics folder_with_parsed_trace_files output_file_for_statistics") exit(1) } guard let directoryURL = fullPathFromCurrentDirectory(for: CommandLine.arguments[1]) else { print(error: "Invalid path \"\(CommandLine.arguments[1])\" for folder with parsed trace files.") exit(1) } guard let outputURL = fullPathFromCurrentDirectory(for: CommandLine.arguments[2]) else { print(error: "Invalid path \"\(CommandLine.arguments[2])\" for output file for statistics.") exit(1) } // Create statistics file /////////////////////////////////////////////////////////////////////// do { let plists = try loadPlists(from: directoryURL) let reports = plists.compactMap { Report(plist: $0) } let stats = Statistics() reports.forEach { stats.analyze(report: $0) } stats.save(to: outputURL) stats.printInfo() } catch { print(error: "\(error)") exit(1) }
mit
e5363df25e51269f4b4120c3bfcaad37
32.073171
138
0.588051
4.500415
false
false
false
false
JohnCido/CKit
Sources/Interface/CKPanMenuViewController.swift
1
13558
// // CKPanMenuViewController.swift // CKit // // Created by CHU on 2017/2/15. // // #if os(iOS) import UIKit @available(iOS 9.0, *) open class CKPanMenuViewController: CKViewController, UIGestureRecognizerDelegate { @IBOutlet public weak var contentView: UIView! @IBOutlet public weak var menuView: UIStackView! //Clockwise constraints @IBOutlet public var menuViewConstraints: [NSLayoutConstraint]! private var menuViewBaseConstraintIndex = 0 fileprivate var panGestureRecognizer: UIPanGestureRecognizer! fileprivate var perpendicularPanGestureRecognizer: UIPanGestureRecognizer! public var safeZone: CGRect! public var position: PanMenuScreenPosition = .top public var items = [CKPanMenuItemType]() { didSet { isEnabled = items.count != 0 } } public var fontSize: CGFloat = 15 public var fontName: String? public var color: UIColor = .black public var spacing: CGFloat = 20 { didSet { menuView.spacing = spacing menuViewConstraints[menuViewBaseConstraintIndex].constant = spacing } } public var endMargin: CGFloat = 0 private var selected: Int! { didSet { for item in items { item.index == selected ? item.highlight() : item.resume() } } } public var isEnabled = false { didSet { panGestureRecognizer.isEnabled = isEnabled } } public enum MenuType { case floatContent case fixContent } public enum PanMenuScreenPosition { case top case bottom case left case right } public enum PanMenuAxis { case horizontal case vertical } public var axis: PanMenuAxis { if position == .top || position == .bottom { return .vertical } else { return .horizontal } } public var isVertical: Bool { return axis == .vertical } public var isHorizontal: Bool { return axis == .horizontal } public var directionFactor: CGFloat { if position == .top || position == .left { return 1.0 } else { return -1.0 } } public var threshold: CGFloat { return spacing + fontSize } public var itemLength: CGFloat { if items.count == 0 { return 0 } else { if isVertical { return items[0].bounds.height } else { return items[0].bounds.width } } } override open func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. //Pan gesture safeZone = view.bounds panGestureRecognizer = UIPanGestureRecognizer(target: self, action: #selector(contentDidPan(_:))) panGestureRecognizer.maximumNumberOfTouches = 1 panGestureRecognizer.delegate = self contentView.addGestureRecognizer(panGestureRecognizer) perpendicularPanGestureRecognizer = UIPanGestureRecognizer(target: self, action: #selector(contentDidPanPerpendicular(_:))) perpendicularPanGestureRecognizer.maximumNumberOfTouches = 1 perpendicularPanGestureRecognizer.delegate = self contentView.addGestureRecognizer(perpendicularPanGestureRecognizer) //Menu view menuView.axis = isVertical ? .vertical : .horizontal menuView.alignment = .center //Item spacing and menuView distance to super view switch position { case .top: menuViewBaseConstraintIndex = 0 view.removeConstraint(menuViewConstraints[2]) case .right: menuViewBaseConstraintIndex = 1 view.removeConstraint(menuViewConstraints[3]) case .bottom: menuViewBaseConstraintIndex = 2 view.removeConstraint(menuViewConstraints[0]) case .left: menuViewBaseConstraintIndex = 3 view.removeConstraint(menuViewConstraints[1]) } menuView.spacing = spacing isVertical ? (menuView.frame.size.height = 0) : (menuView.frame.size.width = 0) menuView.setNeedsUpdateConstraints() } /** Init and append a `menu item`. - parameter itemWithTitle: `item title`. - parameter action: an `action` that will be executed when user highlight and release finger on an `menu item`. */ final public func append(itemWithTitle title: String, action: @escaping (inout CKPanMenuItemType) -> Void) { let item = CKPanMenuItem() item.font = UIFont(name: fontName != nil ? fontName! : item.font.fontName, size: fontSize) item.index = items.count item.action = action item.text = title item.textColor = color item.resume() if directionFactor == 1 { items.append(item) menuView.addArrangedSubview(item) } else { items.insert(item, at: 0) menuView.insertArrangedSubview(item, at: 0) } } /** Init and insert a `menu item` at `index`. - parameter itemWithTitle: `item title`. - parameter action: an `action` that will be executed when user highlight and release finger on an `menu item`. - parameter at: specify `index` that item should be insert at */ final public func insert( itemWithTitle title: String, action: @escaping (inout CKPanMenuItemType) -> Void, at index: Int ) { let item = CKPanMenuItem() item.font = UIFont(name: fontName != nil ? fontName! : item.font.fontName, size: fontSize) item.index = items.count item.action = action item.text = title item.textColor = color item.resume() if directionFactor == 1 { items.insert(item, at: index) menuView.insertArrangedSubview(item, at: index) } else { items.insert(item, at: items.count - 1 - index) menuView.insertArrangedSubview(item, at: items.count - 1 - index) } } /** Append a custome defined `menu item`. - parameter item: an `item title` that conforms to `protocol CKPanMenuItemType`. */ final public func append(item: CKPanMenuItemType) { var item = item item.index = items.count directionFactor == 1 ? items.append(item) : items.insert(item, at: 0) directionFactor == 1 ? menuView.addArrangedSubview(item as! UIView) : menuView.insertArrangedSubview(item as! UIView, at: 0) } public func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool { switch gestureRecognizer { case panGestureRecognizer: let velocity = panGestureRecognizer.velocity(in: view) let factor: CGFloat = 1.2 let result = isVertical ? abs(velocity.x) * factor < abs(velocity.y) : abs(velocity.y) * factor < abs(velocity.x) return result case perpendicularPanGestureRecognizer: let velocity = panGestureRecognizer.velocity(in: view) let factor: CGFloat = 1.2 let result = isVertical ? abs(velocity.x) > abs(velocity.y) * factor : abs(velocity.y) > abs(velocity.x) * factor return result default: return true } } public func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool { let a = gestureRecognizer == panGestureRecognizer && otherGestureRecognizer == perpendicularPanGestureRecognizer let b = gestureRecognizer == perpendicularPanGestureRecognizer && otherGestureRecognizer == panGestureRecognizer return a || b } @objc open func contentDidPanPerpendicular(_ recognizer: UIPanGestureRecognizer) { } @objc open func contentDidPan(_ recognizer: UIPanGestureRecognizer) { if isEnabled { let state = recognizer.state let translation = recognizer.translation(in: view) var origin, limit, end: CGFloat! if isVertical { origin = 20 + contentView.bounds.height / 2 end = origin + translation.y } else { origin = contentView.bounds.width / 2 end = origin + translation.x } let temp = spacing + items.count.cgFloat * (spacing + fontSize) + endMargin limit = origin + temp * directionFactor //Calculate and set position if directionFactor == 1.0 { if end > limit { end = limit } if end < origin { end = origin } } else { if end < limit { end = limit } if end > origin { end = origin } } if isVertical { contentView.layer.position.y = end } else { contentView.layer.position.x = end } //Detect selected menu item let diff = abs(end - origin) var aSelected = ((diff - spacing - itemLength) / (itemLength + spacing)).rounded(.down).int if directionFactor != 1 { aSelected = items.count - 1 - aSelected } //print((diff, itemLength + spacing, selected!)) let min = spacing + fontSize + (fontSize + spacing) * aSelected.cgFloat let max = min + spacing if diff < min || diff > max { aSelected = -1 } selected = aSelected //Pan gesture end if state == .ended { if isVertical { UIView.animate(withDuration: 0.24, delay: 0, options: .curveEaseOut, animations: { [weak self] in self?.contentView.layer.position.y = origin }) } else { UIView.animate(withDuration: 0.24, delay: 0, options: .curveEaseOut, animations: { [weak self] in self?.contentView.layer.position.x = origin }) } //Check if ativate a menu item if selected != nil { if selected! >= 0 && selected! < items.count { items[selected!].action(&items[selected!]) } } } } } override open func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } } public protocol CKPanMenuItemType { var index: Int! { get set } var action: (inout CKPanMenuItemType) -> Void { get set } var title: String! { get set } var reason: String? { get set } var isEnabled: Bool { get set } var bounds: CGRect { get set } func highlight() -> Void func resume() -> Void } open class CKPanMenuItem: UILabel, CKPanMenuItemType { public var index: Int! = 0 public var action: (inout CKPanMenuItemType) -> Void = { _ in } public var title: String! { didSet { text = title } } public var reason: String? open override var isEnabled: Bool { didSet { if isEnabled { text = title } else { let r = reason == nil ? "" : reason! text = "\(String(describing: title)) (\(r))" } } } open override func awakeFromNib() { super.awakeFromNib() textAlignment = .center layer.opacity = 0.48 } open func highlight() { UIView.animate(withDuration: 0.16, delay: 0, options: .curveEaseInOut, animations: { self.layer.opacity = 0.87 }) } open func resume() { UIView.animate(withDuration: 0.16, delay: 0, options: .curveEaseInOut, animations: { self.layer.opacity = 0.48 }) } } #endif
mit
44af3d7495800205ae5a64e718d19670
36.043716
168
0.519988
5.577129
false
false
false
false
dcunited001/SpectraNu
Spectra-OSX/Spectra-OSXExample/ViewController.swift
1
1181
// // ViewController.swift // Spectra-OSXExample // // Created by David Conner on 12/9/15. // Copyright © 2015 Spectra. All rights reserved. // import Cocoa import Spectra import Fuzi import Metal import Swinject class ViewController: NSViewController { var device: MTLDevice? var library: MTLLibrary? override func viewDidLoad() { super.viewDidLoad() // TODO: tie device/library to those initialized in containers self.device = MTLCreateSystemDefaultDevice() self.library = device!.newDefaultLibrary() // Do any additional setup after loading the view. let appBundle = NSBundle(forClass: ViewController.self) let xml = MetalParser.readXML(appBundle, filename: "DefaultPipeline", bundleResourceName: nil)! let metaContainer = MetalParser.initMetalEnums(Container()) MetalParser.initMetal(metaContainer) let metalParser = MetalParser(parentContainer: metaContainer) metalParser.parseXML(xml) } override var representedObject: AnyObject? { didSet { // Update the view, if already loaded. } } }
mit
a9731ffdb29b571749a5dcfcd07f109f
24.652174
103
0.664407
4.816327
false
false
false
false
cwoloszynski/XCGLogger
Sources/XCGLogger/Destinations/SyslogDestination.swift
1
2591
// // SyslogDestination.swift // GotYourBackServer // // Created by Charlie Woloszynski on 1/12/17. // // import Dispatch import Foundation import libc open class SyslogDestination: BaseDestination { open var logQueue: DispatchQueue? = nil /// Option: whether or not to output the date the log was created (Always false for this destination) open override var showDate: Bool { get { return false } set { // ignored, syslog adds the date, so we always want showDate to be false in this subclass } } var identifierPointer: UnsafeMutablePointer<Int8> public init(identifier: String) { // openlog needs access to an const char * value that lasts during the call // but the normal Swift behavior to ensure that the const char * lasts only as // long as the function call. So, we need to create that const char * equivalent // in code let utf = identifier.utf8 let length = utf.count self.identifierPointer = UnsafeMutablePointer<Int8>.allocate(capacity: length+1) let temp = UnsafePointer<Int8>(identifier) memcpy(self.identifierPointer, temp, length) self.identifierPointer[length] = 0 // zero terminate openlog(self.identifierPointer, 0, LOG_USER) } deinit { closelog() } open override func output(logDetails: LogDetails, message: String) { let outputClosure = { var logDetails = logDetails var message = message // Apply filters, if any indicate we should drop the message, we abort before doing the actual logging if self.shouldExclude(logDetails: &logDetails, message: &message) { return } self.applyFormatters(logDetails: &logDetails, message: &message) let syslogLevel = self.mappedLevel(logDetails.level) withVaList([]) { vsyslog(syslogLevel, message, $0) } } if let logQueue = logQueue { logQueue.async(execute: outputClosure) } else { outputClosure() } } func mappedLevel(_ level: XCGLogger.Level) -> Int32 { switch (level) { case .severe: return LOG_ERR case .warning: return LOG_WARNING case .info: return LOG_INFO case .debug: return LOG_DEBUG case .verbose: return LOG_DEBUG default: return LOG_DEBUG } } }
mit
e74f0eb8d75ce1ae530475627a198bec
29.127907
114
0.594751
4.815985
false
false
false
false
hyperconnect/SQLite.swift
Sources/SQLite/Typed/Schema.swift
6
22741
// // SQLite.swift // https://github.com/stephencelis/SQLite.swift // Copyright © 2014-2015 Stephen Celis. // // 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. // extension SchemaType { // MARK: - DROP TABLE / VIEW / VIRTUAL TABLE public func drop(ifExists: Bool = false) -> String { return drop("TABLE", tableName(), ifExists) } } extension Table { // MARK: - CREATE TABLE public func create(temporary: Bool = false, ifNotExists: Bool = false, withoutRowid: Bool = false, block: (TableBuilder) -> Void) -> String { let builder = TableBuilder() block(builder) let clauses: [Expressible?] = [ create(Table.identifier, tableName(), temporary ? .temporary : nil, ifNotExists), "".wrap(builder.definitions) as Expression<Void>, withoutRowid ? Expression<Void>(literal: "WITHOUT ROWID") : nil ] return " ".join(clauses.compactMap { $0 }).asSQL() } public func create(_ query: QueryType, temporary: Bool = false, ifNotExists: Bool = false) -> String { let clauses: [Expressible?] = [ create(Table.identifier, tableName(), temporary ? .temporary : nil, ifNotExists), Expression<Void>(literal: "AS"), query ] return " ".join(clauses.compactMap { $0 }).asSQL() } // MARK: - ALTER TABLE … ADD COLUMN public func addColumn<V : Value>(_ name: Expression<V>, check: Expression<Bool>? = nil, defaultValue: V) -> String { return addColumn(definition(name, V.declaredDatatype, nil, false, false, check, defaultValue, nil, nil)) } public func addColumn<V : Value>(_ name: Expression<V>, check: Expression<Bool?>, defaultValue: V) -> String { return addColumn(definition(name, V.declaredDatatype, nil, false, false, check, defaultValue, nil, nil)) } public func addColumn<V : Value>(_ name: Expression<V?>, check: Expression<Bool>? = nil, defaultValue: V? = nil) -> String { return addColumn(definition(name, V.declaredDatatype, nil, true, false, check, defaultValue, nil, nil)) } public func addColumn<V : Value>(_ name: Expression<V?>, check: Expression<Bool?>, defaultValue: V? = nil) -> String { return addColumn(definition(name, V.declaredDatatype, nil, true, false, check, defaultValue, nil, nil)) } public func addColumn<V : Value>(_ name: Expression<V>, unique: Bool = false, check: Expression<Bool>? = nil, references table: QueryType, _ other: Expression<V>) -> String where V.Datatype == Int64 { return addColumn(definition(name, V.declaredDatatype, nil, false, unique, check, nil, (table, other), nil)) } public func addColumn<V : Value>(_ name: Expression<V>, unique: Bool = false, check: Expression<Bool?>, references table: QueryType, _ other: Expression<V>) -> String where V.Datatype == Int64 { return addColumn(definition(name, V.declaredDatatype, nil, false, unique, check, nil, (table, other), nil)) } public func addColumn<V : Value>(_ name: Expression<V?>, unique: Bool = false, check: Expression<Bool>? = nil, references table: QueryType, _ other: Expression<V>) -> String where V.Datatype == Int64 { return addColumn(definition(name, V.declaredDatatype, nil, true, unique, check, nil, (table, other), nil)) } public func addColumn<V : Value>(_ name: Expression<V?>, unique: Bool = false, check: Expression<Bool?>, references table: QueryType, _ other: Expression<V>) -> String where V.Datatype == Int64 { return addColumn(definition(name, V.declaredDatatype, nil, true, unique, check, nil, (table, other), nil)) } public func addColumn<V : Value>(_ name: Expression<V>, check: Expression<Bool>? = nil, defaultValue: V, collate: Collation) -> String where V.Datatype == String { return addColumn(definition(name, V.declaredDatatype, nil, false, false, check, defaultValue, nil, collate)) } public func addColumn<V : Value>(_ name: Expression<V>, check: Expression<Bool?>, defaultValue: V, collate: Collation) -> String where V.Datatype == String { return addColumn(definition(name, V.declaredDatatype, nil, false, false, check, defaultValue, nil, collate)) } public func addColumn<V : Value>(_ name: Expression<V?>, check: Expression<Bool>? = nil, defaultValue: V? = nil, collate: Collation) -> String where V.Datatype == String { return addColumn(definition(name, V.declaredDatatype, nil, true, false, check, defaultValue, nil, collate)) } public func addColumn<V : Value>(_ name: Expression<V?>, check: Expression<Bool?>, defaultValue: V? = nil, collate: Collation) -> String where V.Datatype == String { return addColumn(definition(name, V.declaredDatatype, nil, true, false, check, defaultValue, nil, collate)) } fileprivate func addColumn(_ expression: Expressible) -> String { return " ".join([ Expression<Void>(literal: "ALTER TABLE"), tableName(), Expression<Void>(literal: "ADD COLUMN"), expression ]).asSQL() } // MARK: - ALTER TABLE … RENAME TO public func rename(_ to: Table) -> String { return rename(to: to) } // MARK: - CREATE INDEX public func createIndex(_ columns: Expressible..., unique: Bool = false, ifNotExists: Bool = false) -> String { let clauses: [Expressible?] = [ create("INDEX", indexName(columns), unique ? .unique : nil, ifNotExists), Expression<Void>(literal: "ON"), tableName(qualified: false), "".wrap(columns) as Expression<Void> ] return " ".join(clauses.compactMap { $0 }).asSQL() } // MARK: - DROP INDEX public func dropIndex(_ columns: Expressible..., ifExists: Bool = false) -> String { return drop("INDEX", indexName(columns), ifExists) } fileprivate func indexName(_ columns: [Expressible]) -> Expressible { let string = (["index", clauses.from.name, "on"] + columns.map { $0.expression.template }).joined(separator: " ").lowercased() let index = string.reduce("") { underscored, character in guard character != "\"" else { return underscored } guard "a"..."z" ~= character || "0"..."9" ~= character else { return underscored + "_" } return underscored + String(character) } return database(namespace: index) } } extension View { // MARK: - CREATE VIEW public func create(_ query: QueryType, temporary: Bool = false, ifNotExists: Bool = false) -> String { let clauses: [Expressible?] = [ create(View.identifier, tableName(), temporary ? .temporary : nil, ifNotExists), Expression<Void>(literal: "AS"), query ] return " ".join(clauses.compactMap { $0 }).asSQL() } // MARK: - DROP VIEW public func drop(ifExists: Bool = false) -> String { return drop("VIEW", tableName(), ifExists) } } extension VirtualTable { // MARK: - CREATE VIRTUAL TABLE public func create(_ using: Module, ifNotExists: Bool = false) -> String { let clauses: [Expressible?] = [ create(VirtualTable.identifier, tableName(), nil, ifNotExists), Expression<Void>(literal: "USING"), using ] return " ".join(clauses.compactMap { $0 }).asSQL() } // MARK: - ALTER TABLE … RENAME TO public func rename(_ to: VirtualTable) -> String { return rename(to: to) } } public final class TableBuilder { fileprivate var definitions = [Expressible]() public func column<V : Value>(_ name: Expression<V>, unique: Bool = false, check: Expression<Bool>? = nil, defaultValue: Expression<V>? = nil) { column(name, V.declaredDatatype, nil, false, unique, check, defaultValue, nil, nil) } public func column<V : Value>(_ name: Expression<V>, unique: Bool = false, check: Expression<Bool>? = nil, defaultValue: V) { column(name, V.declaredDatatype, nil, false, unique, check, defaultValue, nil, nil) } public func column<V : Value>(_ name: Expression<V>, unique: Bool = false, check: Expression<Bool?>, defaultValue: Expression<V>? = nil) { column(name, V.declaredDatatype, nil, false, unique, check, defaultValue, nil, nil) } public func column<V : Value>(_ name: Expression<V>, unique: Bool = false, check: Expression<Bool?>, defaultValue: V) { column(name, V.declaredDatatype, nil, false, unique, check, defaultValue, nil, nil) } public func column<V : Value>(_ name: Expression<V?>, unique: Bool = false, check: Expression<Bool>? = nil, defaultValue: Expression<V>? = nil) { column(name, V.declaredDatatype, nil, true, unique, check, defaultValue, nil, nil) } public func column<V : Value>(_ name: Expression<V?>, unique: Bool = false, check: Expression<Bool>? = nil, defaultValue: Expression<V?>) { column(name, V.declaredDatatype, nil, true, unique, check, defaultValue, nil, nil) } public func column<V : Value>(_ name: Expression<V?>, unique: Bool = false, check: Expression<Bool>? = nil, defaultValue: V) { column(name, V.declaredDatatype, nil, true, unique, check, defaultValue, nil, nil) } public func column<V : Value>(_ name: Expression<V?>, unique: Bool = false, check: Expression<Bool?>, defaultValue: Expression<V>? = nil) { column(name, V.declaredDatatype, nil, true, unique, check, defaultValue, nil, nil) } public func column<V : Value>(_ name: Expression<V?>, unique: Bool = false, check: Expression<Bool?>, defaultValue: Expression<V?>) { column(name, V.declaredDatatype, nil, true, unique, check, defaultValue, nil, nil) } public func column<V : Value>(_ name: Expression<V?>, unique: Bool = false, check: Expression<Bool?>, defaultValue: V) { column(name, V.declaredDatatype, nil, true, unique, check, defaultValue, nil, nil) } public func column<V : Value>(_ name: Expression<V>, primaryKey: Bool, check: Expression<Bool>? = nil, defaultValue: Expression<V>? = nil) { column(name, V.declaredDatatype, primaryKey ? .default : nil, false, false, check, defaultValue, nil, nil) } public func column<V : Value>(_ name: Expression<V>, primaryKey: Bool, check: Expression<Bool?>, defaultValue: Expression<V>? = nil) { column(name, V.declaredDatatype, primaryKey ? .default : nil, false, false, check, defaultValue, nil, nil) } public func column<V : Value>(_ name: Expression<V>, primaryKey: PrimaryKey, check: Expression<Bool>? = nil) where V.Datatype == Int64 { column(name, V.declaredDatatype, primaryKey, false, false, check, nil, nil, nil) } public func column<V : Value>(_ name: Expression<V>, primaryKey: PrimaryKey, check: Expression<Bool?>) where V.Datatype == Int64 { column(name, V.declaredDatatype, primaryKey, false, false, check, nil, nil, nil) } public func column<V : Value>(_ name: Expression<V>, unique: Bool = false, check: Expression<Bool>? = nil, references table: QueryType, _ other: Expression<V>) where V.Datatype == Int64 { column(name, V.declaredDatatype, nil, false, unique, check, nil, (table, other), nil) } public func column<V : Value>(_ name: Expression<V>, unique: Bool = false, check: Expression<Bool?>, references table: QueryType, _ other: Expression<V>) where V.Datatype == Int64 { column(name, V.declaredDatatype, nil, false, unique, check, nil, (table, other), nil) } public func column<V : Value>(_ name: Expression<V?>, unique: Bool = false, check: Expression<Bool>? = nil, references table: QueryType, _ other: Expression<V>) where V.Datatype == Int64 { column(name, V.declaredDatatype, nil, true, unique, check, nil, (table, other), nil) } public func column<V : Value>(_ name: Expression<V?>, unique: Bool = false, check: Expression<Bool?>, references table: QueryType, _ other: Expression<V>) where V.Datatype == Int64 { column(name, V.declaredDatatype, nil, true, unique, check, nil, (table, other), nil) } public func column<V : Value>(_ name: Expression<V>, unique: Bool = false, check: Expression<Bool>? = nil, defaultValue: Expression<V>? = nil, collate: Collation) where V.Datatype == String { column(name, V.declaredDatatype, nil, false, unique, check, defaultValue, nil, collate) } public func column<V : Value>(_ name: Expression<V>, unique: Bool = false, check: Expression<Bool>? = nil, defaultValue: V, collate: Collation) where V.Datatype == String { column(name, V.declaredDatatype, nil, false, unique, check, defaultValue, nil, collate) } public func column<V : Value>(_ name: Expression<V>, unique: Bool = false, check: Expression<Bool?>, defaultValue: Expression<V>? = nil, collate: Collation) where V.Datatype == String { column(name, V.declaredDatatype, nil, false, unique, check, defaultValue, nil, collate) } public func column<V : Value>(_ name: Expression<V>, unique: Bool = false, check: Expression<Bool?>, defaultValue: V, collate: Collation) where V.Datatype == String { column(name, V.declaredDatatype, nil, false, unique, check, defaultValue, nil, collate) } public func column<V : Value>(_ name: Expression<V?>, unique: Bool = false, check: Expression<Bool>? = nil, defaultValue: Expression<V>? = nil, collate: Collation) where V.Datatype == String { column(name, V.declaredDatatype, nil, true, unique, check, defaultValue, nil, collate) } public func column<V : Value>(_ name: Expression<V?>, unique: Bool = false, check: Expression<Bool>? = nil, defaultValue: Expression<V?>, collate: Collation) where V.Datatype == String { column(name, V.declaredDatatype, nil, true, unique, check, defaultValue, nil, collate) } public func column<V : Value>(_ name: Expression<V?>, unique: Bool = false, check: Expression<Bool>? = nil, defaultValue: V, collate: Collation) where V.Datatype == String { column(name, V.declaredDatatype, nil, true, unique, check, defaultValue, nil, collate) } public func column<V : Value>(_ name: Expression<V?>, unique: Bool = false, check: Expression<Bool?>, defaultValue: Expression<V>? = nil, collate: Collation) where V.Datatype == String { column(name, V.declaredDatatype, nil, true, unique, check, defaultValue, nil, collate) } public func column<V : Value>(_ name: Expression<V?>, unique: Bool = false, check: Expression<Bool?>, defaultValue: Expression<V?>, collate: Collation) where V.Datatype == String { column(name, V.declaredDatatype, nil, true, unique, check, defaultValue, nil, collate) } public func column<V : Value>(_ name: Expression<V?>, unique: Bool = false, check: Expression<Bool?>, defaultValue: V, collate: Collation) where V.Datatype == String { column(name, V.declaredDatatype, nil, true, unique, check, defaultValue, nil, collate) } fileprivate func column(_ name: Expressible, _ datatype: String, _ primaryKey: PrimaryKey?, _ null: Bool, _ unique: Bool, _ check: Expressible?, _ defaultValue: Expressible?, _ references: (QueryType, Expressible)?, _ collate: Collation?) { definitions.append(definition(name, datatype, primaryKey, null, unique, check, defaultValue, references, collate)) } // MARK: - public func primaryKey<T : Value>(_ column: Expression<T>) { primaryKey([column]) } public func primaryKey<T : Value, U : Value>(_ compositeA: Expression<T>, _ b: Expression<U>) { primaryKey([compositeA, b]) } public func primaryKey<T : Value, U : Value, V : Value>(_ compositeA: Expression<T>, _ b: Expression<U>, _ c: Expression<V>) { primaryKey([compositeA, b, c]) } public func primaryKey<T : Value, U : Value, V : Value, W : Value>(_ compositeA: Expression<T>, _ b: Expression<U>, _ c: Expression<V>, _ d: Expression<W>) { primaryKey([compositeA, b, c, d]) } fileprivate func primaryKey(_ composite: [Expressible]) { definitions.append("PRIMARY KEY".prefix(composite)) } public func unique(_ columns: Expressible...) { unique(columns) } public func unique(_ columns: [Expressible]) { definitions.append("UNIQUE".prefix(columns)) } public func check(_ condition: Expression<Bool>) { check(Expression<Bool?>(condition)) } public func check(_ condition: Expression<Bool?>) { definitions.append("CHECK".prefix(condition)) } public enum Dependency: String { case noAction = "NO ACTION" case restrict = "RESTRICT" case setNull = "SET NULL" case setDefault = "SET DEFAULT" case cascade = "CASCADE" } public func foreignKey<T : Value>(_ column: Expression<T>, references table: QueryType, _ other: Expression<T>, update: Dependency? = nil, delete: Dependency? = nil) { foreignKey(column, (table, other), update, delete) } public func foreignKey<T : Value>(_ column: Expression<T?>, references table: QueryType, _ other: Expression<T>, update: Dependency? = nil, delete: Dependency? = nil) { foreignKey(column, (table, other), update, delete) } public func foreignKey<T : Value, U : Value>(_ composite: (Expression<T>, Expression<U>), references table: QueryType, _ other: (Expression<T>, Expression<U>), update: Dependency? = nil, delete: Dependency? = nil) { let composite = ", ".join([composite.0, composite.1]) let references = (table, ", ".join([other.0, other.1])) foreignKey(composite, references, update, delete) } public func foreignKey<T : Value, U : Value, V : Value>(_ composite: (Expression<T>, Expression<U>, Expression<V>), references table: QueryType, _ other: (Expression<T>, Expression<U>, Expression<V>), update: Dependency? = nil, delete: Dependency? = nil) { let composite = ", ".join([composite.0, composite.1, composite.2]) let references = (table, ", ".join([other.0, other.1, other.2])) foreignKey(composite, references, update, delete) } fileprivate func foreignKey(_ column: Expressible, _ references: (QueryType, Expressible), _ update: Dependency?, _ delete: Dependency?) { let clauses: [Expressible?] = [ "FOREIGN KEY".prefix(column), reference(references), update.map { Expression<Void>(literal: "ON UPDATE \($0.rawValue)") }, delete.map { Expression<Void>(literal: "ON DELETE \($0.rawValue)") } ] definitions.append(" ".join(clauses.compactMap { $0 })) } } public enum PrimaryKey { case `default` case autoincrement } public struct Module { fileprivate let name: String fileprivate let arguments: [Expressible] public init(_ name: String, _ arguments: [Expressible]) { self.init(name: name.quote(), arguments: arguments) } init(name: String, arguments: [Expressible]) { self.name = name self.arguments = arguments } } extension Module : Expressible { public var expression: Expression<Void> { return name.wrap(arguments) } } // MARK: - Private private extension QueryType { func create(_ identifier: String, _ name: Expressible, _ modifier: Modifier?, _ ifNotExists: Bool) -> Expressible { let clauses: [Expressible?] = [ Expression<Void>(literal: "CREATE"), modifier.map { Expression<Void>(literal: $0.rawValue) }, Expression<Void>(literal: identifier), ifNotExists ? Expression<Void>(literal: "IF NOT EXISTS") : nil, name ] return " ".join(clauses.compactMap { $0 }) } func rename(to: Self) -> String { return " ".join([ Expression<Void>(literal: "ALTER TABLE"), tableName(), Expression<Void>(literal: "RENAME TO"), Expression<Void>(to.clauses.from.name) ]).asSQL() } func drop(_ identifier: String, _ name: Expressible, _ ifExists: Bool) -> String { let clauses: [Expressible?] = [ Expression<Void>(literal: "DROP \(identifier)"), ifExists ? Expression<Void>(literal: "IF EXISTS") : nil, name ] return " ".join(clauses.compactMap { $0 }).asSQL() } } private func definition(_ column: Expressible, _ datatype: String, _ primaryKey: PrimaryKey?, _ null: Bool, _ unique: Bool, _ check: Expressible?, _ defaultValue: Expressible?, _ references: (QueryType, Expressible)?, _ collate: Collation?) -> Expressible { let clauses: [Expressible?] = [ column, Expression<Void>(literal: datatype), primaryKey.map { Expression<Void>(literal: $0 == .autoincrement ? "PRIMARY KEY AUTOINCREMENT" : "PRIMARY KEY") }, null ? nil : Expression<Void>(literal: "NOT NULL"), unique ? Expression<Void>(literal: "UNIQUE") : nil, check.map { " ".join([Expression<Void>(literal: "CHECK"), $0]) }, defaultValue.map { "DEFAULT".prefix($0) }, references.map(reference), collate.map { " ".join([Expression<Void>(literal: "COLLATE"), $0]) } ] return " ".join(clauses.compactMap { $0 }) } private func reference(_ primary: (QueryType, Expressible)) -> Expressible { return " ".join([ Expression<Void>(literal: "REFERENCES"), primary.0.tableName(qualified: false), "".wrap(primary.1) as Expression<Void> ]) } private enum Modifier : String { case unique = "UNIQUE" case temporary = "TEMPORARY" }
mit
ee727dccbc0768b2391621345628e9bd
42.972921
260
0.643442
4.171376
false
false
false
false
johnlui/Pitaya
PitayaTests/ResponseJSON.swift
2
2612
// // ResponseJSON.swift // Pitaya // // Created by 吕文翰 on 15/10/10. // Copyright © 2015年 http://lvwenhan.com. All rights reserved. // import XCTest import Pitaya class ResponseJSON: WithStringParams { func testResponseJSON() { let expectation = self.expectation(description: "testResponseJSON") Pita.build(HTTPMethod: .GET, url: "http://httpbin.org/get") .addParams([param1: param2, param2: param1]) .onNetworkError({ (error) -> Void in XCTAssert(false, error.localizedDescription) }) .responseJSON({ (json, response) -> Void in XCTAssert(json["args"][self.param1].stringValue == self.param2) XCTAssert(json["args"][self.param2].stringValue == self.param1) expectation.fulfill() }) waitForExpectations(timeout: self.defaultTimeout, handler: nil) } func testResponseJSONWithValidBasicAuth() { let expectation = self.expectation(description: "testResponseJSONWithBasicAuth") Pita.build(HTTPMethod: .GET, url: "http://httpbin.org/basic-auth/user/passwd") .addParams([param1: param2, param2: param1]) .setBasicAuth("user", password: "passwd") .onNetworkError({ (error) -> Void in XCTAssert(false, error.localizedDescription) }) .responseJSON { (json, response) -> Void in XCTAssert(json["authenticated"].boolValue) XCTAssert(json["user"].stringValue == "user") expectation.fulfill() } waitForExpectations(timeout: self.defaultTimeout, handler: nil) } func testResponseJSONWithInValidBasicAuth() { let expectation = self.expectation(description: "testResponseJSONWithBasicAuth") Pita.build(HTTPMethod: .GET, url: "http://httpbin.org/basic-auth/user/passwd") .addParams([param1: param2, param2: param1]) .setBasicAuth("foo", password: "bar") .onNetworkError({ (error) -> Void in XCTAssert(false, error.localizedDescription) }) .responseJSON { (json, response) -> Void in XCTAssertNotEqual(response?.statusCode, 200, "Basic Auth should get HTTP status 200") XCTAssert(json["authenticated"].boolValue == false) expectation.fulfill() } waitForExpectations(timeout: self.defaultTimeout, handler: nil) } }
mit
a8ba13999e1524caea2a643b71f6b688
36.185714
101
0.584326
4.69009
false
true
false
false