repo_name
stringlengths
6
91
path
stringlengths
8
968
copies
stringclasses
210 values
size
stringlengths
2
7
content
stringlengths
61
1.01M
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
6
99.8
line_max
int64
12
1k
alpha_frac
float64
0.3
0.91
ratio
float64
2
9.89
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
mnin/on_ruby_ios
onruby/SettingsViewController.swift
1
4685
// // SettingViewController.swift // onruby // // Created by Martin Wilhelmi on 24.09.14. // class SettingsViewController: UITableViewController { override func numberOfSectionsInTableView(tableView: UITableView?) -> Int { return 3 } override func tableView(tableView: UITableView?, numberOfRowsInSection section: Int) -> Int { switch section { case 0: return allUserGroups.count case 1: return 2 case 2: return 1 default: return 0 } } override func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? { switch section { case 0: return "User Groups" case 1: return "User Group contact" case 2: return "app developer contact" default: return "" } } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { var cellIdentifier: String var cell: UITableViewCell! if indexPath.section == 0 { cellIdentifier = "userGroupCellIdentifier" } else { cellIdentifier = "defaultCellIdentifier" } cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier) as UITableViewCell! if cell == nil { cell = UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: cellIdentifier) } let currentCity = UserGroup.current() switch indexPath.section { case 0: var userGroup = allUserGroups[indexPath.row] let imageView = cell.viewWithTag(100) as UIImageView let label = cell.viewWithTag(101) as UILabel label.text = userGroup.name imageView.image = UIImage(named: userGroup.key) if userGroup.key == currentCity.key { cell.accessoryType = UITableViewCellAccessoryType.Checkmark } else { cell.accessoryType = UITableViewCellAccessoryType.None } case 1: cell.accessoryType = UITableViewCellAccessoryType.DisclosureIndicator cell.imageView?.image = nil switch indexPath.row { case 0: cell.textLabel?.text = "Twitter" case 1: cell.textLabel?.text = "Homepage" default: break } case 2: cell.accessoryType = UITableViewCellAccessoryType.DisclosureIndicator cell.imageView?.image = nil switch indexPath.row { case 0: cell.textLabel?.text = "Twitter" default: break } default: break } return cell } override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { tableView.deselectRowAtIndexPath(indexPath, animated: false) switch indexPath.section { case 0: var userGroup : UserGroup = allUserGroups[indexPath.row] as UserGroup self.changeCurrentUserGroup(userGroup) case 1: let currentUserGroup = UserGroup.current() switch indexPath.row { case 0: UIApplication.sharedApplication().openURL(currentUserGroup.twitterUrl()) case 1: UIApplication.sharedApplication().openURL(currentUserGroup.homepageUrl()) default: break } case 2: let url = NSURL(string: "https://twitter.com/mnin") UIApplication.sharedApplication().openURL(url!) default: break } } override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { if indexPath.section == 0 { return 51 } else { return 44 } } func changeCurrentUserGroup(userGroup: UserGroup) { var currentUserGroup = UserGroup.current() if userGroup.key != currentUserGroup.key { userGroup.setAsCurrent() ZeroPush.shared().setChannels([userGroup.key]) postUserGroupChangedNotification() dispatch_async(dispatch_get_main_queue(), { self.tableView.reloadData() }) } } func postUserGroupChangedNotification() { let notificationCenter = NSNotificationCenter.defaultCenter() notificationCenter.postNotificationName("reloadUserGroup", object: UserGroup.current().key) } }
gpl-3.0
95a31130551a638e27ea4ae6efa71c7d
30.233333
118
0.587193
5.62425
false
false
false
false
AlexanderMazaletskiy/RealmObjectEditor
Realm Object Editor/StringExtension.swift
1
4136
// // StringExtension.swift // Realm Object Editor // // Created by Ahmed Ali on 1/15/15. // Copyright (c) 2014 Ahmed Ali. [email protected]. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // 1. Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // 2. Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // 3. The name of the contributor can not be used to endorse or promote products derived from this software // without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS // FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL // THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, // INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) // HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, // STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED // OF THE POSSIBILITY OF SUCH DAMAGE. import Foundation extension String{ /** Very simple method converts the last characters of a string to convert from plural to singular. For example "praties" will be changed to "party" and "stars" will be changed to "star" The method does not hanle any special cases, like uncountable name i.e "people" will not be converted to "person" */ func toSingular() -> String { var singular = self let length = self.characters.count if length > 3{ let range = Range(start: endIndex.advancedBy(-3), end: endIndex) let lastThreeChars = self.substringWithRange(range) if lastThreeChars == "ies" { singular = self.stringByReplacingOccurrencesOfString(lastThreeChars, withString: "y", options: [], range: range) } } if length > 2{ let range = Range(start: endIndex.advancedBy(-1), end: endIndex) let lastChar = self.substringWithRange(range) if lastChar == "s" { singular = self.stringByReplacingOccurrencesOfString(lastChar, withString: "", options: [], range: range) } } return singular } /** Converts the first character to its lower case version - returns: the converted version */ func lowercaseFirstChar() -> String{ let range = Range(start: startIndex, end: startIndex.advancedBy(1)) let firstLowerChar = self.substringWithRange(range).lowercaseString return self.stringByReplacingCharactersInRange(range, withString: firstLowerChar) } /** Converts the first character to its upper case version - returns: the converted version */ func uppercaseFirstChar() -> String{ let range = Range(start: startIndex, end: startIndex.advancedBy(1)) let firstUpperChar = self.substringWithRange(range).uppercaseString return self.stringByReplacingCharactersInRange(range, withString: firstUpperChar) } func getUppercaseOfFirstChar() -> String { return lastCharacter().uppercaseString } func lastCharacter() -> String { let range = Range(start: startIndex, end: startIndex.advancedBy(1)) return self.substringWithRange(range) } mutating func replace(str: String, by replacement: String) { self = self.stringByReplacingOccurrencesOfString(str, withString: replacement) } }
mit
fbcbea950c6d6c4499752772841e00ab
39.165049
186
0.685928
4.792584
false
false
false
false
dreamsxin/swift
validation-test/compiler_crashers_fixed/27369-swift-type-transform.swift
11
916
// This source file is part of the Swift.org open source project // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // RUN: not %target-swift-frontend %s -parse if true {{} k. " if true{ class d<T {let:a{} g {class B<T B:C{let f=e() typealias e enum S<T> : A? func a== f=Dictionary<T.E } class c{struct B<T{ class b<T{struct Q<T B : T{ class c<a typealias () struct B<a:a{ } class A{let a{} k. " } class A<T{} class B<T { struct B class A{var f " class B<T{ class A{{ func f }struct c<T B:C{let f=e() } func g:a{ import a:a{ } enum S<T a{ class A{ func p{ class B<H : T.E struct c<T B :a{ class B< E {} class A{let ad{} let T h.h =b() 1 typealias () let T B :b: AsB class A? f{ typeal
apache-2.0
cc623f7b6a130c5b6dc61364921f7d82
17.32
78
0.663755
2.551532
false
false
false
false
ahcode0919/swift-design-patterns
swift-design-patterns/swift-design-patterns/Creational/Builder.swift
1
2328
// // Builder.swift // swift-design-patterns // // Created by Aaron Hinton on 10/28/17. // Copyright © 2017 No Name Software. All rights reserved. // import Foundation //The main purpose of the builder pattern is to abstract the building of complex objects from its actual construction. //Having the same construction process can create different representations of the product. This pattern can be used when: //A client needs to construct complex objects without having to know its implementation //A client needs to construct complex objects that need to have several implementations or representations protocol AbstractVehicleBuilder { var vehicle: Vehicle { get set } func buildBumper() func buildTowingPackage() func buildWheels() func getResult() -> Vehicle } class BuilderSportsCar: AbstractVehicleBuilder { var vehicle: Vehicle = Vehicle(vehicleType: .car) func buildBumper() { vehicle.bumper = .standard } func buildTowingPackage() { vehicle.towingPackage = false } func buildWheels() { vehicle.wheels = Wheel.touring(size: ._250mm) } func getResult() -> Vehicle { return vehicle } } class BuilderUtilityTruck: AbstractVehicleBuilder { var vehicle: Vehicle = Vehicle(vehicleType: .truck) func buildBumper() { vehicle.bumper = .heavyDuty } func buildTowingPackage() { vehicle.towingPackage = true } func buildWheels() { vehicle.wheels = Wheel.offroad(size: ._250mm) } func getResult() -> Vehicle { return vehicle } } class Director { init() { } func buildVehicle(builder: AbstractVehicleBuilder) { builder.buildBumper() builder.buildTowingPackage() builder.buildWheels() } } class BuilderExample { func buildVehicleExample() -> Vehicle { let director = Director() let utlityTruckBuilder = BuilderUtilityTruck() director.buildVehicle(builder: utlityTruckBuilder) return utlityTruckBuilder.getResult() } } class BuilderWithClosureExample { func buildSimpleObjectExample() -> SimpleObject { let simpleObject = SimpleObject { $0.text = "Test" } return simpleObject } }
mit
18a2041651de47f1b9defd3426c3fa90
23.494737
122
0.659648
4.492278
false
false
false
false
biohazardlover/i3rd
MaChérie/Core/ApplicationDataManager.swift
1
1576
// // ApplicationDataManager.swift // MaChérie // // Created by Leon Li on 2018/6/14. // Copyright © 2018 Leon & Vane. All rights reserved. // import Foundation let ApplicationStateRestorationVersionKey = "ApplicationStateRestorationVersion" let Player1PassiveHitboxHiddenKey = "Player1PassiveHitboxHidden" let Player1OtherVulnerabilityHitboxHiddenKey = "Player1OtherVulnerabilityHitboxHidden" let Player1ActiveHitboxHiddenKey = "Player1ActiveHitboxHidden" let Player1ThrowHitboxHiddenKey = "Player1ThrowHitboxHidden" let Player1ThrowableHitboxHiddenKey = "Player1ThrowableHitboxHidden" let Player1PushHitboxHiddenKey = "Player1PushHitboxHidden" let Player2PassiveHitboxHiddenKey = "Player2PassiveHitboxHidden" let Player2OtherVulnerabilityHitboxHiddenKey = "Player2OtherVulnerabilityHitboxHidden" let Player2ActiveHitboxHiddenKey = "Player2ActiveHitboxHidden" let Player2ThrowHitboxHiddenKey = "Player2ThrowHitboxHidden" let Player2ThrowableHitboxHiddenKey = "Player2ThrowableHitboxHidden" let Player2PushHitboxHiddenKey = "Player2PushHitboxHidden" let PreferredPassiveHitboxRGBColorKey = "PreferredPassiveHitboxRGBColor" let PreferredOtherVulnerabilityHitboxRGBColorKey = "PreferredOtherVulnerabilityHitboxRGBColor" let PreferredActiveHitboxRGBColorKey = "PreferredActiveHitboxRGBColor" let PreferredThrowHitboxRGBColorKey = "PreferredThrowHitboxRGBColor" let PreferredThrowableHitboxRGBColorKey = "PreferredThrowableHitboxRGBColor" let PreferredPushHitboxRGBColorKey = "PreferredPushHitboxRGBColor" let PreferredFramesPerSecondKey = "PreferredFramesPerSecond"
mit
0efffe3d128e615d972c7d40bc3aff13
45.294118
94
0.873571
4.360111
false
false
false
false
xdkoooo/LiveDemo
LiveDemo/LiveDemo/Classes/Main/View/PageTitleView.swift
1
6400
// // PageTitleView.swift // LiveDemo // // Created by xdkoo on 2016/11/21. // Copyright © 2016年 xdkoo. All rights reserved. // import UIKit // MARK:- 定义协议 protocol PageTitleViewDelegate : class { func pageTitleView(titleView : PageTitleView, selectedIndex index : Int) } // MARK:- 定义常量 fileprivate let kscrollLineH : CGFloat = 2 fileprivate let kNormalColor : (CGFloat, CGFloat, CGFloat) = (85, 85, 85) fileprivate let kSelectColor : (CGFloat, CGFloat, CGFloat) = (255, 128, 0) class PageTitleView: UIView { // MARK:- 定义属性 fileprivate var currentIndex : Int = 0 fileprivate var titles: [String] weak var delegate : PageTitleViewDelegate? fileprivate lazy var titleLabels: [UILabel] = [UILabel]() // MARK:- 懒加载属性 fileprivate lazy var scrollView : UIScrollView = { let scrollView = UIScrollView() scrollView.showsHorizontalScrollIndicator = false scrollView.scrollsToTop = false scrollView.bounces = false return scrollView }() fileprivate lazy var scrollLine : UIView = { let scrollLine = UIView() scrollLine.backgroundColor = UIColor.orange return scrollLine }() // MARK:- 自定义构造函数 init(frame: CGRect, titles: [String]){ self.titles = titles super.init(frame: frame) // 设置UI界面 setupUI() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } extension PageTitleView { fileprivate func setupUI() { // 1.添加UIScrollView addSubview(scrollView) scrollView.frame = bounds // 2.添加title对应的label setupTitleLabels() // 3.设置底线和滚动的滑块 setupBottomLineAndScrollLine() } private func setupTitleLabels() { let labelW : CGFloat = frame.width / CGFloat(titles.count) let labelH : CGFloat = frame.height - kscrollLineH let labelY : CGFloat = 0 for(index, title) in titles.enumerated() { // 1.创建label let label = UILabel() // 2.设置label的属性 label.text = title label.tag = index label.font = UIFont.systemFont(ofSize: 16.0) label.textColor = UIColor(r: kNormalColor.0, g: kNormalColor.1, b: kNormalColor.2) label.textAlignment = .center // 3.设置label的frame let labelX : CGFloat = labelW * CGFloat(index) label.frame = CGRect(x: labelX, y: labelY, width: labelW, height: labelH) // 4.将label添加到scrollView中 scrollView.addSubview(label) titleLabels.append(label) // 5.给label添加手势 label.isUserInteractionEnabled = true let tapGes = UITapGestureRecognizer(target: self, action: #selector(self.titleLabelClick(tapGes:))) label.addGestureRecognizer(tapGes) } } private func setupBottomLineAndScrollLine(){ // 1.添加底线 let bottomLine = UIView() bottomLine.backgroundColor = UIColor.lightGray let lineH : CGFloat = 0.5 bottomLine.frame = CGRect(x: 0, y: frame.height - lineH, width: frame.width, height: lineH) addSubview(bottomLine) // 2.添加scrollLine // 2.1获取第一个Label guard let firstLabel = titleLabels.first else { return } firstLabel.textColor = UIColor(r: kSelectColor.0, g: kSelectColor.1, b: kSelectColor.2) // 2.2设置scrollLine的属性 scrollView.addSubview(scrollLine) scrollLine.frame = CGRect(x: firstLabel.frame.origin.x, y: frame.height - kscrollLineH, width: firstLabel.frame.width, height: kscrollLineH) } } // MARK:- 监听Label的点击 extension PageTitleView { @objc fileprivate func titleLabelClick(tapGes : UITapGestureRecognizer) { // 0.获取当前label的下标志 guard let currentLabel = tapGes.view as? UILabel else { return } // 1.如果是重复点击同一个title,直接返回 if currentLabel.tag == currentIndex { return } // 2.获取之前label let oldLabel = titleLabels[currentIndex] // 3.切换文字的颜色 currentLabel.textColor = UIColor(r: kSelectColor.0, g: kSelectColor.1, b: kSelectColor.2) oldLabel.textColor = UIColor(r: kNormalColor.0, g: kNormalColor.1, b: kNormalColor.2) // 4.保存最新的label下标志 currentIndex = currentLabel.tag // 5.滚动条位置发生改变 let scrollLineX = CGFloat(currentLabel.tag) * scrollLine.frame.width UIView.animate(withDuration: 0.15) { self.scrollLine.frame.origin.x = scrollLineX } // 6.通知代理 delegate?.pageTitleView(titleView: self, selectedIndex: currentIndex) } } // MARK:- 对外暴露方法 extension PageTitleView { func setTitleWithProgress(progress : CGFloat, sourceIndex : Int, targetIndex : Int){ // 1.去除sourceLabel/targetLabel let sourceLabel = titleLabels[sourceIndex] let targetLabel = titleLabels[targetIndex] // 2.处理滑块逻辑 let moveTotalX = targetLabel.frame.origin.x - sourceLabel.frame.origin.x let moveX = moveTotalX * progress scrollLine.frame.origin.x = sourceLabel.frame.origin.x + moveX // 3.颜色的渐变 // 3.1.取出变化范围 let colorDelta = (kSelectColor.0 - kNormalColor.0, kSelectColor.1 - kNormalColor.1, kSelectColor.2 - kNormalColor.2) // 3.2.变化sourceLabel sourceLabel.textColor = UIColor(r: kSelectColor.0 - colorDelta.0 * progress, g: kSelectColor.1 - colorDelta.1 * progress, b: kSelectColor.2 - colorDelta.2 * progress) // 3.3.变化targetLabel targetLabel.textColor = UIColor(r: kNormalColor.0 + colorDelta.0 * progress, g: kNormalColor.1 + colorDelta.1 * progress, b: kNormalColor.2 + colorDelta.2 * progress) // 4.记录最新index currentIndex = targetIndex } }
mit
7df1f534b9834cac4335dbacf731240a
31.521505
174
0.611506
4.707393
false
false
false
false
chitaranjan/Album
MYAlbum/MYAlbum/PresentationAnimator.swift
1
4536
// // PresentationAnimator.swift // iOS7Colors // // Created by Ankur Gala on 02/10/14. // Copyright (c) 2014 Ankur Gala. All rights reserved. // import UIKit let animationScale = SCREENWIDTH/SCREENHEIGHT class PresentationAnimator: NSObject, UIViewControllerAnimatedTransitioning { var openingFrame: CGRect? var cellView:UIView? var indexPath : IndexPath? private var selectedCellFrame: CGRect? = nil private var originalTableViewY: CGFloat? = nil //var selectedHomeCell:UIView? func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval { return 0.35 } private func createTransitionImageViewWithFrame(frame: CGRect) -> UIImageView { let imageView = UIImageView(frame: frame) imageView.contentMode = .scaleAspectFill //imageView.setupDefaultTopInnerShadow() imageView.clipsToBounds = true return imageView } func animateTransition(using transitionContext: UIViewControllerContextTransitioning) { let fromViewController = transitionContext.viewController(forKey: UITransitionContextViewControllerKey.from) as UIViewController! let toViewController = transitionContext.viewController(forKey: UITransitionContextViewControllerKey.to) as UIViewController! let containerView = transitionContext.containerView let fromView = fromViewController?.view let toView = toViewController?.view toView?.layoutIfNeeded() containerView.addSubview(fromView!) containerView.addSubview(toView!) // let gridView = cellView // let cell = gridView?.convert(CG, to: nil) // let leftUpperPoint = openingFrame?.origin//gridView!.convert(CGPoint.zero, to: nil) let waterFallView : UITableView = (fromViewController as! NTTransitionProtocol).transitionCollectionView() let gridView = waterFallView.cellForRow(at: indexPath!) as! ListTableViewCell // let leftUpperPoint = gridView?.frame toView?.isHidden = true let offsetY : CGFloat = 0 let offsetStatuBar : CGFloat = 0; let leftUpperPoint = gridView.convert(CGPoint.zero, to: nil) let textHolderPoint = gridView.textViewHolder.frame.origin let snapShot = (gridView as! NTTansitionWaterfallGridViewProtocol).snapShotForTransition() let textHolder = (gridView as! NTTansitionWaterfallGridViewProtocol).snapTitleShotForTransition() containerView.addSubview(snapShot!) // containerView.addSubview(textHolder!) //textHolder?.origin(textHolderPoint) containerView.clipsToBounds = true print("leftUpperPoint\(leftUpperPoint)") print("\(gridView.bounds)") snapShot?.origin(leftUpperPoint) snapShot?.layoutIfNeeded() // containerView.addSubview(snapShot!) // snapShot!.origin(leftUpperPoint!) UIView.animate(withDuration: 0.5, animations: { //snapShot!.transform = CGAffineTransform(scaleX: 1, // y: 1) print("snapShot\(snapShot?.frame.width)") print("toView?.frame.width\(toView?.frame.width)") snapShot!.frame = CGRect(x: 0, y: 0, width: (toView?.frame.width)!, height: (toView?.frame.height)!) UIView.animate(withDuration: 0.1, animations: { snapShot?.contentMode = .scaleAspectFill }) fromView?.alpha = 0 //fromView?.transform = snapShot!.transform // fromView?.frame = CGRect(x: -((leftUpperPoint.x))*animationScale, // y: -((leftUpperPoint.y)-offsetStatuBar)*animationScale+0, // width: (fromView?.frame.size.width)!, // height: (fromView?.frame.size.height)!) },completion:{finished in if finished { snapShot!.removeFromSuperview() toView?.isHidden = false fromView?.alpha = 1 fromView?.transform = CGAffineTransform.identity transitionContext.completeTransition(true) } }) } } extension UIView{ func origin (_ point : CGPoint){ frame.origin.x = point.x frame.origin.y = point.y } }
mit
71e96c972a271c83b961c411098da2d7
38.103448
138
0.622354
5.268293
false
false
false
false
vector-im/riot-ios
Riot/Modules/Room/EmojiPicker/Data/EmojiMart/EmojiMartStore.swift
1
2145
/* Copyright 2019 New Vector Ltd Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ import Foundation struct EmojiMartStore { let categories: [EmojiMartCategory] let emojis: [EmojiItem] } // MARK: - Decodable extension EmojiMartStore: Decodable { /// JSON keys associated to EmojiMartStore properties. enum CodingKeys: String, CodingKey { case categories case emojis } /// JSON key associated to emoji short name. struct EmojiKey: CodingKey { var stringValue: String init?(stringValue: String) { self.stringValue = stringValue } var intValue: Int? { return nil } init?(intValue: Int) { return nil } } public init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) let emojisContainer = try container.nestedContainer(keyedBy: EmojiKey.self, forKey: .emojis) let emojis: [EmojiItem] = emojisContainer.allKeys.compactMap { (emojiKey) -> EmojiItem? in let emojiItem: EmojiItem? do { emojiItem = try emojisContainer.decode(EmojiItem.self, forKey: emojiKey) } catch { print("[EmojiJSONStore] init(from decoder: Decoder) failed to parse emojiItem \(emojiKey) with error: \(error)") emojiItem = nil } return emojiItem } let categories = try container.decode([EmojiMartCategory].self, forKey: .categories) self.init(categories: categories, emojis: emojis) } }
apache-2.0
90008f98878bbf79892c9f633278ca30
31.014925
128
0.641492
4.820225
false
false
false
false
xwu/swift
test/Generics/unify_superclass_types_2.swift
1
2135
// RUN: %target-typecheck-verify-swift -requirement-machine=on -dump-requirement-machine 2>&1 | %FileCheck %s // Note: The GSB fails this test, because it doesn't implement unification of // superclass type constructor arguments. class Generic<T, U, V> {} protocol P1 { associatedtype X : Generic<Int, A1, B1> associatedtype A1 associatedtype B1 } protocol P2 { associatedtype X : Generic<A2, String, B2> associatedtype A2 associatedtype B2 } func sameType<T>(_: T.Type, _: T.Type) {} func takesGenericIntString<U>(_: Generic<Int, String, U>.Type) {} func unifySuperclassTest<T : P1 & P2>(_: T) { sameType(T.A1.self, String.self) sameType(T.A2.self, Int.self) sameType(T.B1.self, T.B2.self) takesGenericIntString(T.X.self) } // CHECK-LABEL: Requirement machine for <τ_0_0 where τ_0_0 : P1, τ_0_0 : P2> // CHECK-NEXT: Rewrite system: { // CHECK: - τ_0_0.[P1&P2:X].[superclass: Generic<τ_0_0, String, τ_0_1> with <τ_0_0.[P2:A2], τ_0_0.[P2:B2]>] => τ_0_0.[P1&P2:X] // CHECK-NEXT: - τ_0_0.[P1&P2:X].[layout: _NativeClass] => τ_0_0.[P1&P2:X] // CHECK-NEXT: - τ_0_0.[P1&P2:X].[superclass: Generic<Int, τ_0_0, τ_0_1> with <τ_0_0.[P1:A1], τ_0_0.[P1:B1]>] => τ_0_0.[P1&P2:X] // CHECK-NEXT: - τ_0_0.[P2:A2].[concrete: Int] => τ_0_0.[P2:A2] // CHECK-NEXT: - τ_0_0.[P1:A1].[concrete: String] => τ_0_0.[P1:A1] // CHECK-NEXT: - τ_0_0.[P2:B2] => τ_0_0.[P1:B1] // CHECK: } // CHECK-NEXT: Homotopy generators: { // CHECK: } // CHECK-NEXT: Property map: { // CHECK-NEXT: [P1:X] => { layout: _NativeClass superclass: [superclass: Generic<Int, τ_0_0, τ_0_1> with <[P1:A1], [P1:B1]>] } // CHECK-NEXT: [P2:X] => { layout: _NativeClass superclass: [superclass: Generic<τ_0_0, String, τ_0_1> with <[P2:A2], [P2:B2]>] } // CHECK-NEXT: τ_0_0 => { conforms_to: [P1 P2] } // CHECK-NEXT: τ_0_0.[P1&P2:X] => { layout: _NativeClass superclass: [superclass: Generic<Int, τ_0_0, τ_0_1> with <τ_0_0.[P1:A1], τ_0_0.[P1:B1]>] } // CHECK-NEXT: τ_0_0.[P2:A2] => { concrete_type: [concrete: Int] } // CHECK-NEXT: τ_0_0.[P1:A1] => { concrete_type: [concrete: String] } // CHECK-NEXT: }
apache-2.0
57d7a3f99eb5e8e4fb8415e231f15377
41.877551
149
0.61619
2.315325
false
false
false
false
vbicer/RealmStore
Carthage/Checkouts/realm-cocoa/examples/ios/swift/GroupedTableView/TableViewController.swift
2
4692
//////////////////////////////////////////////////////////////////////////// // // Copyright 2014 Realm Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //////////////////////////////////////////////////////////////////////////// import UIKit import RealmSwift class DemoObject: Object { @objc dynamic var title = "" @objc dynamic var date = NSDate() @objc dynamic var sectionTitle = "" } class Cell: UITableViewCell { override init(style: UITableViewCellStyle, reuseIdentifier: String!) { super.init(style: .subtitle, reuseIdentifier: reuseIdentifier) } required init(coder: NSCoder) { fatalError("NSCoding not supported") } } var sectionTitles = ["A", "B", "C"] var objectsBySection = [Results<DemoObject>]() class TableViewController: UITableViewController { var notificationToken: NotificationToken? var realm: Realm! override func viewDidLoad() { super.viewDidLoad() setupUI() realm = try! Realm() // Set realm notification block notificationToken = realm.addNotificationBlock { [unowned self] note, realm in self.tableView.reloadData() } for section in sectionTitles { let unsortedObjects = realm.objects(DemoObject.self).filter("sectionTitle == '\(section)'") let sortedObjects = unsortedObjects.sorted(byKeyPath: "date", ascending: true) objectsBySection.append(sortedObjects) } tableView.reloadData() } // UI func setupUI() { tableView.register(Cell.self, forCellReuseIdentifier: "cell") self.title = "GroupedTableView" self.navigationItem.leftBarButtonItem = UIBarButtonItem(title: "BG Add", style: .plain, target: self, action: #selector(TableViewController.backgroundAdd)) self.navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .add, target: self, action: #selector(TableViewController.add)) } // Table view data source override func numberOfSections(in tableView: UITableView) -> Int { return sectionTitles.count } override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { return sectionTitles[section] } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return objectsBySection[section].count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! Cell let object = objectForIndexPath(indexPath: indexPath) cell.textLabel?.text = object?.title cell.detailTextLabel?.text = object?.date.description return cell } override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) { if editingStyle == .delete { try! realm.write { realm.delete(objectForIndexPath(indexPath: indexPath)!) } } } // Actions @objc func backgroundAdd() { // Import many items in a background thread DispatchQueue.global().async { // Get new realm and table since we are in a new thread let realm = try! Realm() realm.beginWrite() for _ in 0..<5 { // Add row via dictionary. Order is ignored. realm.create(DemoObject.self, value: ["title": randomTitle(), "date": NSDate(), "sectionTitle": randomSectionTitle()]) } try! realm.commitWrite() } } @objc func add() { try! realm.write { realm.create(DemoObject.self, value: [randomTitle(), NSDate(), randomSectionTitle()]) } } } // Helpers func objectForIndexPath(indexPath: IndexPath) -> DemoObject? { return objectsBySection[indexPath.section][indexPath.row] } func randomTitle() -> String { return "Title \(arc4random())" } func randomSectionTitle() -> String { return sectionTitles[Int(arc4random()) % sectionTitles.count] }
mit
b224165117f10264d10d1dbd1e432222
32.276596
163
0.64237
4.97561
false
false
false
false
AdaptiveMe/adaptive-arp-api-lib-darwin
Pod/Classes/Sources.Api/LifecycleListenerImpl.swift
1
3879
/** --| ADAPTIVE RUNTIME PLATFORM |---------------------------------------------------------------------------------------- (C) Copyright 2013-2015 Carlos Lozano Diez t/a Adaptive.me <http://adaptive.me>. 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 appli- -cable 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. Original author: * Carlos Lozano Diez <http://github.com/carloslozano> <http://twitter.com/adaptivecoder> <mailto:[email protected]> Contributors: * Ferran Vila Conesa <http://github.com/fnva> <http://twitter.com/ferran_vila> <mailto:[email protected]> * See source code files for contributors. Release: * @version v2.2.15 -------------------------------------------| aut inveniam viam aut faciam |-------------------------------------------- */ import Foundation /** Interface for Managing the Lifecycle listeners Auto-generated implementation of ILifecycleListener specification. */ public class LifecycleListenerImpl : BaseListenerImpl, ILifecycleListener { /** Constructor with listener id. @param id The id of the listener. */ public override init(id : Int64) { super.init(id: id); } /** No data received - error condition, not authorized or hardware not available. @param error Type of error encountered during reading. @since v2.0 */ public func onError(error : ILifecycleListenerError) { let param0 : String = "Adaptive.ILifecycleListenerError.toObject(JSON.parse(\"{ \\\"value\\\": \\\"\(error.toString())\\\"}\"))" var listenerId : Int64 = -1 if (getId() != nil) { listenerId = getId()! } AppRegistryBridge.sharedInstance.getPlatformContextWeb().executeJavaScript("Adaptive.handleLifecycleListenerError( \(listenerId), \(param0))") } /** Called when lifecycle changes somehow. @param lifecycle Lifecycle element @since v2.0 */ public func onResult(lifecycle : Lifecycle) { let param0 : String = "Adaptive.Lifecycle.toObject(JSON.parse(\"\(JSONUtil.escapeString(Lifecycle.Serializer.toJSON(lifecycle)))\"))" var listenerId : Int64 = -1 if (getId() != nil) { listenerId = getId()! } AppRegistryBridge.sharedInstance.getPlatformContextWeb().executeJavaScript("Adaptive.handleLifecycleListenerResult( \(listenerId), \(param0))") } /** Data received with warning @param lifecycle Lifecycle element @param warning Type of warning encountered during reading. @since v2.0 */ public func onWarning(lifecycle : Lifecycle, warning : ILifecycleListenerWarning) { let param0 : String = "Adaptive.Lifecycle.toObject(JSON.parse(\"\(JSONUtil.escapeString(Lifecycle.Serializer.toJSON(lifecycle)))\"))" let param1 : String = "Adaptive.ILifecycleListenerWarning.toObject(JSON.parse(\"{ \\\"value\\\": \\\"\(warning.toString())\\\"}\"))" var listenerId : Int64 = -1 if (getId() != nil) { listenerId = getId()! } AppRegistryBridge.sharedInstance.getPlatformContextWeb().executeJavaScript("Adaptive.handleLifecycleListenerWarning( \(listenerId), \(param0), \(param1))") } } /** ------------------------------------| Engineered with ♥ in Barcelona, Catalonia |-------------------------------------- */
apache-2.0
4c13b1a23014a089034ca02048f3a873
37.009804
163
0.620583
4.699394
false
false
false
false
alexander-ray/StudyOutlet
Sources/App/main.swift
1
1694
// Imports import Vapor import VaporMySQL import Auth import Turnstile import TurnstileCrypto import TurnstileWeb import Fluent import Cookies import Foundation // Creating drop, adding mysql provider let drop = Droplet() try drop.addProvider(VaporMySQL.Provider.self) // Add models drop.preparations.append(Question.self) drop.preparations.append(User.self) // Custom cookie for session management let auth = AuthMiddleware(user: User.self){ value in return Cookie( name: "alex_cookie", value: value, expires: Date().addingTimeInterval(60*60*5), // 1 minute secure: true, httpOnly: true ) } drop.middleware.append(auth) // For access token middleware let protect = ProtectMiddleware(error: Abort.custom(status: .unauthorized, message: "Unauthorized")) let userController = UserController() let questionController = QuestionConroller() drop.group("api") { api in /* * Registration * Create a new Username and Password to receive an authorization token and account */ api.post("register", handler: userController.register) /* * Log In * Pass the Username and Password to receive a new token */ api.post("login", handler: userController.login) // Protected user endpoints api.group(BearerAuthenticationMiddleware(), protect) { user in user.get("users", handler: userController.getUsers) } // Protected question endpoints api.group(BearerAuthenticationMiddleware(), protect) { question in question.post("questions", handler: questionController.addQuestion) question.get("questions", handler: questionController.getQuestions) } } drop.run()
mit
3aba5c9141bd283723fd8bba0576c968
27.233333
100
0.713695
4.434555
false
false
false
false
jubinjacob19/Catapult
NetworkingDemo/NetworkManager.swift
1
2112
// // BaseNetworkManager.swift // Working Title // // Created by Jubin Jacob on 28/01/16. // Copyright © 2016 J. All rights reserved. // import UIKit private let sharedManager = NetworkManager() final class NetworkManager: NSObject { private var myContext = 0 class var sharedInstance: NetworkManager { return sharedManager } lazy var webServiceQueue:NSOperationQueue = { var queue = NSOperationQueue() queue.name = "WebService queue" queue.maxConcurrentOperationCount = 3 return queue }() override init() { super.init() self.webServiceQueue.addObserver(self, forKeyPath: "operations", options: NSKeyValueObservingOptions.New, context: &myContext) } func cancelAllRequests() { self.webServiceQueue.cancelAllOperations() } func evaluateIfReachable(operation : AsyncOperation)->[NSOperation] { let reachablityOperation = ReachablityOperation(host: NSURL(string: "https://www.google.com")!) reachablityOperation |> operation self.webServiceQueue.addOperations([reachablityOperation,operation], waitUntilFinished: false) reachablityOperation.completionBlock = { [weak operation,weak reachablityOperation] in // will cause memmory leak if not used!! operation?.isReachable = reachablityOperation!.isReachable } return [operation,reachablityOperation] } override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) { if context == &myContext { if object as? NSOperationQueue == self.webServiceQueue && keyPath == "operations" { if self.webServiceQueue.operationCount == 0 { } } } else { super.observeValueForKeyPath(keyPath, ofObject: object, change: change, context: context) } } deinit { self.webServiceQueue.removeObserver(self, forKeyPath: "operations", context: &myContext) } }
mit
5bcde1eae75f63e292e07478ea40bf69
33.606557
157
0.659403
5.06235
false
false
false
false
appcompany/SwiftSky
Tests/Data Tests/TemperatureTest.swift
1
7404
// // TemperatureTest.swift // SwiftSky // // Created by Luca Silverentand on 11/04/2017. // Copyright © 2017 App Company.io. All rights reserved. // import Quick import Nimble @testable import SwiftSky class TemperatureTest : QuickSpec { override func tearDown() { SwiftSky.units = UnitProfile() super.tearDown() } override func spec() { let fahrenheit = Temperature(68, withUnit: .fahrenheit) describe("temperature label") { context("label", { it("should be") { expect(fahrenheit.label).to(equal("68℉")) } }) context("celsius label", { it("should be") { expect(fahrenheit.label(as: .celsius)).to(equal("20℃")) } }) context("kelvin label", { it("should be") { expect(fahrenheit.label(as: .kelvin)).to(equal("293K")) } }) } describe("temperature converting") { context("fahrenheit to fahrenheit", { it("should be") { expect(fahrenheit.value(as: .fahrenheit)).to(equal(68)) } }) context("fahrenheit to celsius", { it("should be") { expect(fahrenheit.value(as: .celsius)).to(equal(20)) } }) context("fahrenheit to kelvin", { it("should be") { expect(fahrenheit.value(as: .kelvin)).to(equal((68 + 459.67) * (5/9))) } }) SwiftSky.units.temperature = .celsius let celsius = Temperature(20, withUnit: .celsius) context("celsius to fahrenheit", { it("should be") { expect(celsius.value(as: .fahrenheit)).to(equal(68)) } }) context("celsius to celsius", { it("should be") { expect(celsius.value(as: .celsius)).to(equal(20)) } }) context("celsius to kelvin", { it("should be") { expect(celsius.value(as: .kelvin)).to(equal(293.15)) } }) SwiftSky.units.temperature = .kelvin let kelvin = Temperature(293.15, withUnit: .kelvin) context("kelvin to celsius", { it("should be") { expect(kelvin.value(as: .celsius)).to(equal(20)) } }) context("kelvin to fahrenheit", { it("should be") { expect(kelvin.value(as: .fahrenheit)).to(equal(68)) } }) context("kelvin to kelvin", { it("should be") { expect(kelvin.value(as: .kelvin)).to(equal(293.15)) } }) } describe("apparent temperature") { context("no data", { it("should be") { let apparent = ApparentTemperature(current: nil, max: nil, maxTime: nil, min: nil, minTime: nil) expect(apparent.hasData).to(equal(false)) } }) context("current", { it("should have data") { let apparent = ApparentTemperature(current: fahrenheit, max: nil, maxTime: nil, min: nil, minTime: nil) expect(apparent.hasData).to(equal(true)) } }) context("max", { it("should have data") { let apparent = ApparentTemperature(current: nil, max: fahrenheit, maxTime: nil, min: nil, minTime: nil) expect(apparent.hasData).to(equal(true)) } }) context("max time", { it("should have data") { let apparent = ApparentTemperature(current: nil, max: nil, maxTime: Date(), min: nil, minTime: nil) expect(apparent.hasData).to(equal(true)) } }) context("min", { it("should have data") { let apparent = ApparentTemperature(current: nil, max: nil, maxTime: nil, min: fahrenheit, minTime: nil) expect(apparent.hasData).to(equal(true)) } }) context("min time", { it("should have data") { let apparent = ApparentTemperature(current: nil, max: nil, maxTime: nil, min: nil, minTime: Date()) expect(apparent.hasData).to(equal(true)) } }) } describe("temperature object") { context("no data", { it("should be") { let object = Temperatures(current: nil, max: nil, maxTime: nil, min: nil, minTime: nil, apparent: nil) expect(object.hasData).to(equal(false)) } }) context("current", { it("should have data") { let object = Temperatures(current: fahrenheit, max: nil, maxTime: nil, min: nil, minTime: nil, apparent: nil) expect(object.hasData).to(equal(true)) } }) context("max", { it("should have data") { let object = Temperatures(current: nil, max: fahrenheit, maxTime: nil, min: nil, minTime: nil, apparent: nil) expect(object.hasData).to(equal(true)) } }) context("max time", { it("should have data") { let object = Temperatures(current: nil, max: nil, maxTime: Date(), min: nil, minTime: nil, apparent: nil) expect(object.hasData).to(equal(true)) } }) context("min", { it("should have data") { let object = Temperatures(current: nil, max: nil, maxTime: nil, min: fahrenheit, minTime: nil, apparent: nil) expect(object.hasData).to(equal(true)) } }) context("min time", { it("should have data") { let object = Temperatures(current: nil, max: nil, maxTime: nil, min: nil, minTime: Date(), apparent: nil) expect(object.hasData).to(equal(true)) } }) context("apparent", { it("should have data") { let object = Temperatures(current: nil, max: nil, maxTime: nil, min: nil, minTime: nil, apparent: ApparentTemperature(current: fahrenheit, max: nil, maxTime: nil, min: nil, minTime: nil)) expect(object.hasData).to(equal(true)) } }) } } }
mit
dd8487bb36c444867af76f9c67a39fb7
34.401914
129
0.433978
5.023082
false
false
false
false
happyeverydayzhh/WWDC
WWDC/SearchController.swift
2
2128
// // SearchController.swift // WWDC // // Created by Guilherme Rambo on 05/06/15. // Copyright (c) 2015 Guilherme Rambo. All rights reserved. // import Cocoa class SearchController: NSObject { private var finishedSetup = false var sessions: [Session]? { didSet { if sessions == nil { return } if !finishedSetup { finishedSetup = true let savedTerm = Preferences.SharedPreferences().searchTerm if savedTerm != "" { searchFor(savedTerm) } else { displayedSessions = sessions } } } } var displayedSessions: [Session]? { didSet { if finishedSetup { searchDidFinishCallback() } } } var searchDidStartCallback: () -> Void = {} var searchDidFinishCallback: () -> Void = {} private let searchQ = dispatch_queue_create("Search Queue", DISPATCH_QUEUE_CONCURRENT) private var searchOperationQueue: NSOperationQueue! private var currentSearchOperation: SearchOperation? func searchFor(term: String?) { if term == nil || sessions == nil { return } if ((term!).characters.count <= 3) && ((term!).characters.count != 0) { return } searchDidStartCallback() if searchOperationQueue == nil { searchOperationQueue = NSOperationQueue() searchOperationQueue.underlyingQueue = searchQ } if let operation = currentSearchOperation { operation.cancel() } if let term = term { currentSearchOperation = SearchOperation(sessions: sessions!, term: term) { self.displayedSessions = self.currentSearchOperation!.result } searchOperationQueue.addOperation(currentSearchOperation!) } else { displayedSessions = sessions } } }
bsd-2-clause
6063e12bf578a4aa7c87872528d6a488
26.294872
90
0.530075
5.674667
false
false
false
false
GreenCom-Networks/ios-charts
Charts/Classes/Renderers/ScatterChartRenderer.swift
1
16068
// // ScatterChartRenderer.swift // Charts // // Created by Daniel Cohen Gindi on 4/3/15. // // Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda // A port of MPAndroidChart for iOS // Licensed under Apache License 2.0 // // https://github.com/danielgindi/ios-charts // import Foundation import CoreGraphics #if !os(OSX) import UIKit #endif public class ScatterChartRenderer: LineScatterCandleRadarChartRenderer { public weak var dataProvider: ScatterChartDataProvider? public init(dataProvider: ScatterChartDataProvider?, animator: ChartAnimator?, viewPortHandler: ChartViewPortHandler) { super.init(animator: animator, viewPortHandler: viewPortHandler) self.dataProvider = dataProvider } public override func drawData(context context: CGContext) { guard let scatterData = dataProvider?.scatterData else { return } for i in 0 ..< scatterData.dataSetCount { guard let set = scatterData.getDataSetByIndex(i) else { continue } if set.isVisible { if !(set is IScatterChartDataSet) { fatalError("Datasets for ScatterChartRenderer must conform to IScatterChartDataSet") } drawDataSet(context: context, dataSet: set as! IScatterChartDataSet) } } } private var _lineSegments = [CGPoint](count: 2, repeatedValue: CGPoint()) public func drawDataSet(context context: CGContext, dataSet: IScatterChartDataSet) { guard let dataProvider = dataProvider, animator = animator else { return } let trans = dataProvider.getTransformer(dataSet.axisDependency) let phaseY = animator.phaseY let entryCount = dataSet.entryCount let shapeSize = dataSet.scatterShapeSize let shapeHalf = shapeSize / 2.0 let shapeHoleSizeHalf = dataSet.scatterShapeHoleRadius let shapeHoleSize = shapeHoleSizeHalf * 2.0 let shapeHoleColor = dataSet.scatterShapeHoleColor let shapeStrokeSize = (shapeSize - shapeHoleSize) / 2.0 let shapeStrokeSizeHalf = shapeStrokeSize / 2.0 var point = CGPoint() let valueToPixelMatrix = trans.valueToPixelMatrix let shape = dataSet.scatterShape CGContextSaveGState(context) for j in 0 ..< Int(min(ceil(CGFloat(entryCount) * animator.phaseX), CGFloat(entryCount))) { guard let e = dataSet.entryForIndex(j) else { continue } point.x = CGFloat(e.xIndex) point.y = CGFloat(e.value) * phaseY point = CGPointApplyAffineTransform(point, valueToPixelMatrix); if (!viewPortHandler.isInBoundsRight(point.x)) { break } if (!viewPortHandler.isInBoundsLeft(point.x) || !viewPortHandler.isInBoundsY(point.y)) { continue } if (shape == .Square) { if shapeHoleSize > 0.0 { CGContextSetStrokeColorWithColor(context, dataSet.colorAt(j).CGColor) CGContextSetLineWidth(context, shapeStrokeSize) var rect = CGRect() rect.origin.x = point.x - shapeHoleSizeHalf - shapeStrokeSizeHalf rect.origin.y = point.y - shapeHoleSizeHalf - shapeStrokeSizeHalf rect.size.width = shapeHoleSize + shapeStrokeSize rect.size.height = shapeHoleSize + shapeStrokeSize CGContextStrokeRect(context, rect) if let shapeHoleColor = shapeHoleColor { CGContextSetFillColorWithColor(context, shapeHoleColor.CGColor) rect.origin.x = point.x - shapeHoleSizeHalf rect.origin.y = point.y - shapeHoleSizeHalf rect.size.width = shapeHoleSize rect.size.height = shapeHoleSize CGContextFillRect(context, rect) } } else { CGContextSetFillColorWithColor(context, dataSet.colorAt(j).CGColor) var rect = CGRect() rect.origin.x = point.x - shapeHalf rect.origin.y = point.y - shapeHalf rect.size.width = shapeSize rect.size.height = shapeSize CGContextFillRect(context, rect) } } else if (shape == .Circle) { if shapeHoleSize > 0.0 { CGContextSetStrokeColorWithColor(context, dataSet.colorAt(j).CGColor) CGContextSetLineWidth(context, shapeStrokeSize) var rect = CGRect() rect.origin.x = point.x - shapeHoleSizeHalf - shapeStrokeSizeHalf rect.origin.y = point.y - shapeHoleSizeHalf - shapeStrokeSizeHalf rect.size.width = shapeHoleSize + shapeStrokeSize rect.size.height = shapeHoleSize + shapeStrokeSize CGContextStrokeEllipseInRect(context, rect) if let shapeHoleColor = shapeHoleColor { CGContextSetFillColorWithColor(context, shapeHoleColor.CGColor) rect.origin.x = point.x - shapeHoleSizeHalf rect.origin.y = point.y - shapeHoleSizeHalf rect.size.width = shapeHoleSize rect.size.height = shapeHoleSize CGContextFillEllipseInRect(context, rect) } } else { CGContextSetFillColorWithColor(context, dataSet.colorAt(j).CGColor) var rect = CGRect() rect.origin.x = point.x - shapeHalf rect.origin.y = point.y - shapeHalf rect.size.width = shapeSize rect.size.height = shapeSize CGContextFillEllipseInRect(context, rect) } } else if (shape == .Triangle) { CGContextSetFillColorWithColor(context, dataSet.colorAt(j).CGColor) // create a triangle path CGContextBeginPath(context) CGContextMoveToPoint(context, point.x, point.y - shapeHalf) CGContextAddLineToPoint(context, point.x + shapeHalf, point.y + shapeHalf) CGContextAddLineToPoint(context, point.x - shapeHalf, point.y + shapeHalf) if shapeHoleSize > 0.0 { CGContextAddLineToPoint(context, point.x, point.y - shapeHalf) CGContextMoveToPoint(context, point.x - shapeHalf + shapeStrokeSize, point.y + shapeHalf - shapeStrokeSize) CGContextAddLineToPoint(context, point.x + shapeHalf - shapeStrokeSize, point.y + shapeHalf - shapeStrokeSize) CGContextAddLineToPoint(context, point.x, point.y - shapeHalf + shapeStrokeSize) CGContextAddLineToPoint(context, point.x - shapeHalf + shapeStrokeSize, point.y + shapeHalf - shapeStrokeSize) } CGContextClosePath(context) CGContextFillPath(context) if shapeHoleSize > 0.0 && shapeHoleColor != nil { CGContextSetFillColorWithColor(context, shapeHoleColor!.CGColor) // create a triangle path CGContextBeginPath(context) CGContextMoveToPoint(context, point.x, point.y - shapeHalf + shapeStrokeSize) CGContextAddLineToPoint(context, point.x + shapeHalf - shapeStrokeSize, point.y + shapeHalf - shapeStrokeSize) CGContextAddLineToPoint(context, point.x - shapeHalf + shapeStrokeSize, point.y + shapeHalf - shapeStrokeSize) CGContextClosePath(context) CGContextFillPath(context) } } else if (shape == .Cross) { CGContextSetStrokeColorWithColor(context, dataSet.colorAt(j).CGColor) _lineSegments[0].x = point.x - shapeHalf _lineSegments[0].y = point.y _lineSegments[1].x = point.x + shapeHalf _lineSegments[1].y = point.y CGContextStrokeLineSegments(context, _lineSegments, 2) _lineSegments[0].x = point.x _lineSegments[0].y = point.y - shapeHalf _lineSegments[1].x = point.x _lineSegments[1].y = point.y + shapeHalf CGContextStrokeLineSegments(context, _lineSegments, 2) } else if (shape == .X) { CGContextSetStrokeColorWithColor(context, dataSet.colorAt(j).CGColor) _lineSegments[0].x = point.x - shapeHalf _lineSegments[0].y = point.y - shapeHalf _lineSegments[1].x = point.x + shapeHalf _lineSegments[1].y = point.y + shapeHalf CGContextStrokeLineSegments(context, _lineSegments, 2) _lineSegments[0].x = point.x + shapeHalf _lineSegments[0].y = point.y - shapeHalf _lineSegments[1].x = point.x - shapeHalf _lineSegments[1].y = point.y + shapeHalf CGContextStrokeLineSegments(context, _lineSegments, 2) } else if (shape == .Custom) { CGContextSetFillColorWithColor(context, dataSet.colorAt(j).CGColor) let customShape = dataSet.customScatterShape if customShape == nil { return } // transform the provided custom path CGContextSaveGState(context) CGContextTranslateCTM(context, point.x, point.y) CGContextBeginPath(context) CGContextAddPath(context, customShape!) CGContextFillPath(context) CGContextRestoreGState(context) } } CGContextRestoreGState(context) } public override func drawValues(context context: CGContext) { guard let dataProvider = dataProvider, scatterData = dataProvider.scatterData, animator = animator else { return } // if values are drawn if (scatterData.yValCount < Int(ceil(CGFloat(dataProvider.maxVisibleValueCount) * viewPortHandler.scaleX))) { guard let dataSets = scatterData.dataSets as? [IScatterChartDataSet] else { return } let phaseX = animator.phaseX let phaseY = animator.phaseY var pt = CGPoint() for i in 0 ..< scatterData.dataSetCount { let dataSet = dataSets[i] if !dataSet.isDrawValuesEnabled || dataSet.entryCount == 0 { continue } let valueFont = dataSet.valueFont guard let formatter = dataSet.valueFormatter else { continue } let trans = dataProvider.getTransformer(dataSet.axisDependency) let valueToPixelMatrix = trans.valueToPixelMatrix let entryCount = dataSet.entryCount let shapeSize = dataSet.scatterShapeSize let lineHeight = valueFont.lineHeight for j in 0 ..< Int(ceil(CGFloat(entryCount) * phaseX)) { guard let e = dataSet.entryForIndex(j) else { break } pt.x = CGFloat(e.xIndex) pt.y = CGFloat(e.value) * phaseY pt = CGPointApplyAffineTransform(pt, valueToPixelMatrix) if (!viewPortHandler.isInBoundsRight(pt.x)) { break } // make sure the lines don't do shitty things outside bounds if ((!viewPortHandler.isInBoundsLeft(pt.x) || !viewPortHandler.isInBoundsY(pt.y))) { continue } let text = formatter.stringFromNumber(e.value) ChartUtils.drawText( context: context, text: text!, point: CGPoint( x: pt.x, y: pt.y - shapeSize - lineHeight), align: .Center, attributes: [NSFontAttributeName: valueFont, NSForegroundColorAttributeName: dataSet.valueTextColorAt(j)] ) } } } } public override func drawExtras(context context: CGContext) { } private var _highlightPointBuffer = CGPoint() public override func drawHighlighted(context context: CGContext, indices: [ChartHighlight]) { guard let dataProvider = dataProvider, scatterData = dataProvider.scatterData, animator = animator else { return } let chartXMax = dataProvider.chartXMax CGContextSaveGState(context) for i in 0 ..< indices.count { guard let set = scatterData.getDataSetByIndex(indices[i].dataSetIndex) as? IScatterChartDataSet else { continue } if !set.isHighlightEnabled { continue } CGContextSetStrokeColorWithColor(context, set.highlightColor.CGColor) CGContextSetLineWidth(context, set.highlightLineWidth) if (set.highlightLineDashLengths != nil) { CGContextSetLineDash(context, set.highlightLineDashPhase, set.highlightLineDashLengths!, set.highlightLineDashLengths!.count) } else { CGContextSetLineDash(context, 0.0, nil, 0) } let xIndex = indices[i].xIndex; // get the x-position if (CGFloat(xIndex) > CGFloat(chartXMax) * animator.phaseX) { continue } let yVal = set.yValForXIndex(xIndex) if (yVal.isNaN) { continue } let y = CGFloat(yVal) * animator.phaseY; // get the y-position _highlightPointBuffer.x = CGFloat(xIndex) _highlightPointBuffer.y = y let trans = dataProvider.getTransformer(set.axisDependency) trans.pointValueToPixel(&_highlightPointBuffer) // draw the lines drawHighlightLines(context: context, point: _highlightPointBuffer, set: set) } CGContextRestoreGState(context) } }
apache-2.0
0f85b6ddd464f6711e9aeeadad0a3f32
38.576355
141
0.518795
6.455605
false
false
false
false
benlangmuir/swift
test/api-digester/Inputs/cake_current/cake.swift
7
5262
import APINotesTest public struct S1 { public init(_ : Double) {} mutating public func foo1() {} mutating public func foo2() {} public static func foo3() {} public func foo4() {} public func foo5(x : Int, y: Int, z: Int) {} } public class C0 { public func foo4(a : Void?) {} } public class C1: C0 { public func foo1() {} public func foo2(_ : ()->()) {} public var CIIns1 : C1? public weak var CIIns2 : C1? public func foo3(a : ()?) {} public init(_ : C1) {} } public typealias C3 = C1 public struct NSSomestruct2 { public static func foo1(_ a : C3) {} } public class C4: NewType {} public class C5 { @objc public dynamic func dy_foo() {} } @frozen public struct C6 {} public enum IceKind {} @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) public enum FutureKind { case FineToAdd } public protocol P1 {} public protocol P2 {} public extension P1 { func P1Constraint() {} } @frozen public struct fixedLayoutStruct { public var a = 1 public func OKChange() {} private static let constant = 0 public var b = 2 public func foo() {} private var c = 3 private lazy var lazy_d = 4 public var height: Int { get { return 0 } } } @usableFromInline @frozen struct fixedLayoutStruct2 { public var NoLongerWithFixedBinaryOrder: Int { return 1 } public var BecomeFixedBinaryOrder = 1 } @frozen public enum FrozenKind { case Unchanged case Rigid case Fixed case AddedCase } public class C7: P1 { public func foo(_ a: Int, _ b: Int) {} } public class C8: C7 {} public protocol P3: P1, P4 {} public protocol P4 {} extension fixedLayoutStruct: P2 {} public protocol AssociatedTypePro { associatedtype T1 associatedtype T2 associatedtype T3 = C6 } public class RemoveSetters { public private(set) var Value = 4 public subscript(_ idx: Int) -> Int { get { return 1 } } } public protocol RequirementChanges { associatedtype addedTypeWithDefault = Int associatedtype addedTypeWithoutDefault func addedFunc() var addedVar: Int { get } } /// This protocol shouldn't be complained because its requirements are all derived. public protocol DerivedProtocolRequirementChanges: RequirementChanges {} public class SuperClassRemoval {} public struct ClassToStruct { public init() {} } open class ClassWithMissingDesignatedInits { // Remove the @_hasMissingDesignatedInitializers attribute public init() {} public convenience init(x: Int) { self.init() } } open class ClassWithoutMissingDesignatedInits { // Add the @_hasMissingDesignatedInitializers attribute by adding an inaccessible // init public init() {} public convenience init(x: Int) { self.init() } internal init(y: Int) {} } public class SubclassWithMissingDesignatedInits: ClassWithMissingDesignatedInits { } public class SubclassWithoutMissingDesignatedInits: ClassWithoutMissingDesignatedInits { } public enum ProtocolToEnum {} public class SuperClassChange: C8 {} public class GenericClass<T> {} public class SubGenericClass: GenericClass<P2> {} @objc public protocol ObjCProtocol { @objc func removeOptional() @objc optional func addOptional() } public var GlobalLetChangedToVar = 1 public let GlobalVarChangedToLet = 1 public class ClassWithOpenMember { public class func foo() {} public var property: Int {get { return 1}} public func bar() {} } public class EscapingFunctionType { public func removedEscaping(_ a: ()->()) {} public func addedEscaping(_ a: @escaping ()->()) {} } prefix operator ..*.. public func ownershipChange(_ a: Int, _ b: __owned Int) {} @usableFromInline @_fixed_layout class _NoResilientClass { @usableFromInline func NoLongerFinalFunc() {} private func FuncPositionChange1() {} private func FuncPositionChange0() {} private func FuncPositionChange2() {} } public class FinalFuncContainer { public final func NewFinalFunc() {} public func NoLongerFinalFunc() {} } public protocol AssociatedTypesProtocol { associatedtype T } public class TChangesFromIntToString: AssociatedTypesProtocol { public typealias T = String } public protocol HasMutatingMethod { mutating func foo() var bar: Int { mutating get } } public protocol HasMutatingMethodClone: HasMutatingMethod { func foo() var bar: Int { get } } public protocol Animal {} public class Cat: Animal { public init() {} } public class Dog: Animal { public init() {} } public class Zoo { public init() {} @inlinable @available(iOS 13.0, OSX 10.15, tvOS 13.0, watchOS 6.0, *) public var current: some Animal { return Dog() } @inlinable @available(iOS 13.0, OSX 10.15, tvOS 13.0, watchOS 6.0, *) public func getCurrentAnimalInlinable() -> [some Animal] { return [Dog()] } } public func returnFunctionTypeOwnershipChange() -> (__owned C1) -> () { return { _ in } } @objc(NewObjCClass) public class SwiftObjcClass { @objc(NewObjCFool:NewObjCA:NewObjCB:) public func foo(a:Int, b:Int, c: Int) {} } @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) open class AddingNewDesignatedInit { public init(_ b: Bool) {} public init() {} public convenience init(foo: Int) { self.init() print(foo) } } public extension Float { func floatHigher() {} } infix operator <==> : AssignmentPrecedence
apache-2.0
b1e5c431705675eafc3bdd5e8fd5d9e9
19.716535
89
0.702775
3.664345
false
false
false
false
swipesight/BWWalkthrough
Example/ViewController.swift
2
2031
// // ViewController.swift // BWWalkthroughExample // // Created by Yari D'areglia on 17/09/14. import UIKit import BWWalkthrough class ViewController: UIViewController, BWWalkthroughViewControllerDelegate { override func viewDidLoad() { super.viewDidLoad() } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) let userDefaults = UserDefaults.standard if !userDefaults.bool(forKey: "walkthroughPresented") { showWalkthrough() userDefaults.set(true, forKey: "walkthroughPresented") userDefaults.synchronize() } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } @IBAction func showWalkthrough(){ // Get view controllers and build the walkthrough let stb = UIStoryboard(name: "Walkthrough", bundle: nil) let walkthrough = stb.instantiateViewController(withIdentifier: "walk") as! BWWalkthroughViewController let page_zero = stb.instantiateViewController(withIdentifier: "walk0") let page_one = stb.instantiateViewController(withIdentifier: "walk1") let page_two = stb.instantiateViewController(withIdentifier: "walk2") let page_three = stb.instantiateViewController(withIdentifier: "walk3") // Attach the pages to the master walkthrough.delegate = self walkthrough.add(viewController:page_one) walkthrough.add(viewController:page_two) walkthrough.add(viewController:page_three) walkthrough.add(viewController:page_zero) self.present(walkthrough, animated: true, completion: nil) } // MARK: - Walkthrough delegate - func walkthroughPageDidChange(_ pageNumber: Int) { print("Current Page \(pageNumber)") } func walkthroughCloseButtonPressed() { self.dismiss(animated: true, completion: nil) } }
mit
8f73c109059cd0171780fb00ba4b3cce
29.772727
111
0.650419
5.330709
false
false
false
false
blockchain/My-Wallet-V3-iOS
Modules/Platform/Sources/PlatformKit/Services/SecureChannel/SecureChannelService.swift
1
12930
// Copyright © Blockchain Luxembourg S.A. All rights reserved. import Combine import CommonCryptoKit import DIKit import FeatureAuthenticationDomain import Localization import RxSwift import ToolKit public protocol SecureChannelAPI: AnyObject { func isPairingQRCode(msg: String) -> Bool func onQRCodeScanned(msg: String) -> Completable func isReadyForSecureChannel() -> Single<Bool> func didAcceptSecureChannel(details: SecureChannelConnectionDetails) -> Completable func didRejectSecureChannel(details: SecureChannelConnectionDetails) -> Completable /// Creates a `SecureChannelConnectionCandidate` from the given `userInfo` notification payload. /// - Parameter userInfo: Received notification payload. /// - Returns: Single that emits a `SecureChannelConnectionCandidate` object or nil if the payload is malformed or the browser identity is unknown. func createSecureChannelConnectionCandidate( _ userInfo: [AnyHashable: Any] ) -> Single<SecureChannelConnectionCandidate> } public enum SecureChannelError: LocalizedError, Equatable { private typealias LocalizedString = LocalizationConstants.SecureChannel.Alert case missingGUID case missingSharedKey case missingPassword case malformedPayload case ipMismatch(originIP: String, deviceIP: String) case cantValidateIP case connectionExpired case identityError(IdentityError) case messageError(MessageError) public var errorDescription: String { switch self { case .missingGUID, .missingSharedKey, .missingPassword, .malformedPayload: return LocalizedString.network case .ipMismatch(let originIP, let deviceIP): // only show IPs in internal build if BuildFlag.isInternal { return "\(LocalizedString.ipMismatch)\n\n" + "\(LocalizedString.originIP): \(originIP)\n" + "\(LocalizedString.deviceIP): \(deviceIP)" } else { return LocalizedString.ipMismatch } case .connectionExpired: return LocalizedString.connectionExpired case .cantValidateIP, .identityError, .messageError: return LocalizedString.generic } } } final class SecureChannelService: SecureChannelAPI { // MARK: Private Properties private let browserIdentityService: BrowserIdentityService private let secureChannelNetwork: SecureChannelClientAPI private let walletRepository: WalletRepositoryAPI private let messageService: SecureChannelMessageService // MARK: Init init( browserIdentityService: BrowserIdentityService = resolve(), messageService: SecureChannelMessageService = resolve(), secureChannelNetwork: SecureChannelClientAPI = resolve(), walletRepository: WalletRepositoryAPI = resolve() ) { self.browserIdentityService = browserIdentityService self.messageService = messageService self.secureChannelNetwork = secureChannelNetwork self.walletRepository = walletRepository } // MARK: - SecureChannelAPI func isPairingQRCode(msg: String) -> Bool { decodePairingCode(payload: msg) != nil } func createSecureChannelConnectionCandidate( _ userInfo: [AnyHashable: Any] ) -> Single<SecureChannelConnectionCandidate> { guard let details = SecureChannelConnectionDetails(userInfo) else { return .error(SecureChannelError.malformedPayload) } return browserIdentityService.getBrowserIdentity(pubKeyHash: details.pubkeyHash) .mapError(SecureChannelError.identityError) .flatMap { browserIdentity -> Result<(SecureChannelConnectionCandidate, BrowserIdentity), SecureChannelError> in decryptMessage(details.messageRawEncrypted, pubKeyHash: details.pubkeyHash) .map { message -> SecureChannelConnectionCandidate in SecureChannelConnectionCandidate( details: details, isAuthorized: browserIdentity.authorized, timestamp: message.timestamp, lastUsed: browserIdentity.lastUsed ) } .map { candidate in (candidate, browserIdentity) } } .single .flatMap(weak: self) { (self, data) -> Single<SecureChannelConnectionCandidate> in let (candidate, browserIdentity) = data return self.shouldAcceptSecureChannel( details: details, candidate: candidate, browserIdentity: browserIdentity ) .andThen(Single.just(candidate)) } } func isReadyForSecureChannel() -> Single<Bool> { Single.zip( walletRepository.hasGuid.asSingle(), walletRepository.hasSharedKey.asSingle(), walletRepository.hasPassword.asSingle() ) .map { hasGuid, hasSharedKey, hasPassword in hasGuid && hasSharedKey && hasPassword } .catchAndReturn(false) } func didAcceptSecureChannel(details: SecureChannelConnectionDetails) -> Completable { browserIdentityService .addBrowserIdentityAuthorization(pubKeyHash: details.pubkeyHash, authorized: true) .flatMap { browserIdentityService.updateBrowserIdentityUsedTimestamp(pubKeyHash: details.pubkeyHash) } .mapError(SecureChannelError.identityError) .flatMap { decryptMessage(details.messageRawEncrypted, pubKeyHash: details.pubkeyHash) } .single .flatMapCompletable(weak: self) { (self, message) in self.sendLoginMessage(channelId: message.channelId, pubKeyHash: details.pubkeyHash) } } func onQRCodeScanned(msg: String) -> Completable { guard let pairingCode = decodePairingCode(payload: msg) else { preconditionFailure("Not a pairing code.") } return sendHandshake(pairingCode: pairingCode) } func didRejectSecureChannel(details: SecureChannelConnectionDetails) -> Completable { decryptMessage(details.messageRawEncrypted, pubKeyHash: details.pubkeyHash) .single .flatMapCompletable(weak: self) { (self, message) in self.sendMessage( SecureChannel.EmptyResponse(), channelId: message.channelId, pubKeyHash: details.pubkeyHash, success: false ) .andThen(self.browserIdentityService.deleteBrowserIdentity(pubKeyHash: details.pubkeyHash).completable) } } // MARK: - Private Methods private func shouldAcceptSecureChannel( details: SecureChannelConnectionDetails, candidate: SecureChannelConnectionCandidate, browserIdentity: BrowserIdentity ) -> Completable { validateTimestamp(candidate: candidate) .andThen(validateIPAddress(details: details, browserIdentity: browserIdentity)) } private func validateTimestamp(candidate: SecureChannelConnectionCandidate) -> Completable { Completable.create { observer -> Disposable in let fiveMinutesAgo = Date(timeIntervalSinceNow: -5 * 60) if candidate.timestamp >= fiveMinutesAgo { observer(.completed) } else { observer(.error(SecureChannelError.connectionExpired)) } return Disposables.create() } } private func validateIPAddress( details: SecureChannelConnectionDetails, browserIdentity: BrowserIdentity ) -> Completable { guard !browserIdentity.authorized else { // IP Check only applies to new connections. return .empty() } return secureChannelNetwork.getIp() .mapError { _ in SecureChannelError.cantValidateIP } .flatMap { ip -> AnyPublisher<Void, SecureChannelError> in guard details.originIP == ip else { return .failure(.ipMismatch(originIP: details.originIP, deviceIP: ip)) } return .just(()) } .eraseToAnyPublisher() .asObservable() .ignoreElements() .asCompletable() } private func decodePairingCode(payload: String) -> SecureChannel.PairingCode? { guard let data = payload.data(using: .utf8) else { return nil } return try? JSONDecoder().decode(SecureChannel.PairingCode.self, from: data) } private func sendHandshake(pairingCode: SecureChannel.PairingCode) -> Completable { let browserIdentity = BrowserIdentity(pubKey: pairingCode.pubkey) return browserIdentityService .addBrowserIdentity(identity: browserIdentity) .single .flatMap(weak: self) { (self, _) -> Single<String?> in self.walletRepository.guid.asSingle() } .map { guid -> SecureChannel.PairingHandshake in guard let guid = guid else { throw SecureChannelError.missingGUID } return SecureChannel.PairingHandshake(guid: guid) } .flatMapCompletable(weak: self) { (self, handshake) in self.sendMessage( handshake, channelId: pairingCode.channelId, pubKeyHash: browserIdentity.pubKeyHash, success: true ) } } private func sendLoginMessage(channelId: String, pubKeyHash: String) -> Completable { Single.zip( walletRepository.guid.asSingle(), walletRepository.sharedKey.asSingle(), walletRepository.password.asSingle() ) .map { guid, sharedKey, password -> (guid: String, sharedKey: String, password: String) in guard let guid = guid else { throw SecureChannelError.missingGUID } guard let sharedKey = sharedKey else { throw SecureChannelError.missingSharedKey } guard let password = password else { throw SecureChannelError.missingPassword } return (guid, sharedKey, password) } .map { guid, sharedKey, password in SecureChannel.LoginMessage(guid: guid, password: password, sharedKey: sharedKey) } .flatMapCompletable(weak: self) { (self, message) in self.sendMessage( message, channelId: channelId, pubKeyHash: pubKeyHash, success: true ) } } private func decryptMessage( _ message: String, pubKeyHash: String ) -> Result<SecureChannel.BrowserMessage, SecureChannelError> { browserIdentityService .getBrowserIdentity(pubKeyHash: pubKeyHash) .mapError(SecureChannelError.identityError) .flatMap { browserIdentity in let deviceKey = browserIdentityService.getDeviceKey() return messageService .decryptMessage( message, publicKey: Data(hex: browserIdentity.pubKey), deviceKey: deviceKey ) .mapError(SecureChannelError.messageError) } } private func sendMessage<Message: Encodable>( _ message: Message, channelId: String, pubKeyHash: String, success: Bool ) -> Completable { browserIdentityService.getBrowserIdentity(pubKeyHash: pubKeyHash) .eraseError() .flatMap { browserIdentity -> Result<SecureChannel.PairingResponse, Error> in let deviceKey = browserIdentityService.getDeviceKey() return messageService.buildMessage( message: message, channelId: channelId, success: success, publicKey: Data(hex: browserIdentity.pubKey), deviceKey: deviceKey ) .eraseError() } .single .flatMapCompletable(weak: self) { (self, response) -> Completable in self.secureChannelNetwork.sendMessage(msg: response) .asObservable() .ignoreElements() .asCompletable() } } }
lgpl-3.0
73fc602e2aaf764758c1605eb5b38b1a
38.060423
151
0.609483
5.68058
false
false
false
false
blockchain/My-Wallet-V3-iOS
Modules/CryptoAssets/Sources/BitcoinKit/Models/Accounts/KeyPair/BitcoinKeyPairDeriver.swift
1
2342
// Copyright © Blockchain Luxembourg S.A. All rights reserved. import PlatformKit import RxSwift import WalletCore struct BitcoinPrivateKey: Equatable { let xpriv: String init(xpriv: String) { self.xpriv = xpriv } } struct BitcoinKeyPair: KeyPair, Equatable { let xpub: String let privateKey: BitcoinPrivateKey init(privateKey: BitcoinPrivateKey, xpub: String) { self.privateKey = privateKey self.xpub = xpub } } struct BitcoinKeyDerivationInput: KeyDerivationInput, Equatable { let mnemonic: String let passphrase: String init(mnemonic: String, passphrase: String = "") { self.mnemonic = mnemonic self.passphrase = passphrase } } protocol BitcoinKeyPairDeriverAPI: KeyPairDeriverAPI where Input == BitcoinKeyDerivationInput, Pair == BitcoinKeyPair { func derive(input: Input) -> Result<Pair, HDWalletError> } class AnyBitcoinKeyPairDeriver: BitcoinKeyPairDeriverAPI { private let deriver: AnyKeyPairDeriver<BitcoinKeyPair, BitcoinKeyDerivationInput, HDWalletError> // MARK: - Init convenience init() { self.init(with: BitcoinKeyPairDeriver()) } init<D: KeyPairDeriverAPI>( with deriver: D ) where D.Input == BitcoinKeyDerivationInput, D.Pair == BitcoinKeyPair, D.Error == HDWalletError { self.deriver = AnyKeyPairDeriver(deriver: deriver) } func derive(input: BitcoinKeyDerivationInput) -> Result<BitcoinKeyPair, HDWalletError> { deriver.derive(input: input) } } class BitcoinKeyPairDeriver: BitcoinKeyPairDeriverAPI { func derive(input: BitcoinKeyDerivationInput) -> Result<BitcoinKeyPair, HDWalletError> { let bitcoinCoinType = CoinType.bitcoin guard let hdwallet = HDWallet(mnemonic: input.mnemonic, passphrase: input.passphrase) else { return .failure(.walletFailedToInitialise()) } let privateKey = hdwallet.getExtendedPrivateKey(purpose: .bip44, coin: bitcoinCoinType, version: .xprv) let xpub = hdwallet.getExtendedPublicKey(purpose: .bip44, coin: bitcoinCoinType, version: .xpub) let bitcoinPrivateKey = BitcoinPrivateKey(xpriv: privateKey) let keyPair = BitcoinKeyPair( privateKey: bitcoinPrivateKey, xpub: xpub ) return .success(keyPair) } }
lgpl-3.0
28c297b22c36ad0f417d8ace767d371c
29.802632
119
0.70141
4.187835
false
false
false
false
robzimpulse/mynurzSDK
mynurzSDK/Classes/TokenController.swift
1
2527
// // Token.swift // Pods // // Created by Robyarta on 5/6/17. // // import Foundation import RealmSwift public class Token: Object{ public dynamic var token = "" public dynamic var tokenIssuedAt = "" public dynamic var tokenExpiredAt = "" public dynamic var tokenLimitToRefresh = "" public dynamic var roleId = 0 } class FirebaseToken: Object { dynamic var token = "" dynamic var tokenIssuedAt = "" dynamic var tokenExpiredAt = "" } class FirebaseTokenController { static let sharedInstance = FirebaseTokenController() var realm: Realm? func get() -> FirebaseToken? { self.realm = try! Realm() return self.realm!.objects(FirebaseToken.self).first } func put(token:String, tokenIssuedAt:String, tokenExpiredAt:String){ self.realm = try! Realm() try! self.realm!.write { let currentToken = FirebaseToken() currentToken.token = token currentToken.tokenIssuedAt = tokenIssuedAt currentToken.tokenExpiredAt = tokenExpiredAt if let oldToken = self.realm!.objects(FirebaseToken.self).first { self.realm?.delete(oldToken) } self.realm!.add(currentToken) } } func drop(){ self.realm = try! Realm() try! self.realm!.write { self.realm?.delete((self.realm?.objects(FirebaseToken.self))!) } } } class TokenController { static let sharedInstance = TokenController() var realm: Realm? func get() -> Token? { self.realm = try! Realm() return self.realm!.objects(Token.self).first } func put(token:String, tokenIssuedAt:String, tokenExpiredAt:String, tokenLimitToRefresh:String, roleId:Int){ self.realm = try! Realm() try! self.realm!.write { let currentToken = Token() currentToken.token = token currentToken.tokenIssuedAt = tokenIssuedAt currentToken.tokenExpiredAt = tokenExpiredAt currentToken.tokenLimitToRefresh = tokenLimitToRefresh currentToken.roleId = roleId if let oldToken = self.realm!.objects(Token.self).first { self.realm?.delete(oldToken) } self.realm!.add(currentToken) } } func drop(){ self.realm = try! Realm() try! self.realm!.write { self.realm?.delete((self.realm?.objects(Token.self))!) } } }
mit
f6b1a1ca1b6fca2f27d6062e69bccd32
26.769231
112
0.600317
4.371972
false
false
false
false
nextgenappsllc/NGAEssentials
NGAEssentials/Classes/NGADevice.swift
1
3753
// // NGADevice.swift // Pods // // Created by Jose Castellanos on 5/2/17. // // import Foundation import UIKit import SystemConfiguration public struct NGADevice { public static var currentScreenBounds:CGRect { get { return UIScreen.main.bounds } } public static var portraitScreenBounds:CGRect { get { return UIScreen.main.nativeBounds } } public static var screenLongSide:CGFloat { get { var temp:CGFloat = 0 temp = currentScreenBounds.size.height > currentScreenBounds.size.width ? currentScreenBounds.size.height : currentScreenBounds.size.width return temp } } public static var screenShortSide:CGFloat { get { var temp:CGFloat = 0 temp = currentScreenBounds.size.height < currentScreenBounds.size.width ? currentScreenBounds.size.height : currentScreenBounds.size.width return temp } } public static var window:UIWindow? { get{ guard let w = UIApplication.shared.delegate?.window else {return nil} return w } } public static var statusBarFrame:CGRect {get{return UIApplication.shared.statusBarFrame}} public static var windowShortSide:CGFloat { get { return window?.bounds.shortSide ?? screenShortSide } } public static var windowLongSide:CGFloat { get { return window?.bounds.longSide ?? screenLongSide } } public static var cellularConnected:Bool { var temp = false var flags = SCNetworkReachabilityFlags(rawValue: 0) let netReachability = SCNetworkReachabilityCreateWithName(kCFAllocatorDefault, "www.google.com") if netReachability != nil { SCNetworkReachabilityGetFlags(netReachability!, &flags) } temp = (flags.rawValue & SCNetworkReachabilityFlags.isWWAN.rawValue) != 0 return temp } public static var networkConnected:Bool { var temp = false var flags = SCNetworkReachabilityFlags(rawValue: 0) var retrievedFlags = false let netReachability = SCNetworkReachabilityCreateWithName(kCFAllocatorDefault, "www.google.com") if netReachability != nil { retrievedFlags = SCNetworkReachabilityGetFlags(netReachability!, &flags) } temp = !(!retrievedFlags || flags.rawValue == 0) return temp } public static var wifiConnected:Bool { var temp = false temp = cellularConnected ? false : networkConnected return temp } public static var iPad:Bool { get { return UIDevice.current.userInterfaceIdiom == UIUserInterfaceIdiom.pad } } public static var iPhone:Bool { get { return UIDevice.current.userInterfaceIdiom == UIUserInterfaceIdiom.phone } } public static var multitasking:Bool { get { guard #available(iOS 9.0, *) else {return false} return screenShortSide > windowShortSide } } public static var remSize:CGFloat { get { return remSizeFor(currentScreenBounds.size) } } public static var emSize:CGFloat { get{ guard let window = window else {return remSize} return remSizeFor(window.frameSize) } } public static func remSizeFor(_ size:CGSize) -> CGFloat { return size.diagonalLength * 0.019 } public static func remSizeFor(_ view:UIView) -> CGFloat { return remSizeFor(view.frameSize) } }
mit
f154f462198c609478e3dae195c06d8e
27.431818
150
0.608846
5.148148
false
false
false
false
calkinssean/TIY-Assignments
Day 23/SpotifyAPI 2/Album.swift
1
2018
// // Album.swift // SpotifyAPI // // Created by Sean Calkins on 2/29/16. // Copyright © 2016 Dape App Productions LLC. All rights reserved. // import Foundation class Album: NSObject, NSCoding { //NSCoding Constants let kAlbumTitle = "title" let kAlbumImageUrls = "imageUrls" let kAlbumIdString = "idString" let kAlbumSongs = "songs" var title: String = "" var imageUrls: [String] = [""] var idString: String = "" var songs = [Song]() override init() { } init(dict: JSONDictionary) { if let title = dict["name"] as? String { self.title = title print(title) } else { print("couldn't parse album title") } if let idString = dict["id"] as? String { self.idString = idString } else { print("couldn't parse album idString") } if let items = dict["images"] as? JSONArray { for item in items { if let imageUrl = item["url"] as? String { self.imageUrls.append(imageUrl) print(imageUrls.count) } else { print("error with album image url") } } } } required init?(coder aDecoder: NSCoder) { self.title = aDecoder.decodeObjectForKey(kAlbumTitle) as! String self.imageUrls = aDecoder.decodeObjectForKey(kAlbumImageUrls) as! [String] self.idString = aDecoder.decodeObjectForKey(kAlbumIdString) as! String self.songs = aDecoder.decodeObjectForKey(kAlbumSongs) as! [Song] super.init() } func encodeWithCoder(aCoder: NSCoder) { aCoder.encodeObject(title, forKey: kAlbumTitle) aCoder.encodeObject(imageUrls, forKey: kAlbumImageUrls) aCoder.encodeObject(idString, forKey: kAlbumIdString) aCoder.encodeObject(songs, forKey: kAlbumSongs) } }
cc0-1.0
0baef453844328fc541287049d2e46e0
27.828571
82
0.559742
4.573696
false
false
false
false
MidnightPulse/Tabman
Sources/Tabman/TabmanBar/Components/Indicator/Views/TabmanChevronView.swift
3
829
// // TabmanChevronView.swift // Tabman // // Created by Merrick Sapsford on 17/03/2017. // Copyright © 2017 Merrick Sapsford. All rights reserved. // import UIKit internal class TabmanChevronView: UIView { private var chevronLayer = CAShapeLayer() override func layoutSubviews() { super.layoutSubviews() self.superview?.layoutIfNeeded() let path = UIBezierPath() path.move(to: CGPoint(x: 0.0, y: self.bounds.size.height)) path.addLine(to: CGPoint(x: self.bounds.size.width / 2, y: 0.0)) path.addLine(to: CGPoint(x: self.bounds.size.width, y: self.bounds.size.height)) path.close() self.chevronLayer.frame = self.bounds self.chevronLayer.path = path.cgPath self.layer.mask = self.chevronLayer } }
mit
683c2fe14dc3b8201283c364dc93ebc8
26.6
88
0.63285
3.851163
false
false
false
false
balitm/BLECentralManager
Examples/Peripheral_Example/Peripheral.swift
1
9326
// // Peripheral.swift // Peripheral_Example // // Created by Balázs Kilvády on 6/23/16. // Copyright © 2016 kil-dev. All rights reserved. // import Foundation import CoreBluetooth class Peripheral: NSObject { fileprivate let _kDataServiceUUID = CBUUID(string: "965F6F06-2198-4F4F-A333-4C5E0F238EB7") fileprivate let _kDataCharacteristicUUID = CBUUID(string: "89E63F02-9932-4DF1-91C7-A574C880EFBF") fileprivate let _kControlCharacteristicUUID = CBUUID(string: "88359D38-DEA0-4FA4-9DD2-0A47E2B794BE") fileprivate weak var _delegate: PeripheralDelegate! fileprivate var _sampleData: Data? fileprivate var _repeatCount: UInt = 0 fileprivate var _manager: CBPeripheralManager! fileprivate var _dataCharacteristic: CBMutableCharacteristic? fileprivate var _controlCharacteristic: CBMutableCharacteristic? fileprivate var _dataService: CBMutableService? fileprivate var _serviceRequiresRegistration = false fileprivate var _subscribers = [CBCentral]() var subscribersCount: Int { get { return _subscribers.count } } init(delegate: PeripheralDelegate) { super.init() _delegate = delegate _manager = CBPeripheralManager(delegate: self, queue: nil, options: [CBPeripheralManagerOptionShowPowerAlertKey: true]) } fileprivate func _enableDataService() { // If the service is already registered, we need to re-register it again. _disableDataService() // Create a BTLE Peripheral Service and set it to be the primary. If it // is not set to the primary, it will not be found when the app is in the // background. _dataService = CBMutableService(type: _kDataServiceUUID, primary: true) // Set up the characteristic in the service. This characteristic is only // readable through subscription (CBCharacteristicsPropertyNotify) _dataCharacteristic = CBMutableCharacteristic(type: _kDataCharacteristicUUID, properties: .notify, value: nil, permissions: .readable) _controlCharacteristic = CBMutableCharacteristic(type: _kControlCharacteristicUUID, properties: [.read, .write], value: nil, permissions: [.readable, .writeable]) guard let service = _dataService, let characteristic = _dataCharacteristic, let ctrlCharacteristic = _controlCharacteristic else { return } // Assign the characteristic. service.characteristics = [characteristic, ctrlCharacteristic] // Add the service to the peripheral manager. _manager.add(service) } fileprivate func _disableDataService() { if let service = _dataService { _manager.remove(service) _dataService = nil } } // Called when the BTLE advertisments should start. func startAdvertising() { if (_manager.isAdvertising) { _manager.stopAdvertising() } let advertisment = [CBAdvertisementDataServiceUUIDsKey : [_kDataServiceUUID]] _manager.startAdvertising(advertisment) } func stopAdvertising() { _manager.stopAdvertising() } fileprivate func _notifySubscribers() { while _repeatCount > 0 { let res = _manager.updateValue(_sampleData!, for: _dataCharacteristic!, onSubscribedCentrals: nil) // DLog("Sending \(_sampleData?.bytes) data, rc: \(_repeatCount), max: \(_subscribers.count > 0 ? _subscribers[0].maximumUpdateValueLength : 0)") if (!res) { // DLog("Failed to send data, buffering data for retry once ready.") // _pendingData = _sampleData break } else { _repeatCount -= 1 } } } func sendToSubscribers(_ data: Data, repeatCount: UInt) { guard _manager.state == .poweredOn else { _delegate.logMessage("sendToSubscribers: peripheral not ready for sending state: \(_manager.state)") return } guard let _ = _dataCharacteristic else { return } _repeatCount = repeatCount _sampleData = data // DLog("repeat count set to \(repeatCount)") _notifySubscribers() } } extension Peripheral: CBPeripheralManagerDelegate { func peripheralManagerDidUpdateState(_ peripheral: CBPeripheralManager) { switch peripheral.state { case .poweredOn: _delegate.logMessage("Peripheral powered on.") DLog("Peripheral powered on.") _enableDataService() case .poweredOff: _delegate.logMessage("Peripheral powered off.") _disableDataService() case .resetting: _delegate.logMessage("Peripheral resetting.") _serviceRequiresRegistration = true case .unauthorized: _delegate.logMessage("Peripheral unauthorized.") _serviceRequiresRegistration = true case .unknown: _delegate.logMessage("Peripheral unknown.") _serviceRequiresRegistration = true case .unsupported: _delegate.logMessage("Peripheral unsupported.") _serviceRequiresRegistration = true } } func peripheralManager(_ peripheral: CBPeripheralManager, didAdd service: CBService, error: Error?) { guard error == nil else { _delegate.logMessage("Failed to add a service: : \(error)") return } // As soon as the service is added, we should start advertising. if service == _dataService { _controlCharacteristic?.value = Data(bytes: UnsafePointer<UInt8>([UInt8(0)]), count: 1) startAdvertising() DLog("Peripheral advertising...") } } func peripheralManager(_ peripheral: CBPeripheralManager, central: CBCentral, didSubscribeTo characteristic: CBCharacteristic) { assert(!_subscribers.contains(central)) _subscribers.append(central) _manager.setDesiredConnectionLatency(.low, for: central) DLog("Appended - subscribers: \(_subscribers)") _delegate.central(central.identifier.uuidString, didSubscribeToCharacteristic: characteristic.uuid.uuidString) } func peripheralManager(_ peripheral: CBPeripheralManager, central: CBCentral, didUnsubscribeFrom characteristic: CBCharacteristic) { if let index = _subscribers.index(of: central) { _subscribers.remove(at: index) DLog("Removed - subscribers: \(_subscribers)") } else { assert(false) } _delegate.central(central.identifier.uuidString, didUnsubscribeFromCharacteristic: characteristic.uuid.uuidString) } func peripheralManagerDidStartAdvertising(_ peripheral: CBPeripheralManager, error: Error?) { guard error == nil else { _delegate.logMessage("Failed to start advertising: \(error).") return } _delegate.logMessage("advertising started.") } func peripheralManagerIsReady(toUpdateSubscribers peripheral: CBPeripheralManager) { // DLog("current repeat count is \(_repeatCount)") _notifySubscribers() } func peripheralManager(_ peripheral: CBPeripheralManager, didReceiveRead request: CBATTRequest) { guard let ctrlCharacteristic = _controlCharacteristic else { peripheral.respond(to: request, withResult: .invalidHandle) return } DLog("value to send: \(ctrlCharacteristic.value)") request.value = ctrlCharacteristic.value peripheral.respond(to: request, withResult: .success) } func peripheralManager(_ peripheral: CBPeripheralManager, didReceiveWrite requests: [CBATTRequest]) { guard let ctrlCharacteristic = _controlCharacteristic else { peripheral.respond(to: requests[0], withResult: .invalidHandle) return } for req in requests { if req.characteristic != _controlCharacteristic { continue } guard let value = req.value else { continue } assert(req.offset == 0 && value.count == 1) ctrlCharacteristic.value = value let array = value.withUnsafeBytes { [UInt8](UnsafeBufferPointer(start: $0, count: 1)) } let byte: UInt8 = array[0] _delegate.sending(byte != 0) } peripheral.respond(to: requests[0], withResult: .success) } }
bsd-3-clause
ea37cdd0c4833d90c76b69a3941ae247
37.053061
156
0.591119
5.559332
false
false
false
false
amosavian/FileProvider
Sources/OneDriveFileProvider.swift
2
33064
// // OneDriveFileProvider.swift // FileProvider // // Created by Amir Abbas Mousavian. // Copyright © 2017 Mousavian. Distributed under MIT license. // import Foundation #if os(macOS) || os(iOS) || os(tvOS) import CoreGraphics #endif /** Allows accessing to OneDrive stored files, either hosted on Microsoft servers or business coprporate one. This provider doesn't cache or save files internally, however you can set `useCache` and `cache` properties to use Foundation `NSURLCache` system. - Note: You can pass file id instead of file path, e.g `"id:1234abcd"`, to point to a file or folder by ID. - Note: Uploading files and data are limited to 100MB, for now. */ open class OneDriveFileProvider: HTTPFileProvider, FileProviderSharing { override open class var type: String { return "OneDrive" } /// Route to access file container on OneDrive. For default logined user use `.me` otherwise you can acesss /// container based on drive id, group id, site id or user id for another user's default container public enum Route: RawRepresentable { /// Access to default container for current user case me /// Access to a specific drive by id case drive(uuid: UUID) /// Access to a default drive of a group by their id case group(uuid: UUID) /// Access to a default drive of a site by their id case site(uuid: UUID) /// Access to a default drive of a user by their id case user(uuid: UUID) public init?(rawValue: String) { let components = rawValue.components(separatedBy: ";") guard let type = components.first else { return nil } if type == "me" { self = .me } guard let uuid = components.last.flatMap({ UUID(uuidString: $0) }) else { return nil } switch type { case "drive": self = .drive(uuid: uuid) case "group": self = .group(uuid: uuid) case "site": self = .site(uuid: uuid) case "user": self = .user(uuid: uuid) default: return nil } } public var rawValue: String { switch self { case .me: return "me;" case .drive(uuid: let uuid): return "drive;" + uuid.uuidString case .group(uuid: let uuid): return "group;" + uuid.uuidString case .site(uuid: let uuid): return "site;" + uuid.uuidString case .user(uuid: let uuid): return "user;" + uuid.uuidString } } /// Return path component in URL for selected drive var drivePath: String { switch self { case .me: return "me/drive" case .drive(uuid: let uuid): return "drives/" + uuid.uuidString case .group(uuid: let uuid): return "groups/" + uuid.uuidString + "/drive" case .site(uuid: let uuid): return "sites/" + uuid.uuidString + "/drive" case .user(uuid: let uuid): return "users/" + uuid.uuidString + "/drive" } } } /// Microsoft Graph URL public static var graphURL = URL(string: "https://graph.microsoft.com/")! /// Microsoft Graph URL public static var graphVersion = "v1.0" /// Route for container, default is `.me`. public let route: Route /** Initializer for Onedrive provider with given client ID and Token. These parameters must be retrieved via [Authentication for the OneDrive API](https://dev.onedrive.com/auth/readme.htm). There are libraries like [p2/OAuth2](https://github.com/p2/OAuth2) or [OAuthSwift](https://github.com/OAuthSwift/OAuthSwift) which can facilate the procedure to retrieve token. The latter is easier to use and prefered. - Parameters: - credential: a `URLCredential` object with Client ID set as `user` and Token set as `password`. - serverURL: server url, Set it if you are trying to connect OneDrive Business server, otherwise leave it `nil` to connect to OneDrive Personal user. - drive: drive name for user on server, default value is `root`. - cache: A URLCache to cache downloaded files and contents. */ @available(*, deprecated, message: "use init(credential:, serverURL:, route:, cache:) instead.") public convenience init(credential: URLCredential?, serverURL: URL? = nil, drive: String?, cache: URLCache? = nil) { let route: Route = drive.flatMap({ UUID(uuidString: $0) }).flatMap({ Route.drive(uuid: $0) }) ?? .me self.init(credential: credential, serverURL: serverURL, route: route, cache: cache) } /** Initializer for Onedrive provider with given client ID and Token. These parameters must be retrieved via [Authentication for the OneDrive API](https://dev.onedrive.com/auth/readme.htm). There are libraries like [p2/OAuth2](https://github.com/p2/OAuth2) or [OAuthSwift](https://github.com/OAuthSwift/OAuthSwift) which can facilate the procedure to retrieve token. The latter is easier to use and prefered. Also you can use [auth0/Lock](https://github.com/auth0/Lock.iOS-OSX) which provides graphical user interface. - Parameters: - credential: a `URLCredential` object with Client ID set as `user` and Token set as `password`. - serverURL: server url, Set it if you are trying to connect OneDrive Business server, otherwise leave it `nil` to connect to OneDrive Personal uses. - route: drive name for user on server, default value is `.me`. - cache: A URLCache to cache downloaded files and contents. */ public init(credential: URLCredential?, serverURL: URL? = nil, route: Route = .me, cache: URLCache? = nil) { let baseURL = (serverURL?.absoluteURL ?? OneDriveFileProvider.graphURL) .appendingPathComponent(OneDriveFileProvider.graphVersion, isDirectory: true) let refinedBaseURL = baseURL.absoluteString.hasSuffix("/") ? baseURL : baseURL.appendingPathComponent("") self.route = route super.init(baseURL: refinedBaseURL, credential: credential, cache: cache) } public required convenience init?(coder aDecoder: NSCoder) { let route: Route if let driveId = aDecoder.decodeObject(of: NSString.self, forKey: "drive") as String?, let uuid = UUID(uuidString: driveId) { route = .drive(uuid: uuid) } else { route = (aDecoder.decodeObject(of: NSString.self, forKey: "route") as String?).flatMap({ Route(rawValue: $0) }) ?? .me } self.init(credential: aDecoder.decodeObject(of: URLCredential.self, forKey: "credential"), serverURL: aDecoder.decodeObject(of: NSURL.self, forKey: "baseURL") as URL?, route: route) self.useCache = aDecoder.decodeBool(forKey: "useCache") self.validatingCache = aDecoder.decodeBool(forKey: "validatingCache") } open override func encode(with aCoder: NSCoder) { super.encode(with: aCoder) aCoder.encode(self.route.rawValue, forKey: "route") } open override func copy(with zone: NSZone? = nil) -> Any { let copy = OneDriveFileProvider(credential: self.credential, serverURL: self.baseURL, route: self.route, cache: self.cache) copy.delegate = self.delegate copy.fileOperationDelegate = self.fileOperationDelegate copy.useCache = self.useCache copy.validatingCache = self.validatingCache return copy } /** Returns an Array of `FileObject`s identifying the the directory entries via asynchronous completion handler. If the directory contains no entries or an error is occured, this method will return the empty array. - Parameters: - path: path to target directory. If empty, root will be iterated. - completionHandler: a closure with result of directory entries or error. - contents: An array of `FileObject` identifying the the directory entries. - error: Error returned by system. */ open override func contentsOfDirectory(path: String, completionHandler: @escaping (_ contents: [FileObject], _ error: Error?) -> Void) { _ = paginated(path, requestHandler: { [weak self] (token) -> URLRequest? in guard let `self` = self else { return nil } let url = token.flatMap(URL.init(string:)) ?? self.url(of: path, modifier: "children") var request = URLRequest(url: url) request.httpMethod = "GET" request.setValue(authentication: self.credential, with: .oAuth2) return request }, pageHandler: { [weak self] (data, _) -> (files: [FileObject], error: Error?, newToken: String?) in guard let `self` = self else { return ([], nil, nil) } guard let json = data?.deserializeJSON(), let entries = json["value"] as? [Any] else { let err = URLError(.badServerResponse, url: self.url(of: path)) return ([], err, nil) } var files = [FileObject]() for entry in entries { if let entry = entry as? [String: Any], let file = OneDriveFileObject(baseURL: self.baseURL, route: self.route, json: entry) { files.append(file) } } return (files, nil, json["@odata.nextLink"] as? String) }, completionHandler: completionHandler) } /** Returns a `FileObject` containing the attributes of the item (file, directory, symlink, etc.) at the path in question via asynchronous completion handler. If the directory contains no entries or an error is occured, this method will return the empty `FileObject`. - Parameters: - path: path to target directory. If empty, attributes of root will be returned. - completionHandler: a closure with result of directory entries or error. - attributes: A `FileObject` containing the attributes of the item. - error: Error returned by system. */ open override func attributesOfItem(path: String, completionHandler: @escaping (_ attributes: FileObject?, _ error: Error?) -> Void) { var request = URLRequest(url: url(of: path)) request.httpMethod = "GET" request.setValue(authentication: self.credential, with: .oAuth2) let task = session.dataTask(with: request, completionHandler: { (data, response, error) in var serverError: FileProviderHTTPError? var fileObject: OneDriveFileObject? if let response = response as? HTTPURLResponse, response.statusCode >= 400 { let code = FileProviderHTTPErrorCode(rawValue: response.statusCode) serverError = code.flatMap { self.serverError(with: $0, path: path, data: data) } } if let json = data?.deserializeJSON(), let file = OneDriveFileObject(baseURL: self.baseURL, route: self.route, json: json) { fileObject = file } completionHandler(fileObject, serverError ?? error) }) task.resume() } /// Returns volume/provider information asynchronously. /// - Parameter volumeInfo: Information of filesystem/Provider returned by system/server. open override func storageProperties(completionHandler: @escaping (_ volumeInfo: VolumeObject?) -> Void) { let url = URL(string: route.drivePath, relativeTo: baseURL)! var request = URLRequest(url: url) request.httpMethod = "GET" request.setValue(authentication: self.credential, with: .oAuth2) let task = session.dataTask(with: request, completionHandler: { (data, response, error) in guard let json = data?.deserializeJSON() else { completionHandler(nil) return } let volume = VolumeObject(allValues: [:]) volume.url = request.url volume.uuid = json["id"] as? String volume.name = json["name"] as? String volume.creationDate = (json["createdDateTime"] as? String).flatMap { Date(rfcString: $0) } let quota = json["quota"] as? [String: Any] volume.totalCapacity = (quota?["total"] as? NSNumber)?.int64Value ?? -1 volume.availableCapacity = (quota?["remaining"] as? NSNumber)?.int64Value ?? 0 completionHandler(volume) }) task.resume() } /** Search files inside directory using query asynchronously. Sample predicates: ``` NSPredicate(format: "(name CONTAINS[c] 'hello') && (fileSize >= 10000)") NSPredicate(format: "(modifiedDate >= %@)", Date()) NSPredicate(format: "(path BEGINSWITH %@)", "folder/child folder") ``` - Note: Don't pass Spotlight predicates to this method directly, use `FileProvider.convertSpotlightPredicateTo()` method to get usable predicate. - Important: A file name criteria should be provided for Dropbox. - Parameters: - path: location of directory to start search - recursive: Searching subdirectories of path - query: An `NSPredicate` object with keys like `FileObject` members, except `size` which becomes `filesize`. - foundItemHandler: Closure which is called when a file is found - completionHandler: Closure which will be called after finishing search. Returns an arry of `FileObject` or error if occured. - files: all files meat the `query` criteria. - error: `Error` returned by server if occured. - Returns: An `Progress` to get progress or cancel progress. Use `completedUnitCount` to iterate count of found items. */ @discardableResult open override func searchFiles(path: String, recursive: Bool, query: NSPredicate, foundItemHandler: ((FileObject) -> Void)?, completionHandler: @escaping (_ files: [FileObject], _ error: Error?) -> Void) -> Progress? { let queryStr = query.findValue(forKey: "name") as? String ?? query.findAllValues(forKey: nil).compactMap { $0.value as? String }.first return paginated(path, requestHandler: { [weak self] (token) -> URLRequest? in guard let `self` = self else { return nil } let url: URL if let next = token.flatMap(URL.init(string:)) { url = next } else { let bURL = self.baseURL!.appendingPathComponent(self.route.drivePath).appendingPathComponent("root/search") var components = URLComponents(url: bURL, resolvingAgainstBaseURL: false)! let qItem = URLQueryItem(name: "q", value: (queryStr ?? "*")) components.queryItems = [qItem] if recursive { components.queryItems?.append(URLQueryItem(name: "expand", value: "children")) } url = components.url! } var request = URLRequest(url: url) request.httpMethod = "GET" return request }, pageHandler: { [weak self] (data, progress) -> (files: [FileObject], error: Error?, newToken: String?) in guard let `self` = self else { return ([], nil, nil) } guard let json = data?.deserializeJSON(), let entries = json["value"] as? [Any] else { let err = URLError(.badServerResponse, url: self.url(of: path)) return ([], err, nil) } var foundFiles = [FileObject]() for entry in entries { if let entry = entry as? [String: Any], let file = OneDriveFileObject(baseURL: self.baseURL, route: self.route, json: entry), query.evaluate(with: file.mapPredicate()) { foundFiles.append(file) foundItemHandler?(file) } } return (foundFiles, nil, json["@odata.nextLink"] as? String) }, completionHandler: completionHandler) } /** Returns an independent url to access the file. Some providers like `Dropbox` due to their nature. don't return an absolute url to be used to access file directly. - Parameter path: Relative path of file or directory. - Returns: An url, can be used to access to file directly. */ open override func url(of path: String) -> URL { return OneDriveFileObject.url(of: path, modifier: nil, baseURL: baseURL!, route: route) } /** Returns an independent url to access the file. Some providers like `Dropbox` due to their nature. don't return an absolute url to be used to access file directly. - Parameter path: Relative path of file or directory. - Parameter modifier: Added to end of url to indicate what it can used for, e.g. `contents` to fetch data. - Returns: An url, can be used to access to file directly. */ open func url(of path: String, modifier: String? = nil) -> URL { return OneDriveFileObject.url(of: path, modifier: modifier, baseURL: baseURL!, route: route) } open override func relativePathOf(url: URL) -> String { return OneDriveFileObject.relativePathOf(url: url, baseURL: baseURL, route: route) } /// Checks the connection to server or permission on local /// /// - Note: To prevent race condition, use this method wisely and avoid it as far possible. /// /// - Parameter success: indicated server is reachable or not. open override func isReachable(completionHandler: @escaping (_ success: Bool, _ error: Error?) -> Void) { var request = URLRequest(url: url(of: "")) request.httpMethod = "HEAD" request.setValue(authentication: credential, with: .oAuth2) let task = session.dataTask(with: request, completionHandler: { (data, response, error) in let status = (response as? HTTPURLResponse)?.statusCode ?? 400 if status >= 400, let code = FileProviderHTTPErrorCode(rawValue: status) { let errorDesc = data.flatMap({ String(data: $0, encoding: .utf8) }) let error = FileProviderOneDriveError(code: code, path: "", serverDescription: errorDesc) completionHandler(false, error) return } completionHandler(status == 200, error) }) task.resume() } /*internal var cachedDriveID: String? override func doOperation(_ operation: FileOperationType, overwrite: Bool, progress: Progress?, completionHandler: SimpleCompletionHandler) -> Progress? { switch operation { case .copy(source: let source, destination: let dest) where !source.hasPrefix("file://") && !dest.hasPrefix("file://"): fallthrough case .move: if self.cachedDriveID != nil { return super.doOperation(operation, overwrite: overwrite, progress: progress, completionHandler: completionHandler) } else { let progress = Progress(totalUnitCount: 1) self.storageProperties(completionHandler: { (volume) in if let volumeId = volume?.uuid { self.cachedDriveID = volumeId _ = super.doOperation(operation, overwrite: overwrite, progress: progress, completionHandler: completionHandler) } else { let error = self.urlError(operation.source, code: .badServerResponse) completionHandler?(error) } }) return progress } default: return super.doOperation(operation, overwrite: overwrite, progress: progress, completionHandler: completionHandler) } }*/ /** Uploads a file from local file url to designated path asynchronously. Method will fail if source is not a local url with `file://` scheme. - Note: It's safe to assume that this method only works on individual files and **won't** copy folders recursively. - Parameters: - localFile: a file url to file. - to: destination path of file, including file/directory name. - overwrite: Destination file should be overwritten if file is already exists. **Default** is `false`. - completionHandler: If an error parameter was provided, a presentable `Error` will be returned. - Returns: An `Progress` to get progress or cancel progress. */ @discardableResult open override func copyItem(localFile: URL, to toPath: String, overwrite: Bool, completionHandler: SimpleCompletionHandler) -> Progress? { // check file is not a folder guard (try? localFile.resourceValues(forKeys: [.fileResourceTypeKey]))?.fileResourceType ?? .unknown == .regular else { dispatch_queue.async { completionHandler?(URLError(.fileIsDirectory, url: localFile)) } return nil } let operation = FileOperationType.copy(source: localFile.absoluteString, destination: toPath) guard fileOperationDelegate?.fileProvider(self, shouldDoOperation: operation) ?? true == true else { return nil } return self.upload_multipart_file(toPath, file: localFile, operation: operation, overwrite: overwrite, completionHandler: completionHandler) } /** Write the contents of the `Data` to a location asynchronously. It will return error if file is already exists. Not attomically by default, unless the provider enforces it. - Parameters: - path: Path of target file. - contents: Data to be written into file, pass nil to create empty file. - completionHandler: If an error parameter was provided, a presentable `Error` will be returned. - Returns: An `Progress` to get progress or cancel progress. Doesn't work on `LocalFileProvider`. */ @discardableResult open override func writeContents(path: String, contents data: Data?, atomically: Bool, overwrite: Bool, completionHandler: SimpleCompletionHandler) -> Progress? { let operation = FileOperationType.modify(path: path) guard fileOperationDelegate?.fileProvider(self, shouldDoOperation: operation) ?? true == true else { return nil } return upload_multipart_data(path, data: data ?? Data(), operation: operation, overwrite: overwrite, completionHandler: completionHandler) } override func request(for operation: FileOperationType, overwrite: Bool = false, attributes: [URLResourceKey : Any] = [:]) -> URLRequest { func correctPath(_ path: String) -> String { if path.hasPrefix("id:") { return path } var p = path.hasPrefix("/") ? path : "/" + path if p.hasSuffix("/") { p.remove(at: p.index(before:p.endIndex)) } return p } let method: String let url: URL switch operation { case .fetch(path: let path): method = "GET" url = self.url(of: path, modifier: "content") case .create(path: let path) where path.hasSuffix("/"): method = "POST" let parent = path.deletingLastPathComponent url = self.url(of: parent, modifier: "children") case .modify(path: let path): method = "PUT" let queryStr = overwrite ? "" : "[email protected]=fail" url = URL(string: self.url(of: path, modifier: "content").absoluteString + queryStr)! case .copy(source: let source, destination: let dest) where source.hasPrefix("file://"): method = "PUT" let queryStr = overwrite ? "" : "[email protected]=fail" url = URL(string: self.url(of: dest, modifier: "content").absoluteString + queryStr)! case .copy(source: let source, destination: let dest) where dest.hasPrefix("file://"): method = "GET" url = self.url(of: source, modifier: "content") case .copy(source: let source, destination: _): method = "POST" url = self.url(of: source, modifier: "copy") case .move(source: let source, destination: _): method = "PATCH" url = self.url(of: source) case .remove(path: let path): method = "DELETE" url = self.url(of: path) default: // link fatalError("Unimplemented operation \(operation.description) in \(#file)") } var request = URLRequest(url: url) request.httpMethod = method request.setValue(authentication: self.credential, with: .oAuth2) // Remove gzip to fix availability of progress re. (Oleg Marchik)[https://github.com/evilutioner] PR (#61) if method == "GET" { request.setValue(acceptEncoding: .deflate) request.addValue(acceptEncoding: .identity) } switch operation { case .create(path: let path) where path.hasSuffix("/"): request.setValue(contentType: .json) var requestDictionary = [String: Any]() let name = path.lastPathComponent requestDictionary["name"] = name requestDictionary["folder"] = [String: Any]() requestDictionary["@microsoft.graph.conflictBehavior"] = "fail" request.httpBody = Data(jsonDictionary: requestDictionary) case .copy(let source, let dest) where !source.hasPrefix("file://") && !dest.hasPrefix("file://"), .move(source: let source, destination: let dest): request.setValue(contentType: .json, charset: .utf8) let cdest = correctPath(dest) var parentReference: [String: Any] = [:] if cdest.hasPrefix("id:") { parentReference["id"] = cdest.components(separatedBy: "/").first?.replacingOccurrences(of: "id:", with: "", options: .anchored) } else { parentReference["path"] = "/drive/root:".appendingPathComponent(cdest.deletingLastPathComponent) } switch self.route { case .drive(uuid: let uuid): parentReference["driveId"] = uuid.uuidString default: //parentReference["driveId"] = cachedDriveID ?? "" break } var requestDictionary = [String: Any]() requestDictionary["parentReference"] = parentReference requestDictionary["name"] = cdest.lastPathComponent request.httpBody = Data(jsonDictionary: requestDictionary) default: break } return request } override func serverError(with code: FileProviderHTTPErrorCode, path: String?, data: Data?) -> FileProviderHTTPError { let errorDesc: String? if let response = data?.deserializeJSON() { errorDesc = (response["error"] as? [String: Any])?["message"] as? String } else { errorDesc = data.flatMap({ String(data: $0, encoding: .utf8) }) } return FileProviderOneDriveError(code: code, path: path ?? "", serverDescription: errorDesc) } override var maxUploadSimpleSupported: Int64 { return 4_194_304 // 4MB! } fileprivate func registerNotifcation(path: String, eventHandler: (() -> Void)) { /* There is two ways to monitor folders changing in OneDrive. Either using webooks * which means you have to implement a server to translate it to push notifications * or using apiv2 list_folder/longpoll method. The second one is implemeted here. * Tough webhooks are much more efficient, longpoll is much simpler to implement! * You can implemnt your own webhook service and replace this method accordingly. */ NotImplemented() } fileprivate func unregisterNotifcation(path: String) { NotImplemented() } open func publicLink(to path: String, completionHandler: @escaping ((_ link: URL?, _ attribute: FileObject?, _ expiration: Date?, _ error: Error?) -> Void)) { var request = URLRequest(url: self.url(of: path, modifier: "createLink")) request.httpMethod = "POST" let requestDictionary: [String: Any] = ["type": "view"] request.httpBody = Data(jsonDictionary: requestDictionary) let task = session.dataTask(with: request, completionHandler: { (data, response, error) in var serverError: FileProviderHTTPError? var link: URL? if let response = response as? HTTPURLResponse, response.statusCode >= 400 { let code = FileProviderHTTPErrorCode(rawValue: response.statusCode) serverError = code.flatMap { self.serverError(with: $0, path: path, data: data) } } if let json = data?.deserializeJSON() { if let linkDic = json["link"] as? [String: Any], let linkStr = linkDic["webUrl"] as? String { link = URL(string: linkStr) } } completionHandler(link, nil, nil, serverError ?? error) }) task.resume() } } extension OneDriveFileProvider: ExtendedFileProvider { open func propertiesOfFileSupported(path: String) -> Bool { return true } @discardableResult open func propertiesOfFile(path: String, completionHandler: @escaping ((_ propertiesDictionary: [String : Any], _ keys: [String], _ error: Error?) -> Void)) -> Progress? { var request = URLRequest(url: url(of: path)) request.httpMethod = "GET" request.setValue(authentication: credential, with: .oAuth2) let task = session.dataTask(with: request, completionHandler: { (data, response, error) in var serverError: FileProviderHTTPError? var dic = [String: Any]() var keys = [String]() if let response = response as? HTTPURLResponse { let code = FileProviderHTTPErrorCode(rawValue: response.statusCode) serverError = code.flatMap { self.serverError(with: $0, path: path, data: data) } } if let json = data?.deserializeJSON() { (dic, keys) = self.mapMediaInfo(json) } completionHandler(dic, keys, serverError ?? error) }) task.resume() return nil } #if os(macOS) || os(iOS) || os(tvOS) open func thumbnailOfFileSupported(path: String) -> Bool { let fileExt = path.pathExtension.lowercased() switch fileExt { case "jpg", "jpeg", "bmp", "gif", "png", "tif", "tiff": return true case "mp3", "aac", "m4a", "wma": return true case "mp4", "mpg", "3gp", "mov", "avi", "wmv": return true case "doc", "docx", "xls", "xlsx", "ppt", "pptx", "pdf": return true default: return false } } @discardableResult open func thumbnailOfFile(path: String, dimension: CGSize?, completionHandler: @escaping ((_ image: ImageClass?, _ error: Error?) -> Void)) -> Progress? { let thumbQuery: String switch dimension.map( {max($0.width, $0.height) } ) ?? 0 { case 0...96: thumbQuery = "small" case 97...176: thumbQuery = "medium" default: thumbQuery = "large" } /*if let dimension = dimension { thumbQuery = "c\(Int(dimension.width))x\(Int(dimension.height))" } else { thumbQuery = "small" }*/ let url = self.url(of: path, modifier: "thumbnails") .appendingPathComponent("0").appendingPathComponent(thumbQuery) .appendingPathComponent("content") var request = URLRequest(url: url) request.setValue(authentication: credential, with: .oAuth2) let task = self.session.dataTask(with: request, completionHandler: { (data, response, error) in var image: ImageClass? = nil if let code = (response as? HTTPURLResponse)?.statusCode , code >= 400, let rCode = FileProviderHTTPErrorCode(rawValue: code) { let responseError = self.serverError(with: rCode, path: path, data: data) completionHandler(nil, responseError) return } image = data.flatMap(ImageClass.init(data:)) completionHandler(image, error) }) task.resume() return nil } #endif }
mit
499db86c3af72d79ead2b9c830dc930d
47.765487
223
0.609201
4.712514
false
false
false
false
daxiangfei/RTSwiftUtils
RTSwiftUtils/Core/DateHelper.swift
1
4825
// // DateHelper.swift // XiaoZhuGeJinFu // // Created by rongteng on 16/7/7. // Copyright © 2016年 rongteng. All rights reserved. // import Foundation public class DateHepler { /// 把当前时间按照给定的格式转换为字符串 /// /// - Parameter formatter: 格式参考 yyyy-MM-dd HH:mm:ss /// - Returns: 转换后的结果 public class func transformCurrentTime(_ formatter:String) -> String { let dateFormatter = Foundation.DateFormatter() dateFormatter.dateFormat = formatter let dateStr = dateFormatter.string(from: Date()) return dateStr } /// 把给定的时间专为其时间戳 /// /// - Parameter time: 时间 /// - Returns: 时间戳字符串 public class func achieveTimestamp(time:Date) -> String { let timeInterval:TimeInterval = time.timeIntervalSince1970 let timeStamp = Int(timeInterval) return "\(timeStamp)" } /// 获取给定时间属于礼拜几 /// /// - Parameter time: 时间 /// - Returns: 字符串 "星期X" public class func transformTimeForWeek(time:Date) -> String { //调整时区差 let interval = Int(time.timeIntervalSince1970) + NSTimeZone.local.secondsFromGMT() let days = Int(interval/(24*60*60)) //1970-01-01 是星期四 减去三天为星期一 let weekday = (days-3)%7 //weekday为整形,从0到6分别表示 周日 到周六 var weekDayStr = "" switch weekday { case 1:weekDayStr = "星期一" case 2:weekDayStr = "星期二" case 3:weekDayStr = "星期三" case 4:weekDayStr = "星期四" case 5:weekDayStr = "星期五" case 6:weekDayStr = "星期六" case 0:weekDayStr = "星期日" default: break } return weekDayStr } /// 根据分开的年、月、日 按照给定的格式 转换成字符串日期 /// /// - Parameters: /// - year: 年份 /// - month: 月份 /// - day: 天 /// - dateFormatter: 给定的时间格式 格式参考 yyyy-MM-dd HH:mm:ss /// - Returns: 按照给定格式返回的字符串 public class func transforWith(year:Int,month:Int,day:Int,dateFormatter:String) -> String { let date = getDateWith(year: year, month: month, day: day) let dateF = DateFormatter() dateF.dateFormat = dateFormatter guard let realDate = date else {return ""} return dateF.string(from:realDate) } /// 把分开的年、月、日 转换日期 /// /// - Parameters: /// - year: 年份 /// - month: 月 /// - day: 日 /// - Returns: 返回时间 public class func getDateWith(year:Int,month:Int,day:Int) -> Date? { let calendar = Calendar.autoupdatingCurrent let dd = DateComponents(calendar: calendar, timeZone: nil, era: nil, year: year, month: month, day: day, hour: nil, minute: nil, second: nil, nanosecond: nil, weekday: nil, weekdayOrdinal: nil, quarter: nil, weekOfMonth: nil, weekOfYear: nil, yearForWeekOfYear: nil) return dd.date } ///得到给定时间 当月第几日 public class func getDay(date:Date) -> Int { let calendar = Calendar.autoupdatingCurrent let dayComponent = Calendar.Component.day let dayNum = calendar.component(dayComponent, from: date) return dayNum } ///得到给定时间 是几月 public class func getMouth(date:Date) -> Int { let calendar = Calendar.autoupdatingCurrent let monthComponent = Calendar.Component.month let mouthNum = calendar.component(monthComponent, from: date) return mouthNum } ///得到给定时间 是几几年 public class func getYear(date:Date) -> Int { let calendar = Calendar.autoupdatingCurrent let monthComponent = Calendar.Component.year let mouthNum = calendar.component(monthComponent, from: date) return mouthNum } ///得到1970年距离今天的所有的年分 [1970,1971,....] public class func yearArray() -> [Int] { let toYear = Date() let calendar = Calendar.autoupdatingCurrent let yearComponent = Calendar.Component.year let yearComponentNum = calendar.component(yearComponent, from: toYear) var numArray = [Int]() for dd in 1970 ... yearComponentNum { numArray.append(dd) } return numArray } ///根据对应的年份和月份 得到当月的天数数组 public class func mouthArray(year:Int,mouth:Int) -> [Int] { let calendar = Calendar.autoupdatingCurrent let dateFormatter = DateFormatter() dateFormatter.dateFormat = "yyyy-MM-dd" guard let date = dateFormatter.date(from: "\(year)-\(mouth)-1") else {return [] } let month = Calendar.Component.month let day = Calendar.Component.day let range = calendar.range(of: day, in: month, for: date)! var result = [Int]() for d in 1...range.count { result.append(d) } return result } }
mit
5b026417e48546cda8aeadfbe4166e5a
24.216374
270
0.65538
3.543139
false
false
false
false
castillejoale/Bluefruit_LE_Connect_v2_Minimized_UART
bluefruitconnect/Platform/OSX_CommandLine/CommandLine.swift
1
12994
// // CommandLine.swift // Bluefruit Connect // // Created by Antonio García on 17/05/16. // Copyright © 2016 Adafruit. All rights reserved. // import Foundation class CommandLine: NSObject { // Scanning var discoveredPeripheralsIdentifiers = [String]() private var scanResultsShowIndex = false // DFU private var dfuSemaphore = dispatch_semaphore_create(0) private let firmwareUpdater = FirmwareUpdater() private let dfuUpdateProcess = DfuUpdateProcess() private var dfuPeripheral: CBPeripheral? private var hexUrl: NSURL? private var iniUrl: NSURL? private var releases: [NSObject : AnyObject]? = nil // MARK: - Bluetooth Status func checkBluetoothErrors() -> String? { var errorMessage : String? let bleManager = BleManager.sharedInstance if let state = bleManager.centralManager?.state { switch(state) { case .Unsupported: errorMessage = "This computer doesn't support Bluetooth Low Energy" case .Unauthorized: errorMessage = "The application is not authorized to use the Bluetooth Low Energy" case .PoweredOff: errorMessage = "Bluetooth is currently powered off" default: errorMessage = nil } } return errorMessage } // MARK: - Help func showHelp() { showVersion() print("Usage:") print( "\t\(appName()) <command> [options...]") print("") print("Commands:") print("\tScan peripherals: scan") print("\tAutomatic update: update [--enable-beta] [--uuid <uuid>]") print("\tCustom firmware: dfu --hex <filename> [--init <filename>] [--uuid <uuid>]") print("\tShow this screen: --help") print("\tShow version: --version") print("") print("Options:") print("\t--uuid <uuid> If present the peripheral with that uuid is used. If not present a list of peripherals is displayed") print("\t--enable-beta If not present only stable versions are used") print("") print("Short syntax:") print("\t-u = --uuid, -b = --enable-beta, -h = --hex, -i = --init, -v = --version, -? = --help") /* print("\t--uuid -u") print("\t--enable-beta -b") print("\t--hex -h") print("\t--init -i") print("\t--help -h") print("\t--version -v") */ print("") /* print("\tscan Scan peripherals") print("\tupdate [--uuid <uuid>] [--enable-beta] Automatic update") print("\tdfu -hex <filename> [-init <filename>] [--uuid <uuid>] Custom firmware update") print("\t-h --help Show this screen") print("\t-v --version Show version") */ } private func appName() -> String { let name = (Process.arguments[0] as NSString).lastPathComponent return name } func showVersion() { let appInfo = NSBundle.mainBundle().infoDictionary! let releaseVersionNumber = appInfo["CFBundleShortVersionString"] as! String let appInfoString = "\(appName()) v\(releaseVersionNumber)" //let buildVersionNumber = appInfo["CFBundleVersion"] as! String //let appInfoString = "\(appname()) v\(releaseVersionNumber)b\(buildVersionNumber)" print(appInfoString) } // MARK: - Scan func startScanning() { startScanningAndShowIndex(false) } func startScanningAndShowIndex(scanResultsShowIndex: Bool) { self.scanResultsShowIndex = scanResultsShowIndex // Subscribe to Ble Notifications NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(didDiscoverPeripheral(_:)), name: BleManager.BleNotifications.DidDiscoverPeripheral.rawValue, object: nil) BleManager.sharedInstance.startScan() } func stopScanning() { NSNotificationCenter.defaultCenter().removeObserver(self, name: BleManager.BleNotifications.DidDiscoverPeripheral.rawValue, object: nil) BleManager.sharedInstance.stopScan() } func didDiscoverPeripheral(notification : NSNotification) { if let uuid = notification.userInfo?["uuid"] as? String { if let peripheral = BleManager.sharedInstance.blePeripherals()[uuid] { if !discoveredPeripheralsIdentifiers.contains(uuid) { discoveredPeripheralsIdentifiers.append(uuid) let name = peripheral.name != nil ? peripheral.name! : "{No Name}" if scanResultsShowIndex { if let index = discoveredPeripheralsIdentifiers.indexOf(uuid) { print("\(index) -> \(uuid) - \(name)") } } else { print("\(uuid): \(name)") } } } } } // MARK: - Ask user func askUserForPeripheral() -> String? { print("Scanning... Select a peripheral: ") var peripheralUuid: String? = nil startScanningAndShowIndex(true) let peripheralIndexString = readLine(stripNewline: true) //DLog("selected: \(peripheralIndexString)") if let peripheralIndexString = peripheralIndexString, peripheralIndex = Int(peripheralIndexString) where peripheralIndex>=0 && peripheralIndex < discoveredPeripheralsIdentifiers.count { peripheralUuid = discoveredPeripheralsIdentifiers[peripheralIndex] //print("Selected UUID: \(peripheralUuid!)") stopScanning() print("") // print("Peripheral selected") } return peripheralUuid } // MARK: - DFU func dfuPeripheralWithUUIDString(UUIDString: String, hexUrl: NSURL? = nil, iniUrl: NSURL? = nil, releases: [NSObject : AnyObject]? = nil) { // If hexUrl is nil, then uses releases to auto-update to the lastest release available guard let centralManager = BleManager.sharedInstance.centralManager else { DLog("centralManager is nil") return } if let peripheralUUID = NSUUID(UUIDString: UUIDString) { if let peripheral = centralManager.retrievePeripheralsWithIdentifiers([peripheralUUID]).first { dfuPeripheral = peripheral self.hexUrl = hexUrl self.iniUrl = iniUrl self.releases = releases print("Connecting...") // Connect to peripheral and discover characteristics. This should not be needed but the Dfu library will fail if a previous characteristics discovery has not been done // Subscribe to DidConnect notifications NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(dfuDidConnectToPeripheral(_:)), name: BleManager.BleNotifications.DidConnectToPeripheral.rawValue, object: nil) // Connect to peripheral and wait let blePeripheral = BlePeripheral(peripheral: peripheral, advertisementData: [:], RSSI: 0) BleManager.sharedInstance.connect(blePeripheral) dispatch_semaphore_wait(dfuSemaphore, DISPATCH_TIME_FOREVER) } } else { print("Error. No peripheral found with UUID: \(UUIDString)") dfuPeripheral = nil } } func dfuDidConnectToPeripheral(notification: NSNotification) { // Unsubscribe from DidConnect notifications NSNotificationCenter.defaultCenter().removeObserver(self, name: BleManager.BleNotifications.DidConnectToPeripheral.rawValue, object: nil) // Check connected guard let dfuPeripheral = dfuPeripheral else { DLog("dfuDidConnectToPeripheral dfuPeripheral is nil") dfuFinished() return } // Read services / characteristics print("Reading services and characteristics..."); self.firmwareUpdater.checkUpdatesForPeripheral(dfuPeripheral, delegate: self, shouldDiscoverServices: true, releases: releases, shouldRecommendBetaReleases: true) } private func dfuFinished() { dispatch_semaphore_signal(dfuSemaphore) } func downloadFirmwareUpdatesDatabaseFromUrl(dataUrl: NSURL, showBetaVersions: Bool, completionHandler: (([NSObject : AnyObject]?)->())?){ DataDownloader.downloadDataFromURL(dataUrl) { (data) in let boardsInfo = ReleasesParser.parse(data, showBetaVersions: showBetaVersions) completionHandler?(boardsInfo) } } } // MARK: - DfuUpdateProcessDelegate extension CommandLine: DfuUpdateProcessDelegate { func onUpdateProcessSuccess() { BleManager.sharedInstance.restoreCentralManager() print("") print("Update completed successfully") dfuFinished() } func onUpdateProcessError(errorMessage : String, infoMessage: String?) { BleManager.sharedInstance.restoreCentralManager() print(errorMessage) dfuFinished() } func onUpdateProgressText(message: String) { print("\t"+message) } func onUpdateProgressValue(progress : Double) { print(".", terminator: "") fflush(__stdoutp) } } // MARK: - FirmwareUpdaterDelegate extension CommandLine: FirmwareUpdaterDelegate { func onFirmwareUpdatesAvailable(isUpdateAvailable: Bool, latestRelease: FirmwareInfo?, deviceInfoData: DeviceInfoData!, allReleases: [NSObject : AnyObject]?) { // Info received DLog("onFirmwareUpdatesAvailable: \(isUpdateAvailable)") print("Peripheral info:") print("\tManufacturer: \(deviceInfoData.manufacturer != nil ? deviceInfoData.manufacturer : "{unknown}")") print("\tModel: \(deviceInfoData.modelNumber != nil ? deviceInfoData.modelNumber : "{unknown}")") print("\tSoftware: \(deviceInfoData.softwareRevision != nil ? deviceInfoData.softwareRevision : "{unknown}")") print("\tFirmware: \(deviceInfoData.firmwareRevision != nil ? deviceInfoData.firmwareRevision : "{unknown}")") print("\tBootlader: \(deviceInfoData.bootloaderVersion() != nil ? deviceInfoData.bootloaderVersion() : "{unknown}")") guard deviceInfoData.hasDefaultBootloaderVersion() == false else { print("The legacy bootloader on this device is not compatible with this application") dfuFinished() return } // Determine final hex and init (depending if is a custom firmware selected by the user, or an automatic update comparing the peripheral version with the update server xml) var hexUrl: NSURL? var iniUrl: NSURL? if allReleases != nil { // Use automatic-update guard let latestRelease = latestRelease else { print("No updates available") dfuFinished() return } guard isUpdateAvailable else { print("Latest available version is: \(latestRelease.version)") print("No updates available") dfuFinished() return } print("Auto-update to version: \(latestRelease.version)") hexUrl = NSURL(string: latestRelease.hexFileUrl)! iniUrl = NSURL(string: latestRelease.iniFileUrl) } else { // is a custom update selected by the user hexUrl = self.hexUrl iniUrl = self.iniUrl } // Check update parameters guard let dfuPeripheral = dfuPeripheral else { DLog("dfuDidConnectToPeripheral dfuPeripheral is nil") dfuFinished() return } guard hexUrl != nil else { DLog("dfuDidConnectToPeripheral hexPath is nil") dfuFinished() return } // Start update print("Start Update") dfuUpdateProcess.delegate = self dfuUpdateProcess.startUpdateForPeripheral(dfuPeripheral, hexUrl: hexUrl!, iniUrl: iniUrl, deviceInfoData: deviceInfoData) } func onDfuServiceNotFound() { print("DFU service not found") dfuFinished() } }
mit
ce20881a777df3f8532566ece7968a8a
38.13253
202
0.587746
5.302857
false
false
false
false
Hout/SwiftDate
Sources/SwiftDate/TimePeriod/Groups/TimePeriodCollection.swift
7
8271
// // SwiftDate // Parse, validate, manipulate, and display dates, time and timezones in Swift // // Created by Daniele Margutti // - Web: https://www.danielemargutti.com // - Twitter: https://twitter.com/danielemargutti // - Mail: [email protected] // // Copyright © 2019 Daniele Margutti. Licensed under MIT License. // import Foundation /// Sort type /// /// - ascending: sort in ascending order /// - descending: sort in descending order public enum SortMode { case ascending case descending } /// Sorting type /// /// - start: sort by start date /// - end: sort by end date /// - duration: sort by duration /// - custom: sort using custom function public enum SortType { case start(_: SortMode) case end(_: SortMode) case duration(_: SortMode) case custom(_: ((TimePeriodProtocol, TimePeriodProtocol) -> Bool)) } /// Time period collections serve as loose sets of time periods. /// They are unorganized unless you decide to sort them, and have their own characteristics /// like a `start` and `end` that are extrapolated from the time periods within. /// Time period collections allow overlaps within their set of time periods. open class TimePeriodCollection: TimePeriodGroup { // MARK: - Collection Manipulation /// Append a TimePeriodProtocol to the periods array and check if the Collection's start and end should change. /// /// - Parameter period: TimePeriodProtocol to add to the collection public func append(_ period: TimePeriodProtocol) { periods.append(period) updateExtremes(period: period) } /// Append a TimePeriodProtocol array to the periods array and check if the Collection's /// start and end should change. /// /// - Parameter periodArray: TimePeriodProtocol list to add to the collection public func append(_ periodArray: [TimePeriodProtocol]) { for period in periodArray { periods.append(period) updateExtremes(period: period) } } /// Append a TimePeriodGroup's periods array to the periods array of self and check if the Collection's /// start and end should change. /// /// - Parameter newPeriods: TimePeriodGroup to merge periods arrays with public func append<C: TimePeriodGroup>(contentsOf newPeriods: C) { for period in newPeriods as TimePeriodGroup { periods.append(period) updateExtremes(period: period) } } /// Insert period into periods array at given index. /// /// - Parameters: /// - newElement: The period to insert /// - index: Index to insert period at public func insert(_ newElement: TimePeriodProtocol, at index: Int) { periods.insert(newElement, at: index) updateExtremes(period: newElement) } /// Remove from period array at the given index. /// /// - Parameter at: The index in the collection to remove public func remove(at: Int) { periods.remove(at: at) updateExtremes() } /// Remove all periods from period array. public func removeAll() { periods.removeAll() updateExtremes() } // MARK: - Sorting /// Sort elements in place using given method. /// /// - Parameter type: sorting method public func sort(by type: SortType) { switch type { case .duration(let mode): periods.sort(by: sortFuncDuration(mode)) case .start(let mode): periods.sort(by: sortFunc(byStart: true, type: mode)) case .end(let mode): periods.sort(by: sortFunc(byStart: false, type: mode)) case .custom(let f): periods.sort(by: f) } } /// Generate a new `TimePeriodCollection` where items are sorted with specified method. /// /// - Parameters: /// - type: sorting method /// - Returns: collection ordered by given function public func sorted(by type: SortType) -> TimePeriodCollection { var sortedList: [TimePeriodProtocol]! switch type { case .duration(let mode): sortedList = periods.sorted(by: sortFuncDuration(mode)) case .start(let mode): sortedList = periods.sorted(by: sortFunc(byStart: true, type: mode)) case .end(let mode): sortedList = periods.sorted(by: sortFunc(byStart: false, type: mode)) case .custom(let f): sortedList = periods.sorted(by: f) } return TimePeriodCollection(sortedList) } // MARK: - Collection Relationship /// Returns from the `TimePeriodCollection` a sub-collection of `TimePeriod`s /// whose start and end dates fall completely inside the interval of the given `TimePeriod`. /// /// - Parameter period: The period to compare each other period against /// - Returns: Collection of periods inside the given period public func periodsInside(period: TimePeriodProtocol) -> TimePeriodCollection { return TimePeriodCollection(periods.filter({ $0.isInside(period) })) } // Returns from the `TimePeriodCollection` a sub-collection of `TimePeriod`s containing the given date. /// /// - Parameter date: The date to compare each period to /// - Returns: Collection of periods intersected by the given date public func periodsIntersected(by date: DateInRegion) -> TimePeriodCollection { return TimePeriodCollection(periods.filter({ $0.contains(date: date, interval: .closed) })) } /// Returns from the `TimePeriodCollection` a sub-collection of `TimePeriod`s /// containing either the start date or the end date--or both--of the given `TimePeriod`. /// /// - Parameter period: The period to compare each other period to /// - Returns: Collection of periods intersected by the given period public func periodsIntersected(by period: TimePeriodProtocol) -> TimePeriodCollection { return TimePeriodCollection(periods.filter({ $0.intersects(with: period) })) } /// Returns an instance of DTTimePeriodCollection with all the time periods in the receiver that overlap a given time period. /// Overlap with the given time period does NOT include other time periods that simply touch it. /// (i.e. one's start date is equal to another's end date) /// /// - Parameter period: The time period to check against the receiver's time periods. /// - Returns: Collection of periods overlapped by the given period public func periodsOverlappedBy(_ period: TimePeriodProtocol) -> TimePeriodCollection { return TimePeriodCollection(periods.filter({ $0.overlaps(with: period) })) } // MARK: - Map public func map(_ transform: (TimePeriodProtocol) throws -> TimePeriodProtocol) rethrows -> TimePeriodCollection { var mappedArray = [TimePeriodProtocol]() mappedArray = try periods.map(transform) let mappedCollection = TimePeriodCollection() for period in mappedArray { mappedCollection.periods.append(period) mappedCollection.updateExtremes(period: period) } return mappedCollection } // MARK: - Helpers private func sortFuncDuration(_ type: SortMode) -> ((TimePeriodProtocol, TimePeriodProtocol) -> Bool) { switch type { case .ascending: return { $0.duration < $1.duration } case .descending: return { $0.duration > $1.duration } } } private func sortFunc(byStart start: Bool = true, type: SortMode) -> ((TimePeriodProtocol, TimePeriodProtocol) -> Bool) { return { let date0 = (start ? $0.start : $0.end) let date1 = (start ? $1.start : $1.end) if date0 == nil && date1 == nil { return false } else if date0 == nil { return true } else if date1 == nil { return false } else { return (type == .ascending ? date1! > date0! : date0! > date1!) } } } private func updateExtremes(period: TimePeriodProtocol) { //Check incoming period against previous start and end date guard count != 1 else { start = period.start end = period.end return } start = nilOrEarlier(date1: start, date2: period.start) end = nilOrLater(date1: end, date2: period.end) } private func updateExtremes() { guard periods.count > 0 else { start = nil end = nil return } start = periods.first!.start end = periods.first!.end for i in 1..<periods.count { start = nilOrEarlier(date1: start, date2: periods[i].start) end = nilOrEarlier(date1: end, date2: periods[i].end) } } private func nilOrEarlier(date1: DateInRegion?, date2: DateInRegion?) -> DateInRegion? { guard date1 != nil && date2 != nil else { return nil } return date1!.earlierDate(date2!) } private func nilOrLater(date1: DateInRegion?, date2: DateInRegion?) -> DateInRegion? { guard date1 != nil && date2 != nil else { return nil } return date1!.laterDate(date2!) } }
mit
00014db2e5b3c3545e6116ad745af8ea
33.315353
126
0.713059
3.586297
false
false
false
false
bryanro92/Recipe-Sharing
Recipe-Sharing/SignInViewController.swift
1
5224
// // SignInViewController.swift // Recipe-Sharing // // Created by Developer on 4/24/17. // Copyright © 2017 rtbdesigns. All rights reserved. // import UIKit import Firebase import FirebaseAuth import GoogleSignIn class SignInViewController: UIViewController { @IBOutlet weak var usernameField: UITextField! @IBOutlet weak var passwordField: UITextField! var uId: String = "" override func viewDidLoad() { super.viewDidLoad() let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(SignInViewController.DismissKeyboard)) view.addGestureRecognizer(tap) } /**************************************** ******************************************/ func DismissKeyboard(){ view.endEditing(true) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func LoginPressed(_ sender: Any) { if self.usernameField.text == "" || self.passwordField.text == "" { //Alert to tell the user that there was an error because they didn't fill anything in the textfields because they didn't fill anything in let alertController = UIAlertController(title: "Error", message: "Please enter an email and password.", preferredStyle: .alert) let defaultAction = UIAlertAction(title: "OK", style: .cancel, handler: nil) alertController.addAction(defaultAction) self.present(alertController, animated: true, completion: nil) } else { FIRAuth.auth()?.signIn(withEmail: self.usernameField.text!, password: self.passwordField.text!) { (user, error) in if error == nil { //Print into the console if successfully logged in print("You have successfully logged in") //Go to the HomeViewController if the login is sucessful let mainTabBarController = self.storyboard?.instantiateViewController(withIdentifier: "MainTabController") as! MainTabBarController self.present(mainTabBarController, animated: true, completion: nil) } else { //Tells the user that there is an error and then gets firebase to tell them the error let alertController = UIAlertController(title: "Error", message: error?.localizedDescription, preferredStyle: .alert) let defaultAction = UIAlertAction(title: "OK", style: .cancel, handler: nil) alertController.addAction(defaultAction) self.present(alertController, animated: true, completion: nil) } } } } @IBAction func regiserPressed(_ sender: Any) { if usernameField.text == "" { let alertController = UIAlertController(title: "Error", message: "Please enter your email and password", preferredStyle: .alert) let defaultAction = UIAlertAction(title: "OK", style: .cancel, handler: nil) alertController.addAction(defaultAction) present(alertController, animated: true, completion: nil) } else { FIRAuth.auth()?.createUser(withEmail: usernameField.text!, password: passwordField.text!) { (user, error) in if error == nil { let alertController = UIAlertController(title: "Success", message: "You have succesfully signed up", preferredStyle: .alert) let defaultAction = UIAlertAction(title: "OK", style: .cancel, handler: nil) alertController.addAction(defaultAction) self.present(alertController, animated: true, completion: nil) print("You have successfully signed up") } else { let alertController = UIAlertController(title: "Error", message: error?.localizedDescription, preferredStyle: .alert) let defaultAction = UIAlertAction(title: "OK", style: .cancel, handler: nil) alertController.addAction(defaultAction) self.present(alertController, animated: true, completion: nil) } } } } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
mit
d4134c38195f3c44fec20db7e2470b4b
36.847826
151
0.557151
6.094516
false
false
false
false
Hidebush/McBlog
McBlog/McBlog/Classes/Module/Home/StatusCell/StatusForwardCell.swift
1
2346
// // StatusForwardCell.swift // McBlog // // Created by admin on 16/5/6. // Copyright © 2016年 郭月辉. All rights reserved. // import UIKit class StatusForwardCell: StatusCell { override var status: Status? { didSet { let name = status?.retweeted_status?.user?.name ?? "" let text = status?.retweeted_status?.text ?? "" forwardLabel.text = "@" + name + ":" + text let pictureViewTopMargin = status?.picURLs?.count == 0 ? 0 : statusCellMarginEight pictureView.snp_remakeConstraints { (make) in make.top.equalTo(forwardLabel.snp_bottom).offset(pictureViewTopMargin) make.left.equalTo(forwardLabel) make.width.equalTo(pictureView.bounds.size.width) make.height.equalTo(pictureView.bounds.size.height) } } } override func setUpUI() { super.setUpUI() contentView.insertSubview(backButton, belowSubview: pictureView) contentView.insertSubview(forwardLabel, aboveSubview: backButton) backButton.snp_makeConstraints { (make) in make.top.equalTo(contentLabel.snp_bottom).offset(statusCellMarginEight) make.left.right.equalTo(contentView) make.bottom.equalTo(bottomView.snp_top) } forwardLabel.snp_makeConstraints { (make) in make.top.left.equalTo(backButton).offset(statusCellMarginEight) make.right.equalTo(backButton).offset(-statusCellMarginEight) } pictureView.snp_makeConstraints { (make) in make.top.equalTo(forwardLabel.snp_bottom).offset(statusCellMarginEight) make.left.equalTo(forwardLabel) make.width.equalTo(forwardLabel.snp_width) make.height.equalTo(290) } } private lazy var forwardLabel: UILabel = { let label = UILabel(color: UIColor.darkGrayColor(), fontSize: 14) label.numberOfLines = 0 label.preferredMaxLayoutWidth = UIScreen.mainScreen().bounds.size.width - 2.0 * statusCellMarginEight return label }() private lazy var backButton: UIButton = { let button = UIButton() button.backgroundColor = UIColor(white: 0.8, alpha: 0.8) return button }() }
mit
eab757a76a1fa4b1535a01708fb3c507
34.953846
109
0.620881
4.582353
false
false
false
false
wiltonlazary/kotlin-native
performance/KotlinVsSwift/ring/src/ClassBaselineBenchmark.swift
4
1554
/* * Copyright 2010-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license * that can be found in the LICENSE file. */ import Foundation class ClassBaselineBenchmark { func consume() { for item in 1...Constants.BENCHMARK_SIZE { Blackhole.consume(Value(item)) } } func consumeField() { let value = Value(0) for item in 1...Constants.BENCHMARK_SIZE { value.value = item Blackhole.consume(value) } } func allocateList() -> [Value] { let list = [Value](repeating: Value(0), count: Constants.BENCHMARK_SIZE) return list } func allocateArray() -> [Value?] { let list = [Value?](repeating: nil, count: Constants.BENCHMARK_SIZE) return list } func allocateListAndFill() -> [Value] { var list: [Value] = [] for item in 1...Constants.BENCHMARK_SIZE { list.append(Value(item)) } return list } func allocateListAndWrite() -> [Value] { let value = Value(0) var list: [Value] = [] for _ in 1...Constants.BENCHMARK_SIZE { list.append(value) } return list } func allocateArrayAndFill() -> [Value?] { var list = [Value?](repeating: nil, count: Constants.BENCHMARK_SIZE) var index = 0 for item in 1...Constants.BENCHMARK_SIZE { list[index] = Value(item) index += 1 } return list } }
apache-2.0
24ef9fcb06b161d32b06c60d15e16dd6
24.9
101
0.545689
3.934177
false
false
false
false
VideonaTalentum/TalentumVideonaSwift
VideonaTalentum/ViewController.swift
1
15745
// ViewController.swift // // The MIT License (MIT) // // Copyright (c) 2015 ActionButton // // 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 GLKit import AVFoundation import CoreMedia class ViewController: UIViewController { @IBOutlet weak var Camera: UIButton! @IBOutlet weak var recordPlay: UIButton! enum Enum { case EnumFace case EnumMouth case EnumEyes case EnumHat } let eaglContext = EAGLContext(API: .OpenGLES2) let captureSession = AVCaptureSession() let imageView = GLKView() var enumNull = Enum.EnumFace let comicEffect = CIFilter(name: "CIComicEffect")! let eyeballImage = CIImage(image: UIImage(named: "eyeball.png")!)! let mouthballImage = CIImage(image: UIImage(named: "boca.png")!)! let hatBallImage = CIImage(image: UIImage(named:"sombrero.png")!)! var cameraImage: CIImage? var usingCamera = false lazy var ciContext: CIContext = { [unowned self] in return CIContext(EAGLContext: self.eaglContext) }() lazy var detector: CIDetector = { [unowned self] in CIDetector(ofType: CIDetectorTypeFace, context: self.ciContext, options: [ CIDetectorAccuracy: CIDetectorAccuracyHigh, CIDetectorTracking: true]) }() var actionButton: ActionButton! override func viewDidLoad() { super.viewDidLoad() initialiseCaptureSession() view.addSubview(imageView) imageView.context = eaglContext imageView.delegate = self let eyesImage = UIImage(named: "eyes_icon.png")! let moustacheImage = UIImage(named: "moustache_icon.png")! let hatImage = UIImage(named: "hat_icon.png")! let mouthImage = UIImage(named: "mouth_icon.png")! let eyes = ActionButtonItem(title: "Eyes", image: eyesImage) eyes.action = { item in print("Ojitos...") self.enumNull = Enum.EnumEyes } let moustache = ActionButtonItem(title: "Moustache", image: moustacheImage) moustache.action = { item in print("Bigotito...") } let hat = ActionButtonItem(title: "Hat", image: hatImage) hat.action = { item in print("Sombrerito...") self.enumNull = Enum.EnumHat } let mouth = ActionButtonItem(title:"Mouth", image:mouthImage) mouth.action = { item in print("Boca...") self.enumNull = Enum.EnumMouth } actionButton = ActionButton(attachedToView: self.view, items: [hat, eyes, moustache, mouth]) actionButton.action = { button in button.toggleMenu() } actionButton.setTitle("+", forState: .Normal) actionButton.backgroundColor = UIColor(red: 167.0/255.0, green: 169.0/255.0, blue: 173.0/255.0, alpha:0.8) self.view.bringSubviewToFront(Camera) self.view.bringSubviewToFront(recordPlay) } @IBAction func Camera(sender: AnyObject) { changeCamera() } func initialiseCaptureSession() { captureSession.sessionPreset = AVCaptureSessionPresetPhoto guard let frontCamera = (AVCaptureDevice.devicesWithMediaType(AVMediaTypeVideo) as! [AVCaptureDevice]) .filter({ $0.position == .Front }) .first else { fatalError("Unable to access front camera") } do { let input = try AVCaptureDeviceInput(device: frontCamera) captureSession.addInput(input) } catch { fatalError("Unable to access front camera") } let videoOutput = AVCaptureVideoDataOutput() videoOutput.setSampleBufferDelegate(self, queue: dispatch_queue_create("sample buffer delegate", DISPATCH_QUEUE_SERIAL)) if captureSession.canAddOutput(videoOutput) { captureSession.addOutput(videoOutput) } captureSession.startRunning() } static func deviceWithMediaType(position: AVCaptureDevicePosition) -> AVCaptureDevice { guard let device = (AVCaptureDevice.devicesWithMediaType(AVMediaTypeVideo) as! [AVCaptureDevice]) .filter({ $0.position == position }) .first else { fatalError("Unable to access front camera") } return device } func changeCamera() { let deviceInput = self.captureSession.inputs.first as? AVCaptureDeviceInput let device = deviceInput?.device if let device = device { let position = device.position var videoDevice : AVCaptureDevice? switch position { case .Front: videoDevice = ViewController.deviceWithMediaType(.Back) break; case .Back: videoDevice = ViewController.deviceWithMediaType(.Front) break; case .Unspecified : break; } do { if let videoDevice = videoDevice { self.captureSession.removeInput(deviceInput) let input = try AVCaptureDeviceInput(device: videoDevice) captureSession.addInput(input) } } catch { fatalError("Unable to access front camera") } } } // Detects either the left or right eye from `cameraImage` and, if detected, composites // `eyeballImage` over `backgroundImage`. If no eye is detected, simply returns the // `backgroundImage`. func eyeImage(cameraImage: CIImage, backgroundImage: CIImage, leftEye: Bool) -> CIImage { let compositingFilter = CIFilter(name: "CISourceAtopCompositing")! let transformFilter = CIFilter(name: "CIAffineTransform")! let halfEyeWidth = eyeballImage.extent.width / 2 let halfEyeHeight = eyeballImage.extent.height / 2 if let features = detector.featuresInImage(cameraImage).first as? CIFaceFeature where leftEye ? features.hasLeftEyePosition : features.hasRightEyePosition { let eyePosition = CGAffineTransformMakeTranslation( leftEye ? features.leftEyePosition.x - halfEyeWidth : features.rightEyePosition.x - halfEyeWidth, leftEye ? features.leftEyePosition.y - halfEyeHeight : features.rightEyePosition.y - halfEyeHeight) let eyeDimensions = CGAffineTransformScale(eyePosition, 1, 1) let myCGFloat = CGFloat(features.faceAngle) let myPIFloat = CGFloat(2*M_PI) let angleRadians = myCGFloat*myPIFloat / 360 let eyeAngle = CGAffineTransformRotate(eyeDimensions, -angleRadians) transformFilter.setValue(eyeballImage, forKey: "inputImage") transformFilter.setValue(NSValue(CGAffineTransform: eyeAngle), forKey: "inputTransform") let transformResult = transformFilter.valueForKey("outputImage") as! CIImage compositingFilter.setValue(backgroundImage, forKey: kCIInputBackgroundImageKey) compositingFilter.setValue(transformResult, forKey: kCIInputImageKey) return compositingFilter.valueForKey("outputImage") as! CIImage } else { return backgroundImage } } func noneImage(cameraImage: CIImage, backgroundImage: CIImage, mouth: Bool) -> CIImage { return backgroundImage } func hatImage(cameraImage: CIImage, backgroundImage: CIImage, hat: Bool) -> CIImage { let compositingFilter = CIFilter(name: "CISourceAtopCompositing")! let transformFilter = CIFilter(name: "CIAffineTransform")! let halfMouthWidth = hatBallImage.extent.width //let halfMouthHeight = hatBallImage.extent.height if let features = detector.featuresInImage(cameraImage).first as? CIFaceFeature { if (features.hasFaceAngle) { let mouthPosition = CGAffineTransformMakeTranslation( features.bounds.width - halfMouthWidth, features.bounds.maxY) let hatDimensions = CGAffineTransformScale(mouthPosition, 2, 2) let myCGFloat = CGFloat(features.faceAngle) let myPIFloat = CGFloat(2*M_PI) let angleRadians = myCGFloat*myPIFloat / 360 let hatAngle = CGAffineTransformRotate(hatDimensions, -angleRadians) transformFilter.setValue(hatBallImage, forKey: "inputImage") transformFilter.setValue(NSValue(CGAffineTransform: hatAngle), forKey: "inputTransform") let transformResult = transformFilter.valueForKey("outputImage") as! CIImage compositingFilter.setValue(backgroundImage, forKey: kCIInputBackgroundImageKey) compositingFilter.setValue(transformResult, forKey: kCIInputImageKey) return compositingFilter.valueForKey("outputImage") as! CIImage } else { return backgroundImage } } return backgroundImage } func mouthImage(cameraImage: CIImage, backgroundImage: CIImage, mouth: Bool) -> CIImage { let compositingFilter = CIFilter(name: "CISourceAtopCompositing")! let transformFilter = CIFilter(name: "CIAffineTransform")! let halfMouthWidth = mouthballImage.extent.width / 2 let halfMouthHeight = mouthballImage.extent.height / 2 if let features = detector.featuresInImage(cameraImage).first as? CIFaceFeature { if (features.hasMouthPosition) { let mouthPosition = CGAffineTransformMakeTranslation( features.hasMouthPosition ? features.mouthPosition.x - halfMouthWidth : features.mouthPosition.x - halfMouthWidth, features.hasMouthPosition ? features.mouthPosition.y - halfMouthHeight : features.mouthPosition.y - halfMouthHeight) let mouthDimensions = CGAffineTransformScale(mouthPosition, 1, 1) let myCGFloat = CGFloat(features.faceAngle) let myPIFloat = CGFloat(2*M_PI) let angleRadians = myCGFloat*myPIFloat / 360 let mouthAngle = CGAffineTransformRotate(mouthDimensions, -angleRadians) transformFilter.setValue(mouthballImage, forKey: "inputImage") transformFilter.setValue(NSValue(CGAffineTransform: mouthAngle), forKey: "inputTransform") let transformResult = transformFilter.valueForKey("outputImage") as! CIImage compositingFilter.setValue(backgroundImage, forKey: kCIInputBackgroundImageKey) compositingFilter.setValue(transformResult, forKey: kCIInputImageKey) return compositingFilter.valueForKey("outputImage") as! CIImage } else { return backgroundImage } } return backgroundImage } override func viewDidLayoutSubviews() { imageView.frame = view.bounds } } extension ViewController: AVCaptureVideoDataOutputSampleBufferDelegate { func captureOutput(captureOutput: AVCaptureOutput!, didOutputSampleBuffer sampleBuffer: CMSampleBuffer!, fromConnection connection: AVCaptureConnection!) { connection.videoOrientation = AVCaptureVideoOrientation(rawValue: UIApplication.sharedApplication().statusBarOrientation.rawValue)! let pixelBuffer = CMSampleBufferGetImageBuffer(sampleBuffer) cameraImage = CIImage(CVPixelBuffer: pixelBuffer!) dispatch_async(dispatch_get_main_queue()) { self.imageView.setNeedsDisplay() } } } extension ViewController: GLKViewDelegate { func glkView(view: GLKView, drawInRect rect: CGRect) { guard let cameraImage = cameraImage else { return } switch enumNull { case Enum.EnumFace: let noImage = noneImage(cameraImage, backgroundImage: cameraImage, mouth: true) ciContext.drawImage(noImage, inRect: CGRect(x: 0, y: 0, width: imageView.drawableWidth, height: imageView.drawableHeight), fromRect: noImage.extent) case Enum.EnumEyes: let leftEyeImage = eyeImage(cameraImage, backgroundImage: cameraImage, leftEye: true) let rightEyeImage = eyeImage(cameraImage, backgroundImage: leftEyeImage, leftEye: false) ciContext.drawImage(rightEyeImage, inRect: CGRect(x: 0, y: 0, width: imageView.drawableWidth, height: imageView.drawableHeight), fromRect: rightEyeImage.extent) case Enum.EnumMouth: let mImage = mouthImage(cameraImage, backgroundImage: cameraImage, mouth: true) ciContext.drawImage(mImage, inRect: CGRect(x: 0, y: 0, width: imageView.drawableWidth, height: imageView.drawableHeight), fromRect: mImage.extent) case Enum.EnumHat: let hattImage = hatImage(cameraImage, backgroundImage: cameraImage, hat: true) ciContext.drawImage(hattImage, inRect: CGRect(x: 0, y: 0, width: imageView.drawableWidth, height: imageView.drawableHeight), fromRect: hattImage.extent) } } }
mit
922b09e02cc7bd7cadb08428b1dd4067
37.590686
159
0.594093
5.573451
false
false
false
false
mshhmzh/firefox-ios
Sync/Synchronizers/Downloader.swift
4
9323
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import Foundation import Shared import Storage import XCGLogger import Deferred private let log = Logger.syncLogger class BatchingDownloader<T: CleartextPayloadJSON> { let client: Sync15CollectionClient<T> let collection: String let prefs: Prefs var batch: [Record<T>] = [] func store(records: [Record<T>]) { self.batch += records } func retrieve() -> [Record<T>] { let ret = self.batch self.batch = [] return ret } var _advance: (() -> ())? func advance() { guard let f = self._advance else { return } self._advance = nil f() } init(collectionClient: Sync15CollectionClient<T>, basePrefs: Prefs, collection: String) { self.client = collectionClient self.collection = collection let branchName = "downloader." + collection + "." self.prefs = basePrefs.branch(branchName) log.info("Downloader configured with prefs '\(self.prefs.getBranchPrefix())'.") } static func resetDownloaderWithPrefs(basePrefs: Prefs, collection: String) { // This leads to stupid paths like 'profile.sync.synchronizer.history..downloader.history..'. // Sorry, but it's out in the world now... let branchName = "downloader." + collection + "." let prefs = basePrefs.branch(branchName) let lm = prefs.timestampForKey("lastModified") let bt = prefs.timestampForKey("baseTimestamp") log.debug("Resetting downloader prefs \(prefs.getBranchPrefix()). Previous values: \(lm), \(bt).") prefs.removeObjectForKey("nextOffset") prefs.removeObjectForKey("offsetNewer") prefs.removeObjectForKey("baseTimestamp") prefs.removeObjectForKey("lastModified") } /** * Clients should provide the same set of parameters alongside an `offset` as was * provided with the initial request. The only thing that varies in our batch fetches * is `newer`, so we track the original value alongside. */ var nextFetchParameters: (String, Timestamp)? { get { let o = self.prefs.stringForKey("nextOffset") let n = self.prefs.timestampForKey("offsetNewer") guard let offset = o, let newer = n else { return nil } return (offset, newer) } set (value) { if let (offset, newer) = value { self.prefs.setString(offset, forKey: "nextOffset") self.prefs.setTimestamp(newer, forKey: "offsetNewer") } else { self.prefs.removeObjectForKey("nextOffset") self.prefs.removeObjectForKey("offsetNewer") } } } // Set after each batch, from record timestamps. var baseTimestamp: Timestamp { get { return self.prefs.timestampForKey("baseTimestamp") ?? 0 } set (value) { self.prefs.setTimestamp(value ?? 0, forKey: "baseTimestamp") } } // Only set at the end of a batch, from headers. var lastModified: Timestamp { get { return self.prefs.timestampForKey("lastModified") ?? 0 } set (value) { self.prefs.setTimestamp(value ?? 0, forKey: "lastModified") } } /** * Call this when a significant structural server change has been detected. */ func reset() -> Success { self.baseTimestamp = 0 self.lastModified = 0 self.nextFetchParameters = nil self.batch = [] self._advance = nil return succeed() } func go(info: InfoCollections, limit: Int) -> Deferred<Maybe<DownloadEndState>> { guard let modified = info.modified(self.collection) else { log.debug("No server modified time for collection \(self.collection).") return deferMaybe(.NoNewData) } log.debug("Modified: \(modified); last \(self.lastModified).") if modified == self.lastModified { log.debug("No more data to batch-download.") return deferMaybe(.NoNewData) } // If the caller hasn't advanced after the last batch, strange things will happen -- // potentially looping indefinitely. Warn. if self._advance != nil && !self.batch.isEmpty { log.warning("Downloading another batch without having advanced. This might be a bug.") } return self.downloadNextBatchWithLimit(limit, infoModified: modified) } func advanceTimestampTo(timestamp: Timestamp) { log.debug("Advancing downloader lastModified from \(self.lastModified) to \(timestamp).") self.lastModified = timestamp } // We're either fetching from our current base timestamp with no offset, // or the timestamp we were using when we last saved an offset. func fetchParameters() -> (String?, Timestamp) { if let (offset, since) = self.nextFetchParameters { return (offset, since) } return (nil, max(self.lastModified, self.baseTimestamp)) } func downloadNextBatchWithLimit(limit: Int, infoModified: Timestamp) -> Deferred<Maybe<DownloadEndState>> { let (offset, since) = self.fetchParameters() log.debug("Fetching newer=\(since), offset=\(offset).") let fetch = self.client.getSince(since, sort: SortOption.OldestFirst, limit: limit, offset: offset) func handleFailure(err: MaybeErrorType) -> Deferred<Maybe<DownloadEndState>> { log.debug("Handling failure.") guard let badRequest = err as? BadRequestError<[Record<T>]> where badRequest.response.metadata.status == 412 else { // Just pass through the failure. return deferMaybe(err) } // Conflict. Start again. log.warning("Server contents changed during offset-based batching. Stepping back.") self.nextFetchParameters = nil return deferMaybe(.Interrupted) } func handleSuccess(response: StorageResponse<[Record<T>]>) -> Deferred<Maybe<DownloadEndState>> { log.debug("Handling success.") let nextOffset = response.metadata.nextOffset let responseModified = response.value.last?.modified // Queue up our metadata advance. We wait until the consumer has fetched // and processed this batch; they'll call .advance() on success. self._advance = { // Shift to the next offset. This might be nil, in which case… fine! // Note that we preserve the previous 'newer' value from the offset or the original fetch, // even as we update baseTimestamp. self.nextFetchParameters = nextOffset == nil ? nil : (nextOffset!, since) // If there are records, advance to just before the timestamp of the last. // If our next fetch with X-Weave-Next-Offset fails, at least we'll start here. // // This approach is only valid if we're fetching oldest-first. if let newBase = responseModified { log.debug("Advancing baseTimestamp to \(newBase) - 1") self.baseTimestamp = newBase - 1 } if nextOffset == nil { // If we can't get a timestamp from the header -- and we should always be able to -- // we fall back on the collection modified time in i/c, as supplied by the caller. // In any case where there is no racing writer these two values should be the same. // If they differ, the header should be later. If it's missing, and we use the i/c // value, we'll simply redownload some records. // All bets are off if we hit this case and are filtering somehow… don't do that. let lm = response.metadata.lastModifiedMilliseconds log.debug("Advancing lastModified to \(lm) ?? \(infoModified).") self.lastModified = lm ?? infoModified } } log.debug("Got success response with \(response.metadata.records) records.") // Store the incoming records for collection. self.store(response.value) return deferMaybe(nextOffset == nil ? .Complete : .Incomplete) } return fetch.bind { result in guard let response = result.successValue else { return handleFailure(result.failureValue!) } return handleSuccess(response) } } } public enum DownloadEndState: String { case Complete // We're done. Records are waiting for you. case Incomplete // applyBatch was called, and we think there are more records. case NoNewData // There were no records. case Interrupted // We got a 412 conflict when fetching the next batch. }
mpl-2.0
f2d584f115d336c4a3096bf200c54504
39.341991
127
0.601137
4.97544
false
false
false
false
czerenkow/LublinWeather
App/Architecture/Router.swift
1
1922
// // Router.swift // LublinWeather // // Created by Damian Rzeszot on 17/04/2018. // Copyright © 2018 Damian Rzeszot. All rights reserved. // import UIKit class Router { // MARK: - var controller: UIViewController? var interactor: Interactable? // MARK: - func load() { } func unload() { } // MARK: - private(set) var children: [Router] = [] private(set) weak var parent: Router? public func attach(child: Router) { precondition(child.parent == nil) child.parent = self children.append(child) child.load() child.interactor?.activate() } public func deattach(child: Router) { precondition(child.parent == self) child.interactor?.deactivate() child.unload() child.parent = nil children.remove(element: child) } // MARK: - public func each(_ block: (Router) -> Void) { for child in children { block(child) } } public func traverse(_ block: (Router) -> Void) { block(self) for child in children { child.traverse(block) } } // MARK: - func present(_ child: Router, nav: Bool = true, animated: Bool = true, completion: @escaping () -> Void = {}) { let vc = nav ? UINavigationController(rootViewController: child.controller!) : child.controller! controller!.present(vc, animated: animated, completion: completion) attach(child: child) } // MARK: - func get<T>(_ type: T.Type) -> T? { let objects: [Any?] = [interactor, controller] for object in objects { if let object = object as? T { return object } } return nil } } extension Router: Equatable { static func == (lhs: Router, rhs: Router) -> Bool { return lhs === rhs } }
mit
89be799d639f8b78afe47e6dc54692a1
16.953271
115
0.550234
4.185185
false
false
false
false
benlangmuir/swift
test/decl/protocol/special/coding/codable_immutable_property_with_initial_value.swift
4
2899
// RUN: %target-typecheck-verify-swift -verify-ignore-unknown // https://github.com/apple/swift/issues/54430 // Warning when a immutable decodable property has an initial value // Implicit CodingKeys enum // struct Foo1: Codable { let bar: Int = 1 // expected-warning@-1 {{immutable property will not be decoded because it is declared with an initial value which cannot be overwritten}} // expected-note@-2 {{set the initial value via the initializer or explicitly define a CodingKeys enum including a 'bar' case to silence this warning}} // expected-note@-3 {{make the property mutable instead}}{{3-6=var}} let baz1: String var baz2 = 8 } struct Foo2: Decodable { let bar: Int = 1 // expected-warning@-1 {{immutable property will not be decoded because it is declared with an initial value which cannot be overwritten}} // expected-note@-2 {{set the initial value via the initializer or explicitly define a CodingKeys enum without a 'bar' case to silence this warning}} // expected-note@-3 {{make the property mutable instead}}{{3-6=var}} let baz1: String var baz2 = 8 } struct Foo3: Encodable { let bar: Int = 1 // Ok, since 'Foo3' isn't decodable let baz1: String var baz2 = 8 } // Explicit CodingKeys enum // struct Foo4: Codable { let bar: Int = 1 // Ok, since removing 'bar' from 'CodingKeys' will break encoding let baz1: String var baz2 = 8 private enum CodingKeys: String, CodingKey { case bar case baz1 case baz2 } } struct Foo5: Decodable { let bar: Int = 1 // expected-warning@-1 {{immutable property will not be decoded because it is declared with an initial value which cannot be overwritten}} // expected-note@-2 {{set the initial value via the initializer or remove the 'bar' case from the CodingKeys enum to silence this warning}} // expected-note@-3 {{make the property mutable instead}}{{3-6=var}} let baz1: String var baz2 = 8 private enum CodingKeys: String, CodingKey { case bar case baz1 case baz2 } } struct Foo6: Encodable { let bar: Int = 1 // Ok, since 'Foo6' isn't decodable let baz1: String var baz2 = 8 private enum CodingKeys: String, CodingKey { case bar case baz1 case baz2 } } struct Foo7: Codable { let bar: Int = 1 // Ok, since 'bar' doesn't exist in CodingKeys enum let baz1: String var baz2 = 8 private enum CodingKeys: String, CodingKey { case baz1 case baz2 } } struct Foo8: Decodable { let bar: Int = 1 // Ok, since 'bar' does not exist in CodingKeys enum let baz1: String var baz2 = 8 private enum CodingKeys: String, CodingKey { case baz1 case baz2 } } struct Foo9: Encodable { let bar: Int = 1 // Ok, since 'Foo9' isn't decodable (and 'bar' doesn't exist in CodingKeys enum anyway) let baz1: String var baz2 = 8 private enum CodingKeys: String, CodingKey { case baz1 case baz2 } }
apache-2.0
530007d79d837674f3aa804b6db25531
26.875
153
0.691963
3.77474
false
false
false
false
Den-Ree/InstagramAPI
src/InstagramAPI/InstagramAPITests/RequestsTests/CommentTests.swift
2
1968
// // CommentTests.swift // // // Created by Admin on 15.08.17. // // import XCTest @testable import InstagramAPI class CommentTests: XCTestCase { func testGet() { let getCommentRouter = InstagramCommentRouter.getComments(mediaId: "{media-id}") guard let UrlRequest = try? getCommentRouter.asURLRequest(withAccessToken: "ACCESS-TOKEN") else { return } XCTAssert(UrlRequest.url?.absoluteString == TestConstants.URL.Comment.get.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)) } func testPost() { let postCommentParameter = InstagramCommentRouter.PostCommentParameter.init(mediaId: "{media-id}", text: "This is my comment") let postCommentRouter = InstagramCommentRouter.postComment(postCommentParameter) guard let UrlRequest = try? postCommentRouter.asURLRequest(withAccessToken: "ACCESS-TOKEN") else { return } guard let json = try? JSONSerialization.jsonObject(with: UrlRequest.httpBody!, options: .allowFragments) as! [String:Any] else { return } XCTAssert(UrlRequest.url?.absoluteString == TestConstants.URL.Comment.post.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)) XCTAssert(UrlRequest.httpMethod == TestConstants.HTTPMethod.post) XCTAssert(json.parametersString() == TestConstants.HTTPBody.comment) } func testDelete() { let deleteCommentParameter = InstagramCommentRouter.DeleteCommentParameter.init(mediaId: "{media-id}", commentId:"{comment-id}") let deleteCommentRouter = InstagramCommentRouter.deleteComment(deleteCommentParameter) guard let UrlRequest = try? deleteCommentRouter.asURLRequest(withAccessToken: "ACCESS-TOKEN") else { return } XCTAssert(UrlRequest.url?.absoluteString == TestConstants.URL.Comment.delete.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)) XCTAssert(UrlRequest.httpMethod == TestConstants.HTTPMethod.delete) } }
mit
892ba82e22eee6bcbb3a864d1a1716ca
41.782609
146
0.743394
4.685714
false
true
false
false
danielsaidi/KeyboardKit
Tests/KeyboardKitTests/Keyboard/KeyboardInputViewControllerTests.swift
1
8308
// // KeyboardInputViewControllerTests.swift // KeyboardKit // // Created by Daniel Saidi on 2019-05-28. // Copyright © 2021 Daniel Saidi. All rights reserved. // import Quick import Nimble import KeyboardKit import MockingKit import UIKit class KeyboardInputViewControllerTests: QuickSpec { override func spec() { var vc: TestClass! func expectSyncedContext(for function: () -> Void) { vc.hasFullAccessValue = true function() expect(vc.keyboardContext.hasFullAccess).to(beTrue()) vc.hasFullAccessValue = false function() expect(vc.keyboardContext.hasFullAccess).to(beFalse()) expect(vc.keyboardContext.textDocumentProxy).to(be(vc.textDocumentProxy)) } beforeEach { TestClass.shared = nil vc = TestClass(nibName: nil, bundle: nil) } describe("keyboard context") { it("is setup with default state") { let context = vc.keyboardContext expect(context.hasFullAccess).to(beFalse()) expect(context.keyboardType).to(equal(.alphabetic(.lowercased))) expect(context.needsInputModeSwitchKey).to(beFalse()) } } describe("view did load") { it("sets vc as shared") { expect(TestClass.shared).to(beNil()) vc.viewDidLoad() expect(TestClass.shared).toNot(beNil()) } } describe("view will appear") { it("updates context") { expectSyncedContext { vc.viewWillAppear(false) } } } describe("view will layout subviews") { it("updates context") { expectSyncedContext(for: vc.viewWillLayoutSubviews) } } describe("view trait collection did change") { it("updates context") { expectSyncedContext { vc.traitCollectionDidChange(.none) } } } describe("keyboard action handler") { it("is standard by default") { let obj = vc.keyboardActionHandler expect(obj as? StandardKeyboardActionHandler).toNot(beNil()) } } describe("keyboard appearance provider") { it("is standard by default") { let obj = vc.keyboardAppearance expect(obj as? StandardKeyboardAppearance).toNot(beNil()) } } describe("keyboard behavior") { it("is standard by default") { let obj = vc.keyboardBehavior expect(obj as? StandardKeyboardBehavior).toNot(beNil()) } } describe("keyboard context") { it("is observable to self by default") { let context = vc.keyboardContext expect(context.textDocumentProxy).to(be(vc.textDocumentProxy)) } } describe("keyboard input callout context") { it("is correctly setup") { let context = vc.keyboardInputCalloutContext expect(context).to(be(context)) } } describe("keyboard input set provider") { it("is standard by default") { let obj = vc.keyboardInputSetProvider expect(obj as? StandardKeyboardInputSetProvider).toNot(beNil()) } it("is registered into the layout provider when changed") { let newProvider = MockKeyboardInputSetProvider() vc.keyboardInputSetProvider = newProvider let layoutProvider = vc.keyboardLayoutProvider as? StandardKeyboardLayoutProvider expect(layoutProvider?.inputSetProvider).to(be(newProvider)) } } describe("keyboard layout provider") { it("is standard by default") { let obj = vc.keyboardLayoutProvider expect(obj as? StandardKeyboardLayoutProvider).toNot(beNil()) } } describe("keyboard secondary input action provider") { it("is standard by default") { let obj = vc.keyboardSecondaryCalloutActionProvider expect(obj as? StandardSecondaryCalloutActionProvider).toNot(beNil()) } } describe("keyboard secondary input callout context") { it("is correctly setup") { let context = vc.keyboardSecondaryInputCalloutContext expect(context).to(be(context)) } } describe("keyboard stack view") { it("is not added to vc view if not referred") { let view = vc.view vc.viewDidLoad() expect(view?.subviews.count).to(equal(2)) } it("is added to vc view when it's first referred") { let view = vc.view _ = vc.keyboardStackView expect(view?.subviews.count).to(equal(3)) expect(view?.subviews[2]).to(be(vc.keyboardStackView)) } it("is correctly configured") { let view = vc.keyboardStackView expect(view.axis).to(equal(.vertical)) expect(view.alignment).to(equal(.fill)) expect(view.distribution).to(equal(.equalSpacing)) } } describe("perform autocomplete") { it("is triggered by textDidChange") { expect(vc.hasCalled(vc.performAutocompleteRef)).to(beFalse()) vc.textDidChange(nil) expect(vc.hasCalled(vc.performAutocompleteRef)).to(beTrue()) } } describe("reset autocomplete") { it("is triggered by selectionWillChange") { expect(vc.hasCalled(vc.resetAutocompleteRef)).to(beFalse()) vc.selectionWillChange(nil) expect(vc.hasCalled(vc.resetAutocompleteRef)).to(beTrue()) } } describe("reset autocomplete") { it("is triggered by selectionWillChange") { expect(vc.hasCalled(vc.resetAutocompleteRef)).to(beFalse()) vc.selectionDidChange(nil) expect(vc.hasCalled(vc.resetAutocompleteRef)).to(beTrue()) } } describe("text will change") { it("calls viewWillSyncWithTextDocumentProxy") { vc.textWillChange(nil) expect(vc.keyboardContext.textDocumentProxy).to(be(vc.textDocumentProxy)) } } } } private class TestClass: KeyboardInputViewController, Mockable { lazy var viewWillSyncWithTextDocumentProxyRef = MockReference(viewWillSyncWithTextDocumentProxy) lazy var performAutocompleteRef = MockReference(performAutocomplete) lazy var resetAutocompleteRef = MockReference(resetAutocomplete) let mock = Mock() var hasDictationKeyValue = false var hasFullAccessValue = false override var hasFullAccess: Bool { hasFullAccessValue } override var hasDictationKey: Bool { get { hasDictationKeyValue } set { hasDictationKeyValue = newValue } } var needsInputModeSwitchKeyValue = false override var needsInputModeSwitchKey: Bool { needsInputModeSwitchKeyValue } override func viewWillSyncWithTextDocumentProxy() { super.viewWillSyncWithTextDocumentProxy() mock.invoke(viewWillSyncWithTextDocumentProxyRef, args: ()) } override func performAutocomplete() { mock.invoke(performAutocompleteRef, args: ()) } override func resetAutocomplete() { mock.invoke(resetAutocompleteRef, args: ()) } }
mit
1708f65c6c4920757a23fa12787051c2
32.228
100
0.541953
5.519601
false
false
false
false
jasperscholten/programmeerproject
JasperScholten-project/NewsAdminVC.swift
1
3283
// // NewsAdminVC.swift // JasperScholten-project // // Created by Jasper Scholten on 12-01-17. // Copyright © 2017 Jasper Scholten. All rights reserved. // // In this ViewController, a user can see all the newsItems of his own location (where he is employed). Selecting one of them segues to the next ViewController, which will show the newsItem. If the user is an admin, he also gets the option to create a new item. import UIKit import Firebase class NewsAdminVC: UIViewController, UITableViewDataSource, UITableViewDelegate { // MARK: - Constants and variables let newsRef = FIRDatabase.database().reference(withPath: "News") var admin = Bool() var organisationID = String() var location = String() var newsItems = [News]() // MARK: - Outlets @IBOutlet weak var newsTableView: UITableView! // MARK: - UIViewController lifecycle override func viewDidLoad() { super.viewDidLoad() // Only allow admin users to create new newsitems. [1] if admin == false { self.navigationItem.rightBarButtonItem = nil } // Retrieve newsitems for current location from Firebase. newsRef.observe(.value, with: { snapshot in var newItems: [News] = [] for item in snapshot.children { let newsData = News(snapshot: item as! FIRDataSnapshot) if newsData.organisation == self.organisationID && newsData.location == self.location { newItems.append(newsData) } } self.newsItems = newItems self.newsTableView.reloadData() }) } // MARK: - Tableview Population func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return newsItems.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = newsTableView.dequeueReusableCell(withIdentifier: "newsItemAdmin", for: indexPath) as! NewsItemAdminCell cell.title.text = newsItems[indexPath.row].title cell.date.text = newsItems[indexPath.row].date return cell } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { performSegue(withIdentifier: "showNewsItem", sender: self) newsTableView.deselectRow(at: indexPath, animated: true) } // Segue details needed to create new item, or details of selected newsItem. override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if let news = segue.destination as? NewsItemAdminVC { let indexPath = newsTableView.indexPathForSelectedRow news.newsItem = newsItems[(indexPath?.row)!] news.admin = admin } else if let addItem = segue.destination as? AddNewsItemVC { addItem.organisationID = organisationID addItem.location = location } } // MARK: - Actions @IBAction func addNewsItem(_ sender: Any) { performSegue(withIdentifier: "addNewsItem", sender: nil) } } // MARK: - References // 1. http://stackoverflow.com/questions/27887218/how-to-hide-a-bar-button-item-for-certain-users
apache-2.0
e56282c9f2caac3a091e15e05bc071c8
36.295455
262
0.649299
4.702006
false
false
false
false
sgr-ksmt/Alertift
Sources/InnerAlertController.swift
1
8230
// // InnerAlertController.swift // Alertift // // Created by Suguru Kishimoto on 4/27/17. // Copyright © 2017 Suguru Kishimoto. All rights reserved. // import Foundation import UIKit extension Alertift { public enum ImageTopMargin { case none case belowRoundCorner var margin: CGFloat { switch self { case .none: return 0.0 case .belowRoundCorner: return 16.0 } } } } /// InnerAlertController /// subclass of **UIAlertController** class InnerAlertController: UIAlertController { typealias AdjustInfo = (lineCount: Int, height: CGFloat) private(set) var originalTitle: String? private var spaceAdjustedTitle: String = "" private(set) var originalMessage: String? private var spaceAdjustedMessage: String = "" private var imageView: UIImageView? = nil private var previousImgViewSize: CGSize = .zero private var imageTopMargin: Alertift.ImageTopMargin = .none override var title: String? { didSet { if title != spaceAdjustedTitle { originalTitle = title } } } override var message: String? { didSet { if message != spaceAdjustedMessage { originalMessage = message } } } public func setImage(_ image: UIImage?, imageTopMargin: Alertift.ImageTopMargin = .none) { if let _ = image, title == nil { title = " " } self.imageTopMargin = imageTopMargin guard let imageView = self.imageView else { let imageView = UIImageView(image: image) imageView.contentMode = .scaleAspectFill imageView.clipsToBounds = true self.imageView = imageView return } imageView.image = image imageView.frame.size = image?.size ?? .zero } // MARK: - Layout code override func viewDidLayoutSubviews() { guard let imageView = imageView, let _ = imageView.image else { super.viewDidLayoutSubviews() return } adjustImageViewPosition() super.viewDidLayoutSubviews() } private func adjustImageViewPosition() { guard let imageView = imageView, let image = imageView.image else { return } if imageView.superview == nil { mainView?.addSubview(imageView) } if imageView.frame.width > view.frame.width { imageView.frame.size.width = view.frame.width imageView.frame.size.height = imageView.frame.size.width * image.size.height / image.size.width } // Adjust title if image size has changed if previousImgViewSize != imageView.bounds.size { previousImgViewSize = imageView.bounds.size adjustLabel(for: imageView) imageView.center.x = view.bounds.width / 2.0 imageView.frame.origin.y = imageTopMargin.margin } } private func adjustLabel(for imageView: UIImageView) { if let label = titleLabel { let lineCount = getLineCount(for: imageView, label: label) let lines = String(repeating: "\n", count: lineCount) spaceAdjustedTitle = lines + (originalTitle ?? "") title = spaceAdjustedTitle } else if let label = messageLabel { let lineCount = getLineCount(for: imageView, label: label) let lines = String(repeating: "\n", count: lineCount) spaceAdjustedMessage = lines + (originalMessage ?? "") message = spaceAdjustedMessage } } private func getLineCount(for imageView: UIImageView, label: UILabel?) -> Int { guard let label = label else { return 0 } let _label = UILabel(frame: .zero) _label.font = label.font _label.text = "" _label.numberOfLines = 0 var lineCount = 1 while _label.frame.height < imageView.frame.height { _label.text = _label.text.map { $0 + "\n" } _label.sizeToFit() lineCount += 1 } return lineCount } private lazy var lineHeight: CGFloat = { return titleLabel?.font.lineHeight ?? messageLabel?.font.lineHeight ?? 1.0 }() /// textFieldTextDidChangeHandler: ((UITextField, Int) -> Void) var textFieldTextDidChangeHandler: Alertift.Alert.TextFieldHandler? public typealias FinallyHandler = (UIAlertAction, Int, [UITextField]?) -> Void var finallyHandler: FinallyHandler? var alertBackgroundColor: UIColor? var titleTextColor: UIColor? = .black var messageTextColor: UIColor? = .black var titleTextAlignment: NSTextAlignment = .center var messageTextAlignment: NSTextAlignment = .center /// Register UITextFieldTextDidChange notification /// /// - Parameter textField: textField func registerTextFieldObserver(_ textField: UITextField) { NotificationCenter.default.addObserver( self, selector: #selector(self.textFieldDidChange(_:)), name: UITextField.textDidChangeNotification, object: textField ) } /// Delegate method for UITextFieldTextDidChange /// /// - Parameter notification: notification (object is UITextField) @objc private func textFieldDidChange(_ notification: Notification) { guard let textField = notification.object as? UITextField else { return } guard let index = textFields?.firstIndex(of: textField) else { return } textFieldTextDidChangeHandler?(textField, index) } /// Returns actionHandler var actionHandler: (UIAlertAction) -> (UIAlertAction, Int) { return { [weak self] action in (action, self?.actions.firstIndex(of: action) ?? -1) } } /// Returns actionWithTextFieldsHandler var actionWithTextFieldsHandler: (UIAlertAction) -> (UIAlertAction, Int, [UITextField]?) { return { [weak self] action in (action, self?.actions.firstIndex(of: action) ?? -1, self?.textFields) } } /// Returns finallyExecutor var finallyExecutor: (UIAlertAction) -> Void { return { [weak self] action in self?.finallyHandler?(action, self?.actions.firstIndex(of: action) ?? -1, self?.textFields) } } override public func viewWillLayoutSubviews() { super.viewWillLayoutSubviews() adaptBackgroundColor() updateTitleLabel() updateMessageLabel() } private func adaptBackgroundColor() { mainView?.backgroundColor = alertBackgroundColor if preferredStyle == .actionSheet { if let cancelTitle = actions.filter({ $0.style == .cancel }).first?.title { if let cancelButton = searchLabel(from: cancelTitle )?.superview?.superview { cancelButton.backgroundColor = alertBackgroundColor } } } } var titleLabel: UILabel? { return title.flatMap(searchLabel(from:)) } var messageLabel: UILabel? { return message.flatMap(searchLabel(from:)) } private func updateTitleLabel() { if let titleLabel = titleLabel { titleLabel.textColor = titleTextColor titleLabel.textAlignment = titleTextAlignment } } private func updateMessageLabel() { if let messageLabel = messageLabel { messageLabel.textColor = messageTextColor messageLabel.textAlignment = messageTextAlignment } } private var mainView: UIView? { return view.subviews.first?.subviews.first?.subviews.first } private func searchLabel(from text: String) -> UILabel? { return view.recursiveSubviews .compactMap { $0 as? UILabel} .first { $0.text == text } } deinit { NotificationCenter.default.removeObserver(self) Debug.log() } } extension UIView { var recursiveSubviews: [UIView] { return subviews.reduce(subviews, { return $0 + $1.recursiveSubviews }) } }
mit
d5a374494f8d81b7e511822f396438ad
30.772201
111
0.611982
5.089054
false
false
false
false
hujiaweibujidao/Gank
Gank/Class/Gank/AHImageCell.swift
2
3673
// // AHImageCell.swift // Gank // // Created by AHuaner on 2016/12/14. // Copyright © 2016年 CoderAhuan. All rights reserved. // import UIKit import YYWebImage class AHImageCell: UICollectionViewCell { var index: Int! var classModel: AHClassModel! { didSet { if let count = classModel.images?.count { let urlString = classModel.images![index] // 只有一张图片 if count == 1 { // 可以得到图片的高度宽度, 根据宽高比缩放图片 if classModel.imageW != 0 && classModel.imageH != 0 { // 先从缓存中查找对应的高清图 let image = imageFromCache(urlString: urlString) if image != nil { // 缓存中有高清图, 直接加载 imageView.image = image } else { let small_url = urlString + "?imageView2/1/w/\(Int(classModel.imageContainFrame.width))/h/\(Int(classModel.imageContainFrame.height))/interlace/1" // 当前网络不是wifi, 而且仅允许wifi网络下载图片 if ToolKit.getNetWorkType() != "Wifi" && onlyWifiDownPic == true { // 缓存中有缩略图,直接加载 imageView.image = imageFromCache(urlString: small_url) ?? UIImage(named: "placeImage") return } imageView.yy_imageURL = URL(string: small_url) } // 获取不到图片的高度宽度 } else { if ToolKit.getNetWorkType() != "Wifi" && onlyWifiDownPic == true { imageView.image = imageFromCache(urlString: urlString) ?? UIImage(named: "placeImage") return } imageView.yy_imageURL = URL(string: urlString) } // 有多张图片 } else if count > 1 { // 先从缓存中查找对应的高清图 let image = imageFromCache(urlString: urlString) if image != nil { // 缓存中有高清图, 直接加载 imageView.image = image } else { let small_url = urlString + "?imageView2/0/w/\(Int(cellMaxWidth))" if ToolKit.getNetWorkType() != "Wifi" && onlyWifiDownPic == true { imageView.image = imageFromCache(urlString: small_url) ?? UIImage(named: "placeImage") return } imageView.yy_imageURL = URL(string: small_url) } } } } } @IBOutlet weak var imageView: YYAnimatedImageView! override func awakeFromNib() { super.awakeFromNib() self.backgroundColor = UIColorMainBG } fileprivate func imageFromCache(urlString: String) -> UIImage? { let url = URL(string: urlString) let cacheKey = YYWebImageManager.shared().cacheKey(for: url!) let image = YYWebImageManager.shared().cache?.getImageForKey(cacheKey) return image } } extension AHImageCell: ViewNameReusable {}
mit
81637087abd371555933c873dac13663
38.022727
174
0.454281
5.258806
false
false
false
false
archpoint/sparkmap
app/Spark/CommentComposerViewController.swift
1
7524
// // CommentComposerViewController.swift // SparkMap // // Created by Edvard Holst on 22/07/16. // Copyright © 2016 Zygote Labs. All rights reserved. // import UIKit class CommentComposerViewController: UIViewController { @IBOutlet weak var scrollView: UIScrollView? @IBOutlet var commentTextView: UITextView! @IBOutlet var chargingStationTitleLabel: UILabel! @IBOutlet var ratingSegmentedControl: UISegmentedControl! @IBOutlet var submitButton: UIButton! // Charging Station Details var chargerID: Int! var chargingStationTitle: String! override func viewDidLoad() { super.viewDidLoad() // Add Gesture recognizer for hiding the keyboard when tapping outside it. let tapGesture = UITapGestureRecognizer(target: self, action: #selector(CommentComposerViewController.tapOutsideTextView(_:))) view.addGestureRecognizer(tapGesture) // Prepare the comment text view. formatTextView() // Make the comment text view the first responder commentTextView.becomeFirstResponder() // Register to be notified if the keyboard is changing size NotificationCenter.default.addObserver(self, selector: #selector(CommentComposerViewController.keyboardWillShowOrHide(_:)), name: NSNotification.Name.UIKeyboardWillShow, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(CommentComposerViewController.keyboardWillShowOrHide(_:)), name: NSNotification.Name.UIKeyboardWillHide, object: nil) // Set the charging station title text. chargingStationTitleLabel.text = chargingStationTitle // Set the view controller title. let newCommentString = NSLocalizedString("New Comment", comment: "New Comment") self.title = newCommentString // Add rounded corners to the submit button. self.submitButton.layer.cornerRadius = 5.0 } deinit { NotificationCenter.default.removeObserver(self) } func keyboardWillShowOrHide(_ notification: Notification) { // Pull a bunch of info out of the notification if let scrollView = scrollView, let userInfo = (notification as NSNotification).userInfo, let endValue = userInfo[UIKeyboardFrameEndUserInfoKey], let durationValue = userInfo[UIKeyboardAnimationDurationUserInfoKey] { // Transform the keyboard's frame into our view's coordinate system let endRect = view.convert((endValue as AnyObject).cgRectValue, from: view.window) // Find out how much the keyboard overlaps the scroll view // We can do this because our scroll view's frame is already in our view's coordinate system let keyboardOverlap = scrollView.frame.maxY - endRect.origin.y // Set the scroll view's content inset to avoid the keyboard // Don't forget the scroll indicator too! scrollView.contentInset.bottom = keyboardOverlap scrollView.scrollIndicatorInsets.bottom = keyboardOverlap let duration = (durationValue as AnyObject).doubleValue UIView.animate(withDuration: duration!, delay: 0, options: .beginFromCurrentState, animations: { self.view.layoutIfNeeded() }, completion: nil) } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func tapOutsideTextView(_ gesture: UITapGestureRecognizer) { // Resign first responder from commentTextview if user taps outside the keyboard area. commentTextView.resignFirstResponder() } func formatTextView() { self.commentTextView.layer.borderWidth = 1.0 self.commentTextView.layer.borderColor = UIColor.lightGray.cgColor self.commentTextView.layer.cornerRadius = 5.0 } @IBAction func postCommentAction(){ // Register notification listeners NotificationCenter.default.addObserver(self, selector: #selector(CommentComposerViewController.failedToGetNewAccessToken(_:)), name: NSNotification.Name(rawValue: "OCMLoginFailed"), object: nil) NotificationCenter.default.addObserver(self, selector: #selector(CommentComposerViewController.gotNewAccessToken(_:)), name: NSNotification.Name(rawValue: "OCMLoginSuccess"), object: nil) updateAccessToken() NotificationCenter.default.addObserver(self, selector: #selector(CommentComposerViewController.commentNotPosted(_:)), name: NSNotification.Name(rawValue: "OCMCommentPostError"), object: nil) NotificationCenter.default.addObserver(self, selector: #selector(CommentComposerViewController.commentPostedSuccessfully(_:)), name: NSNotification.Name(rawValue: "OCMCommentPostSuccess"), object: nil) // Authenticate to OCM and get a new access token updateAccessToken() // Resign text view first responder. commentTextView.resignFirstResponder() // Show loading spinner let postingCommentSpinnerString = NSLocalizedString("Posting Comment...", comment: "Posting comment spinner text") SwiftSpinner.show(postingCommentSpinnerString) } func gotNewAccessToken(_ notification: Notification){ // New access token received. Go ahead and post comment if let accessToken = (notification as NSNotification).userInfo?["accessToken"] as? NSString { submitCommentToOCM(String(accessToken)) } } func failedToGetNewAccessToken(_ notification: Notification) { // Notify user that authentication failed. Notification includes error message. if let errorMessage = (notification as NSNotification).userInfo?["errorMesssage"] as? NSString { SwiftSpinner.show(String(errorMessage), animated: false).addTapHandler({ SwiftSpinner.hide() }) } } func updateAccessToken(){ AuthenticationManager.authenticateUserWithStoredCredentials() } func commentPostedSuccessfully(_ notification: Notification) { // Comment posted. Post notification and pop view controller. DispatchQueue.main.async(execute: { () -> Void in SwiftSpinner.hide() NotificationCenter.default.post(name: Notification.Name(rawValue: "DataUpdateRequired"), object: nil) self.navigationController?.popViewController(animated: true) }) } func commentNotPosted(_ notification: Notification) { // Notify user that the comment was not posted. Notification includes error message. if let errorMessage = (notification as NSNotification).userInfo?["errorMesssage"] as? NSString { SwiftSpinner.show(String(errorMessage), animated: false).addTapHandler({ SwiftSpinner.hide() }) } } func submitCommentToOCM(_ accessToken: String){ NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: "OCMLoginFailed"), object: nil) NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: "OCMLoginSuccess"), object: nil) CommentSubmissionManager.submitComment(chargerID, commentText: commentTextView.text, rating: ratingSegmentedControl.selectedSegmentIndex, accessToken: accessToken) } }
mit
72259ab3aa5bc54dbbd4694c25ffd4b6
46.613924
224
0.69467
5.523495
false
false
false
false
mkoehnke/WKZombie
Sources/WKZombie/HTMLForm.swift
1
3636
// // HTMLForm.swift // // Copyright (c) 2015 Mathias Koehnke (http://www.mathiaskoehnke.de) // // 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 /// HTML Form class, which represents the <form> element in the DOM. public class HTMLForm : HTMLElement { /// All inputs fields (keys and values) of this form. public fileprivate(set) var inputElements = [String : String]() required public init?(element: AnyObject, XPathQuery: String? = nil) { super.init(element: element, XPathQuery: XPathQuery) if let element = HTMLElement(element: element, XPathQuery: XPathQuery) { retrieveAllInputs(element) } } /// Returns the value for the name attribute. public var name : String? { return objectForKey("name") } /// Returns the value for the id attribute. public var id : String? { return objectForKey("id") } /// Returns the value for the action attribute. public var action : String? { return objectForKey("action") } /** Enables subscripting for modifying the input field values. - parameter input: The Input field attribute name. - returns: The Input field attribute value. */ public subscript(key: String) -> String? { return inputElements[key] } //======================================== // MARK: Form Submit Script //======================================== internal func actionScript() -> String? { if let name = name { return "document.\(name).submit();" } else if let id = id { return "document.getElementById('\(id)').submit();" } return nil } //======================================== // MARK: Overrides //======================================== internal override class func createXPathQuery(_ parameters: String) -> String { return "//form\(parameters)" } //======================================== // MARK: Private Methods //======================================== fileprivate func retrieveAllInputs(_ element: HTMLElement) { if let tagName = element.tagName as String? , tagName == "input" { if let name = element.objectForKey("name") { inputElements[name] = element.objectForKey("value") } } if let children = element.children() as [HTMLElement]? , children.count > 0 { for child in children { retrieveAllInputs(child) } } } }
mit
144cf4ed6b9d0b04a32d0b335eb87252
34.647059
85
0.597635
4.967213
false
false
false
false
LawrenceHan/Games
ZombieConga/ZombieConga/MyUtils.swift
1
3119
// // MyUtils.swift // ZombieConga // // Created by Hanguang on 3/28/16. // Copyright © 2016 Hanguang. All rights reserved. // import Foundation import CoreGraphics import AVFoundation func + (left: CGPoint, right: CGPoint) -> CGPoint { return CGPoint(x: left.x + right.x, y: left.y + right.y) } func += (inout left: CGPoint, right: CGPoint) { left = left + right } func - (left: CGPoint, right: CGPoint) -> CGPoint { return CGPoint(x: left.x - right.x, y: left.y - right.y) } func -= (inout left: CGPoint, right: CGPoint) { left = left - right } func * (left: CGPoint, right: CGPoint) -> CGPoint { return CGPoint(x: left.x * right.x, y: left.y * right.y) } func *= (inout left: CGPoint, right: CGPoint) { left = left * right } func * (point: CGPoint, scalar: CGFloat) -> CGPoint { return CGPoint(x: point.x * scalar, y: point.y * scalar) } func *= (inout point: CGPoint, scalar: CGFloat) { point = point * scalar } func / (left: CGPoint, right: CGPoint) -> CGPoint { return CGPoint(x: left.x / right.x, y: left.y / right.y) } func /= (inout left: CGPoint, right: CGPoint) { left = left / right } func / (point: CGPoint, scalar: CGFloat) -> CGPoint { return CGPoint(x: point.x / scalar, y: point.y / scalar) } func /= (inout point: CGPoint, scalar: CGFloat) { point = point / scalar } #if !(arch(x86_64) || arch(arm64)) func atan2(y: CGFloat, x: CGFloat) -> CGFloat { return CGFloat(atan2f(Float(y), Float(x))) } func sqrt(a: CGFloat) -> CGFloat { return CGFloat(sqrtf(Float(a))) } #endif extension CGPoint { func length() -> CGFloat { return sqrt(x*x + y*y) } func normalized() -> CGPoint { return self / length() } var angle: CGFloat { return atan2(y, x) } } let π = CGFloat(M_PI) func shortestAngleBetween(angle1: CGFloat, angle2: CGFloat) -> CGFloat { let twoπ = π * 2.0 var angle = (angle2 - angle1) % twoπ if (angle >= π) { angle = angle - twoπ } if (angle <= -π) { angle = angle + twoπ } return angle } extension CGFloat { func sign() -> CGFloat { return (self >= 0.0) ? 1.0 : -1.0 } } extension CGFloat { static func random() -> CGFloat { return CGFloat(Float(arc4random()) / Float(UInt32.max)) } static func random(min min: CGFloat, max: CGFloat) -> CGFloat { assert(min < max) return CGFloat.random() * (max - min) + min } } var backgroundMusicPlayer: AVAudioPlayer! func playBackgroundMusic(fileName: String) { let resourceUrl = NSBundle.mainBundle().URLForResource(fileName, withExtension: nil) guard let url = resourceUrl else { print("Could not find file: \(fileName)") return } do { try backgroundMusicPlayer = AVAudioPlayer(contentsOfURL: url) backgroundMusicPlayer.numberOfLoops = 1 backgroundMusicPlayer.prepareToPlay() backgroundMusicPlayer.play() } catch { print("Could not create audio player!") return } }
mit
283d375b5400504f01975bd914148e3c
21.536232
88
0.600322
3.502252
false
false
false
false
getsocial-im/getsocial-ios-sdk
example/GetSocialDemo/Views/Communities/Tags/TagsModel.swift
1
2741
// // GenericModel.swift // GetSocialDemo // // Copyright © 2020 GetSocial BV. All rights reserved. // import Foundation class TagsModel { var onInitialDataLoaded: (() -> Void)? var onDidOlderLoad: ((Bool) -> Void)? var onError: ((Error) -> Void)? var tagFollowed: ((Int) -> Void)? var tagUnfollowed: ((Int) -> Void)? var pagingQuery: TagsPagingQuery? var query: TagsQuery? var tags: [Tag] = [] var nextCursor: String = "" func loadEntries(query: TagsQuery) { self.query = query self.pagingQuery = TagsPagingQuery.init(query) self.tags.removeAll() executeQuery(success: { self.onInitialDataLoaded?() }, failure: onError) } func loadNewer() { self.pagingQuery?.nextCursor = "" self.tags.removeAll() executeQuery(success: { self.onInitialDataLoaded?() }, failure: onError) } func loadOlder() { if self.nextCursor.count == 0 { onDidOlderLoad?(false) return } self.pagingQuery?.nextCursor = self.nextCursor executeQuery(success: { self.onDidOlderLoad?(true) }, failure: onError) } func numberOfEntries() -> Int { return self.tags.count } func entry(at: Int) -> Tag { return self.tags[at] } func findTag(_ name: String) -> Tag? { return self.tags.filter { return $0.name == name }.first } func followTag(_ name: String, remove: Bool = false) { if let tag = findTag(name), let tagIndex = self.tags.firstIndex(of: tag) { let query = FollowQuery.tags([name]) if tag.isFollowedByMe { Communities.unfollow(query, success: { _ in if remove { self.tags.remove(at: tagIndex) } else { PrivateTagBuilder.updateTag(tag: tag, isFollowed: false) } self.tagUnfollowed?(tagIndex) }) { error in self.onError?(error) } } else { Communities.follow(query, success: { _ in PrivateTagBuilder.updateTag(tag: tag, isFollowed: true) self.tagFollowed?(tagIndex) }) { error in self.onError?(error) } } } } private func executeQuery(success: (() -> Void)?, failure: ((Error) -> Void)?) { Communities.tags(self.pagingQuery!, success: { result in self.nextCursor = result.nextCursor self.tags.append(contentsOf: result.tags) success?() }) { error in failure?(error) } } }
apache-2.0
72305d004b29a14294c17ac82c98010d
25.862745
84
0.533212
4.267913
false
false
false
false
meantheory/octopus
strings.swift
1
2324
import Cocoa import Darwin class Constant<T> : Parser { let value: T let str: String init(value:T) { self.value = value self.str = "\(value)" } typealias Target = T func parse(stream: CharStream) -> Target? { if stream.startsWith(str) { stream.advance(count(str)) return value } stream.error("Expected \(str)") return nil } } func const<T>(value:T) -> Constant<T> { return Constant(value:value) } class Regex : Parser { typealias Target = String let pattern:String init(pattern:String) { self.pattern = pattern } func parse(stream:CharStream) -> Target? { if let match = stream.startsWithRegex(pattern) { stream.advance(count(match)) return match } return nil } } func regex(pattern:String) -> Regex { return Regex(pattern:pattern) } class Satisfy : Parser { let condition: Character -> Bool typealias Target = Character init(condition:Character -> Bool) { self.condition = condition } func parse(stream:CharStream) -> Target? { if let ch = stream.head { if condition(ch) { stream.advance(1) return ch } } return nil } } func satisfy(condition:Character->Bool) -> Satisfy { return Satisfy(condition:condition) } class EndOfFile : Parser { typealias Target = Void func parse(stream:CharStream) -> Target? { if stream.eof { return Target() } else { return nil } } } func eof() -> EndOfFile { return EndOfFile() } // Helpful versions which turn arrays of Characters into Strings func arrayToString<T:Parser where T.Target==Array<Character>> (parser: T) -> Pipe<T, String> { return pipe(parser, {return String($0)}) } func manychars<T:Parser where T.Target==Character> (item:T) -> Pipe<Many<T>, String> { return arrayToString(many(item)) } func many1chars<T:Parser where T.Target==Character> (item:T) -> Pipe<Many<T>, String> { return arrayToString(many1(item)) } // Overloaded followed-by operators func >~ <T: Parser>(first: String, second: T) -> FollowedBySecond<Constant<String>,T> { return FollowedBySecond(first: const(first), second: second) } func ~> <T: Parser>(first: T, second: String) -> FollowedByFirst<T,Constant<String>> { return FollowedByFirst(first: first, second: const(second)) }
apache-2.0
ddb3279ede5237735a07aa82dc24119c
19.385965
87
0.654045
3.537291
false
false
false
false
CraigZheng/KomicaViewer
KomicaViewer/KomicaViewer/ViewController/BookmarkTableViewController.swift
1
2785
// // BookmarkTableViewController.swift // KomicaViewer // // Created by Craig Zheng on 14/7/17. // Copyright © 2017 Craig. All rights reserved. // import UIKit class BookmarkTableViewController: UITableViewController { let manager = BookmarkManager.shared private enum Segue: String { case showThread } fileprivate var bookmarks: [Bookmark] { return manager.bookmarks.reversed() } override func viewDidLoad() { super.viewDidLoad() tableView.rowHeight = UITableViewAutomaticDimension tableView.estimatedRowHeight = 120 tableView.register(UINib(nibName: "ThreadTableViewCell", bundle: nil), forCellReuseIdentifier: ThreadTableViewCell.identifier) } @IBAction func editAction(_ sender: Any) { tableView.setEditing(!tableView.isEditing, animated: true) } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return bookmarks.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: ThreadTableViewCell.identifier, for: indexPath) if let cell = cell as? ThreadTableViewCell { let thread = bookmarks[indexPath.row].thread // Home view does not show parasite view. cell.shouldShowParasitePost = false cell.shouldShowImage = Configuration.singleton.showImage cell.layoutWithThread(thread, forTableViewController: nil) } return cell } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { performSegue(withIdentifier: Segue.showThread.rawValue, sender: tableView.cellForRow(at: indexPath)) } override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) { switch editingStyle { case .delete: BookmarkManager.shared.remove(bookmarks[indexPath.row]) tableView.reloadData() default: // Nothing break } } } // MARK: Prepare for segue. extension BookmarkTableViewController { override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if let selectedCell = sender as? UITableViewCell, let destinationViewController = segue.destination as? ThreadTableViewController, let indexPath = tableView.indexPath(for: selectedCell) { destinationViewController.forum = bookmarks[indexPath.row].forum destinationViewController.selectedThread = bookmarks[indexPath.row].thread } } }
mit
6a5304841ff98a94d71e6262e72d01c8
33.8
136
0.677083
5.512871
false
false
false
false
Fenrikur/ef-app_ios
EurofurenceTests/Firebase Notification Registration/EurofurenceFCMDeviceRegistrationTests.swift
1
2990
import Eurofurence import EurofurenceModelTestDoubles import XCTest class EurofurenceFCMDeviceRegistrationTests: XCTestCase { var capturingJSONSession: CapturingJSONSession! var registration: EurofurenceFCMDeviceRegistration! var urlProviding: StubAPIURLProviding! override func setUp() { super.setUp() capturingJSONSession = CapturingJSONSession() urlProviding = StubAPIURLProviding() registration = EurofurenceFCMDeviceRegistration(JSONSession: capturingJSONSession, urlProviding: urlProviding) } private func performRegistration(_ fcm: String = "", topics: [FirebaseTopic] = [], authenticationToken: String? = "", completionHandler: ((Error?) -> Void)? = nil) { registration.registerFCM(fcm, topics: topics, authenticationToken: authenticationToken) { completionHandler?($0) } } func testRegisteringTheFCMTokenSubmitsRequestToFCMRegistrationURL() { performRegistration() let expectedURL = urlProviding.url + "/PushNotifications/FcmDeviceRegistration" XCTAssertEqual(expectedURL, capturingJSONSession.postedURL) } func testRegisteringTheFCMTokenShouldNotSubmitRequestUntilRegistrationActuallyOccurs() { XCTAssertNil(capturingJSONSession.postedURL) } func testRegisteringTheFCMTokenShouldPostJSONBodyWithDeviceIDAsFCMToken() { let fcm = "Something unique" performRegistration(fcm) XCTAssertEqual(fcm, capturingJSONSession.postedJSONValue(forKey: "DeviceId")) } func testRegisteringTheFCMTokenShouldSupplyAllTopicsWithinAnArrayUnderTheTopicsKey() { let topics: [FirebaseTopic] = [.debug, .ios] performRegistration(topics: topics) let expected: [String] = topics.map({ $0.description }) XCTAssertEqual(expected, capturingJSONSession.postedJSONValue(forKey: "Topics") ?? []) } func testRegisteringTheFCMTokenWithUserAuthenticationTokenSuppliesItUsingTheAuthHeader() { let authenticationToken = "Token" performRegistration(authenticationToken: authenticationToken) XCTAssertEqual("Bearer \(authenticationToken)", capturingJSONSession.capturedAdditionalPOSTHeaders?["Authorization"]) } func testRegisteringTheFCMTokenWithoutUserAuthenticationTokenDoesNotSupplyAuthHeader() { performRegistration(authenticationToken: nil) XCTAssertNil(capturingJSONSession.capturedAdditionalPOSTHeaders?["Authorization"]) } func testFailingToRegisterFCMTokenPropagatesErrorToCompletionHandler() { let expectedError = NSError(domain: "Test", code: 0, userInfo: nil) var observedError: NSError? performRegistration { observedError = $0 as NSError? } capturingJSONSession.invokeLastPOSTCompletionHandler(responseData: nil, error: expectedError) XCTAssertEqual(expectedError, observedError) } }
mit
963c6c683bd6474e6a9c311d252e66ed
39.958904
125
0.725753
5.301418
false
true
false
false
Explora-codepath/explora
Explora/ExploraParseSeed.swift
1
8115
// // ExploraParseSeed.swift // Explora // // Created by admin on 11/1/15. // Copyright © 2015 explora-codepath. All rights reserved. // import UIKit import Parse class ExploraParseSeed { // var createdBy: PFUser? // var attendees: PFRelation? // var attendeesLimit: Int? // var eventTitle: String? // var eventDescription: String? // var eventLocation: PFGeoPoint? // var eventAddress: String? // var meetingLocationLat: CLLocationDegrees? // var meetingLocationLng: CLLocationDegrees? // var meetingStartTime: NSDate? // var meetingEndTime: NSDate? // var category: Int? class func seedDatabase() { PFUser.logOut() generateUser1AndEvent() generateUser2AndEvent() generateUser3AndEvent() generateUser4AndEvent() generateUser5AndEvent() } // Montgomery class func generateUser1AndEvent() { // Create users let user1 = PFUser() user1.username = "mark123" user1.password = "testing" user1.email = "[email protected]" try! user1.signUp() // Create events let event1 = ExploraEvent() event1.createdBy = PFUser.currentUser() // Attendees event1.attendeesLimit = 8; let participateRelation1 = event1.attendees participateRelation1!.addObject(event1.createdBy!) // @37.80266,-122.4079787 event1.eventLocation = PFGeoPoint(latitude: 37.80266, longitude: -122.4079787); event1.eventTitle = "Coit Tower!" event1.eventDescription = "Let's get some exercise and climb all the way to the top of Coit Tower." event1.eventAddress = "1 Telegraph Hill Blvd\nSan Francisco, CA 94133" // meeting location // @37.7955277,-122.3956398 event1.meetingLocationLat = 37.7955277 event1.meetingLocationLng = -122.3956398 event1.meetingAddress = "Ferry Building Marketplace\nSan Francisco, CA" // meeting time event1.meetingStartTime = NSDate(timeIntervalSinceNow: 300000) event1.meetingEndTime = NSDate(timeIntervalSinceNow: 303600) // category event1.category = ExploraEventCategory.Travel.rawValue try! event1.save() print("event1 saved?") PFUser.logOut() } // Little Italy class func generateUser2AndEvent() { let user2 = PFUser() user2.username = "lisa345" user2.password = "testing" user2.email = "[email protected]" try! user2.signUp() let event2 = ExploraEvent() event2.createdBy = user2 // Attendees event2.attendeesLimit = -1; let participateRelation2 = event2.attendees participateRelation2!.addObject(user2) // @37.8007601,37.8007601 event2.eventLocation = PFGeoPoint(latitude: 37.8007601, longitude: 37.8007601); event2.eventTitle = "Party startin'" event2.eventDescription = "Bar hopping around Little Italy" event2.eventAddress = "Little Italy\nSan Francisco, CA 94133" // meeting location // @37.7894069,-122.403256 event2.meetingLocationLat = 37.7894069 event2.meetingLocationLng = -122.403256 event2.meetingAddress = "Montgomery St. BART Station\nSan Francisco, CA" // meeting time event2.meetingStartTime = NSDate(timeIntervalSinceNow: 400000) event2.meetingEndTime = NSDate(timeIntervalSinceNow: 403600) // category event2.category = ExploraEventCategory.FoodDrink.rawValue try! event2.save() print("event2 saved?") PFUser.logOut() } // Yosemite class func generateUser3AndEvent() { let user3 = PFUser() user3.username = "Linda333" user3.password = "testing" user3.email = "[email protected]" try! user3.signUp() let event3 = ExploraEvent() event3.createdBy = user3 // Attendees event3.attendeesLimit = 5; let participateRelation3 = event3.attendees participateRelation3!.addObject(user3) // @37.729092,-119.5363824 event3.eventLocation = PFGeoPoint(latitude: 37.729092, longitude: -119.5363824); event3.eventTitle = "Hiking!" event3.eventDescription = "Let's hike up the John Muir Trail!" event3.eventAddress = "Liberty Cap\nMariposa County, CA" // meeting location // @37.8741697,-122.2708621 event3.meetingLocationLat = 37.8741697 event3.meetingLocationLng = -122.2708621 event3.meetingAddress = "1860 Shattuck Ave\nBerkeley, CA 94704" // meeting time event3.meetingStartTime = NSDate(timeIntervalSinceNow: 300000) event3.meetingEndTime = NSDate(timeIntervalSinceNow: 303600) // category event3.category = ExploraEventCategory.Travel.rawValue try! event3.save() print("event3 saved?") PFUser.logOut() } // Twitter class func generateUser4AndEvent() { let user4 = PFUser() user4.username = "Sarah333" user4.password = "testing" user4.email = "[email protected]" try! user4.signUp() let event4 = ExploraEvent() event4.createdBy = user4 // Attendees event4.attendeesLimit = 30; let participateRelation3 = event4.attendees participateRelation3!.addObject(user4) // @37.776692,-122.4189706 event4.eventLocation = PFGeoPoint(latitude: 37.776692, longitude: -122.4189706); event4.eventTitle = "Tour of Twitter!" event4.eventDescription = "Check out the Twitter HQ!" event4.eventAddress = "1355 Market St #900\nSan Francisco, CA 94103" // meeting location // @37.776692,-122.4189706 event4.meetingLocationLat = 37.776692 event4.meetingLocationLng = -122.4189706 event4.meetingAddress = "1355 Market St #900\nSan Francisco, CA 94103" // meeting time event4.meetingStartTime = NSDate(timeIntervalSinceNow: 500000) event4.meetingEndTime = NSDate(timeIntervalSinceNow: 503600) // category event4.category = ExploraEventCategory.CommunityCulture.rawValue try! event4.save() print("event4 saved?") PFUser.logOut() } // Codepath class func generateUser5AndEvent() { let user5 = PFUser() user5.username = "Jim433" user5.password = "testing" user5.email = "[email protected]" try! user5.signUp() let event5 = ExploraEvent() event5.createdBy = user5 // Attendees event5.attendeesLimit = 10; let participateRelation3 = event5.attendees participateRelation3!.addObject(user5) // @37.7708021,-122.4060909 event5.eventLocation = PFGeoPoint(latitude: 37.7708021, longitude: -122.4060909); event5.eventTitle = "Codepath iOS" event5.eventDescription = "Learn iOS with Ben" event5.eventAddress = "699 8th St\nSan Francisco, CA 94103" // meeting location // @37.7708021,-122.4060909 event5.meetingLocationLat = 37.7708021 event5.meetingLocationLng = -122.4060909 event5.meetingAddress = "699 8th St\nSan Francisco, CA 94103" // meeting time event5.meetingStartTime = NSDate(timeIntervalSinceNow: 300000) event5.meetingEndTime = NSDate(timeIntervalSinceNow: 303600) // category event5.category = ExploraEventCategory.FamilyEducation.rawValue try! event5.save() PFUser.logOut() print("event5 saved?") } }
mit
7092909e634de5ba11cde8e5fae0ba73
32.254098
107
0.604018
4.129262
false
false
false
false
zavsby/ProjectHelpersSwift
Classes/Categories/String+Extensions.swift
1
2020
// // String+Extensions.swift // ProjectHelpers-Swift // // Created by Sergey on 03.11.15. // Copyright © 2015 Sergey Plotkin. All rights reserved. // import Foundation import UIKit public extension String { //MARK:- Properties public var length: Int { return self.characters.count } public var anyText: Bool { return !self.isEmpty } // MARK:- Methods public func md5() -> String { var digest = [UInt8](count: Int(CC_MD5_DIGEST_LENGTH), repeatedValue: 0) if let data = self.dataUsingEncoding(NSUTF8StringEncoding) { CC_MD5(data.bytes, CC_LONG(data.length), &digest) } var digestHex = "" for index in 0..<Int(CC_MD5_DIGEST_LENGTH) { digestHex += String(format: "%02x", digest[index]) } return digestHex } // MARK:- Text dimensions methods public func textViewHeightWithFont(font: UIFont, maxWidth: Double) -> Double { let textView = UITextView() textView.font = font textView.text = self let size = textView.sizeThatFits(CGSize(width: maxWidth, height: DBL_MAX)) return Double(size.height) } public func labelHeightWithFont(font: UIFont, maxWidth: Double, linebreakMode: NSLineBreakMode) -> Double { guard self.anyText else { return 0.0 } let paragraphStyle = NSMutableParagraphStyle() paragraphStyle.lineBreakMode = linebreakMode let attributes = [NSFontAttributeName: font, NSParagraphStyleAttributeName: paragraphStyle] let maximumSize = CGSize(width: maxWidth, height: DBL_MAX) let rect = (self as NSString).boundingRectWithSize(maximumSize, options: [.UsesLineFragmentOrigin, .UsesFontLeading], attributes: attributes, context: nil ) return ceil(Double(rect.size.height)) } }
mit
4e9d7b3f4abbc3a94416afedcdfeb4a3
26.671233
111
0.59683
4.750588
false
false
false
false
bingoogolapple/SwiftNote-PartOne
天猫抽屉/天猫抽屉/FolderView.swift
1
7509
// // FolderView.swift // 天猫抽屉 // // Created by bingoogol on 14/10/2. // Copyright (c) 2014年 bingoogol. All rights reserved. // import UIKit class FolderView: UITableView { let ROW_HEIGHT:CGFloat = 80 let EMBEDVIEW_HEIGHT:CGFloat = 200 // 动画的表格行 var animationRows:NSMutableArray! var shopListViewController:ShopListViewController! override init?(frame: CGRect, style: UITableViewStyle) { super.init(frame: frame, style: style) // 设置背景图片 var image = UIImage(named: "tmall_bg_furley.png")! self.backgroundColor = UIColor(patternImage: image) self.rowHeight = ROW_HEIGHT self.showsVerticalScrollIndicator = false shopListViewController = ShopListViewController() shopListViewController.view.frame.size.height = EMBEDVIEW_HEIGHT } required init(coder aDecoder: NSCoder) { super.init(coder: aDecoder) println("init coder") } // func openFolderAtIndexPath(indexPath:NSIndexPath, shopList:NSArray) { // if animationRows == nil { // shopListViewController.shopList = shopList // shopListViewController.tableView.reloadData() // // 新建一个数组,把所有可能有动画的表格行的indexPath全部记录下来,一遍之后还原 // animationRows = NSMutableArray(array: self.indexPathsForVisibleRows()!) // // 表格的偏移。注意:表格是继承自UIScrollView,有偏移量 // var bottomY = self.contentOffset.y + self.frame.height // // 计算准备插入子视图的y值 // var selectedCell = self.cellForRowAtIndexPath(indexPath)! // var subViewY = selectedCell.frame.origin.y + ROW_HEIGHT // // 准备加入子视图的最大y值 // var maxSubViewY = bottomY - EMBEDVIEW_HEIGHT // // 判断空间是否够大 // if maxSubViewY >= subViewY { // shopListViewController.tableView.frame.origin.y = subViewY // // 空间够大。只要挪动选中行下方的表格行即可 // UIView.animateWithDuration(0.5, animations: { // for path in self.animationRows { // var cell:ShopTypeCell = self.cellForRowAtIndexPath(path as NSIndexPath) as ShopTypeCell! // cell.saveOriginY() // var newFrame = cell.frame // // if path.row > indexPath.row { // newFrame.origin.y += self.shopListViewController.tableView.frame.height // } // // cell.frame = newFrame // } // }) // } else { // shopListViewController.tableView.frame.origin.y = maxSubViewY // var up = maxSubViewY - subViewY // var down = self.shopListViewController.tableView.frame.height + up // // 空间不够。上面的要挪,下边也要挪 // UIView.animateWithDuration(0.5, animations: { // // for path in self.animationRows { // var cell:ShopTypeCell = self.cellForRowAtIndexPath(path as NSIndexPath) as ShopTypeCell! // cell.saveOriginY() // var newFrame = cell.frame // // if path.row > indexPath.row { // newFrame.origin.y += down // } else { // newFrame.origin.y += up // } // // cell.frame = newFrame // } // }) // } // self.insertSubview(shopListViewController.tableView, atIndex: 0) // } else { // self.closeFolder() // } // } func openFolderAtIndexPath(indexPath:NSIndexPath, shopList:NSArray) { self.scrollEnabled = false if animationRows == nil { shopListViewController.shopList = shopList shopListViewController.tableView.reloadData() // 新建一个数组,把所有可能有动画的表格行的indexPath全部记录下来,一遍之后还原 animationRows = NSMutableArray(array: self.indexPathsForVisibleRows()!) // 表格的偏移。注意:表格是继承自UIScrollView,有偏移量 var bottomY = self.contentOffset.y + self.frame.height // 计算准备插入子视图的y值 var selectedCell = self.cellForRowAtIndexPath(indexPath)! var subViewY = selectedCell.frame.origin.y + ROW_HEIGHT // 准备加入子视图的最大y值 var maxSubViewY = bottomY - EMBEDVIEW_HEIGHT // 判断空间是否够大 if maxSubViewY >= subViewY { shopListViewController.tableView.frame.origin.y = subViewY self.openFolderFromIndexPath(indexPath, up: 0, down: self.shopListViewController.tableView.frame.height, newFrame: { (up, down, path, cell) -> CGRect in var newFrame:CGRect = cell.frame if path.row > indexPath.row { newFrame.origin.y += down } return newFrame }) } else { shopListViewController.tableView.frame.origin.y = maxSubViewY // 空间不够。上面的要挪,下边也要挪 var up = maxSubViewY - subViewY var down = self.shopListViewController.tableView.frame.height + up self.openFolderFromIndexPath(indexPath, up: up, down: down, newFrame: { (up, down, path, cell) -> CGRect in var newFrame = cell.frame if path.row > indexPath.row { newFrame.origin.y += down } else { newFrame.origin.y += up } return newFrame }) } self.insertSubview(shopListViewController.tableView, atIndex: 0) } else { self.closeFolder() } } func openFolderFromIndexPath(indexPath:NSIndexPath,up:CGFloat,down:CGFloat,newFrame:(up:CGFloat,down:CGFloat,path:NSIndexPath,cell:ShopTypeCell) -> CGRect) { // 空间够大。只要挪动选中行下方的表格行即可 UIView.animateWithDuration(0.3, animations: { for path in self.animationRows { var cell:ShopTypeCell = self.cellForRowAtIndexPath(path as NSIndexPath) as ShopTypeCell! cell.saveOriginY() cell.frame = newFrame(up: up, down: down, path: path as NSIndexPath,cell:cell) } }) } func closeFolder() { UIView.animateWithDuration(0.3, animations: { for path in self.animationRows { var cell:ShopTypeCell = self.cellForRowAtIndexPath(path as NSIndexPath) as ShopTypeCell! cell.restoreOriginY() } }, completion: { (finished:Bool) in self.shopListViewController.tableView.removeFromSuperview() self.animationRows = nil self.scrollEnabled = true } ) } }
apache-2.0
9659b70656188fdca8fff89e447c4295
42.209877
168
0.543649
4.57451
false
false
false
false
WittyBrains/demo1
WhatsTheWeatherIn/RxAlamofire.swift
1
7193
import Foundation import Alamofire import RxSwift // MARK: Request - Common Response Handlers extension Request { /** Returns an `Observable` of NSData for the current request. - parameter cancelOnDispose: Indicates if the request has to be canceled when the observer is disposed, **default:** `false` - returns: An instance of `Observable<NSData>` */ func rx_response(cancelOnDispose: Bool = false) -> Observable<NSData> { return create { observer -> Disposable in self.response { request, response, data, error in if let e = error as NSError? { observer.onError(e) } else { if let d = data { if 200 ..< 300 ~= response?.statusCode ?? 0 { observer.onNext(d) observer.onCompleted() } else { observer.onError(NSError(domain: "Wrong status code, expected 200 - 206, got \(response?.statusCode ?? -1)", code: -1, userInfo: nil)) } } else { observer.onError(error ?? NSError(domain: "Empty data received", code: -1, userInfo: nil)) } } } return AnonymousDisposable { if cancelOnDispose { self.cancel() } } } } /** Returns an `Observable` of a String for the current request - parameter encoding: Type of the string encoding, **default:** `nil` - parameter cancelOnDispose: Indicates if the request has to be canceled when the observer is disposed, **default:** `false` - returns: An instance of `Observable<String>` */ func rx_responseString(encoding: NSStringEncoding? = nil, cancelOnDispose: Bool = false) -> Observable<String> { return create { observer -> Disposable in self.responseString(encoding: encoding) { responseData in let result = responseData.result let response = responseData.response switch result { case .Success(let s): if 200 ..< 300 ~= response?.statusCode ?? 0 { observer.onNext(s) observer.onCompleted() } else { observer.onError(NSError(domain: "Wrong status code, expected 200 - 206, got \(response?.statusCode ?? -1)", code: -1, userInfo: nil)) } case .Failure(let e): observer.onError(e) } } return AnonymousDisposable { if cancelOnDispose { self.cancel() } } } } /** Returns an `Observable` of a deserialized JSON for the current request. - parameter options: Reading options for JSON decoding process, **default:** `.AllowFragments` - parameter cancelOnDispose: Indicates if the request has to be canceled when the observer is disposed, **default:** `false` - returns: An instance of `Observable<AnyObject>` */ func rx_responseJSON(options: NSJSONReadingOptions = .AllowFragments, cancelOnDispose: Bool = false) -> Observable<AnyObject> { return create { observer in self.responseJSON(options: options) { responseData in let result = responseData.result let response = responseData.response switch result { case .Success(let d): if 200 ..< 300 ~= response?.statusCode ?? 0 { observer.onNext(d) observer.onCompleted() } else { observer.onError(NSError(domain: "Wrong status code, expected 200 - 206, got \(response?.statusCode ?? -1)", code: -1, userInfo: nil)) } case .Failure(let e): observer.onError(e) } } return AnonymousDisposable { if cancelOnDispose { self.cancel() } } } } /** Returns and `Observable` of a deserialized property list for the current request. - parameter options: Property list reading options, **default:** `NSPropertyListReadOptions()` - parameter cancelOnDispose: Indicates if the request has to be canceled when the observer is disposed, **default:** `false` - returns: An instance of `Observable<AnyData>` */ func rx_responsePropertyList(options: NSPropertyListReadOptions = NSPropertyListReadOptions(), cancelOnDispose: Bool = false) -> Observable<AnyObject> { return create { observer in self.responsePropertyList(options: options) { responseData in let result = responseData.result let response = responseData.response switch result { case .Success(let d): if 200 ..< 300 ~= response?.statusCode ?? 0 { observer.onNext(d) observer.onCompleted() } else { observer.onError(NSError(domain: "Wrong status code, expected 200 - 206, got \(response?.statusCode ?? -1)", code: -1, userInfo: nil)) } case .Failure(let e): observer.onError(e) } } return AnonymousDisposable { if cancelOnDispose { self.cancel() } } } } } // MARK: Request - Upload and download progress extension Request { /** Returns an `Observable` for the current progress status. Parameters on observed tuple: 1. bytes written 1. total bytes written 1. total bytes expected to write. - returns: An instance of `Observable<(Int64, Int64, Int64)>` */ func rx_progress() -> Observable<(Int64, Int64, Int64)> { return create { observer in self.progress() { bytesWritten, totalBytesWritten, totalBytesExpectedToWrite in observer.onNext((bytesWritten, totalBytesWritten, totalBytesExpectedToWrite)) } return AnonymousDisposable { } } } }
mit
7d2ed583da05a9b3407a7ad6d445ffd3
33.753623
156
0.48144
5.999166
false
false
false
false
zzyrd/ChicagoFoodInspection
ChicagoFoodApp/ChicagoFoodApp/FavoriteTableViewController.swift
1
3663
// // FavoriteTableViewController.swift // ChicagoFoodApp // // Created by zhang zhihao on 5/10/17. // Copyright © 2017 YUNFEI YANG. All rights reserved. // import UIKit class FavoriteTableViewController: UITableViewController { @IBOutlet var facilityTableView: UITableView! var facilities: [Facility] = [] var numOfFavorites = 0 override func viewDidLoad() { super.viewDidLoad() Model.sharedInstance.loadData() facilities = Model.sharedInstance.fetchFacilities() for facility in facilities { if facility.favorited == true{ numOfFavorites += 1 } } // print(numOfFavorites) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Table view data source override func numberOfSections(in tableView: UITableView) -> Int { // #warning Incomplete implementation, return the number of sections return 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // #warning Incomplete implementation, return the number of rows return numOfFavorites } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "favoritetablecell", for: indexPath) if let cell = cell as? FavoriteTableViewCell { cell.facilityName.text = facilities[indexPath.row].name ?? "" if(facilities[indexPath.row].risk == 1){ cell.facilityImage.image = UIImage.init(named: "risk1List") }else if(facilities[indexPath.row].risk == 2){ cell.facilityImage.image = UIImage.init(named: "risk2List") }else{ cell.facilityImage.image = UIImage.init(named: "risk3List") } } return cell } // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if let destination = segue.destination as? DetailsViewController, let row = facilityTableView.indexPathForSelectedRow?.row{ destination.facilityName = facilities[row].name ?? "" destination.facilityAddress = facilities[row].address ?? "" if let riskValue = facilities[row].risk { if riskValue == 1 { destination.facilityRisk = "Risk 1 (High)" } else if riskValue == 2 { destination.facilityRisk = "Risk 2 (Medium)" } else if riskValue == 3 { destination.facilityRisk = "Risk 3 (Low)" } else{ destination.facilityRisk = "Not applicable" } } if let inspections = facilities[row].inspectionArray{ for inspection in inspections{ if let violation = inspection.violation{ destination.facilityViolations.append(violation) } } } destination.latitude = facilities[row].latitude destination.longitude = facilities[row].longitude destination.favorites = facilities[row].favorited } } }
mit
984f6e3ac1ed4a74f053e82c430ffdf5
31.696429
109
0.578646
5.157746
false
false
false
false
Ricky-Choi/AppUIKit
AppUIKit/Navigation/AUINavigationController.swift
1
12357
// // AUINavigationController.swift // AppUIKit // // Created by ricky on 2016. 12. 5.. // Copyright © 2016년 appcid. All rights reserved. // import Cocoa @objc public protocol AUINavigationControllerDelegate: class { @objc optional func navigationController(_ navigationController: AUINavigationController, willShow viewController: AUIViewController, animated: Bool) @objc optional func navigationController(_ navigationController: AUINavigationController, didShow viewController: AUIViewController, animated: Bool) } open class AUINavigationController: AUIViewController { enum PushAnimation { case push case pop case viewControllerTransitionOptions(NSViewController.TransitionOptions) case none var isAnimated: Bool { switch self { case .none: return false default: return true } } } // Creating Navigation Controllers public init(rootViewController: AUIViewController) { _viewControllers = [rootViewController] super.init() } required public init?(coder: NSCoder) { _viewControllers = [AUIViewController]() super.init(coder: coder) } // Accessing Items on the Navigation Stack public var topViewController: AUIViewController? { return viewControllers.last } public var visibleViewController: AUIViewController? { return topViewController } fileprivate var _viewControllers: [AUIViewController] public var viewControllers: [AUIViewController] { get { return _viewControllers } set { setViewControllers(newValue, animated: false) } } public func setViewControllers(_ viewControllers: [AUIViewController], animated: Bool) { self._viewControllers = viewControllers if let currentViewController = visibleViewController { currentViewController.removeFromParent() currentViewController.view.removeFromSuperview() } if let lastViewController = viewControllers.last { setupInitialViewController(lastViewController) } } // Pushing and Popping Stack Items public func pushViewController(_ viewController: AUIViewController, animated: Bool) { guard let currentViewController = visibleViewController else { return } _viewControllers.append(viewController) navigationBar.pushItem(viewController.navigationItem, animated: animated) _navigate(fromViewController: currentViewController, toViewController: viewController, animation: animated ? .push : .none) } @discardableResult public func popViewController(animated: Bool) -> AUIViewController? { guard viewControllers.count > 1 else { return nil } let popedViewController = _viewControllers.removeLast() navigationBar.popItem(animated: animated) _navigate(fromViewController: popedViewController, toViewController: viewControllers.last!, animation: animated ? .pop : .none) return popedViewController } @discardableResult public func popToRootViewController(animated: Bool) -> [AUIViewController]? { guard viewControllers.count > 1 else { return nil } let rootViewController = viewControllers.first! let removeViewControllers = _viewControllers.dropFirst() navigationBar.setItems([rootViewController.navigationItem], animated: animated) _navigate(fromViewController: removeViewControllers.last!, toViewController: rootViewController, animation: animated ? .pop : .none) return Array(removeViewControllers) } @discardableResult public func popToViewController(_ viewController: AUIViewController, animated: Bool) -> [AUIViewController]? { guard viewControllers.count > 1 && viewControllers.last != viewController else { return nil } guard let targetIndex = viewControllers.firstIndex(of: viewController) else { return nil } if targetIndex == 0 { return popToRootViewController(animated: animated) } let removeViewControllers = viewControllers[targetIndex + 1..<viewControllers.count] let remainViewControllers = viewControllers[0...targetIndex] let remainNavigationItems = remainViewControllers.map { $0.navigationItem } navigationBar.setItems(remainNavigationItems, animated: animated) _navigate(fromViewController: removeViewControllers.last!, toViewController: remainViewControllers.last!, animation: animated ? .pop : .none) return Array(removeViewControllers) } // Configuring Navigation Bars public var navigationBar: AUINavigationBar { get { if _navigationBar == nil { _navigationBar = AUINavigationBar() _navigationBar?.delegate = self } return _navigationBar! } set { _navigationBar = newValue _navigationBar?.delegate = self } } public func setNavigationBarHidden(_ hidden: Bool, animated: Bool) { } private var _navigationBarHeight: CGFloat = 44 private var _titleBarHeight: CGFloat = 24 private var _navigationAreaHeight: CGFloat { return _navigationBarHeight + _titleBarHeight } // Configuring Custom Toolbars public var toolbar: AUIToolbar { get { if _toolbar == nil { _toolbar = AUIToolbar() } return _toolbar! } set { _toolbar = newValue } } public func setToolbarHidden(_ hidden: Bool, animated: Bool) { } public var isToolbarHidden: Bool = true public var toolbarHeight: CGFloat = 44 // Hiding the Navigation Bar public var hidesBarsOnTap: Bool = false public var hidesBarsOnSwipe: Bool = false public var hidesBarsWhenVerticallyCompact: Bool = false public var hidesBarsWhenKeyboardAppears: Bool = false public var isNavigationBarHidden: Bool = false // Accessing the Delegate weak open var delegate: AUINavigationControllerDelegate? // View LifeCycle open override func loadView() { view = AUIView() view.addSubview(_contentContainerView) _contentContainerView.fillToSuperview() view.addSubview(_navigationBarContainerView) _navigationBarContainerView.fillXToSuperview() _navigationBarContainerView.topAnchor.constraint(equalTo: view.topAnchor).isActive = true _navigationBarContainerView.fixHeight(_navigationAreaHeight) _navigationBarContainerView.addSubview(navigationBar); navigationBar.fillToSuperview() navigationBar.barHeight = _navigationBarHeight if let viewController = topViewController { setupInitialViewController(viewController) } } open override func becomeFirstResponder() -> Bool { return view.window?.makeFirstResponder(topViewController) ?? true } private var _title: String? open override var title: String? { get { if _title != nil { return _title } return visibleViewController?.title } set { _title = newValue } } // fileprivate implementation fileprivate var _navigationBar: AUINavigationBar? fileprivate var _toolbar: AUIToolbar? fileprivate var _contentContainerView = NSView() fileprivate var _navigationBarContainerView = NSView() fileprivate var _toolbarContainerView = NSView() fileprivate var _constraintForLastViewController: MarginConstraints? } extension AUINavigationController { fileprivate func setupInitialViewController(_ viewController: AUIViewController) { navigationBar.setItems([viewController.navigationItem], animated: false) addChild(viewController) _contentContainerView.addSubview(viewController.view) _constraintForLastViewController = viewController.view.fillToSuperview() } fileprivate func _navigate(fromViewController: AUIViewController, toViewController: AUIViewController, animation: PushAnimation) { delegate?.navigationController?(self, willShow: toViewController, animated: animation.isAnimated) addChild(toViewController) switch animation { case .push: let viewWidth = view.bounds.size.width _contentContainerView.addSubview(toViewController.view) let newConstraintX = toViewController.view.fillToSuperview(ACDMargin(leading: viewWidth, top: 0, trailing: viewWidth, bottom: 0)) NSAnimationContext.runAnimationGroup({ (context) in _constraintForLastViewController?.leadingConstraint.animator().constant = -viewWidth / 3.0 _constraintForLastViewController?.trailingConstraint.animator().constant = -viewWidth / 3.0 newConstraintX.leadingConstraint.animator().constant = 0 newConstraintX.trailingConstraint.animator().constant = 0 }, completionHandler: { fromViewController.removeFromParent() fromViewController.view.removeFromSuperview() self._constraintForLastViewController = newConstraintX self.delegate?.navigationController?(self, didShow: toViewController, animated: animation.isAnimated) }) case .pop: let viewWidth = view.bounds.size.width _contentContainerView.addSubview(toViewController.view, positioned: .below, relativeTo: fromViewController.view) let newConstraintX = toViewController.view.fillToSuperview(ACDMargin(leading: -viewWidth / 3.0, top: 0, trailing: -viewWidth / 3.0, bottom: 0)) NSAnimationContext.runAnimationGroup({ (context) in _constraintForLastViewController?.leadingConstraint.animator().constant = viewWidth _constraintForLastViewController?.trailingConstraint.animator().constant = viewWidth newConstraintX.leadingConstraint.animator().constant = 0 newConstraintX.trailingConstraint.animator().constant = 0 }, completionHandler: { fromViewController.removeFromParent() fromViewController.view.removeFromSuperview() self._constraintForLastViewController = newConstraintX self.delegate?.navigationController?(self, didShow: toViewController, animated: animation.isAnimated) }) case .viewControllerTransitionOptions(let options): _contentContainerView.addSubview(toViewController.view) _constraintForLastViewController = toViewController.view.fillToSuperview() transition(from: fromViewController, to: toViewController, options: options, completionHandler: { fromViewController.removeFromParent() fromViewController.view.removeFromSuperview() self.delegate?.navigationController?(self, didShow: toViewController, animated: animation.isAnimated) }) case .none: _contentContainerView.addSubview(toViewController.view) _constraintForLastViewController = toViewController.view.fillToSuperview() fromViewController.removeFromParent() fromViewController.view.removeFromSuperview() delegate?.navigationController?(self, didShow: toViewController, animated: animation.isAnimated) } } } extension AUINavigationController: AUINavigationBarDelegate { func navigationBarInvokeBackButton(_ navigationBar: AUINavigationBar) { popViewController(animated: true) } }
mit
bfa5a72c4aeb0d0615ea44a96922df80
37.247678
155
0.653311
6.173913
false
false
false
false
micazeve/MAGearRefreshControl
Classes/MASingleGearView.swift
1
7165
// // MASingleGearView.swift // MAGearRefreshControl-Demo // // Created by Michaël Azevedo on 20/02/2017. // Copyright © 2017 micazeve. All rights reserved. // import UIKit //MARK: - MASingleGearView Class /// This class is used to draw a gear in a UIView. public class MASingleGearView : UIView { //MARK: Instance properties /// Gear linked to this view. internal var gear:MAGear! /// Color of the gear. public var gearColor = UIColor.black /// Phase of the gear. Varies between 0 and 1. /// A phase of 0 represents a gear with the rightmost tooth fully horizontal, while a phase of 0.5 represents a gear with a hole in the rightmost point. /// A phase of 1 thus is graphically equivalent to a phase of 0 public var phase:Double = 0 /// Enum representing the style of the Gear public enum MAGearStyle: UInt8 { case Normal // Default style, full gear case WithBranchs // With `nbBranches` inside the gear } /// Style of the gear let style:MAGearStyle /// Number of branches inside the gear. /// Ignored if style == .Normal. /// Default value is 5. let nbBranches:UInt //MARK: Init methods /// Custom init method /// /// - parameter gear: Gear linked to this view /// - parameter gearColor: Color of the gear /// - parameter style: Style of the gear /// - parameter nbBranches: Number of branches if the gear style is 'WithBranches' public init(gear:MAGear, gearColor:UIColor, style:MAGearStyle = .Normal, nbBranches:UInt = 5) { var width = Int(gear.outsideDiameter + 1) if width%2 == 1 { width += 1 } self.style = style self.gearColor = gearColor self.nbBranches = nbBranches self.gear = gear super.init(frame: CGRect(x: 0, y: 0, width: CGFloat(width), height: CGFloat(width))) self.backgroundColor = UIColor.clear } /// Required initializer required public init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } //MARK: Drawing methods /// Override of drawing method override public func draw(_ rect: CGRect) { _ = CGColorSpaceCreateDeviceRGB() let currentContext = UIGraphicsGetCurrentContext() currentContext?.clear(rect) let pitchRadius = gear.pitchDiameter/2 let outsideRadius = gear.outsideDiameter/2 let insideRadius = gear.insideDiameter/2 currentContext?.saveGState() currentContext?.translateBy(x: rect.width/2, y: rect.height/2) currentContext?.addEllipse(in: CGRect(x: -insideRadius/3, y: -insideRadius/3, width: insideRadius*2/3, height: insideRadius*2/3)); currentContext?.addEllipse(in: CGRect(x: -insideRadius, y: -insideRadius, width: insideRadius*2, height: insideRadius*2)); if style == .WithBranchs { let rayon1 = insideRadius*5/10 let rayon2 = insideRadius*8/10 let angleBig = Double(360/nbBranches) * Double.pi / 180 let angleSmall = Double(min(10, 360/nbBranches/6)) * Double.pi / 180 let originX = rayon1 * CGFloat(cos(angleSmall)) let originY = -rayon1 * CGFloat(sin(angleSmall)) let finX = sqrt(rayon2*rayon2 - originY*originY) let angle2 = Double(acos(finX/rayon2)) let originX2 = rayon1 * CGFloat(cos(angleBig - angleSmall)) let originY2 = -rayon1 * CGFloat(sin(angleBig - angleSmall)) for i in 0..<nbBranches { // Saving the context before rotating it currentContext?.saveGState() let gearOriginAngle = CGFloat((Double(i)) * Double.pi * 2 / Double(nbBranches)) currentContext?.rotate(by: gearOriginAngle) currentContext?.move(to: CGPoint(x: originX, y: originY)) currentContext?.addLine(to: CGPoint(x: finX, y: originY)) currentContext?.addArc(center: CGPoint.zero, radius: rayon2, startAngle: -CGFloat(angle2), endAngle: -CGFloat(angleBig - angle2), clockwise: true) currentContext?.addLine(to: CGPoint(x: originX2, y: originY2)) currentContext?.addArc(center: CGPoint.zero, radius: rayon1, startAngle: -CGFloat(angleBig - angleSmall), endAngle: -CGFloat(angleSmall), clockwise: false) currentContext?.closePath() currentContext?.restoreGState() } } currentContext?.setFillColor(self.gearColor.cgColor) currentContext?.fillPath(using: .evenOdd) let angleUtile = CGFloat(Double.pi / (2 * Double(gear.nbTeeth))) let angleUtileDemi = angleUtile/2 // In order to draw the teeth quite easily, instead of having complexs calculations, // we calcule the needed point for drawing the rightmost horizontal tooth and will rotate the context // in order to use the same points let pointPitchHaut = CGPoint(x: cos(angleUtile) * pitchRadius, y: sin(angleUtile) * pitchRadius) let pointPitchBas = CGPoint(x: cos(angleUtile) * pitchRadius, y: -sin(angleUtile) * pitchRadius) let pointInsideHaut = CGPoint(x: cos(angleUtile) * insideRadius, y: sin(angleUtile) * insideRadius) let pointInsideBas = CGPoint(x: cos(angleUtile) * insideRadius, y: -sin(angleUtile) * insideRadius) let pointOutsideHaut = CGPoint(x: cos(angleUtileDemi) * outsideRadius, y: sin(angleUtileDemi) * outsideRadius) let pointOutsideBas = CGPoint(x: cos(angleUtileDemi) * outsideRadius, y: -sin(angleUtileDemi) * outsideRadius) for i in 0..<gear.nbTeeth { // Saving the context before rotating it currentContext?.saveGState() let gearOriginAngle = CGFloat((Double(i)) * Double.pi * 2 / Double(gear.nbTeeth)) currentContext?.rotate(by: gearOriginAngle) // Drawing the tooth currentContext?.move(to: CGPoint(x: pointInsideHaut.x, y: pointInsideHaut.y)) currentContext?.addLine(to: CGPoint(x: pointPitchHaut.x, y: pointPitchHaut.y)) currentContext?.addLine(to: CGPoint(x: pointOutsideHaut.x, y: pointOutsideHaut.y)) currentContext?.addLine(to: CGPoint(x: pointOutsideBas.x, y: pointOutsideBas.y)) currentContext?.addLine(to: CGPoint(x: pointPitchBas.x, y: pointPitchBas.y)) currentContext?.addLine(to: CGPoint(x: pointInsideBas.x, y: pointInsideBas.y)) currentContext?.fillPath() // Restoring the context currentContext?.restoreGState() } currentContext?.restoreGState() } }
mit
44918356eff676ac529fe42014c84091
39.241573
172
0.603099
4.383721
false
false
false
false
theappbusiness/TABResourceLoader
Example/Models/Failure model example/RegistrationResource.swift
1
1524
// // RegistrationResource.swift // TABResourceLoader // // Created by Dean Brindley on 24/02/2017. // Copyright © 2017 Kin + Carta. All rights reserved. // import Foundation import TABResourceLoader private let baseURL = URL(string: "http://localhost:8000/")! struct RegistrationParsingError: Error { } enum RegistrationErrorType { case invalidEmailFormat case invalidPasswordFormat init(error: String) throws { switch error { case "RegisterUserErrorCodes.InvalidPasswordFormat": self = .invalidPasswordFormat case "RegisterUserErrorCodes.InvalidEmailFormat": self = .invalidEmailFormat default: throw RegistrationParsingError() } } var description: String { switch self { case .invalidEmailFormat: return "Please enter a valid email address" case .invalidPasswordFormat: return "Please enter a secure password" } } } enum RegistrationResult { case success(id: Int) case failure(type: RegistrationErrorType) } struct RegistrationResource: NetworkJSONDictionaryResourceType { typealias Model = RegistrationResult let url: URL init(emailAddress: String) { url = baseURL.appendingPathComponent("registration.json") } // MARK: JSONDictionaryResourceType func model(from jsonDictionary: [String: Any]) throws -> Model { if let error = jsonDictionary["errorCode"] as? String { let error = try RegistrationErrorType(error: error) return .failure(type: error) } return .success(id: 123) } }
mit
d5823fdb402e640dcad55eaae5f9d3fc
22.796875
66
0.718319
4.414493
false
false
false
false
emilstahl/swift
validation-test/compiler_crashers_fixed/0193-swift-typebase-gettypevariables.swift
12
790
// RUN: not %target-swift-frontend %s -parse // Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing [] } protocol p { } protocol g : p { } n j } } protocol k { class func q() } class n: k{ class func q {} func r<e: t, s where j<s> == e.m { func g k q<n : t> { q g: n } func p<n>() ->(b: T) { } f(true as BooleanType) f> { c(d ()) } func b(e)-> <d>(() -> d) d "" e} class d { func b((Any, d)typealias b = b d> Bool { e !(f) [] } f m) return "" } } class C: B, A { over } } func e<T where T: A, T: B>(t: T) { t.c() } func a<T>() -> (T -> T) -> T { T, T -> T) ->)func typealias F = Int func g<T where T.E == F>(f: B<T>) { } }
apache-2.0
b6ce74162f01946fd6dd0e207448b8a5
13.90566
87
0.512658
2.461059
false
false
false
false
blstream/mEatUp
mEatUp/mEatUp/RoomListDataLoader.swift
1
10577
// // RoomDataLoader.swift // mEatUp // // Created by Paweł Knuth on 18.04.2016. // Copyright © 2016 BLStream. All rights reserved. // import UIKit import CloudKit class RoomListDataLoader { var cloudKitHelper: CloudKitHelper? let userSettings = UserSettings() var myRoom: [Room] = [] var joinedRooms: [Room] = [] var invitedRooms: [Room] = [] var publicRooms: [Room] = [] var currentRoomList: [Room] { get { return loadCurrentRoomList(dataScope, filter: filter) } } var dataScope: RoomDataScopes = .Public var filter: ((Room) -> Bool)? = nil var completionHandler: (() -> Void)? var errorHandler: (() -> Void)? var userRecordID: CKRecordID? init() { cloudKitHelper = CloudKitHelper() } func addNotifications() { NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(roomAddedNotification), name: "roomAdded", object: nil) NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(roomDeletedNotification), name: "roomDeleted", object: nil) NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(roomUpdatedNotification), name: "roomUpdated", object: nil) NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(userInRoomAddedNotification), name: "userInRoomAdded", object: nil) NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(userInRoomRemovedNotification), name: "userInRoomRemoved", object: nil) } func removeNotifications() { NSNotificationCenter.defaultCenter().removeObserver(self) } @objc func userInRoomRemovedNotification(aNotification: NSNotification) { if let queryNotification = aNotification.object as? CKQueryNotification { if let userRecordName = queryNotification.recordFields?["userRecordID"] as? String, roomRecordName = queryNotification.recordFields?["roomRecordID"] as? String { if userRecordName == userRecordID?.recordName { cloudKitHelper?.loadRoomRecord(CKRecordID(recordName: roomRecordName), completionHandler: { room in guard let owner = room.owner?.recordID else { return } if owner != userRecordName { let message = "You have been kicked out of a room" AlertCreator.singleActionAlert("Info", message: message, actionTitle: "OK", actionHandler: nil) } }, errorHandler: nil) } } } } @objc func userInRoomAddedNotification(aNotification: NSNotification) { if let userInRoomRecordID = aNotification.object as? CKRecordID { cloudKitHelper?.loadUsersInRoomRecord(userInRoomRecordID, completionHandler: { userInRoom in if self.userRecordID == userInRoom.user?.recordID { guard let userRecordID = self.userRecordID else { return } let message = "You have been invited to a room. Check the 'Invited' section." self.invitedRooms.removeAll() self.loadInvitedRoomRecords(userRecordID) AlertCreator.singleActionAlert("Info", message: message, actionTitle: "OK", actionHandler: nil) } }, errorHandler: nil) } } @objc func roomUpdatedNotification(aNotification: NSNotification) { if let roomRecordID = aNotification.object as? CKRecordID { cloudKitHelper?.loadRoomRecord(roomRecordID, completionHandler: { room in self.replaceRoomInArray(&self.publicRooms, room: room) self.replaceRoomInArray(&self.joinedRooms, room: room) self.replaceRoomInArray(&self.invitedRooms, room: room) self.completionHandler?() }, errorHandler: nil) if let userRecordID = userRecordID { cloudKitHelper?.checkIfUserInRoom(roomRecordID, userRecordID: userRecordID, completionHandler: { inRoom in if inRoom != nil { self.cloudKitHelper?.loadRoomRecord(roomRecordID, completionHandler: { room in guard let didEnd = room.didEnd else { return } if didEnd { self.removeRoomFromArrays(roomRecordID) } let message = (didEnd ? "A room that you have joined has ended. Please check settlements tab and enter balance." : "A room that you have joined has been modified.") AlertCreator.singleActionAlert("Info", message: message, actionTitle: "OK", actionHandler: nil) }, errorHandler: nil) } }, errorHandler: nil) } } } func replaceRoomInArray(inout array: [Room], room: Room) { if let index = array.findIndex(room) { array.removeAtIndex(index) array.append(room) } } @objc func roomAddedNotification(aNotification: NSNotification) { if let roomRecordID = aNotification.object as? CKRecordID { cloudKitHelper?.loadRoomRecord(roomRecordID, completionHandler: { room in self.publicRooms.append(room) self.completionHandler?() }, errorHandler: nil) } } @objc func roomDeletedNotification(aNotification: NSNotification) { if let roomRecordID = aNotification.object as? CKRecordID, userRecordID = userRecordID { removeRoomFromArrays(roomRecordID) cloudKitHelper?.checkIfUserInRoom(roomRecordID, userRecordID: userRecordID, completionHandler: { inRoom in if inRoom != nil { AlertCreator.singleActionAlert("Info", message: "Room you were in has been deleted", actionTitle: "OK", actionHandler: nil) } }, errorHandler: nil) self.completionHandler?() } } func removeRoomFromArrays(roomRecordID: CKRecordID) { self.publicRooms = self.publicRooms.filter({return filterRemovedRoom($0, roomRecordID: roomRecordID)}) self.joinedRooms = self.joinedRooms.filter({return filterRemovedRoom($0, roomRecordID: roomRecordID)}) self.invitedRooms = self.invitedRooms.filter({return filterRemovedRoom($0, roomRecordID: roomRecordID)}) } func loadUserRecordFromCloudKit() { if let fbID = userSettings.facebookID() { cloudKitHelper?.loadUserRecordWithFbId(fbID, completionHandler: { userRecord in if let userRecordID = userRecord.recordID { self.userRecordID = userRecordID self.loadRoomsForRoomList(userRecordID) } }, errorHandler: { error in self.loadUserRecordFromCloudKit() }) } } func filterRemovedRoom(room: Room, roomRecordID: CKRecordID) -> Bool { if let recordID = room.recordID { return !(recordID == roomRecordID) } return false } func clearRooms() { myRoom.removeAll() joinedRooms.removeAll() invitedRooms.removeAll() publicRooms.removeAll() } func loadRoomsForRoomList(userRecordID: CKRecordID) { clearRooms() loadPublicRoomRecords() loadInvitedRoomRecords(userRecordID) loadUsersInRoomRecordsWithUserId(userRecordID) loadUserRoomRecord(userRecordID) } func loadPublicRoomRecords() { cloudKitHelper?.loadPublicRoomRecords({ room in if !room.eventOccured { self.publicRooms.append(room) self.completionHandler?() } }, errorHandler: {error in self.errorHandler?() }) } func loadInvitedRoomRecords(userRecordID: CKRecordID) { cloudKitHelper?.loadInvitedRoomRecords(userRecordID, completionHandler: { room in if let room = room where !room.eventOccured { self.invitedRooms.append(room) self.completionHandler?() } }, errorHandler: {error in self.errorHandler?() }) } func loadUsersInRoomRecordsWithUserId(userRecordID: CKRecordID) { cloudKitHelper?.loadUsersInRoomRecordWithUserId(userRecordID, completionHandler: { userRoom in if let userRoom = userRoom { self.joinedRooms.append(userRoom) self.completionHandler?() } }, errorHandler: {error in self.errorHandler?() }) } func loadUserRoomRecord(userRecordID: CKRecordID) { cloudKitHelper?.loadUserRoomRecord(userRecordID, completionHandler: { room in if let room = room { self.myRoom.append(room) self.completionHandler?() } }, errorHandler: {error in self.errorHandler?() }) } func loadCurrentRoomList(dataScope: RoomDataScopes, filter: ((Room) -> Bool)?) -> [Room] { switch dataScope { case .Joined: if let filter = filter { return joinedRooms.filter({filter($0)}) } else { return joinedRooms } case .Invited: if let filter = filter { return invitedRooms.filter({filter($0)}) } else { return invitedRooms } case .MyRoom: if let filter = filter { return myRoom.filter({filter($0)}) } else { return myRoom } case .Public: if let filter = filter { return publicRooms.filter({filter($0)}) } else { return publicRooms } } } }
apache-2.0
f75e72cd571447aa28bb913cc10c7ec9
38.312268
192
0.567565
5.467942
false
false
false
false
carlo-/ipolito
iPoliTO2/DownloadsViewController.swift
1
14710
// // DownloadsViewController.swift // iPoliTO2 // // Created by Carlo Rapisarda on 04/08/2016. // Copyright © 2016 crapisarda. All rights reserved. // import UIKit class DownloadsViewController: UITableViewController, PTDownloadManagerDelegate { @IBOutlet var clearAllButton: UIBarButtonItem! class var hasContentToShow: Bool { let manager = PTDownloadManager.shared return manager.queue.isEmpty && manager.downloadedFiles.isEmpty } var downloadManager: PTDownloadManager { return PTDownloadManager.shared } var transfersQueue: [PTFileTransfer] { return downloadManager.queue } var downloadedFiles: [PTDownloadedFile] { return downloadManager.downloadedFiles } var documentInteractionController: UIDocumentInteractionController? var highlightedDownloadedFile: PTDownloadedFile? override func viewDidLoad() { super.viewDidLoad() if #available(iOS 11.0, *) { // Disable use of 'large title' display mode navigationItem.largeTitleDisplayMode = .never } downloadManager.delegate = self // Removes annoying row separators after the last cell tableView.tableFooterView = UIView() } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) if highlightedDownloadedFile != nil, let indexPath = indexPath(forDownloadedFile: highlightedDownloadedFile!) { highlightRow(atIndexPath: indexPath) } highlightedDownloadedFile = nil } override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) { super.viewWillTransition(to: size, with: coordinator) coordinator.animate(alongsideTransition: { _ in self.tableView.backgroundView?.setNeedsDisplay() }, completion: nil) } func highlightRow(atIndexPath indexPath: IndexPath) { tableView.selectRow(at: indexPath, animated: true, scrollPosition: .top) unowned let unownedSelf = self delay(1) { unownedSelf.tableView.deselectRow(at: indexPath, animated: true) } } func indexPath(forDownloadedFile downloadedFile: PTDownloadedFile) -> IndexPath? { guard let row = downloadedFiles.index(of: downloadedFile) else { return nil; } return IndexPath(row: row, section: 1) } func presentPDFViewer(title: String, path: String) { let id = PDFViewerController.parentIdentifier guard let viewerNavController = storyboard?.instantiateViewController(withIdentifier: id) as? UINavigationController, let viewer = viewerNavController.topViewController as? PDFViewerController else { return } viewer.configure(title: title, filePath: path, canShare: true) present(viewerNavController, animated: true, completion: nil) } func presentOpenIn(path: String) { documentInteractionController = UIDocumentInteractionController() documentInteractionController?.url = URL(fileURLWithPath: path) documentInteractionController?.uti = "public.filename-extension" documentInteractionController?.presentOpenInMenu(from: view.bounds, in: view, animated: true) } func fileTransferDidChangeStatus(_ transfer: PTFileTransfer) { if transfer.status == .completed { tableView.reloadData() return } if let index = transfersQueue.index(of: transfer) { let indexPath = IndexPath(row: index, section: 0) if let visibleIndexPaths = tableView.indexPathsForVisibleRows { if visibleIndexPaths.contains(indexPath) { let cell = tableView.cellForRow(at: indexPath) as? PTFileTransferCell cell?.setFileTransfer(transfer, animated: true) } } } } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if transfersQueue.isEmpty && downloadedFiles.isEmpty { tableView.backgroundView = NoDownloadsBackgroundView(frame: tableView.bounds) clearAllButton.isEnabled = false } else { tableView.backgroundView = nil clearAllButton.isEnabled = true } switch section { case 0: return transfersQueue.count case 1: return downloadedFiles.count default: return 0 } } override func numberOfSections(in tableView: UITableView) -> Int { return 2 } override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { switch section { case 0: return (transfersQueue.isEmpty ? nil : ~"ls.downloadsVC.section.transfers") case 1: return (downloadedFiles.isEmpty ? nil : ~"ls.downloadsVC.section.completed") default: return nil } } override func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? { if indexPath.section == 0 { let transfer = transfersQueue[indexPath.row] let retryAction = UITableViewRowAction(style: .normal, title: ~"ls.downloadsVC.action.retry", handler: { (action, indexPath) in self.setEditing(false, animated: true) self.downloadManager.retry(fileTransfer: transfer) }) retryAction.backgroundColor = #colorLiteral(red: 0.4028071761, green: 0.7315050364, blue: 0.2071235478, alpha: 1) let resumeAction = UITableViewRowAction(style: .normal, title: ~"ls.downloadsVC.action.resume", handler: { (action, indexPath) in self.setEditing(false, animated: true) self.downloadManager.resume(fileTransfer: transfer) }) resumeAction.backgroundColor = #colorLiteral(red: 0.4028071761, green: 0.7315050364, blue: 0.2071235478, alpha: 1) let pauseAction = UITableViewRowAction(style: .normal, title: ~"ls.downloadsVC.action.pause", handler: { (action, indexPath) in self.setEditing(false, animated: true) self.downloadManager.pause(fileTransfer: transfer) }) let cancelAction = UITableViewRowAction(style: .destructive, title: ~"ls.downloadsVC.action.cancel", handler: { (action, indexPath) in tableView.beginUpdates() self.downloadManager.cancel(fileTransfer: transfer) tableView.deleteRows(at: [indexPath], with: .automatic) tableView.endUpdates() }) switch transfer.status { case .downloading, .ready, .waitingForURL: return [cancelAction, pauseAction] case .paused: return [cancelAction, resumeAction] case .failed: return [cancelAction, retryAction] default: return nil } } else { let file = downloadedFiles[indexPath.row] let deleteAction = UITableViewRowAction(style: .destructive, title: ~"ls.downloadsVC.action.delete", handler: { (action, indexPath) in tableView.beginUpdates() self.downloadManager.delete(downloadedFile: file) tableView.deleteRows(at: [indexPath], with: .automatic) tableView.endUpdates() }) return [deleteAction] } } override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { if indexPath.section == 0 { return PTFileTransferCell.height } else { return PTDownloadedFileCell.height } } override func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) { if let cell = cell as? PTFileTransferCell { let transfer = transfersQueue[indexPath.row] cell.setFileTransfer(transfer, animated: false) } else if let cell = cell as? PTDownloadedFileCell { let file = downloadedFiles[indexPath.row] cell.setDownloadedFile(file) } } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let identifier: String if indexPath.section == 0 { identifier = PTFileTransferCell.identifier } else { identifier = PTDownloadedFileCell.identifier } return tableView.dequeueReusableCell(withIdentifier: identifier, for: indexPath) } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: true) if indexPath.section == 0 { if let cell = tableView.cellForRow(at: indexPath) { cell.setEditing(true, animated: true) } } else { let downloadedFile = downloadedFiles[indexPath.row] let fileName = downloadedFile.fileName if let path = downloadManager.absolutePath(forDownloadedFileNamed: fileName, checkValidity: true) { if PDFViewerController.canOpenFile(atPath: path) { presentPDFViewer(title: fileName, path: path) } else { presentOpenIn(path: path) } } else { // File does not exist! let alert = UIAlertController(title: ~"ls.generic.alert.error.title", message: ~"ls.downloadsVC.fileDoesntExistAlert.body", preferredStyle: .alert) alert.addAction(UIAlertAction(title: ~"ls.generic.alert.dismiss", style: .default, handler: { action in tableView.beginUpdates() self.downloadManager.delete(downloadedFileNamed: fileName) tableView.deleteRows(at: [indexPath], with: .automatic) tableView.endUpdates() })) present(alert, animated: true, completion: nil) } } } @IBAction func donePressed(_ sender: UIBarButtonItem) { self.dismiss(animated: true, completion: nil) } @IBAction func clearPressed(_ sender: UIBarButtonItem) { let title = ~"ls.downloadsVC.clearAllAlert.title" let message = ~"ls.downloadsVC.clearAllAlert.body" let alert = UIAlertController(title: title, message: message, preferredStyle: .alert) alert.addAction(UIAlertAction(title: ~"ls.generic.alert.confirm", style: .destructive, handler: { _ in PTDownloadManager.clearAll() self.tableView.reloadData() })) alert.addAction(UIAlertAction(title: ~"ls.generic.alert.cancel", style: .cancel, handler: nil)) present(alert, animated: true, completion: nil) } } class PTFileTransferCell: UITableViewCell { static let identifier = "PTFileTransferCell_id" static let height = 113 as CGFloat @IBOutlet var fileNameLabel: UILabel! @IBOutlet var subjectNameLabel: UILabel! @IBOutlet var progressLabel: UILabel! @IBOutlet var statusLabel: UILabel! @IBOutlet var progressBar: UIProgressView! func setFileTransfer(_ transfer: PTFileTransfer, animated: Bool) { fileNameLabel.text = transfer.file.description subjectNameLabel.text = transfer.subject.name setProgress(transfer.progress, animated: animated, finalSizeKB: transfer.file.size) statusLabel.text = transfer.status.localizedDescription() } private func setProgress(_ progress: Float, animated: Bool, finalSizeKB: Int?) { if let size = finalSizeKB { let downloadedKB = progress*Float(size) progressLabel.text = "\(downloadedKB) "+(~"ls.downloadsVC.progressPreposition")+" \(size) KB (\(progress*100.0)%)" } progressBar.setProgress(progress, animated: animated) } } class PTDownloadedFileCell: UITableViewCell { static let identifier = "PTDownloadedFileCell_id" static let height = 90 as CGFloat @IBOutlet var fileNameLabel: UILabel! @IBOutlet var subjectNameLabel: UILabel! @IBOutlet var detailsLabel: UILabel! func setDownloadedFile(_ file: PTDownloadedFile) { fileNameLabel.text = file.fileDescription subjectNameLabel.text = file.subjectName let formatter = DateFormatter() formatter.timeZone = TimeZone.Turin formatter.dateStyle = .medium detailsLabel.text = ~"ls.downloadsVC.downloadedOn"+" "+formatter.string(from: file.downloadDate) } } fileprivate class NoDownloadsBackgroundView: UIView { private let label: UILabel override init(frame: CGRect) { label = UILabel() super.init(frame: frame) backgroundColor = UIColor.clear label.font = UIFont.systemFont(ofSize: 15.0) label.textColor = UIColor.lightGray label.text = ~"ls.downloadsVC.noDownloads" label.sizeToFit() addSubview(label) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func draw(_ rect: CGRect) { super.draw(rect) label.center = CGPoint(x: frame.width/2.0, y: frame.height/2.0) } }
gpl-3.0
50e596d60197d34abfe96e1685e03367
33.609412
163
0.588143
5.508989
false
false
false
false
thatseeyou/iOSSDKExamples
Pages/CIQRCodeGenerator.xcplaygroundpage/Contents.swift
1
2901
/*: ### CIFilter를 이용한 QR 코드 생성 - 작은 이미지를 확대할 경우에 anti-aliasing이 되지 않도록 하는 과정도 필요 - maginificationFilter를 FilterNearest로 사용하는 경우에 CIImage로 부터 UIImage를 만든 경우에는 효과가 없다. - Graphics Context에 InterpolationQuality를 조정해서 다시 그리는 방법도 가능 */ import Foundation import UIKit class ViewController : UIViewController { override func viewDidLoad() { super.viewDidLoad() } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) makeQRCode() } func makeQRCode() { let qrFilter = CIFilter(name:"CIQRCodeGenerator") qrFilter?.setValue("H", forKey: "inputCorrectionLevel") let stringData = "https://github.com/thatseeyou".dataUsingEncoding(NSUTF8StringEncoding) qrFilter?.setValue(stringData, forKey: "inputMessage") let result = qrFilter?.valueForKey("outputImage") as? CIImage let smallImage = UIImage(CIImage: result!) let image = resizeImageWithoutInterpolation(smallImage, size: CGSizeMake(140, 140)) // 1. InterpolationQuality showImage(image, center: CGPointMake(self.view.bounds.midX, 70)) // 2. magnificationFilter : CGImage backed UIImage showScaledImage(UIImage(CGImage:CGImageFromCIImage(result!)), center: CGPointMake(self.view.bounds.midX, 220)) // 3. magnificationFilter : CIImage backed UIImage (No effective) showScaledImage(smallImage, center: CGPointMake(self.view.bounds.midX, 370)) } func showImage(image:UIImage, center:CGPoint) { let imageView = UIImageView(image: image) imageView.center = center imageView.contentMode = .Center self.view.addSubview(imageView) } func showScaledImage(image:UIImage, center:CGPoint) { let imageView = UIImageView(image: image) imageView.bounds = CGRectMake(0,0,140,140) imageView.center = center imageView.contentMode = .ScaleAspectFit imageView.layer.magnificationFilter = kCAFilterNearest self.view.addSubview(imageView) } func CGImageFromCIImage(image: CIImage) -> CGImage { let context = CIContext(options: nil) return context.createCGImage(image, fromRect:image.extent) } func resizeImageWithoutInterpolation(sourceImage:UIImage, size:CGSize) -> UIImage { UIGraphicsBeginImageContextWithOptions(size, false, 0) do { CGContextSetInterpolationQuality(UIGraphicsGetCurrentContext(), .None) sourceImage.drawInRect(CGRectMake(0, 0, size.width, size.height)) } let result = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return result } } PlaygroundHelper.showViewController(ViewController())
mit
43026345d198e47bc56ca4c88c0a5465
33.873418
118
0.692922
4.479675
false
false
false
false
twocentstudios/todostream
todostream/TodoViewModel.swift
1
842
// // Created by Christopher Trott on 12/9/15. // Copyright © 2015 twocentstudios. All rights reserved. // import Foundation struct TodoViewModel { let todo: Todo let title: String let subtitle: String let complete: Bool let deleted: Bool var completeActionTitle: String { return complete ? "Uncomplete" : "Complete" } init(todo: Todo) { self.todo = todo let priority = todo.priority.rawValue.uppercaseString self.title = todo.title self.subtitle = "Priority: \(priority)" self.complete = todo.complete self.deleted = todo.deleted } } // TODO: change this to isEqualIdentity extension TodoViewModel: Equatable {} func ==(lhs: TodoViewModel, rhs: TodoViewModel) -> Bool { return lhs.todo.id == rhs.todo.id }
mit
e3a523aae56ece4b61f8403b7a480605
22.361111
61
0.630202
4.163366
false
false
false
false
coderZsq/coderZsq.target.swift
StudyNotes/iOS Collection/Business/Business/Video/VideoViewController.swift
1
2377
// // VideoViewController.swift // Business // // Created by 朱双泉 on 2018/11/20. // Copyright © 2018 Castie!. All rights reserved. // import UIKit import AVFoundation import MediaPlayer import AVKit class VideoViewController: UIViewController { var layer: AVPlayerLayer? = { var layer: AVPlayerLayer? if let url = Bundle.main.url(forResource: "video.mov", withExtension: nil) { let playItem = AVPlayerItem(url: url) let player = AVPlayer(playerItem: playItem) // let player = AVPlayer(url: url) // player.play() layer = AVPlayerLayer(player: player) } return layer }() var moviePlayer: MPMoviePlayerController? = { var moviePlayer: MPMoviePlayerController? if let url = Bundle.main.url(forResource: "video.mov", withExtension: nil) { moviePlayer = MPMoviePlayerController(contentURL: url) moviePlayer?.prepareToPlay() } return moviePlayer }() override func viewDidLoad() { super.viewDidLoad() title = "Video" if let layer = layer { self.view.layer.addSublayer(layer) } // if let movieView = moviePlayer?.view { // self.view.addSubview(movieView) // } } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() layer?.frame = view.bounds moviePlayer?.view.frame = view.bounds } @IBAction func avPlayer(_ sender: Any) { if let url = Bundle.main.url(forResource: "video.mov", withExtension: nil) { let vc = AVPlayerViewController() let player = AVPlayer(url: url) vc.player = player vc.allowsPictureInPicturePlayback = true present(vc, animated: true) { vc.player?.play() } } } @IBAction func moviePlayer(_ sender: UIButton) { // moviePlayer?.play() if let url = Bundle.main.url(forResource: "video.mov", withExtension: nil), let vc = MPMoviePlayerViewController(contentURL: url) { present(vc, animated: true) { vc.moviePlayer.play() } } } @IBAction func remotePlay(_ sender: UIButton) { layer?.player?.play() } }
mit
89b10f4e7a7c6979ec17b76ae0f3db88
29
84
0.573418
4.797571
false
false
false
false
jonasman/JNSocialDownload
JNSocialDownload-Swift/JNSocialDownload.swift
1
14866
// // JNSocialDownload.swift // JNSocialDownloadDemo // // Created by Joao Nunes on 04/02/15. // Copyright (c) 2015 joao. All rights reserved. // import UIKit import Accounts import Social import Foundation private enum SocialDownloadType { case Avatar case Cover case Information } enum JNSocialDownloadNetwork { case Facebook case Twitter } let JNSocialDownloadNoAPPID = 1 let JNSocialDownloadNoPermissions = 2 let JNSocialDownloadNoAccount = 3 typealias SocialDownloadImageClosure = (image : UIImage?, error: NSError?) -> () typealias SocialDownloadInformationClosure = (userInfo : NSDictionary?, error: NSError?) -> () private class RequestConfiguration { let network:JNSocialDownloadNetwork let imageClosure:SocialDownloadImageClosure? let infoClosure:SocialDownloadInformationClosure? init(infoClosure:SocialDownloadInformationClosure, network:JNSocialDownloadNetwork) { self.network = network self.infoClosure = infoClosure } init(imageClosure:SocialDownloadImageClosure, network:JNSocialDownloadNetwork) { self.network = network self.imageClosure = imageClosure } } public class JNSocialDownload: NSObject { var appID:NSString? lazy var accountStore: ACAccountStore = { var tempAccountStore: ACAccountStore = ACAccountStore() return tempAccountStore }() convenience init(appID:NSString) { self.init() self.appID = appID } func downloadInformation(ForNetwork network:JNSocialDownloadNetwork, completionHandler: SocialDownloadInformationClosure) -> Void { let request = RequestConfiguration(infoClosure: completionHandler,network: network) self.selectSocialIOS(.Information, request: request) } func downloadAvatar(ForNetwork network:JNSocialDownloadNetwork, completionHandler: SocialDownloadImageClosure) -> Void { let request = RequestConfiguration(imageClosure: completionHandler,network: network) self.selectSocialIOS(.Avatar, request: request) } func downloadCover(ForNetwork network:JNSocialDownloadNetwork, completionHandler: SocialDownloadImageClosure) -> Void { let request = RequestConfiguration(imageClosure: completionHandler,network: network) self.selectSocialIOS(.Cover, request: request) } } // MARK: Logic extension JNSocialDownload { private func selectSocialIOS(downloadType: SocialDownloadType, request:RequestConfiguration) { var socialAPPID :NSString? if let appID = self.appID { socialAPPID = appID } else { socialAPPID = NSBundle.mainBundle().objectForInfoDictionaryKey("SocialAppID") as NSString? } if (socialAPPID == nil) { if (downloadType == .Avatar || downloadType == .Cover) { if let closure = request.imageClosure { closure(image: nil, error: NSError( domain: "JNSocialDownload", code: JNSocialDownloadNoAPPID, userInfo: [NSLocalizedDescriptionKey:"No app ID configured"])) } } else if (downloadType == .Information) { if let closure = request.infoClosure { closure(userInfo: nil, error: NSError( domain: "JNSocialDownload", code: JNSocialDownloadNoAPPID, userInfo: [NSLocalizedDescriptionKey:"No app ID configured"])) } } return } var accountType :ACAccountType! var socialOptions:Dictionary<String,AnyObject>? = nil if (request.network == .Facebook) { accountType = self.accountStore.accountTypeWithAccountTypeIdentifier(ACAccountTypeIdentifierFacebook) socialOptions = [ACFacebookAppIdKey:socialAPPID!, ACFacebookPermissionsKey:["user_birthday"]] } else if (request.network == .Twitter) { accountType = self.accountStore.accountTypeWithAccountTypeIdentifier(ACAccountTypeIdentifierTwitter) } self.accountStore.requestAccessToAccountsWithType(accountType, options: socialOptions, completion: { [weak self] (granted, error) -> Void in if (error != nil) { if (downloadType == .Avatar || downloadType == .Cover) { if let closure = request.imageClosure { closure(image: nil, error: NSError( domain: "JNSocialDownload", code: JNSocialDownloadNoAccount, userInfo: [NSLocalizedDescriptionKey:"No Social Account configured"])) } } else if (downloadType == .Information) { if let closure = request.infoClosure { closure(userInfo: nil, error: NSError( domain: "JNSocialDownload", code: JNSocialDownloadNoAccount, userInfo: [NSLocalizedDescriptionKey:"No Social Account configured"])) } } return } if (granted) { self?.requestMe(downloadType, request: request) } else { if (downloadType == .Avatar || downloadType == .Cover) { if let closure = request.imageClosure { closure(image: nil, error: NSError( domain: "JNSocialDownload", code: JNSocialDownloadNoPermissions, userInfo: [NSLocalizedDescriptionKey:"Social permission not granted"])) } } else if (downloadType == .Information) { if let closure = request.infoClosure { closure(userInfo: nil, error: NSError( domain: "JNSocialDownload", code: JNSocialDownloadNoPermissions, userInfo: [NSLocalizedDescriptionKey:"Social permission not granted"])) } } } }) } private func requestMe(downloadType: SocialDownloadType, request:RequestConfiguration) { let merequest = self.requestFor( request.network, dataType: .Information, userData: nil) merequest?.performRequestWithHandler( { [weak self] (responseData, urlResponse, error) -> Void in let userData = NSJSONSerialization.JSONObjectWithData(responseData!, options: NSJSONReadingOptions.allZeros, error: nil) as Dictionary<String,AnyObject> if (downloadType == .Avatar) { self?.requestAvatarFrom(userData, request: request) } else if (downloadType == .Cover) { self?.requestCoverFrom(userData, request: request) } else if (downloadType == .Information) { let closure = request.infoClosure! closure(userInfo: userData , error: nil) } }) } private func requestAvatarFrom(userData:Dictionary<String,AnyObject>, request:RequestConfiguration) { let avatarRequest = self.requestFor( request.network, dataType: .Avatar, userData: userData) // (NSData!, NSHTTPURLResponse!, NSError!) -> Void avatarRequest?.performRequestWithHandler( { [weak self] (responseData: NSData!, urlResponse:NSHTTPURLResponse!, error:NSError!) -> Void in if (self != nil){ self!.processImage(responseData, request: request) } }) } private func requestCoverFrom(userData:Dictionary<String,AnyObject>, request:RequestConfiguration) { let coverRequest = self.requestFor( request.network, dataType: .Cover, userData: userData) coverRequest?.performRequestWithHandler( { [weak self] (responseData, urlResponse, error) -> Void in if (request.network == .Facebook) { let response = NSJSONSerialization.JSONObjectWithData(responseData, options: NSJSONReadingOptions.allZeros, error: nil) as Dictionary<String,AnyObject>? let anyError = false if (response != nil) { let cover = response!["cover"] as Dictionary<String,AnyObject>? if (cover != nil) { let url = cover!["source"] as String let request3 = SLRequest(forServiceType: SLServiceTypeFacebook, requestMethod: .GET, URL: NSURL(string: url), parameters: nil) request3.performRequestWithHandler( { [weak self] (responseData, urlResponse, error) -> Void in if (self != nil){ self!.processImage(responseData, request: request) } }) } } } else if (request.network == .Twitter) { if (self != nil){ self!.processImage(responseData, request: request) } } }) } private func processImage(data:NSData, request:RequestConfiguration) { if (data.length > 100) { let image = UIImage(data: data) let closure = request.imageClosure! closure(image: image,error: nil) } } // MARK: Request preparation private func requestFor( network: JNSocialDownloadNetwork, dataType:SocialDownloadType, userData:Dictionary<String,AnyObject>?) -> SLRequest? { if (network == .Facebook) { var request:SLRequest? if (dataType == .Information) { let meurl = NSURL(string: "https://graph.facebook.com/me") request = SLRequest( forServiceType: SLServiceTypeFacebook, requestMethod: .GET, URL: meurl, parameters: nil) } else if (dataType == .Avatar) { let socialID = userData!["id"] as String let imageURL = "https://graph.facebook.com/v2.1/\(socialID)/picture" request = SLRequest( forServiceType: SLServiceTypeFacebook, requestMethod: .GET, URL: NSURL(string: imageURL), parameters: ["height":"512","width":"512"]) } else if (dataType == .Cover) { let socialID = userData!["id"] as String let coverURL = "https://graph.facebook.com/v2.1/\(socialID)" request = SLRequest( forServiceType: SLServiceTypeFacebook, requestMethod: .GET, URL: NSURL(string: coverURL), parameters: ["fields":"cover"]) } let accountType = self.accountStore.accountTypeWithAccountTypeIdentifier(ACAccountTypeIdentifierFacebook) let account = self.accountStore.accountsWithAccountType(accountType).last! as ACAccount if (request != nil){ request!.account = account } return request } else if (network == .Twitter) { var request:SLRequest? if (dataType == .Information) { let meurl = NSURL(string: "https://api.twitter.com/1.1/account/verify_credentials.json") request = SLRequest( forServiceType: SLServiceTypeTwitter, requestMethod: .GET, URL: meurl, parameters: nil) } else if (dataType == .Avatar) { let imageURL = userData!["profile_image_url"] as String request = SLRequest( forServiceType: SLServiceTypeTwitter, requestMethod: .GET, URL: NSURL(string: imageURL), parameters: nil) } else if (dataType == .Cover) { let imageURL = userData!["profile_background_image_url"] as String request = SLRequest( forServiceType: SLServiceTypeTwitter, requestMethod: .GET, URL: NSURL(string: imageURL), parameters: nil) } let accountType = self.accountStore.accountTypeWithAccountTypeIdentifier(ACAccountTypeIdentifierTwitter) let account = self.accountStore.accountsWithAccountType(accountType).last! as ACAccount if (request != nil){ request!.account = account } return request } return nil } }
mit
4586820d155a138b27e990da6cbf6340
30.035491
168
0.498587
6.023501
false
false
false
false
ReactiveKit/ReactiveGitter
Views/View Controllers/Authentication.swift
1
944
// // AuthenticationViewController.swift // ReactiveGitter // // Created by Srdan Rasic on 15/01/2017. // Copyright © 2017 ReactiveKit. All rights reserved. // import UIKit extension ViewController { public class Authentication: UIViewController { public private(set) lazy var titleLabel = UILabel().setup { $0.text = "Reactive Gitter" $0.font = .preferredFont(forTextStyle: .title1) } public private(set) lazy var loginButton = UIButton(type: .system).setup { $0.setTitle("Log in", for: .normal) } public init() { super.init(nibName: nil, bundle: nil) view.backgroundColor = .white view.addSubview(titleLabel) titleLabel.center(in: view) view.addSubview(loginButton) loginButton.center(in: view, offset: .init(x: 0, y: 60)) } public required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } }
mit
40aff54d99866ab2bc3adf67ad980d0b
23.179487
78
0.658537
3.978903
false
false
false
false
hooliooo/Astral
Sources/Astral/MultiPartFormBodyBuilder.swift
1
8646
// // Astral // Copyright (c) Julio Miguel Alorro // Licensed under the MIT license. See LICENSE file // import class Foundation.InputStream import class Foundation.FileManager import class Foundation.OutputStream import struct Foundation.Data import struct Foundation.URL import struct Foundation.UUID import struct Foundation.FileAttributeKey /** An implementation of DataStrategy specifically for creating an HTTP body for multipart form-data. */ public struct MultiPartFormBodyBuilder { // MARK: Initializer /** Initializer. */ public init(fileManager: FileManager, boundary: String) { self.fileManager = fileManager self.boundary = boundary } // MARK: Instance Properties /** The FileManager used to create temporary multipart/form-data files in the cache directory */ private let fileManager: FileManager /** The boundary used in creating the multipart/form-data */ private let boundary: String private let streamBufferSize: Int = 1_024 // MARK: Instance Methods /** The method used to modify the HTTP body to create the multipart form-data payload. - parameter string: The string to be converted into Data. - parameter data: The data the string will be appended to. */ private func append(string: String, to data: inout Data) { let stringData: Data = string.data(using: String.Encoding.utf8)! // swiftlint:disable:this force_unwrapping data.append(stringData) } /** Creates the end part of the Data body needed for a multipart-form data HTTP Request. */ internal var postfixData: Data { var data: Data = Data() self.append(string: "--\(self.boundary)--\r\n", to: &data) return data } /** Creates the body of the multipart form data request by writing the entire multipart form data into a file. This method is very efficient, it utilizes input and output streams to read and write to a file. Should be used for large multipart form data. - parameter url: The URL of the file the multipart form data is written to - parameter request: The MultiPartFormDataRequest instance */ @discardableResult public func writeData(to url: URL, components: [MultiPartFormDataComponent]) throws -> UInt64 { guard self.fileManager.fileExists(atPath: url.path) == false else { throw MultiPartFormBodyBuilder.WriteError.fileExists } guard let outputStream = OutputStream(url: url, append: false) else { throw MultiPartFormBodyBuilder.WriteError.couldNotCreateOutputStream } outputStream.open() defer { outputStream.close() } for component in components { let boundaryPrefix: String = "--\(self.boundary)\r\n" try self.write(string: boundaryPrefix, to: outputStream) try self.write( string: "Content-Disposition: form-data; name=\"\(component.name)\";", to: outputStream ) if case let .image(_, fileName, _, _) = component { try self.write(string: " filename=\"\(fileName)\"\r\n", to: outputStream) } else { try self.write(string: "\r\n", to: outputStream) } try self.write(string: "Content-Type: \"\(component.contentType)\"\r\n\r\n", to: outputStream) switch component { case let .image(_, _, _, file): let inputStream: InputStream switch file { case .data(let data): inputStream = InputStream(data: data) case .url(let url): guard let possibleStream = InputStream(url: url) else { throw MultiPartFormBodyBuilder.ReadError.couldNotCreateInputStream } inputStream = possibleStream } inputStream.open() defer { inputStream.close() } while inputStream.hasBytesAvailable { var buffer: [UInt8] = [UInt8](repeating: 0, count: self.streamBufferSize) let bytesRead: Int = inputStream.read(&buffer, maxLength: self.streamBufferSize) if let streamError = inputStream.streamError { throw MultiPartFormBodyBuilder.ReadError.inputStreamReadError(streamError) } guard bytesRead > 0 else { break } if buffer.count != bytesRead { buffer = Array(buffer[0..<bytesRead]) } try self.write(buffer: &buffer, to: outputStream) } case .text, .json, .other: try self.write(string: "\(component.value)", to: outputStream) } try self.write(string: "\r\n", to: outputStream) } let postfixData: Data = self.postfixData try self.write(data: postfixData, to: outputStream) return (try self.fileManager.attributesOfItem(atPath: url.path)[FileAttributeKey.size] as? UInt64) ?? 0 } // MARK: Private Write methods to OutputStream private func write(buffer: inout [UInt8], to outputStream: OutputStream) throws { var bytesToWrite: Int = buffer.count while bytesToWrite > 0, outputStream.hasSpaceAvailable { let bytesWritten: Int = outputStream.write(buffer, maxLength: bytesToWrite) if let streamError = outputStream.streamError { throw MultiPartFormBodyBuilder.WriteError.outputStreamWriteError(streamError) } bytesToWrite -= bytesWritten if bytesToWrite > 0 { buffer = Array(buffer[bytesWritten..<buffer.count]) } } } private func write(string: String, to outputStream: OutputStream) throws { guard let stringData = string.data(using: String.Encoding.utf8) else { throw MultiPartFormBodyBuilder.WriteError.stringToDataFailed } return try self.write(data: stringData, to: outputStream) } private func write(data: Data, to outputStream: OutputStream) throws { var buffer: [UInt8] = [UInt8](repeating: 0, count: data.count) data.copyBytes(to: &buffer, count: data.count) return try self.write(buffer: &buffer, to: outputStream) } } // MARK: Public API Functions public extension MultiPartFormBodyBuilder { func fileURL(for fileName: String) -> URL { return self.fileManager.ast.fileURL(with: fileName) } } // MARK: Enums public extension MultiPartFormBodyBuilder { // MARK: Enums /** WriteError represents errors related to writing to or creating an OutputStream */ enum WriteError: Swift.Error { /** The file already exists at the URL. */ case fileExists /** The OutputStream instance could not be initialized. */ case couldNotCreateOutputStream /** Writing to the OutputStream resulted in an error. */ case outputStreamWriteError(Error) /** The String instance could not be transformed into a Data instance. */ case stringToDataFailed } /** ReadError represents errors related to reading or creating an InputStream or reading a file's attributes. */ enum ReadError: Swift.Error { /** The InputStream instance could not be initialized. */ case couldNotCreateInputStream /** Reading an InputStream resulted in an error. */ case inputStreamReadError(Error) } } // MARK: Old Implementations private extension MultiPartFormBodyBuilder { // /** // Creates a Data instance based on the contents of MultiPartFormDataComponents. May throw an error. // - parameter components: The MultiPartFormDataComponent instances. // - returns: Data // */ // internal func data(for components: [MultiPartFormDataComponent]) throws -> Data { // var data: Data = Data() // // for component in components { // let boundaryPrefix: String = "--\(self.boundary)\r\n" // self.append(string: boundaryPrefix, to: &data) // self.append( // string: "Content-Disposition: form-data; name=\"\(component.name)\";", // to: &data // ) // // if case let .image(_, fileName, _, _) = component { // self.append(string: " filename=\"\(fileName)\"\r\n", to: &data) // } else { // self.append(string: "\r\n", to: &data) // } // // self.append(string: "Content-Type: \(component.contentType)\r\n\r\n", to: &data) // // switch component { // case let .image(_, _, _, file): // switch file { // case .data(let fileData): // data.append(fileData) // // case .url(let url): // data.append(try Data(contentsOf: url)) // } // case .text, .json, .other: // self.append(string: "\(component.value)", to: &data) // // } // // self.append(string: "\r\n", to: &data) // } // // return data // } }
mit
42bcb445eca3b14cc15a8f8720455753
29.659574
140
0.649665
4.338184
false
false
false
false
xwu/swift
validation-test/compiler_crashers_2_fixed/0022-rdar21625478.swift
1
11398
// RUN: %target-swift-frontend %s -emit-silgen -requirement-machine=off // rdar://80395274 tracks getting this to pass with the requirement machine. import StdlibUnittest public struct MyRange<Bound : ForwardIndex> { var startIndex: Bound var endIndex: Bound } public protocol ForwardIndex : Equatable { associatedtype Distance : SignedNumeric func successor() -> Self } public protocol MySequence { associatedtype Iterator : IteratorProtocol associatedtype SubSequence = Void func makeIterator() -> Iterator var underestimatedCount: Int { get } func map<T>( _ transform: (Iterator.Element) -> T ) -> [T] func filter( _ isIncluded: (Iterator.Element) -> Bool ) -> [Iterator.Element] func _customContainsEquatableElement( _ element: Iterator.Element ) -> Bool? func _preprocessingPass<R>( _ preprocess: (Self) -> R ) -> R? func _copyToContiguousArray() -> ContiguousArray<Iterator.Element> func _copyContents( initializing ptr: UnsafeMutablePointer<Iterator.Element> ) -> UnsafeMutablePointer<Iterator.Element> } extension MySequence { var underestimatedCount: Int { return 0 } public func map<T>( _ transform: (Iterator.Element) -> T ) -> [T] { return [] } public func filter( _ isIncluded: (Iterator.Element) -> Bool ) -> [Iterator.Element] { return [] } public func _customContainsEquatableElement( _ element: Iterator.Element ) -> Bool? { return nil } public func _preprocessingPass<R>( _ preprocess: (Self) -> R ) -> R? { return nil } public func _copyToContiguousArray() -> ContiguousArray<Iterator.Element> { fatalError() } public func _copyContents( initializing ptr: UnsafeMutablePointer<Iterator.Element> ) -> UnsafeMutablePointer<Iterator.Element> { fatalError() } } public protocol MyIndexable : MySequence { associatedtype Index : ForwardIndex var startIndex: Index { get } var endIndex: Index { get } associatedtype _Element subscript(_: Index) -> _Element { get } } public protocol MyCollection : MyIndexable { associatedtype Iterator : IteratorProtocol = IndexingIterator<Self> associatedtype SubSequence : MySequence subscript(_: Index) -> Iterator.Element { get } subscript(_: MyRange<Index>) -> SubSequence { get } var first: Iterator.Element? { get } var isEmpty: Bool { get } var count: Index.Distance { get } func _customIndexOfEquatableElement(_ element: Iterator.Element) -> Index?? } extension MyCollection { public var isEmpty: Bool { return startIndex == endIndex } public func _preprocessingPass<R>( _ preprocess: (Self) -> R ) -> R? { return preprocess(self) } public var count: Index.Distance { return 0 } public func _customIndexOfEquatableElement(_ element: Iterator.Element) -> Index?? { return nil } } public struct IndexingIterator<I : MyIndexable> : IteratorProtocol { public func next() -> I._Element? { return nil } } protocol Resettable : AnyObject { func reset() } internal var _allResettables: [Resettable] = [] public class TypeIndexed<Value> : Resettable { public init(_ value: Value) { self.defaultValue = value _allResettables.append(self) } public subscript(t: Any.Type) -> Value { get { return byType[ObjectIdentifier(t)] ?? defaultValue } set { byType[ObjectIdentifier(t)] = newValue } } public func reset() { byType = [:] } internal var byType: [ObjectIdentifier:Value] = [:] internal var defaultValue: Value } //===--- LoggingWrappers.swift --------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// public protocol Wrapper { associatedtype Base init(_: Base) var base: Base {get set} } public protocol LoggingType : Wrapper { associatedtype Log : AnyObject } extension LoggingType { public var log: Log.Type { return Log.self } public var selfType: Any.Type { return type(of: self) } } public class IteratorLog { public static func dispatchTester<G : IteratorProtocol>( _ g: G ) -> LoggingIterator<LoggingIterator<G>> { return LoggingIterator(LoggingIterator(g)) } public static var next = TypeIndexed(0) } public struct LoggingIterator<Base: IteratorProtocol> : IteratorProtocol, LoggingType { public typealias Log = IteratorLog public init(_ base: Base) { self.base = base } public mutating func next() -> Base.Element? { Log.next[selfType] += 1 return base.next() } public var base: Base } public class SequenceLog { public static func dispatchTester<S: MySequence>( _ s: S ) -> LoggingSequence<LoggingSequence<S>> { return LoggingSequence(LoggingSequence(s)) } public static var iterator = TypeIndexed(0) public static var underestimatedCount = TypeIndexed(0) public static var map = TypeIndexed(0) public static var filter = TypeIndexed(0) public static var _customContainsEquatableElement = TypeIndexed(0) public static var _preprocessingPass = TypeIndexed(0) public static var _copyToContiguousArray = TypeIndexed(0) public static var _copyContents = TypeIndexed(0) } public protocol LoggingSequenceType : MySequence, LoggingType { associatedtype Base : MySequence associatedtype Log : AnyObject = SequenceLog associatedtype Iterator : IteratorProtocol = LoggingIterator<Base.Iterator> } extension LoggingSequenceType { public var underestimatedCount: Int { SequenceLog.underestimatedCount[selfType] += 1 return base.underestimatedCount } } extension LoggingSequenceType where Log == SequenceLog, Iterator == LoggingIterator<Base.Iterator> { public func makeIterator() -> LoggingIterator<Base.Iterator> { Log.iterator[selfType] += 1 return LoggingIterator(base.makeIterator()) } public func map<T>( _ transform: (Base.Iterator.Element) -> T ) -> [T] { Log.map[selfType] += 1 return base.map(transform) } public func filter( _ isIncluded: (Base.Iterator.Element) -> Bool ) -> [Base.Iterator.Element] { Log.filter[selfType] += 1 return base.filter(isIncluded) } public func _customContainsEquatableElement( _ element: Base.Iterator.Element ) -> Bool? { Log._customContainsEquatableElement[selfType] += 1 return base._customContainsEquatableElement(element) } /// If `self` is multi-pass (i.e., a `Collection`), invoke /// `preprocess` on `self` and return its result. Otherwise, return /// `nil`. public func _preprocessingPass<R>( _ preprocess: (Self) -> R ) -> R? { Log._preprocessingPass[selfType] += 1 return base._preprocessingPass { _ in preprocess(self) } } /// Create a native array buffer containing the elements of `self`, /// in the same order. public func _copyToContiguousArray() -> ContiguousArray<Base.Iterator.Element> { Log._copyToContiguousArray[selfType] += 1 return base._copyToContiguousArray() } /// Copy a Sequence into an array. public func _copyContents( initializing ptr: UnsafeMutablePointer<Base.Iterator.Element> ) -> UnsafeMutablePointer<Base.Iterator.Element> { Log._copyContents[selfType] += 1 return base._copyContents(initializing: ptr) } } public struct LoggingSequence< Base_: MySequence > : LoggingSequenceType, MySequence { public typealias Log = SequenceLog public typealias Base = Base_ public init(_ base: Base_) { self.base = base } public var base: Base_ } public class CollectionLog : SequenceLog { public class func dispatchTester<C: MyCollection>( _ c: C ) -> LoggingCollection<LoggingCollection<C>> { return LoggingCollection(LoggingCollection(c)) } static var startIndex = TypeIndexed(0) static var endIndex = TypeIndexed(0) static var subscriptIndex = TypeIndexed(0) static var subscriptRange = TypeIndexed(0) static var isEmpty = TypeIndexed(0) static var count = TypeIndexed(0) static var _customIndexOfEquatableElement = TypeIndexed(0) static var first = TypeIndexed(0) } public protocol LoggingCollectionType : LoggingSequenceType, MyCollection { associatedtype Base : MyCollection associatedtype Index : ForwardIndex = Base.Index } extension LoggingCollectionType where Index == Base.Index { public var startIndex: Base.Index { CollectionLog.startIndex[selfType] += 1 return base.startIndex } public var endIndex: Base.Index { CollectionLog.endIndex[selfType] += 1 return base.endIndex } public subscript(position: Base.Index) -> Base.Iterator.Element { CollectionLog.subscriptIndex[selfType] += 1 return base[position] } public subscript(_prext_bounds: MyRange<Base.Index>) -> Base.SubSequence { CollectionLog.subscriptRange[selfType] += 1 return base[_prext_bounds] } public var isEmpty: Bool { CollectionLog.isEmpty[selfType] += 1 return base.isEmpty } public var count: Base.Index.Distance { CollectionLog.count[selfType] += 1 return base.count } public func _customIndexOfEquatableElement(_ element: Base.Iterator.Element) -> Base.Index?? { CollectionLog._customIndexOfEquatableElement[selfType] += 1 return base._customIndexOfEquatableElement(element) } public var first: Base.Iterator.Element? { CollectionLog.first[selfType] += 1 return base.first } } public struct LoggingCollection<Base_ : MyCollection> : LoggingCollectionType { public typealias Iterator = LoggingIterator<Base.Iterator> public typealias Log = CollectionLog public typealias Base = Base_ public typealias SubSequence = Base.SubSequence public func makeIterator() -> Iterator { return Iterator(base.makeIterator()) } public init(_ base: Base_) { self.base = base } public var base: Base_ } public func expectCustomizable< T : Wrapper >(_: T, _ counters: TypeIndexed<Int>, stackTrace: SourceLocStack? = nil, file: String = #file, line: UInt = #line, collectMoreInfo: (()->String)? = nil ) where T : LoggingType, T.Base : Wrapper, T.Base : LoggingType, T.Log == T.Base.Log { expectNotEqual( 0, counters[T.self], collectMoreInfo?() ?? "", stackTrace: stackTrace ?? SourceLocStack(), file: file, line: line) expectEqual( counters[T.self], counters[T.Base.self], collectMoreInfo?() ?? "", stackTrace: stackTrace ?? SourceLocStack(), file: file, line: line) } public func expectNotCustomizable< T : Wrapper >(_: T, _ counters: TypeIndexed<Int>, stackTrace: SourceLocStack? = nil, file: String = #file, line: UInt = #line, collectMoreInfo: (()->String)? = nil ) where T : LoggingType, T.Base : Wrapper, T.Base : LoggingType, T.Log == T.Base.Log { expectNotEqual( 0, counters[T.self], collectMoreInfo?() ?? "", stackTrace: stackTrace ?? SourceLocStack(), file: file, line: line) expectEqual( 0, counters[T.Base.self], collectMoreInfo?() ?? "", stackTrace: stackTrace ?? SourceLocStack(), file: file, line: line) }
apache-2.0
e6ab7e449e6a87a2714ac2395c8fb143
25.445476
96
0.687665
4.372075
false
false
false
false
jingkecn/WatchWorker
src/ios/JSCore/Workers/SharedWorker.swift
1
1220
// // SharedWorker.swift // WTVJavaScriptCore // // Created by Jing KE on 29/07/16. // Copyright © 2016 WizTiVi. All rights reserved. // import Foundation import JavaScriptCore @objc protocol SharedWorkerJSExport: JSExport { var scriptURL: String { get } var name: String { get } var port: MessagePort { get } } class SharedWorker: AbstractWorker, SharedWorkerJSExport { let scriptURL: String var name: String init(context: ScriptContext, scriptURL: String, name: String = "") { self.scriptURL = scriptURL self.name = name super.init(context: context, scriptURL: scriptURL) print("\(self.port)") } override func run() { print("==================== [\(self.className)] Start running shared worker ====================") SharedWorkerGlobalScope.runWorker(self) print("==================== [\(self.className)] End running shared worker ====================") } } extension SharedWorker { class func create(context: ScriptContext, scriptURL: String, name: String = "") -> SharedWorker { return SharedWorker(context: context, scriptURL: scriptURL, name: name) } }
mit
e76425b965bc2802cd7ae228017d8d9f
24.957447
106
0.599672
4.353571
false
false
false
false
richeterre/jumu-nordost-ios
JumuNordost/Application/Mediator.swift
1
883
// // Mediator.swift // JumuNordost // // Created by Martin Richter on 14/02/16. // Copyright © 2016 Martin Richter. All rights reserved. // import ReactiveCocoa import Result class Mediator { // MARK: - Inputs let active = MutableProperty<Bool>(false) let refreshObserver: Observer<Void, NoError> // MARK: - Outputs let isLoading: MutableProperty<Bool> // MARK: - Internal Properties let store: StoreType let refreshTrigger: SignalProducer<Void, NoError> // MARK: - Lifecycle init(store: StoreType) { self.store = store (refreshTrigger, refreshObserver) = SignalProducer<Void, NoError>.buffer(0) let isLoading = MutableProperty<Bool>(false) self.isLoading = isLoading active.producer .filter { $0 } .map { _ in () } .start(refreshObserver) } }
mit
034a1d1ce814171c2b4f5c67a89c0b03
19.511628
83
0.628118
4.302439
false
false
false
false
mattjgalloway/emoncms-ios
Pods/Former/Former/Cells/FormSelectorDatePickerCell.swift
1
2690
// // FormSelectorDatePickerCell.swift // Former-Demo // // Created by Ryo Aoyama on 8/25/15. // Copyright © 2015 Ryo Aoyama. All rights reserved. // import UIKit open class FormSelectorDatePickerCell: FormCell, SelectorDatePickerFormableRow { // MARK: Public open var selectorDatePicker: UIDatePicker? open var selectorAccessoryView: UIView? public private(set) weak var titleLabel: UILabel! public private(set) weak var displayLabel: UILabel! public func formTitleLabel() -> UILabel? { return titleLabel } public func formDisplayLabel() -> UILabel? { return displayLabel } open override func updateWithRowFormer(_ rowFormer: RowFormer) { super.updateWithRowFormer(rowFormer) rightConst.constant = (accessoryType == .none) ? -15 : 0 } open override func setup() { super.setup() let titleLabel = UILabel() titleLabel.setContentHuggingPriority(500, for: .horizontal) titleLabel.translatesAutoresizingMaskIntoConstraints = false contentView.insertSubview(titleLabel, at: 0) self.titleLabel = titleLabel let displayLabel = UILabel() displayLabel.textColor = .lightGray displayLabel.textAlignment = .right displayLabel.translatesAutoresizingMaskIntoConstraints = false contentView.insertSubview(displayLabel, at: 0) self.displayLabel = displayLabel let constraints = [ NSLayoutConstraint.constraints( withVisualFormat: "V:|-0-[title]-0-|", options: [], metrics: nil, views: ["title": titleLabel] ), NSLayoutConstraint.constraints( withVisualFormat: "V:|-0-[display]-0-|", options: [], metrics: nil, views: ["display": displayLabel] ), NSLayoutConstraint.constraints( withVisualFormat: "H:|-15-[title]-10-[display(>=0)]", options: [], metrics: nil, views: ["title": titleLabel, "display": displayLabel] ) ].flatMap { $0 } let rightConst = NSLayoutConstraint( item: displayLabel, attribute: .trailing, relatedBy: .equal, toItem: contentView, attribute: .trailing, multiplier: 1, constant: 0 ) contentView.addConstraints(constraints + [rightConst]) self.rightConst = rightConst } // MARK: Private private weak var rightConst: NSLayoutConstraint! }
mit
5190e47598d92c871434b090d446102d
30.267442
80
0.587951
5.532922
false
false
false
false
wordpress-mobile/WordPress-iOS
WordPress/Classes/ViewRelated/Developer/StoreSandboxSecretScreen.swift
2
1991
import SwiftUI struct StoreSandboxSecretScreen: View { private static let storeSandboxSecretKey = "store_sandbox" @SwiftUI.Environment(\.presentationMode) var presentationMode @State private var secret: String private let cookieJar: CookieJar var body: some View { NavigationView { VStack(alignment: .leading) { Text("Enter the Store Sandbox Cookie Secret:") TextField("Secret", text: $secret) .padding(EdgeInsets(top: 16, leading: 16, bottom: 16, trailing: 16)) .border(Color.black) Spacer() } .padding(EdgeInsets(top: 16, leading: 16, bottom: 16, trailing: 16)) } .onDisappear() { // This seems to be necessary due to an iOS bug where // accessing presentationMode.wrappedValue crashes. DispatchQueue.main.async { if self.presentationMode.wrappedValue.isPresented == false, let cookie = HTTPCookie(properties: [ .name: StoreSandboxSecretScreen.storeSandboxSecretKey, .value: secret, .domain: ".wordpress.com", .path: "/" ]) { cookieJar.setCookies([cookie]) {} } } } } init(cookieJar: CookieJar) { var cookies: [HTTPCookie] = [] self.cookieJar = cookieJar cookieJar.getCookies { jarCookies in cookies = jarCookies } if let cookie = cookies.first(where: { $0.name == StoreSandboxSecretScreen.storeSandboxSecretKey }) { _secret = State(initialValue: cookie.value) } else { _secret = State(initialValue: "") } } } struct StoreSandboxSecretScreen_Previews: PreviewProvider { static var previews: some View { StoreSandboxSecretScreen(cookieJar: HTTPCookieStorage.shared) } }
gpl-2.0
a45932cb3045e8ac2adddb4384d3de5c
32.745763
109
0.56454
5.092072
false
false
false
false
mleiv/IBIncludedThing
IBIncludedThingDemo/IBIncludedThingDemo/IBIncludedThing.swift
2
16822
//// //// IBIncludedThing.swift //// //// Copyright 2016 Emily Ivie // //// Licensed under The MIT License //// For full copyright and license information, please see http://opensource.org/licenses/MIT //// Redistributions of files must retain the above copyright notice. import UIKit /// Allows for removing individual scene design from the flow storyboards and into individual per-controller storyboards, which minimizes git merge conflicts. // *NOT* @IBDesignable - we only use preview for IB preview open class IBIncludedThing: UIViewController, IBIncludedThingLoadable { @IBInspectable open var incStoryboard: String? // abbreviated for shorter label in IB open var includedStoryboard: String? { get { return incStoryboard } set { incStoryboard = newValue } } @IBInspectable open var sceneId: String? @IBInspectable open var incNib: String? // abbreviated for shorter label in IB open var includedNib: String? { get { return incNib } set { incNib = newValue } } @IBInspectable open var nibController: String? /// The controller loaded during including the above storyboard or nib open weak var includedController: UIViewController? /// Typical initialization of IBIncludedThing when it is created during normal scene loading at run time. open override func awakeFromNib() { super.awakeFromNib() attach(toController: self, toView: nil) } open override func loadView() { super.loadView() attach(toController: nil, toView: self.view) } open override func prepare(for segue: UIStoryboardSegue, sender: Any?) { super.prepare(for: segue, sender: sender) includedController?.prepare(for: segue, sender: sender) // The following code will run prepareForSegue in all child view controllers. // This can cause unexpected multiple calls to prepareForSegue, so I prefer to be more cautious about which view controllers invoke prepareForSegue. // See IBIncludedThingDemo FourthController and SixthController for examples and options with embedded view controllers. // includedController?.findType(UIViewController.self) { controller in // controller.prepareForSegue(segue, sender: sender) // } } } /// Because UIViewController does not preview in Interface Builder, this is an Interface-Builder-only companion to IBIncludedThing. Typically you would set the scene owner to IBIncludedThing and then set the top-level view to IBIncludedThingPreview, with identical IBInspectable values. @IBDesignable open class IBIncludedThingPreview: UIView, IBIncludedThingLoadable { @IBInspectable open var incStoryboard: String? // abbreviated for shorter label in IB open var includedStoryboard: String? { get { return incStoryboard } set { incStoryboard = newValue } } @IBInspectable open var sceneId: String? @IBInspectable open var incNib: String? // abbreviated for shorter label in IB open var includedNib: String? { get { return incNib } set { incNib = newValue } } @IBInspectable open var nibController: String? override open func prepareForInterfaceBuilder() { super.prepareForInterfaceBuilder() attach(toController: nil, toView: self) } // protocol conformance only (does not use): open weak var includedController: UIViewController? } /// Can be used identically to IBIncludedThing, but for subviews inside scenes rather than an entire scene. The major difference is that IBIncludedSubThing views, unfortunately, cannot be configured using prepareForSegue, because they are loaded too late in the view controller lifecycle. @IBDesignable open class IBIncludedSubThing: UIView, IBIncludedThingLoadable { @IBInspectable open var incStoryboard: String? // abbreviated for shorter label in IB open var includedStoryboard: String? { get { return incStoryboard } set { incStoryboard = newValue } } @IBInspectable open var sceneId: String? @IBInspectable open var incNib: String? // abbreviated for shorter label in IB open var includedNib: String? { get { return incNib } set { incNib = newValue } } @IBInspectable open var nibController: String? /// The controller loaded during including the above storyboard or nib open weak var includedController: UIViewController? /// An optional parent controller to use when this is being instantiated in code (and so might not have a hierarchy). /// This would be private, but the protocol needs it. open weak var parentController: UIViewController? // /// Convenience initializer for programmatic inclusion // public init?(incStoryboard: String? = nil, sceneId: String? = nil, incNib: String? = nil, nibController: String? = nil, intoView parentView: UIView? = nil, intoController parentController: UIViewController? = nil) { // self.incStoryboard = incStoryboard // self.sceneId = sceneId // self.incNib = incNib // self.nibController = nibController // self.parentController = parentController // super.init(frame: CGRectZero) // guard incStoryboard != nil || incNib != nil else { // return nil // } // // then also pin this IBIncludedSubThing to a parent view if so requested: // if let view = parentView ?? parentController?.view { // attach(incView: self, toView: view) // } // } // // public required init?(coder aDecoder: NSCoder) { // fatalError("init(coder:) has not been implemented") // } /// Initializes the IBIncludedSubThing for preview inside Xcode. /// Does not bother attaching view controller to hierarchy. open override func prepareForInterfaceBuilder() { super.prepareForInterfaceBuilder() attach(toController: nil, toView: self) } /// Typical initialization of IBIncludedSubThing when it is created during normal scene loading at run time. open override func awakeFromNib() { super.awakeFromNib() if parentController == nil { parentController = findParent(ofController: activeController(under: topController())) } attach(toController: parentController, toView: self) } // And then we need all these to get parent controller: /// Grabs access to view controller hierarchy if possible. fileprivate func topController() -> UIViewController? { if let controller = window?.rootViewController { return controller } else if let controller = UIApplication.shared.keyWindow?.rootViewController { return controller } return nil } /// Locates the top-most currently visible controller. fileprivate func activeController(under controller: UIViewController?) -> UIViewController? { guard let controller = controller else { return nil } if let tabController = controller as? UITabBarController, let nextController = tabController.selectedViewController { return activeController(under: nextController) } else if let navController = controller as? UINavigationController, let nextController = navController.visibleViewController { return activeController(under: nextController) } else if let nextController = controller.presentedViewController { return activeController(under: nextController) } return controller } /// Locates the view controller with this view inside of it (depth first, since in a hierarchy of view controllers the view would likely be in all the parentViewControllers of its view controller). fileprivate func findParent(ofController topController: UIViewController!) -> UIViewController? { if topController == nil { return nil } for viewController in topController.childViewControllers { // first try, deep dive into child controllers if let parentViewController = findParent(ofController: viewController) { return parentViewController } } // second try, top view controller (most generic, most things will be in this view) if let topView = topController?.view , findSelf(inView: topView) { return topController } return nil } /// Identifies if the IBIncludedSubThing view is equal to or under the view given. fileprivate func findSelf(inView topView: UIView) -> Bool { if topView == self || topView == self.superview { return true } else { for view in topView.subviews { if findSelf(inView: view ) { return true } } } return false } } /// This holds all the shared functionality of the IBIncludedThing variants. public protocol IBIncludedThingLoadable: class { // defining properties: var includedStoryboard: String? { get set } var sceneId: String? { get set } var includedNib: String? { get set } var nibController: String? { get set } // reference: weak var includedController: UIViewController? { get set } // main: func attach(toController parentController: UIViewController?, toView parentView: UIView?) func detach() // supporting: func getController(inBundle bundle: Bundle) -> UIViewController? func attach(controller: UIViewController?, toParent parentController: UIViewController?) func attach(view: UIView?, toView parentView: UIView) // useful: func reload(includedStoryboard: String, sceneId: String?) func reload(includedNib: String, nibController: String?) } extension IBIncludedThingLoadable { /// Main function to attach the included content. public func attach(toController parentController: UIViewController?, toView parentView: UIView?) { guard let includedController = includedController ?? getController(inBundle: Bundle(for: type(of: self))) else { return } if let parentController = parentController { attach(controller: includedController, toParent: parentController) } if let parentView = parentView { attach(view: includedController.view, toView: parentView) } } /// Main function to remove the included content. public func detach() { includedController?.view.removeFromSuperview() includedController?.removeFromParentViewController() self.includedStoryboard = nil self.sceneId = nil self.includedNib = nil self.nibController = nil } /// Internal: loads the controller from the storyboard or nib public func getController(inBundle bundle: Bundle) -> UIViewController? { var foundController: UIViewController? if let storyboardName = self.includedStoryboard { // load storyboard let storyboardObj = UIStoryboard(name: storyboardName, bundle: bundle) let sceneId = self.sceneId ?? "" foundController = sceneId.isEmpty ? storyboardObj.instantiateInitialViewController() : storyboardObj.instantiateViewController(withIdentifier: sceneId) } else if let nibName = self.includedNib { // load nib if let controllerName = nibController, let appName = bundle.object(forInfoDictionaryKey: "CFBundleName") as? String { // load specified controller let classStringName = "\(appName).\(controllerName)" if let ControllerType = NSClassFromString(classStringName) as? UIViewController.Type { foundController = ControllerType.init(nibName: nibName, bundle: bundle) as UIViewController } } else { // load generic controller foundController = UIViewController(nibName: nibName, bundle: bundle) } } return foundController } /// Internal: inserts the included controller into the view hierarchy (this helps trigger correct view hierarchy lifecycle functions) public func attach(controller: UIViewController?, toParent parentController: UIViewController?) { // save for later (do not explicitly reference view or you will trigger viewDidLoad) guard let controller = controller, let parentController = parentController else { return } // save for later use includedController = controller // attach to hierarchy controller.willMove(toParentViewController: parentController) parentController.addChildViewController(controller) controller.didMove(toParentViewController: parentController) } /// Internal: inserts the included view inside the IBIncludedThing view. Makes this nesting invisible by removing any background on IBIncludedThing and sets constraints so included content fills IBIncludedThing. public func attach(view: UIView?, toView parentView: UIView) { guard let view = view else { return } parentView.addSubview(view) //clear out top-level view visibility, so only subview shows parentView.isOpaque = false parentView.backgroundColor = UIColor.clear //tell child to fit itself to the edges of wrapper (self) view.translatesAutoresizingMaskIntoConstraints = false view.topAnchor.constraint(equalTo: parentView.topAnchor).isActive = true view.bottomAnchor.constraint(equalTo: parentView.bottomAnchor).isActive = true view.leadingAnchor.constraint(equalTo: parentView.leadingAnchor).isActive = true view.trailingAnchor.constraint(equalTo: parentView.trailingAnchor).isActive = true } /// Programmatic reloading of a storyboard inside the same IBIncludedSubThing view. /// parentController is only necessary when the storyboard has had no previous storyboard, and so is missing an included controller (and its parent). public func reload(includedStoryboard: String, sceneId: String?) { let parentController = (self as? IBIncludedThing) ?? (self as? IBIncludedSubThing)?.parentController guard includedStoryboard != self.includedStoryboard || sceneId != self.sceneId, let parentView = (self as? IBIncludedSubThing) ?? parentController?.view else { return } // cleanup old stuff detach() self.includedController = nil // reset to new values self.includedStoryboard = includedStoryboard self.sceneId = sceneId self.includedNib = nil self.nibController = nil // reload attach(toController: parentController, toView: parentView) } /// Programmatic reloading of a nib inside the same IBIncludedSubThing view. /// parentController is only necessary when the storyboard has had no previous storyboard, and so is missing an included controller (and its parent). public func reload(includedNib: String, nibController: String?) { let parentController = (self as? IBIncludedThing) ?? (self as? IBIncludedSubThing)?.parentController guard includedNib != self.includedNib || nibController != self.nibController, let parentView = (self as? IBIncludedSubThing) ?? parentController?.view else { return } // cleanup old stuff detach() self.includedController = nil // reset to new values self.includedStoryboard = nil self.sceneId = nil self.includedNib = includedNib self.nibController = nibController // reload attach(toController: parentController, toView: parentView) } } extension UIViewController { /// A convenient utility for quickly running some code on a view controller of a specific type in the current view controller hierarchy. public func find<T: UIViewController>(controllerType: T.Type, apply: ((T) -> Void)) { for childController in childViewControllers { if let foundController = childController as? T { apply(foundController) } else { childController.find(controllerType: controllerType, apply: apply) } } if let foundController = self as? T { apply(foundController) } } } extension UIWindow { static var isInterfaceBuilder: Bool { #if TARGET_INTERFACE_BUILDER return true #else return false #endif } }
mit
d4f39930ea29fbd8be8fa7652d3c9114
41.913265
288
0.676792
5.384763
false
false
false
false
kickstarter/ios-oss
Kickstarter-iOS/Features/Dashboard/Views/DashboardTitleView.swift
1
3262
import KsApi import Library import Prelude import Prelude_UIKit import UIKit internal protocol DashboardTitleViewDelegate: AnyObject { /// Call when dashboard should show/hide the projects drawer view controller. func dashboardTitleViewShowHideProjectsDrawer() } internal final class DashboardTitleView: UIView { fileprivate let viewModel: DashboardTitleViewViewModelType = DashboardTitleViewViewModel() @IBOutlet fileprivate var titleButton: UIButton! @IBOutlet fileprivate var titleLabel: UILabel! @IBOutlet fileprivate var arrowImageView: UIImageView! internal weak var delegate: DashboardTitleViewDelegate? override func awakeFromNib() { super.awakeFromNib() _ = self.titleButton |> UIButton.lens.contentEdgeInsets %~ { insets in .init(topBottom: insets.top, leftRight: 0) } |> UIButton.lens.accessibilityLabel %~ { _ in Strings.tabbar_dashboard() } |> UIButton.lens.accessibilityTraits .~ UIAccessibilityTraits.staticText |> UIButton.lens.targets .~ [(self, #selector(self.titleButtonTapped), .touchUpInside)] _ = self.arrowImageView |> UIImageView.lens.isHidden .~ true |> UIImageView.lens.tintColor .~ .ksr_support_700 _ = self.titleLabel |> dashboardTitleViewTextDisabledStyle self.titleButton.rac.accessibilityLabel = self.viewModel.outputs.titleAccessibilityLabel self.titleButton.rac.accessibilityHint = self.viewModel.outputs.titleAccessibilityHint self.titleLabel.rac.text = self.viewModel.outputs.titleText self.titleButton.rac.enabled = self.viewModel.outputs.titleButtonIsEnabled self.viewModel.outputs.hideArrow .observeForUI() .observeValues { [weak self] hide in guard let _self = self else { return } UIView.animate(withDuration: 0.2) { _self.arrowImageView.isHidden = hide } if !hide { _ = _self.titleButton |> UIView.lens.accessibilityTraits .~ UIAccessibilityTraits.button } } self.viewModel.outputs.updateArrowState .observeForUI() .observeValues { [weak self] drawerState in self?.animateArrow(forDrawerState: drawerState) } self.viewModel.outputs.notifyDelegateShowHideProjectsDrawer .observeForUI() .observeValues { [weak self] in self?.delegate?.dashboardTitleViewShowHideProjectsDrawer() } self.viewModel.outputs.titleButtonIsEnabled .observeForUI() .observeValues { [weak self] isEnabled in guard let _titleLabel = self?.titleLabel else { return } if isEnabled { _ = _titleLabel |> dashboardTitleViewTextEnabledStyle } } } internal func updateData(_ data: DashboardTitleViewData) { self.viewModel.inputs.updateData(data) } fileprivate func animateArrow(forDrawerState drawerState: DrawerState) { var scale: CGFloat = 1.0 switch drawerState { case .open: scale = -1.0 case .closed: scale = 1.0 } UIView.animate(withDuration: 0.2, delay: 0.0, options: .curveEaseOut, animations: { self.arrowImageView.transform = CGAffineTransform(scaleX: 1.0, y: scale) }, completion: nil) } @objc fileprivate func titleButtonTapped() { self.viewModel.inputs.titleButtonTapped() } }
apache-2.0
395a2129725eed5bf353c0eaa3f55440
32.979167
100
0.711527
4.762044
false
false
false
false
whiteshadow-gr/HatForIOS
HAT/Objects/Google Calendar/HATGoogleCalendarEntryPoints.swift
1
4843
// /** * Copyright (C) 2018 HAT Data Exchange Ltd * * SPDX-License-Identifier: MPL2 * * This file is part of the Hub of All Things project (HAT). * * 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/ */ // MARK: Struct public struct HATGoogleCalendarEntryPoints: HATObject { // MARK: - Coding Keys /** The JSON fields used by the hat The Fields are the following: * `accessCode` in JSON is `accessCode` * `entryPointType` in JSON is `entryPointType` * `title` in JSON is `label` * `meetingCode` in JSON is `meetingCode` * `passcode` in JSON is `passcode` * `password` in JSON is `password` * `pin` in JSON is `pin` * `url` in JSON is `uri` */ private enum CodingKeys: String, CodingKey { case accessCode = "accessCode" case entryPointType = "entryPointType" case title = "label" case meetingCode = "meetingCode" case passcode = "passcode" case password = "password" case pin = "pin" case url = "uri" } // MARK: - Variables /// The Access Code to access the conference. The maximum length is 128 characters. /// When creating new conference data, populate only the subset of **{meetingCode, accessCode, passcode, password, pin}** fields that match the terminology that the conference provider uses. Only the populated fields should be displayed. /// /// Optional. public var accessCode: String? /// The type of the conference entry point. /// Possible values are: /// /// - `video` - joining a conference over HTTP. A conference can have zero or one video entry point. /// - `phone` - joining a conference by dialing a phone number. A conference can have zero or more phone entry points. /// - `sip` - joining a conference over SIP. A conference can have zero or one sip entry point. /// - `more` - further conference joining instructions, for example additional phone numbers. A conference can have zero or one more entry point. A conference with only a more entry point is not a valid conference. public var entryPointType: String? /// The title for the URL. Visible to end users. Not localized. The maximum length is 512 characters. /// Examples: /// - for `video`: meet.google.com/aaa-bbbb-ccc /// - for `phone`: +1 123 268 2601 /// - for `sip`: sip:[email protected] /// - for `more`: should not be filled /// Optional. public var title: String? // The **Meeting Code** to access the conference. The maximum length is 128 characters. /// When creating new conference data, populate only the subset of **{meetingCode, accessCode, passcode, password, pin}** fields that match the terminology that the conference provider uses. Only the populated fields should be displayed. /// Optional. public var meetingCode: String? /// The **Passcode** to access the conference. The maximum length is 128 characters. Optional /// When creating new conference data, populate only the subset of **{meetingCode, accessCode, passcode, password, pin}** fields that match the terminology that the conference provider uses. Only the populated fields should be displayed. public var passcode: String? /// The **Password** to access the conference. The maximum length is 128 characters. /// When creating new conference data, populate only the subset of **{meetingCode, accessCode, passcode, password, pin}** fields that match the terminology that the conference provider uses. Only the populated fields should be displayed. /// /// Optional. public var password: String? /// The **PIN** to access the conference. The maximum length is 128 characters. // When creating new conference data, populate only the subset of **{meetingCode, accessCode, passcode, password, pin}** fields that match the terminology that the conference provider uses. Only the populated fields should be displayed. /// /// Optional. public var pin: String? /// The `URL` of the entry point. The maximum length is 1300 characters. Optional /// Format: /// - for `video`, http: or https: schema is required. /// - for `phone`, tel: schema is required. The URI should include the entire dial sequence (e.g., tel:+12345678900,,,123456789;1234). /// - for `sip`, sip: schema is required, e.g., sip:[email protected]. /// - for `more`, http: or https: schema is required. public var url: String? // MARK: - Initialisers /** The default initialiser. Initialises everything to default values. */ public init() { } }
mpl-2.0
ec70c4dfec6f9cd6a8dd7bb76a44d565
45.567308
241
0.671278
4.378843
false
false
false
false
arnaudbenard/npm-stats
Pods/Charts/Charts/Classes/Data/PieChartDataSet.swift
79
1738
// // PieChartDataSet.swift // Charts // // Created by Daniel Cohen Gindi on 24/2/15. // // Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda // A port of MPAndroidChart for iOS // Licensed under Apache License 2.0 // // https://github.com/danielgindi/ios-charts // import Foundation import CoreGraphics import UIKit public class PieChartDataSet: ChartDataSet { private var _sliceSpace = CGFloat(0.0) /// indicates the selection distance of a pie slice public var selectionShift = CGFloat(18.0) public override init() { super.init() self.valueTextColor = UIColor.whiteColor() self.valueFont = UIFont.systemFontOfSize(13.0) } public override init(yVals: [ChartDataEntry]?, label: String?) { super.init(yVals: yVals, label: label) self.valueTextColor = UIColor.whiteColor() self.valueFont = UIFont.systemFontOfSize(13.0) } /// the space that is left out between the piechart-slices, default: 0° /// --> no space, maximum 45, minimum 0 (no space) public var sliceSpace: CGFloat { get { return _sliceSpace } set { _sliceSpace = newValue if (_sliceSpace > 45.0) { _sliceSpace = 45.0 } if (_sliceSpace < 0.0) { _sliceSpace = 0.0 } } } // MARK: NSCopying public override func copyWithZone(zone: NSZone) -> AnyObject { var copy = super.copyWithZone(zone) as! PieChartDataSet copy._sliceSpace = _sliceSpace copy.selectionShift = selectionShift return copy } }
mit
ae6a4ef063eee2d86108686a62f174a1
22.808219
75
0.576281
4.523438
false
false
false
false
RedMadRobot/input-mask-ios
Source/InputMask/InputMask/Classes/View/MaskedTextViewDelegate.swift
1
14875
// // Project «InputMask» // Created by Jeorge Taflanidi // import Foundation import UIKit /** ### MaskedTextViewDelegateListener Allows clients to obtain value extracted by the mask from user input. Provides callbacks from listened UITextView. */ @objc public protocol MaskedTextViewDelegateListener: UITextViewDelegate { /** Callback to return extracted value and to signal whether the user has complete input. */ @objc optional func textView( _ textView: UITextView, didFillMandatoryCharacters complete: Bool, didExtractValue value: String ) } /** ### MaskedTextViewDelegate UITextViewDelegate, which applies masking to the user input. Might be used as a decorator, which forwards UITextViewDelegate calls to its own listener. */ @IBDesignable open class MaskedTextViewDelegate: NSObject, UITextViewDelegate { open weak var listener: MaskedTextViewDelegateListener? open var onMaskedTextChangedCallback: ((_ textField: UITextView, _ value: String, _ complete: Bool) -> ())? @IBInspectable open var primaryMaskFormat: String @IBInspectable open var autocomplete: Bool @IBInspectable open var autocompleteOnFocus: Bool @IBInspectable open var autoskip: Bool @IBInspectable open var rightToLeft: Bool /** Allows input suggestions from keyboard */ @IBInspectable open var allowSuggestions: Bool /** Shortly after new text is being pasted from the clipboard, ```UITextView``` receives a new value for its `selectedTextRange` property from the system. This new range is not consistent with the formatted text and calculated cursor position most of the time, yet it's being assigned just after ```set cursorPosition``` call. To ensure correct cursor position is set, it is assigned asynchronously (presumably after a vanishingly small delay), if cursor movement is set to be non-atomic. Default is ```false```. */ @IBInspectable open var atomicCursorMovement: Bool = false open var affineFormats: [String] open var affinityCalculationStrategy: AffinityCalculationStrategy open var customNotations: [Notation] open var primaryMask: Mask { return try! maskGetOrCreate(withFormat: primaryMaskFormat, customNotations: customNotations) } public init( primaryFormat: String = "", autocomplete: Bool = true, autocompleteOnFocus: Bool = true, autoskip: Bool = false, rightToLeft: Bool = false, affineFormats: [String] = [], affinityCalculationStrategy: AffinityCalculationStrategy = .wholeString, customNotations: [Notation] = [], onMaskedTextChangedCallback: ((_ textInput: UITextInput, _ value: String, _ complete: Bool) -> ())? = nil, allowSuggestions: Bool = true ) { self.primaryMaskFormat = primaryFormat self.autocomplete = autocomplete self.autocompleteOnFocus = autocompleteOnFocus self.autoskip = autoskip self.rightToLeft = rightToLeft self.affineFormats = affineFormats self.affinityCalculationStrategy = affinityCalculationStrategy self.customNotations = customNotations self.onMaskedTextChangedCallback = onMaskedTextChangedCallback self.allowSuggestions = allowSuggestions super.init() } public override init() { /** Interface Builder support https://developer.apple.com/documentation/xcode_release_notes/xcode_10_2_release_notes/swift_5_release_notes_for_xcode_10_2 From known issue no.2: > To reduce the size taken up by Swift metadata, convenience initializers defined in Swift now only allocate an > object ahead of time if they’re calling a designated initializer defined in Objective-C. In most cases, this > has no effect on your program, but if your convenience initializer is called from Objective-C, the initial > allocation from +alloc is released without any initializer being called. */ self.primaryMaskFormat = "" self.autocomplete = true self.autocompleteOnFocus = true self.autoskip = false self.rightToLeft = false self.affineFormats = [] self.affinityCalculationStrategy = .wholeString self.customNotations = [] self.onMaskedTextChangedCallback = nil self.allowSuggestions = true super.init() } /** Maximal length of the text inside the field. - returns: Total available count of mandatory and optional characters inside the text field. */ open var placeholder: String { return primaryMask.placeholder } /** Minimal length of the text inside the field to fill all mandatory characters in the mask. - returns: Minimal satisfying count of characters inside the text field. */ open var acceptableTextLength: Int { return primaryMask.acceptableTextLength } /** Maximal length of the text inside the field. - returns: Total available count of mandatory and optional characters inside the text field. */ open var totalTextLength: Int { return primaryMask.totalTextLength } /** Minimal length of the extracted value with all mandatory characters filled. - returns: Minimal satisfying count of characters in extracted value. */ open var acceptableValueLength: Int { return primaryMask.acceptableValueLength } /** Maximal length of the extracted value. - returns: Total available count of mandatory and optional characters for extracted value. */ open var totalValueLength: Int { return primaryMask.totalValueLength } @discardableResult open func put(text: String, into textView: UITextView, autocomplete putAutocomplete: Bool? = nil) -> Mask.Result { let autocomplete: Bool = putAutocomplete ?? self.autocomplete let mask: Mask = pickMask( forText: CaretString( string: text, caretPosition: text.endIndex, caretGravity: CaretString.CaretGravity.forward(autocomplete: autocomplete) ) ) let result: Mask.Result = mask.apply( toText: CaretString( string: text, caretPosition: text.endIndex, caretGravity: CaretString.CaretGravity.forward(autocomplete: autocomplete) ) ) textView.text = result.formattedText.string textView.cursorPosition = result.formattedText.string.distanceFromStartIndex( to: result.formattedText.caretPosition ) notifyOnMaskedTextChangedListeners(forTextView: textView, result: result) return result } open func textViewShouldBeginEditing(_ textView: UITextView) -> Bool { return listener?.textViewShouldBeginEditing?(textView) ?? true } open func textViewDidBeginEditing(_ textView: UITextView) { if autocompleteOnFocus && textView.text.isEmpty { let result: Mask.Result = put(text: "", into: textView, autocomplete: true) notifyOnMaskedTextChangedListeners(forTextView: textView, result: result) } listener?.textViewDidBeginEditing?(textView) } open func textViewShouldEndEditing(_ textView: UITextView) -> Bool { return listener?.textViewShouldEndEditing?(textView) ?? true } open func textViewDidEndEditing(_ textView: UITextView) { listener?.textViewDidEndEditing?(textView) } open func textView( _ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String ) -> Bool { // UITextView edge case let updatedText: String = replaceCharacters(inText: textView.text ?? "", range: range, withCharacters: text) // https://stackoverflow.com/questions/52131894/shouldchangecharactersin-combined-with-suggested-text if (allowSuggestions && text == " " && updatedText == " ") { return true } let isDeletion = (0 < range.length && 0 == text.count) || (0 == range.length && 0 == range.location && 0 == text.count) let useAutocomplete = isDeletion ? false : autocomplete let useAutoskip = isDeletion ? autoskip : false let caretGravity: CaretString.CaretGravity = isDeletion ? .backward(autoskip: useAutoskip) : .forward(autocomplete: useAutocomplete) let caretPositionInt: Int = isDeletion ? range.location : range.location + text.count let caretPosition: String.Index = updatedText.startIndex(offsetBy: caretPositionInt) let text = CaretString(string: updatedText, caretPosition: caretPosition, caretGravity: caretGravity) let mask: Mask = pickMask(forText: text) let result: Mask.Result = mask.apply(toText: text) textView.text = result.formattedText.string if self.atomicCursorMovement { textView.cursorPosition = result.formattedText.string.distanceFromStartIndex( to: result.formattedText.caretPosition ) } else { DispatchQueue.main.asyncAfter(deadline: DispatchTime.now()) { textView.cursorPosition = result.formattedText.string.distanceFromStartIndex( to: result.formattedText.caretPosition ) } } notifyOnMaskedTextChangedListeners(forTextView: textView, result: result) return false } open func textViewDidChange(_ textView: UITextView) { listener?.textViewDidChange?(textView) } open func textViewDidChangeSelection(_ textView: UITextView) { listener?.textViewDidChangeSelection?(textView) } @available(iOS 10.0, *) open func textView(_ textView: UITextView, shouldInteractWith URL: URL, in characterRange: NSRange, interaction: UITextItemInteraction) -> Bool { return listener?.textView?(textView, shouldInteractWith: URL, in: characterRange, interaction: interaction) ?? true } @available(iOS 10.0, *) open func textView(_ textView: UITextView, shouldInteractWith textAttachment: NSTextAttachment, in characterRange: NSRange, interaction: UITextItemInteraction) -> Bool { return listener?.textView?(textView, shouldInteractWith: textAttachment, in: characterRange, interaction: interaction) ?? true } @available(iOS, introduced: 7.0, deprecated: 10.0, message: "Use textView:shouldInteractWithURL:inRange:forInteractionType: instead") open func textView(_ textView: UITextView, shouldInteractWith URL: URL, in characterRange: NSRange) -> Bool { return listener?.textView?(textView, shouldInteractWith: URL, in: characterRange) ?? true } @available(iOS, introduced: 7.0, deprecated: 10.0, message: "Use textView:shouldInteractWithTextAttachment:inRange:forInteractionType: instead") open func textView(_ textView: UITextView, shouldInteractWith textAttachment: NSTextAttachment, in characterRange: NSRange) -> Bool { return listener?.textView?(textView, shouldInteractWith: textAttachment, in: characterRange) ?? true } open func replaceCharacters(inText text: String, range: NSRange, withCharacters newText: String) -> String { if 0 < range.length { let result = NSMutableString(string: text) result.replaceCharacters(in: range, with: newText) return result as String } else { let result = NSMutableString(string: text) result.insert(newText, at: range.location) return result as String } } open func pickMask(forText text: CaretString) -> Mask { guard !affineFormats.isEmpty else { return primaryMask } let primaryAffinity: Int = affinityCalculationStrategy.calculateAffinity(ofMask: primaryMask, forText: text, autocomplete: autocomplete) var masksAndAffinities: [MaskAndAffinity] = affineFormats.map { (affineFormat: String) -> MaskAndAffinity in let mask = try! maskGetOrCreate(withFormat: affineFormat, customNotations: customNotations) let affinity = affinityCalculationStrategy.calculateAffinity(ofMask: mask, forText: text, autocomplete: autocomplete) return MaskAndAffinity(mask: mask, affinity: affinity) }.sorted { (left: MaskAndAffinity, right: MaskAndAffinity) -> Bool in return left.affinity > right.affinity } var insertIndex: Int = -1 for (index, maskAndAffinity) in masksAndAffinities.enumerated() { if primaryAffinity >= maskAndAffinity.affinity { insertIndex = index break } } if (insertIndex >= 0) { masksAndAffinities.insert(MaskAndAffinity(mask: primaryMask, affinity: primaryAffinity), at: insertIndex) } else { masksAndAffinities.append(MaskAndAffinity(mask: primaryMask, affinity: primaryAffinity)) } return masksAndAffinities.first!.mask } open func notifyOnMaskedTextChangedListeners(forTextView textView: UITextView, result: Mask.Result) { listener?.textView?(textView, didFillMandatoryCharacters: result.complete, didExtractValue: result.extractedValue) onMaskedTextChangedCallback?(textView, result.extractedValue, result.complete) } private func maskGetOrCreate(withFormat format: String, customNotations: [Notation]) throws -> Mask { if rightToLeft { return try RTLMask.getOrCreate(withFormat: format, customNotations: customNotations) } return try Mask.getOrCreate(withFormat: format, customNotations: customNotations) } private struct MaskAndAffinity { let mask: Mask let affinity: Int } /** Workaround to support Interface Builder delegate outlets. Allows assigning ```MaskedTextViewDelegate.listener``` within the Interface Builder. Consider using ```MaskedTextViewDelegate.listener``` property from your source code instead of ```MaskedTextViewDelegate.delegate``` outlet. */ @IBOutlet public var delegate: NSObject? { get { return self.listener as? NSObject } set(newDelegate) { if let listener = newDelegate as? MaskedTextViewDelegateListener { self.listener = listener } } } }
mit
6fbfa6cdd189252a81eae6fc3316621e
39.300813
173
0.665456
5.232583
false
false
false
false
blg-andreasbraun/ProcedureKit
Sources/Cloud/CloudKitCapability.swift
2
4466
// // ProcedureKit // // Copyright © 2016 ProcedureKit. All rights reserved. // import CloudKit /** # Cloud Status Value represents the current CloudKit status for the user. CloudKit has a relatively convoluted status API. First, we must check the user's accout status, i.e. are they logged in to iCloud. Next, we check the status for the application permissions. Then, we might need to request the application permissions. */ public struct CloudKitStatus: AuthorizationStatus { public typealias Requirement = CKApplicationPermissions /// - returns: the CKAccountStatus public let account: CKAccountStatus /// - returns: the CKApplicationPermissionStatus? public let permissions: CKApplicationPermissionStatus? /// - returns: any NSError? public let error: Error? /** Determine whether the application permissions have been met. This method takes into account, any errors received from CloudKit, the account status, application permission status, and the required application permissions. */ public func meets(requirement: CKApplicationPermissions?) -> Bool { guard error == nil else { return false } guard let requirement = requirement else { return account == .available } switch (requirement, account, permissions) { case ([], .available, _): return true case (_, .available, .some(.granted)) where requirement != []: return true default: return false } } } extension Capability { public class CloudKit: CapabilityProtocol { public private(set) var requirement: CKApplicationPermissions? internal let containerId: String? internal var storedRegistrar: CloudKitContainerRegistrar? = nil internal var registrar: CloudKitContainerRegistrar { get { storedRegistrar = storedRegistrar ?? containerId.map { CKContainer(identifier: $0) } ?? CKContainer.default() return storedRegistrar! } } public init(_ requirement: CKApplicationPermissions? = nil, containerId: String? = nil) { self.requirement = requirement self.containerId = containerId } public func isAvailable() -> Bool { return true } public func getAuthorizationStatus(_ completion: @escaping (CloudKitStatus) -> Void) { verifyAccountStatus(completion: completion) } public func requestAuthorization(withCompletion completion: @escaping () -> Void) { verifyAccountStatus(andPermissions: true, completion: { _ in completion() }) } func verifyAccountStatus(andPermissions shouldVerifyAndRequestPermissions: Bool = false, completion: @escaping (CloudKitStatus) -> Void) { let hasRequirements = requirement.map { $0 != [] } ?? false registrar.pk_accountStatus { [weak self] accountStatus, error in switch (accountStatus, hasRequirements) { case (.available, true): self?.verifyApplicationPermissions(andRequestPermission: shouldVerifyAndRequestPermissions, completion: completion) default: completion(CloudKitStatus(account: accountStatus, permissions: nil, error: error)) } } } func verifyApplicationPermissions(andRequestPermission shouldRequestPermission: Bool = false, completion: @escaping (CloudKitStatus) -> Void) { registrar.pk_status(forApplicationPermission: requirement!) { [weak self] permissionStatus, error in switch (permissionStatus, shouldRequestPermission) { case (.initialState, true): self?.requestPermissions(withCompletion: completion) default: completion(CloudKitStatus(account: .available, permissions: permissionStatus, error: error)) } } } func requestPermissions(withCompletion completion: @escaping (CloudKitStatus) -> Void) { DispatchQueue.main.async { self.registrar.pk_requestApplicationPermission(self.requirement!) { permissionStatus, error in completion(CloudKitStatus(account: .available, permissions: permissionStatus, error: error)) } } } } }
mit
14f840cb9f8618f4f9475978b3ac9fa5
35.008065
151
0.643225
5.471814
false
false
false
false
johnnysay/GoodAccountsMakeGoodFriends
Good Accounts/Models/Participant.swift
1
1663
// // Participant.swift // Good Accounts // // Created by Johnny on 12/02/2016. // Copyright © 2016 fake. All rights reserved. // import UIKit import RealmSwift import SwiftHEXColors /// Participant. class Participant: Object { /// Name of the participant. @objc dynamic var name = "" /// Initial investment of the participant. @objc dynamic var investment = 0.0 /// Current debt of the participant. @objc dynamic var debt = 0.0 /// Current deals of the participant. let deals = List<Deal>() /// Color hex string. @objc dynamic var colorHexString = UIColor.random.hexString /// Color to better identify the participant. var color: UIColor? { return UIColor(hexString: colorHexString) } convenience init(name: String, investment: Double) { self.init() self.name = name self.investment = investment } /// Gives money to another participant. /// This is done by modifying the debts of the two involved participants. /// - Parameter money: Money given. /// - Parameter participant: The other involved participant. func give(money: Double, to participant: Participant) { let realm = RealmManager.getRealm() try! realm.write { debt -= money participant.debt += money deals.append(Deal(transaction: .give, giver: self, receiver: participant, money: money)) participant.deals.append(Deal(transaction: .receive, giver: self, receiver: participant, money: money)) } } /// Get '.Give' deals. /// - Returns: The list of '.give' deals. func getGiveDeals() -> [Deal] { return deals.filter { $0.transaction == Transaction.give } } }
mit
52d37ea0cbd33a272a8dcc05395569a2
25.806452
115
0.669073
3.838337
false
false
false
false
jtsmrd/Intrview
ViewControllers/PersonalSummaryEditVC.swift
1
3468
// // PersonalSummaryEditVC.swift // SnapInterview // // Created by JT Smrdel on 1/16/17. // Copyright © 2017 SmrdelJT. All rights reserved. // import UIKit class PersonalSummaryEditVC: UIViewController, UITextViewDelegate { @IBOutlet weak var infoLabel: UILabel! @IBOutlet weak var personalSummaryTextView: UITextView! var profile = (UIApplication.shared.delegate as! AppDelegate).profile var currentFirstResponder: UIView! var navToolBar: UIToolbar! override func viewDidLoad() { super.viewDidLoad() let saveBarButtonItem = UIBarButtonItem(title: "Save", style: .plain, target: self, action: #selector(saveButtonAction)) saveBarButtonItem.tintColor = UIColor.white navigationItem.rightBarButtonItem = saveBarButtonItem let backBarButtonItem = UIBarButtonItem(image: UIImage(named: "left_icon"), style: .plain, target: self, action: #selector(backButtonAction)) backBarButtonItem.tintColor = UIColor.white navigationItem.leftBarButtonItem = backBarButtonItem if let personalSummary = profile.individualProfile?.personalSummary { personalSummaryTextView.text = personalSummary } else { personalSummaryTextView.text = "Personal Summary" } navToolBar = createKeyboardToolBar() } @objc func saveButtonAction() { if currentFirstResponder != nil { currentFirstResponder.resignFirstResponder() } profile.individualProfile?.personalSummary = personalSummaryTextView.text profile.save() let _ = navigationController?.popViewController(animated: true) } @objc func backButtonAction() { if currentFirstResponder != nil { currentFirstResponder.resignFirstResponder() } let _ = navigationController?.popViewController(animated: true) } func textViewShouldBeginEditing(_ textView: UITextView) -> Bool { textView.inputAccessoryView = navToolBar return true } func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool { guard let existingText = textView.text else { return true } let newLength = existingText.characters.count + text.characters.count - range.length return newLength <= 500 } func textViewDidBeginEditing(_ textView: UITextView) { currentFirstResponder = textView } // MARK: - Keyboard toolbar @objc func doneAction() { if currentFirstResponder != nil { currentFirstResponder.resignFirstResponder() } } private func createKeyboardToolBar() -> UIToolbar { let keyboardToolBar = UIToolbar(frame: CGRect(x: 0, y: 0, width: self.view.frame.size.width, height: 50)) keyboardToolBar.barStyle = .default let done = UIBarButtonItem(title: "Done", style: .plain, target: self, action: #selector(doneAction)) done.width = 50 done.tintColor = Global.greenColor let flexSpace = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.flexibleSpace, target: nil, action: nil) keyboardToolBar.items = [flexSpace, done] keyboardToolBar.sizeToFit() return keyboardToolBar } }
mit
dcbae24b2477b6ff063c22a4334718f0
32.019048
149
0.65013
5.565008
false
false
false
false
rymcol/Linux-Server-Side-Swift-Benchmarking
VaporJSON/App/main.swift
1
1544
import HTTP import HTTPRouting import Transport import TypeSafeRouting import Foundation import JSON #if os(Linux) import SwiftGlibc public func arc4random_uniform(_ max: UInt32) -> Int32 { return (SwiftGlibc.rand() % Int32(max-1)) + 1 } #endif final class App: HTTP.Responder { let router: Router let port = 8321 init() { router = Router() router.get("json") { req in var json: Bytes = "{ ".bytes for (key, value) in JSONCreator().generateJSON() { json += "\"".bytes json += key.bytes json += "\"".bytes json += " : ".bytes json += String(value).bytes json += ", ".bytes } json += " }".bytes return Response(status: .ok, headers: [ "Content-Type": "application/json; charset=utf-8" ], body: json) } } func respond(to request: Request) throws -> Response { if let handler = router.route(request, with: request) { return try handler.respond(to: request) } else { return Response(status: .notFound, body: "Not found.") } } } let app = App() let server = try Server<TCPServerStream, Parser<Request>, Serializer<Response>>(port: app.port) print("visit http://localhost:\(app.port)/") try server.start(responder: app) { error in print("Got error: \(error)") }
apache-2.0
aa03154e895886194bd48bb35709af97
24.733333
95
0.520078
4.312849
false
false
false
false
ashfurrow/RxSwift
RxTests/RxCocoaTests/DelegateProxyTest.swift
2
9026
// // DelegateProxyTest.swift // RxTests // // Created by Krunoslav Zaher on 7/5/15. // // import Foundation import XCTest import RxSwift import RxCocoa #if os(iOS) import UIKit #endif // MARK: Protocols @objc protocol TestDelegateProtocol { optional func testEventHappened(value: Int) } protocol TestDelegateControl: NSObjectProtocol { func doThatTest(value: Int) var test: Observable<Int> { get } } // MARK: Tests class DelegateProxyTest : RxTest { func test_OnInstallDelegateIsRetained() { let view = ThreeDSectionedView() let mock = MockThreeDSectionedViewProtocol() view.delegate = mock let _ = view.rx_proxy XCTAssertEqual(mock.messages, []) XCTAssertTrue(view.rx_proxy.forwardToDelegate() === mock) } func test_forwardsUnobservedMethods() { let view = ThreeDSectionedView() let mock = MockThreeDSectionedViewProtocol() view.delegate = mock let _ = view.rx_proxy view.delegate?.threeDView?(view, didLearnSomething: "Psssst ...") XCTAssertEqual(mock.messages, ["didLearnSomething"]) } func test_forwardsObservedMethods() { let view = ThreeDSectionedView() let mock = MockThreeDSectionedViewProtocol() view.delegate = mock var observedFeedRequest = false let d = view.rx_proxy.observe("threeDView:didLearnSomething:") .subscribeNext { n in observedFeedRequest = true } defer { d.dispose() } XCTAssertTrue(!observedFeedRequest) view.delegate?.threeDView?(view, didLearnSomething: "Psssst ...") XCTAssertTrue(observedFeedRequest) XCTAssertEqual(mock.messages, ["didLearnSomething"]) } func test_forwardsObserverDispose() { let view = ThreeDSectionedView() let mock = MockThreeDSectionedViewProtocol() view.delegate = mock var nMessages = 0 let d = view.rx_proxy.observe("threeDView:didLearnSomething:") .subscribeNext { n in nMessages++ } XCTAssertTrue(nMessages == 0) view.delegate?.threeDView?(view, didLearnSomething: "Psssst ...") XCTAssertTrue(nMessages == 1) d.dispose() view.delegate?.threeDView?(view, didLearnSomething: "Psssst ...") XCTAssertTrue(nMessages == 1) } func test_forwardsUnobservableMethods() { let view = ThreeDSectionedView() let mock = MockThreeDSectionedViewProtocol() view.delegate = mock view.delegate?.threeDView?(view, didLearnSomething: "Psssst ...") XCTAssertEqual(mock.messages, ["didLearnSomething"]) } func test_observesUnimplementedOptionalMethods() { let view = ThreeDSectionedView() let mock = MockThreeDSectionedViewProtocol() view.delegate = mock XCTAssertTrue(!mock.respondsToSelector("threeDView(threeDView:didGetXXX:")) let sentArgument = NSIndexPath(index: 0) var receivedArgument: NSIndexPath? = nil let d = view.rx_proxy.observe("threeDView:didGetXXX:") .subscribeNext { n in let ip = n[1] as! NSIndexPath receivedArgument = ip } defer { d.dispose() } XCTAssertTrue(receivedArgument === nil) view.delegate?.threeDView?(view, didGetXXX: sentArgument) XCTAssertTrue(receivedArgument === sentArgument) XCTAssertEqual(mock.messages, []) } func test_delegateProxyCompletesOnDealloc() { var view: ThreeDSectionedView! = ThreeDSectionedView() let mock = MockThreeDSectionedViewProtocol() view.delegate = mock let completed = RxMutableBox(false) autoreleasepool { XCTAssertTrue(!mock.respondsToSelector("threeDView(threeDView:didGetXXX:")) let sentArgument = NSIndexPath(index: 0) _ = view .rx_proxy .observe("threeDView:didGetXXX:") .subscribeCompleted { completed.value = true } view.delegate?.threeDView?(view, didGetXXX: sentArgument) } XCTAssertTrue(!completed.value) view = nil XCTAssertTrue(completed.value) } } #if os(iOS) extension DelegateProxyTest { func test_DelegateProxyHierarchyWorks() { let tableView = UITableView() _ = tableView.rx_delegate.observe("scrollViewWillBeginDragging:") } } #endif // MARK: Testing extensions extension DelegateProxyTest { func performDelegateTest<Control: TestDelegateControl>(@autoclosure createControl: () -> Control) { var control: TestDelegateControl! autoreleasepool { control = createControl() } var receivedValue: Int! var completed = false var deallocated = false autoreleasepool { _ = control.test.subscribe(onNext: { value in receivedValue = value }, onCompleted: { completed = true }) _ = (control as! NSObject).rx_deallocated.subscribeNext { _ in deallocated = true } } XCTAssertTrue(receivedValue == nil) autoreleasepool { control.doThatTest(382763) } XCTAssertEqual(receivedValue, 382763) XCTAssertFalse(deallocated) XCTAssertFalse(completed) autoreleasepool { control = nil } XCTAssertTrue(deallocated) XCTAssertTrue(completed) } } // MARK: Mocks // test case { class Food: NSObject { } @objc protocol ThreeDSectionedViewProtocol { func threeDView(threeDView: ThreeDSectionedView, listenToMeee: NSIndexPath) func threeDView(threeDView: ThreeDSectionedView, feedMe: NSIndexPath) func threeDView(threeDView: ThreeDSectionedView, howTallAmI: NSIndexPath) -> CGFloat optional func threeDView(threeDView: ThreeDSectionedView, didGetXXX: NSIndexPath) optional func threeDView(threeDView: ThreeDSectionedView, didLearnSomething: String) optional func threeDView(threeDView: ThreeDSectionedView, didFallAsleep: NSIndexPath) optional func threeDView(threeDView: ThreeDSectionedView, getMeSomeFood: NSIndexPath) -> Food } class ThreeDSectionedView: NSObject { var delegate: ThreeDSectionedViewProtocol? } // } // integration { class ThreeDSectionedViewDelegateProxy : DelegateProxy , ThreeDSectionedViewProtocol , DelegateProxyType { required init(parentObject: AnyObject) { super.init(parentObject: parentObject) } // delegate func threeDView(threeDView: ThreeDSectionedView, listenToMeee: NSIndexPath) { } func threeDView(threeDView: ThreeDSectionedView, feedMe: NSIndexPath) { } func threeDView(threeDView: ThreeDSectionedView, howTallAmI: NSIndexPath) -> CGFloat { return 1.1 } // integration class func setCurrentDelegate(delegate: AnyObject?, toObject object: AnyObject) { let view = object as! ThreeDSectionedView view.delegate = delegate as? ThreeDSectionedViewProtocol } class func currentDelegateFor(object: AnyObject) -> AnyObject? { let view = object as! ThreeDSectionedView return view.delegate } } extension ThreeDSectionedView { var rx_proxy: DelegateProxy { get { return proxyForObject(ThreeDSectionedViewDelegateProxy.self, self) } } } // } class MockThreeDSectionedViewProtocol : NSObject, ThreeDSectionedViewProtocol { var messages: [String] = [] func threeDView(threeDView: ThreeDSectionedView, listenToMeee: NSIndexPath) { messages.append("listenToMeee") } func threeDView(threeDView: ThreeDSectionedView, feedMe: NSIndexPath) { messages.append("feedMe") } func threeDView(threeDView: ThreeDSectionedView, howTallAmI: NSIndexPath) -> CGFloat { messages.append("howTallAmI") return 3 } /*func threeDView(threeDView: ThreeDSectionedView, didGetXXX: NSIndexPath) { messages.append("didGetXXX") }*/ func threeDView(threeDView: ThreeDSectionedView, didLearnSomething: String) { messages.append("didLearnSomething") } //optional func threeDView(threeDView: ThreeDSectionedView, didFallAsleep: NSIndexPath) func threeDView(threeDView: ThreeDSectionedView, getMeSomeFood: NSIndexPath) -> Food { messages.append("getMeSomeFood") return Food() } }
mit
eaa763022e037aebf31901cb976cfcc4
27.11838
103
0.619876
4.698594
false
true
false
false
AmitaiB/MyPhotoViewer
Pods/Cache/Source/Shared/Storage/TypeWrapperStorage.swift
1
1413
import Foundation /// Deal with top level primitive. Use TypeWrapper as wrapper /// Because we use `JSONEncoder` and `JSONDecoder`. /// Avoid issue like "Top-level T encoded as number JSON fragment" final class TypeWrapperStorage { let internalStorage: StorageAware init(storage: StorageAware) { self.internalStorage = storage } } extension TypeWrapperStorage: StorageAware { public func entry<T: Codable>(ofType type: T.Type, forKey key: String) throws -> Entry<T> { let wrapperEntry = try internalStorage.entry(ofType: TypeWrapper<T>.self, forKey: key) return Entry(object: wrapperEntry.object.object, expiry: wrapperEntry.expiry) } public func removeObject(forKey key: String) throws { try internalStorage.removeObject(forKey: key) } public func setObject<T: Codable>(_ object: T, forKey key: String, expiry: Expiry? = nil) throws { let wrapper = TypeWrapper<T>(object: object) try internalStorage.setObject(wrapper, forKey: key, expiry: expiry) } public func removeAll() throws { try internalStorage.removeAll() } public func removeExpiredObjects() throws { try internalStorage.removeExpiredObjects() } } /// Used to wrap Codable object struct TypeWrapper<T: Codable>: Codable { enum CodingKeys: String, CodingKey { case object } let object: T init(object: T) { self.object = object } }
mit
af9e31df291c3190122e0873772d852f
27.26
93
0.703468
4.307927
false
false
false
false
Acidburn0zzz/firefox-ios
Client/Frontend/Browser/DownloadQueue.swift
1
9617
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import Foundation protocol DownloadDelegate { func download(_ download: Download, didCompleteWithError error: Error?) func download(_ download: Download, didDownloadBytes bytesDownloaded: Int64) func download(_ download: Download, didFinishDownloadingTo location: URL) } class Download: NSObject { var delegate: DownloadDelegate? fileprivate(set) var filename: String fileprivate(set) var mimeType: String fileprivate(set) var isComplete = false fileprivate(set) var totalBytesExpected: Int64? fileprivate(set) var bytesDownloaded: Int64 override init() { self.filename = "unknown" self.mimeType = "application/octet-stream" self.bytesDownloaded = 0 super.init() } func cancel() {} func pause() {} func resume() {} fileprivate func uniqueDownloadPathForFilename(_ filename: String) throws -> URL { let downloadsPath = try FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false).appendingPathComponent("Downloads") let basePath = downloadsPath.appendingPathComponent(filename) let fileExtension = basePath.pathExtension let filenameWithoutExtension = fileExtension.count > 0 ? String(filename.dropLast(fileExtension.count + 1)) : filename var proposedPath = basePath var count = 0 while FileManager.default.fileExists(atPath: proposedPath.path) { count += 1 let proposedFilenameWithoutExtension = "\(filenameWithoutExtension) (\(count))" proposedPath = downloadsPath.appendingPathComponent(proposedFilenameWithoutExtension).appendingPathExtension(fileExtension) } return proposedPath } } class HTTPDownload: Download { let preflightResponse: URLResponse let request: URLRequest var state: URLSessionTask.State { return task?.state ?? .suspended } fileprivate(set) var session: URLSession? fileprivate(set) var task: URLSessionDownloadTask? private var resumeData: Data? // Used to avoid name spoofing using Unicode RTL char to change file extension public static func stripUnicode(fromFilename string: String) -> String { let allowed = CharacterSet.alphanumerics.union(CharacterSet.punctuationCharacters) return string.components(separatedBy: allowed.inverted).joined() } init?(preflightResponse: URLResponse, request: URLRequest) { self.preflightResponse = preflightResponse self.request = request // Verify scheme is a secure http or https scheme before moving forward with HTTPDownload initialization guard let scheme = request.url?.scheme, (scheme == "http" || scheme == "https") else { return nil } super.init() if let filename = preflightResponse.suggestedFilename { self.filename = HTTPDownload.stripUnicode(fromFilename: filename) } if let mimeType = preflightResponse.mimeType { self.mimeType = mimeType } self.totalBytesExpected = preflightResponse.expectedContentLength > 0 ? preflightResponse.expectedContentLength : nil self.session = URLSession(configuration: .default, delegate: self, delegateQueue: .main) self.task = session?.downloadTask(with: request) } override func cancel() { task?.cancel() } override func pause() { task?.cancel(byProducingResumeData: { resumeData in self.resumeData = resumeData }) } override func resume() { guard let resumeData = self.resumeData else { task?.resume() return } task = session?.downloadTask(withResumeData: resumeData) task?.resume() } } extension HTTPDownload: URLSessionTaskDelegate, URLSessionDownloadDelegate { func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) { // Don't bubble up cancellation as an error if the // error is `.cancelled` and we have resume data. if let urlError = error as? URLError, urlError.code == .cancelled, resumeData != nil { return } delegate?.download(self, didCompleteWithError: error) } func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) { bytesDownloaded = totalBytesWritten totalBytesExpected = totalBytesExpectedToWrite delegate?.download(self, didDownloadBytes: bytesWritten) } func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) { do { let destination = try uniqueDownloadPathForFilename(filename) try FileManager.default.moveItem(at: location, to: destination) isComplete = true delegate?.download(self, didFinishDownloadingTo: destination) } catch let error { delegate?.download(self, didCompleteWithError: error) } } } class BlobDownload: Download { fileprivate let data: Data init(filename: String, mimeType: String, size: Int64, data: Data) { self.data = data super.init() self.filename = filename self.mimeType = mimeType self.totalBytesExpected = size } override func resume() { // Wait momentarily before continuing here and firing off the delegate // callbacks. Otherwise, these may end up getting called before the // delegate is set up and the UI may never be notified of completion. DispatchQueue.main.asyncAfter(deadline: .now() + .milliseconds(500)) { do { let destination = try self.uniqueDownloadPathForFilename(self.filename) try self.data.write(to: destination) self.isComplete = true self.delegate?.download(self, didFinishDownloadingTo: destination) } catch let error { self.delegate?.download(self, didCompleteWithError: error) } } } } protocol DownloadQueueDelegate { func downloadQueue(_ downloadQueue: DownloadQueue, didStartDownload download: Download) func downloadQueue(_ downloadQueue: DownloadQueue, didDownloadCombinedBytes combinedBytesDownloaded: Int64, combinedTotalBytesExpected: Int64?) func downloadQueue(_ downloadQueue: DownloadQueue, download: Download, didFinishDownloadingTo location: URL) func downloadQueue(_ downloadQueue: DownloadQueue, didCompleteWithError error: Error?) } class DownloadQueue { var downloads: [Download] var delegate: DownloadQueueDelegate? var isEmpty: Bool { return downloads.isEmpty } fileprivate var combinedBytesDownloaded: Int64 = 0 fileprivate var combinedTotalBytesExpected: Int64? fileprivate var lastDownloadError: Error? init() { self.downloads = [] } func enqueue(_ download: Download) { // Clear the download stats if the queue was empty at the start. if downloads.isEmpty { combinedBytesDownloaded = 0 combinedTotalBytesExpected = 0 lastDownloadError = nil } downloads.append(download) download.delegate = self if let totalBytesExpected = download.totalBytesExpected, combinedTotalBytesExpected != nil { combinedTotalBytesExpected! += totalBytesExpected } else { combinedTotalBytesExpected = nil } download.resume() delegate?.downloadQueue(self, didStartDownload: download) } func cancelAll() { for download in downloads where !download.isComplete { download.cancel() } } func pauseAll() { for download in downloads where !download.isComplete { download.pause() } } func resumeAll() { for download in downloads where !download.isComplete { download.resume() } } } extension DownloadQueue: DownloadDelegate { func download(_ download: Download, didCompleteWithError error: Error?) { guard let error = error, let index = downloads.firstIndex(of: download) else { return } lastDownloadError = error downloads.remove(at: index) if downloads.isEmpty { delegate?.downloadQueue(self, didCompleteWithError: lastDownloadError) } } func download(_ download: Download, didDownloadBytes bytesDownloaded: Int64) { combinedBytesDownloaded += bytesDownloaded delegate?.downloadQueue(self, didDownloadCombinedBytes: combinedBytesDownloaded, combinedTotalBytesExpected: combinedTotalBytesExpected) } func download(_ download: Download, didFinishDownloadingTo location: URL) { guard let index = downloads.firstIndex(of: download) else { return } downloads.remove(at: index) delegate?.downloadQueue(self, download: download, didFinishDownloadingTo: location) NotificationCenter.default.post(name: .FileDidDownload, object: location) if downloads.isEmpty { delegate?.downloadQueue(self, didCompleteWithError: lastDownloadError) } } }
mpl-2.0
3acf4520248332d6e9730d1f54f77ff5
32.982332
176
0.671831
5.458002
false
false
false
false
NickDovgenko/projectmeal
projectmeal/projectmeal/RecipeCollection.swift
1
8148
// // RecipeCollection.swift // Мои рецепты // // Created by Nick on 04.10.16. // Copyright © 2016 Nick. All rights reserved. // import UIKit import CoreData @available(iOS 10.0, *) class RecipeCollection: UIViewController,UICollectionViewDelegate,UICollectionViewDataSource,NSFetchedResultsControllerDelegate { @IBOutlet weak var collectionCustomView: UICollectionView! var recipes: [Recipe] = [] var filterRecipes: [Recipe] = [] var deliverRecipe = [NSManagedObject]() var request: NSFetchedResultsController<Recipe>! var menuView: BTNavigationDropdownMenu! var menuSelected: String = "Все рецепты" @IBAction func dismissController(_ sender: UISwipeGestureRecognizer) { self.dismiss(animated: true, completion: {}) } override func viewDidLoad() { super.viewDidLoad() let items = ["Все рецепты", "Избранное", "Первые блюда", "Вторые блюда", "Салаты", "Закуски", "Десерты", "Напитки", "Разное"] //Прозрачный Navigation bar self.navigationController?.navigationBar.barStyle = UIBarStyle.blackTranslucent self.navigationController?.navigationBar.titleTextAttributes = [NSForegroundColorAttributeName: UIColor.white] menuView = BTNavigationDropdownMenu(navigationController: self.navigationController, containerView: self.navigationController!.view, title: "Все рецепты", items: items as [AnyObject]) menuView.cellHeight = 50 menuView.cellBackgroundColor = self.navigationController?.navigationBar.barTintColor menuView.cellSelectionColor = UIColor(red: 0.0/255.0, green:0.0/255.0, blue:0.0/255.0, alpha: 0.3) menuView.shouldKeepSelectedCellColor = true menuView.cellTextLabelColor = UIColor.white menuView.cellTextLabelAlignment = .center menuView.arrowPadding = 15 menuView.animationDuration = 0.5 menuView.maskBackgroundColor = UIColor.black menuView.maskBackgroundOpacity = 0.3 menuView.didSelectItemAtIndexHandler = {(indexPath: Int) -> () in print("Did select item at index: \(indexPath)") if items[indexPath] == "Все рецепты" { self.menuSelected = items[indexPath] self.filterContentForSearchText(searchText: self.menuSelected) print(self.menuSelected) } else if items[indexPath] == "Избранное" { self.menuSelected = items[indexPath] self.filterContentForSearchText(searchText: self.menuSelected) print(self.menuSelected) } else if items[indexPath] == "Первые блюда" { self.menuSelected = items[indexPath] self.filterContentForSearchText(searchText: self.menuSelected) print(self.menuSelected) } else if items[indexPath] == "Вторые блюда" { self.menuSelected = items[indexPath] self.filterContentForSearchText(searchText: self.menuSelected) print(self.menuSelected) } else if items[indexPath] == "Салаты" { self.menuSelected = items[indexPath] self.filterContentForSearchText(searchText: self.menuSelected) print(self.menuSelected) } else if items[indexPath] == "Закуски" { self.menuSelected = items[indexPath] self.filterContentForSearchText(searchText: self.menuSelected) print(self.menuSelected) } else if items[indexPath] == "Десерты" { self.menuSelected = items[indexPath] self.filterContentForSearchText(searchText: self.menuSelected) print(self.menuSelected) } else if items[indexPath] == "Напитки" { self.menuSelected = items[indexPath] self.filterContentForSearchText(searchText: self.menuSelected) print(self.menuSelected) } else if items[indexPath] == "Разное" { self.menuSelected = items[indexPath] self.filterContentForSearchText(searchText: self.menuSelected) print(self.menuSelected) } } self.navigationItem.titleView = menuView self.automaticallyAdjustsScrollViewInsets = false self.collectionCustomView.contentInset = UIEdgeInsets(top: 60, left: 20, bottom: 30, right: 20) let fetchRequest = NSFetchRequest<Recipe>(entityName: "Recipe") let sortDescriptor = NSSortDescriptor(key: "name", ascending: true) fetchRequest.sortDescriptors = [sortDescriptor] if let managedObjectContext = (UIApplication.shared.delegate as? AppDelegate)?.managedObjectContext { request = NSFetchedResultsController(fetchRequest: fetchRequest , managedObjectContext: managedObjectContext, sectionNameKeyPath: nil, cacheName: nil) request.delegate = self do { try request.performFetch() recipes = request.fetchedObjects! } catch { print("Ошибка") } } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } func filterContentForSearchText(searchText: String) { if searchText != "Избранное" { filterRecipes = recipes.filter { recipe in return recipe.type.lowercased().contains(searchText.lowercased()) } } else { filterRecipes = recipes.filter { recipe in return recipe.favorite == true } } self.collectionCustomView.reloadData() } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { if menuSelected != "Все рецепты" { return self.filterRecipes.count } return recipes.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath as IndexPath) as! RecipeCollectionViewCell if menuSelected == "Все рецепты" { cell.recipeName.text = self.recipes[indexPath.item].name cell.recipeImage.image = UIImage(data: recipes[indexPath.item].photo1 as! Data) cell.recipeImage.layer.cornerRadius = 20 cell.recipeImage.clipsToBounds = true } else { cell.recipeName.text = self.filterRecipes[indexPath.item].name cell.recipeImage.image = UIImage(data: filterRecipes[indexPath.item].photo1 as! Data) cell.recipeImage.layer.cornerRadius = 20 cell.recipeImage.clipsToBounds = true } return cell } // Выбор ячейки func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { if menuSelected == "Все рецепты" { deliverRecipe = [recipes[indexPath.item]] } else { deliverRecipe = [filterRecipes[indexPath.item]] } self.performSegue(withIdentifier: "detailView", sender: indexPath) print(deliverRecipe) } // Переход в Detail View override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "detailView" { let secondScene: DetailViewController = segue.destination as! DetailViewController secondScene.recipe = deliverRecipe print("RecipesList", recipes) } } func itemSelected(withIndex: Int, name: String) { print("\(name) selected"); } }
apache-2.0
0a292b69c1efab04daeec8e4efd3f897
40.119792
191
0.626852
4.993675
false
false
false
false
davidlivadaru/DLAngle
Sources/DLAngle/Trigonometry/Trigonometry+InverseHyperbolicTrigonometricFunctions.swift
1
5370
// // Trigonometry+InverseHyperbolicTrigonometricFunctions.swift // DLAngle // // Created by David Livadaru on 12/26/17. // import Foundation #if !os(Linux) import CoreGraphics #endif extension Trigonometry { static func asinh(_ value: Double) -> Double { let angle = GenericTrigonometry.asinh(value) return angle } public static func asinh(_ value: Double) -> Radian { return Radian(rawValue: asinh(value)) } public static func asinh(_ value: Float) -> Radian { return Radian(float: GenericTrigonometry.asinh(value)) } #if !os(Linux) static func asinh(_ value: CGFloat) -> CGFloat { let angle = GenericTrigonometry.asinh(Double(value)) return CGFloat(angle) } public static func asinh(_ value: CGFloat) -> Radian { return Radian(cgFloat: asinh(value)) } #endif static func acosh(_ value: Double) throws -> Double { try validate(value: value, for: .acosh) let angle = GenericTrigonometry.acosh(value) return angle } public static func acosh(_ value: Double) throws -> Radian { let acoshValue: Double = try acosh(value) return Radian(rawValue: acoshValue) } public static func acosh(_ value: Float) throws -> Radian { let acoshValue: Double = try acosh(Double(value)) return Radian(rawValue: acoshValue) } #if !os(Linux) static func acosh(_ value: CGFloat) throws -> CGFloat { try validate(value: value, for: .acosh) let angle = GenericTrigonometry.acosh(Double(value)) return CGFloat(angle) } public static func acosh(_ value: CGFloat) throws -> Radian { let acoshValue: CGFloat = try acosh(value) return Radian(cgFloat: acoshValue) } #endif static func atanh(_ value: Double) throws -> Double { try validate(value: value, for: .atanh) let angle = GenericTrigonometry.atanh(value) return angle } public static func atanh(_ value: Double) throws -> Radian { let atanhValue: Double = try atanh(value) return Radian(rawValue: atanhValue) } public static func atanh(_ value: Float) throws -> Radian { let atanhValue: Double = try atanh(Double(value)) return Radian(rawValue: atanhValue) } #if !os(Linux) static func atanh(_ value: CGFloat) throws -> CGFloat { try validate(value: value, for: .atanh) let angle = GenericTrigonometry.atanh(Double(value)) return CGFloat(angle) } public static func atanh(_ value: CGFloat) throws -> Radian { let atanhValue: CGFloat = try atanh(value) return Radian(cgFloat: atanhValue) } #endif static func acoth(_ value: Double) throws -> Double { try validate(value: value, for: .acoth) return log((value + 1) / (value - 1)) / 2.0 } public static func acoth(_ value: Double) throws -> Radian { let acothValue: Double = try acoth(value) return Radian(rawValue: acothValue) } public static func acoth(_ value: Float) throws -> Radian { let acothValue: Double = try acoth(Double(value)) return Radian(rawValue: acothValue) } #if !os(Linux) static func acoth(_ value: CGFloat) throws -> CGFloat { let acothValue: Double = try acoth(Double(value)) return CGFloat(acothValue) } public static func acoth(_ value: CGFloat) throws -> Radian { let acothValue: CGFloat = try acoth(value) return Radian(cgFloat: acothValue) } #endif static func asech(_ value: Double) throws -> Double { try validate(value: value, for: .asech) return log(1.0 / value + sqrt(1.0 / value - 1.0) * sqrt(1.0 / value + 1.0)) } public static func asech(_ value: Double) throws -> Radian { let asechValue: Double = try asech(value) return Radian(rawValue: asechValue) } public static func asech(_ value: Float) throws -> Radian { let asechValue: Double = try asech(Double(value)) return Radian(rawValue: asechValue) } #if !os(Linux) static func asech(_ value: CGFloat) throws -> CGFloat { let asechValue: Double = try asech(Double(value)) return CGFloat(asechValue) } public static func asech(_ value: CGFloat) throws -> Radian { let asechValue: CGFloat = try asech(value) return Radian(cgFloat: asechValue) } #endif static func acsch(_ value: Double) throws -> Double { try validate(value: value, for: .acsch) return log(1.0 / value + sqrt(1.0 / pow(value, 2.0) + 1.0)) } public static func acsch(_ value: Double) throws -> Radian { let acschValue: Double = try acsch(value) return Radian(rawValue: acschValue) } public static func acsch(_ value: Float) throws -> Radian { let acschValue: Double = try acsch(Double(value)) return Radian(rawValue: acschValue) } #if !os(Linux) static func acsch(_ value: CGFloat) throws -> CGFloat { let acschValue: Double = try acsch(Double(value)) return CGFloat(acschValue) } public static func acsch(_ value: CGFloat) throws -> Radian { let acschValue: CGFloat = try acsch(value) return Radian(cgFloat: acschValue) } #endif }
mit
1dd1a007772b97b707571ec8a72f0db9
29.511364
83
0.624395
3.863309
false
false
false
false
tbaranes/FittableFontLabel
Source/UILabelExtension.swift
1
5798
// FittableLabel.swift // // Copyright (c) 2016 Tom Baranes (https://github.com/tbaranes) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import UIKit extension UILabel { /** Resize the font to make the current text fit the label frame. - parameter maxFontSize: The max font size available - parameter minFontScale: The min font scale that the font will have - parameter rectSize: Rect size where the label must fit */ public func fontSizeToFit(maxFontSize: CGFloat = 100, minFontScale: CGFloat = 0.1, rectSize: CGSize? = nil) { guard let unwrappedText = self.text else { return } let newFontSize = fontSizeThatFits(text: unwrappedText, maxFontSize: maxFontSize, minFontScale: minFontScale, rectSize: rectSize) font = font.withSize(newFontSize) } /** Returns a font size of a specific string in a specific font that fits a specific size - parameter text: The text to use - parameter maxFontSize: The max font size available - parameter minFontScale: The min font scale that the font will have - parameter rectSize: Rect size where the label must fit */ public func fontSizeThatFits(text string: String, maxFontSize: CGFloat = 100, minFontScale: CGFloat = 0.1, rectSize: CGSize? = nil) -> CGFloat { let maxFontSize = maxFontSize.isNaN ? 100 : maxFontSize let minFontScale = minFontScale.isNaN ? 0.1 : minFontScale let minimumFontSize = maxFontSize * minFontScale let rectSize = rectSize ?? bounds.size guard !string.isEmpty else { return self.font.pointSize } let constraintSize = numberOfLines == 1 ? CGSize(width: CGFloat.greatestFiniteMagnitude, height: rectSize.height) : CGSize(width: rectSize.width, height: CGFloat.greatestFiniteMagnitude) let calculatedFontSize = binarySearch(string: string, minSize: minimumFontSize, maxSize: maxFontSize, size: rectSize, constraintSize: constraintSize) return (calculatedFontSize * 10.0).rounded(.down) / 10.0 } } // MARK: - Helpers extension UILabel { private func currentAttributedStringAttributes() -> [NSAttributedString.Key: Any] { var newAttributes = [NSAttributedString.Key: Any]() attributedText?.enumerateAttributes(in: NSRange(0..<(text?.count ?? 0)), options: .longestEffectiveRangeNotRequired, using: { attributes, _, _ in newAttributes = attributes }) return newAttributes } } // MARK: - Search extension UILabel { private enum FontSizeState { case fit, tooBig, tooSmall } private func binarySearch(string: String, minSize: CGFloat, maxSize: CGFloat, size: CGSize, constraintSize: CGSize) -> CGFloat { let fontSize = (minSize + maxSize) / 2 var attributes = currentAttributedStringAttributes() attributes[NSAttributedString.Key.font] = font.withSize(fontSize) let rect = string.boundingRect(with: constraintSize, options: .usesLineFragmentOrigin, attributes: attributes, context: nil) let state = numberOfLines == 1 ? singleLineSizeState(rect: rect, size: size) : multiLineSizeState(rect: rect, size: size) // if the search range is smaller than 0.1 of a font size we stop // returning either side of min or max depending on the state let diff = maxSize - minSize guard diff > 0.1 else { switch state { case .tooSmall: return maxSize default: return minSize } } switch state { case .fit: return fontSize case .tooBig: return binarySearch(string: string, minSize: minSize, maxSize: fontSize, size: size, constraintSize: constraintSize) case .tooSmall: return binarySearch(string: string, minSize: fontSize, maxSize: maxSize, size: size, constraintSize: constraintSize) } } private func singleLineSizeState(rect: CGRect, size: CGSize) -> FontSizeState { if rect.width >= size.width + 10 && rect.width <= size.width { return .fit } else if rect.width > size.width { return .tooBig } else { return .tooSmall } } private func multiLineSizeState(rect: CGRect, size: CGSize) -> FontSizeState { // if rect within 10 of size if rect.height < size.height + 10 && rect.height > size.height - 10 && rect.width > size.width + 10 && rect.width < size.width - 10 { return .fit } else if rect.height > size.height || rect.width > size.width { return .tooBig } else { return .tooSmall } } }
mit
8321e826308ea86ed7f28809e8f5faff
39.830986
157
0.665747
4.61257
false
false
false
false
NordicSemiconductor/IOS-Pods-DFU-Library
iOSDFULibrary/Classes/Implementation/DFUPeripheralSelector.swift
1
2384
/* * Copyright (c) 2019, Nordic Semiconductor * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, this * list of conditions and the following disclaimer in the documentation and/or * other materials provided with the distribution. * * 3. Neither the name of the copyright holder nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ import CoreBluetooth /// The default selector. /// /// Selects the first device with Legacy or Secure DFU Service UUID in the advertising packet. @objc open class DFUPeripheralSelector : NSObject, DFUPeripheralSelectorDelegate { open func select(_ peripheral: CBPeripheral, advertisementData: [String : AnyObject], RSSI: NSNumber, hint name: String? = nil) -> Bool { // peripheral.name may be cached, use the name from advertising data if let name = name, let localName = advertisementData[CBAdvertisementDataLocalNameKey] as? String { return localName == name } return true } open func filterBy(hint dfuServiceUUID: CBUUID) -> [CBUUID]? { return [dfuServiceUUID] } }
bsd-3-clause
8940061e0498f711a500945a419d41f0
43.148148
94
0.727349
4.946058
false
false
false
false
alimysoyang/CommunicationDebugger
CommunicationDebugger/AYHTCPClientSocket.swift
1
1454
// // AYHTCPClientSocket.swift // CommunicationDebugger // // Created by alimysoyang on 15/11/23. // Copyright © 2015年 alimysoyang. All rights reserved. // import Foundation /** * TCP服务端管理的TCP客户端连接的对象 */ class AYHTCPClientSocket: NSObject, NSCopying { // MARK: - properties var host:String?; var port:UInt16?; var socket:GCDAsyncSocket?; // MARK: - life cycle override init() { super.init(); self.host = ""; self.port = 0; self.socket = nil; } convenience init(clientSocket:GCDAsyncSocket) { self.init(); self.host = clientSocket.connectedHost; self.port = clientSocket.connectedPort; self.socket = clientSocket; } convenience init(tcpClientSocket:AYHTCPClientSocket) { self.init(); self.host = tcpClientSocket.host; self.port = tcpClientSocket.port; self.socket = tcpClientSocket.socket; } deinit { if let lSocket = self.socket { lSocket.disconnectAfterReadingAndWriting(); } self.socket = nil; } // MARK: - public methods func copyWithZone(zone: NSZone) -> AnyObject { let copyObject:AYHTCPClientSocket = AYHTCPClientSocket(); copyObject.host = self.host; copyObject.port = self.port; copyObject.socket = self.socket; return copyObject; } }
mit
6751161f17543b44b69f0702681f410a
21.25
65
0.605762
3.909341
false
false
false
false
steven7/ParkingApp
MapboxCoreNavigation/Constants.swift
2
5303
import Foundation import CoreLocation import MapboxDirections public let RouteControllerProgressDidChangeNotificationProgressKey = MBRouteControllerProgressDidChangeNotificationProgressKey public let RouteControllerProgressDidChangeNotificationLocationKey = MBRouteControllerProgressDidChangeNotificationLocationKey public let RouteControllerProgressDidChangeNotificationSecondsRemainingOnStepKey = MBRouteControllerProgressDidChangeNotificationSecondsRemainingOnStepKey public let RouteControllerAlertLevelDidChangeNotificationRouteProgressKey = MBRouteControllerAlertLevelDidChangeNotificationRouteProgressKey public let RouteControllerAlertLevelDidChangeNotificationDistanceToEndOfManeuverKey = MBRouteControllerAlertLevelDidChangeNotificationDistanceToEndOfManeuverKey public let RouteControllerNotificationShouldRerouteKey = MBRouteControllerNotificationShouldRerouteKey public let RouteControllerProgressDidChange = Notification.Name(MBRouteControllerNotificationProgressDidChange) public let RouteControllerAlertLevelDidChange = Notification.Name(MBRouteControllerAlertLevelDidChange) public let RouteControllerShouldReroute = Notification.Name(MBRouteControllerShouldReroute) /* Maximum number of meters the user can travel away from step before `RouteControllerShouldReroute` is emitted. */ public var RouteControllerMaximumDistanceBeforeRecalculating: CLLocationDistance = 50 /* Accepted deviation excluding horizontal accuracy before the user is considered to be off route. */ public var RouteControllerUserLocationSnappingDistance: CLLocationDistance = 10 /* Threshold user must be in within to count as completing a step. One of two heuristics used to know when a user completes a step, see `RouteControllerManeuverZoneRadius`. The users `heading` and the `finalHeading` are compared. If this number is within `RouteControllerMaximumAllowedDegreeOffsetForTurnCompletion`, the user has completed the step. */ public var RouteControllerMaximumAllowedDegreeOffsetForTurnCompletion: Double = 30 /* Number of seconds left on step when a `medium` alert is emitted. */ public var RouteControllerMediumAlertInterval: TimeInterval = 70 /* Number of seconds left on step when a `high` alert is emitted. */ public var RouteControllerHighAlertInterval: TimeInterval = 15 /* Radius in meters the user must enter to count as completing a step. One of two heuristics used to know when a user completes a step, see `RouteControllerMaximumAllowedDegreeOffsetForTurnCompletion`. */ public var RouteControllerManeuverZoneRadius: CLLocationDistance = 40 /* Maximum number of seconds the user can travel away from the start of the route before rerouting occurs */ public var MaxSecondsSpentTravelingAwayFromStartOfRoute: TimeInterval = 3 /* Distance in meters for the minimum length of a step for giving a `medium` alert. */ public var RouteControllerMinimumDistanceForMediumAlertDriving: CLLocationDistance = 400 public var RouteControllerMinimumDistanceForMediumAlertCycling: CLLocationDistance = 200 public var RouteControllerMinimumDistanceForMediumAlertWalking: CLLocationDistance = 100 public func RouteControllerMinimumDistanceForMediumAlert(identifier: MBDirectionsProfileIdentifier) -> CLLocationDistance { switch identifier { case MBDirectionsProfileIdentifier.automobileAvoidingTraffic: return RouteControllerMinimumDistanceForMediumAlertDriving case MBDirectionsProfileIdentifier.automobile: return RouteControllerMinimumDistanceForMediumAlertDriving case MBDirectionsProfileIdentifier.cycling: return RouteControllerMinimumDistanceForMediumAlertCycling case MBDirectionsProfileIdentifier.walking: return RouteControllerMinimumDistanceForMediumAlertWalking default: break } return RouteControllerMinimumDistanceForMediumAlertDriving } /* Distance in meters for the minimum length of a step for giving a `high` alert. */ public var RouteControllerMinimumDistanceForHighAlertDriving: CLLocationDistance = 100 public var RouteControllerMinimumDistanceForHighAlertCycling: CLLocationDistance = 60 public var RouteControllerMinimumDistanceForHighAlertWalking: CLLocationDistance = 20 public func RouteControllerMinimumDistanceForHighAlert(identifier: MBDirectionsProfileIdentifier) -> CLLocationDistance { switch identifier { case MBDirectionsProfileIdentifier.automobileAvoidingTraffic: return RouteControllerMinimumDistanceForHighAlertDriving case MBDirectionsProfileIdentifier.automobile: return RouteControllerMinimumDistanceForHighAlertDriving case MBDirectionsProfileIdentifier.cycling: return RouteControllerMinimumDistanceForHighAlertCycling case MBDirectionsProfileIdentifier.walking: return RouteControllerMinimumDistanceForHighAlertWalking default: break } return RouteControllerMinimumDistanceForHighAlertDriving } /* When calculating whether or not the user is on the route, we look where the user will be given their speed and this variable. */ public var RouteControllerDeadReckoningTimeInterval:TimeInterval = 1.0 /* Maximum angle the user puck will be rotated when snapping the user's course to the route line. */ public var RouteControllerMaxManipulatedCourseAngle:CLLocationDirection = 25
isc
49b200dd414fdb6ef54ccf195f0daf55
43.563025
199
0.848011
5.281873
false
false
false
false
AccessLite/BYT-Golden
BYT/Models/FoaasTemplate.swift
1
1922
// // FoaasTemplate.swift // AC3.2-BiteYourThumb // // Created by Louis Tur on 11/17/16. // Copyright © 2016 C4Q. All rights reserved. // import Foundation internal struct FoaasKey { internal static let from: String = "from" internal static let company: String = "company" internal static let tool: String = "tool" internal static let name: String = "name" internal static let doAction: String = "do" internal static let something: String = "something" internal static let thing: String = "thing" internal static let behavior: String = "behavior" internal static let language: String = "language" internal static let reaction: String = "reaction" internal static let noun: String = "noun" internal static let reference: String = "reference" } internal struct FoaasTemplate { let from: String let company: String? let tool: String? let name: String? let doAction: String? let something: String? let thing: String? let behavior: String? let language: String? let reaction: String? let noun: String? let reference: String? } extension FoaasTemplate: JSONConvertible { init?(json: [String : AnyObject]) { guard let jFrom = json[FoaasKey.from] as? String else { return nil } self.from = jFrom self.company = json[FoaasKey.company] as? String self.tool = json[FoaasKey.tool] as? String self.name = json[FoaasKey.name] as? String self.doAction = json[FoaasKey.doAction] as? String self.something = json[FoaasKey.something] as? String self.thing = json[FoaasKey.thing] as? String self.behavior = json[FoaasKey.behavior] as? String self.language = json[FoaasKey.language] as? String self.reaction = json[FoaasKey.reaction] as? String self.noun = json[FoaasKey.noun] as? String self.reference = json[FoaasKey.reference] as? String } func toJson() -> [String : AnyObject] { return [:] } }
mit
338c427492d2bf5f17b8690f6b2a0791
28.553846
59
0.695471
3.577281
false
false
false
false
artemkrachulov/AKImageCropperView
AKImageCropperView/IC_UIImageExtensions.swift
2
2320
// // IC_UIImageExtensions.swift // AKImageCropperView // // Created by Artem Krachulov. // Copyright (c) 2016 Artem Krachulov. All rights reserved. // import Foundation extension UIImage { /** Returns image cropped from selected rectangle. */ func ic_imageInRect(_ rect: CGRect) -> UIImage? { UIGraphicsBeginImageContext(rect.size) // Create the bitmap context guard let context = UIGraphicsGetCurrentContext() else { return nil } // Sets the clipping path to the intersection of the current clipping path with the area defined by the specified rectangle. context.clip(to: CGRect(origin: .zero, size: rect.size)) self.draw(in: CGRect(origin: CGPoint(x: -rect.origin.x, y: -rect.origin.y), size: self.size)) // Returns an image based on the contents of the current bitmap-based graphics context. let contextImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return contextImage } /** Returns image rotated by specified angle. */ func ic_rotateByAngle(_ angle: Double) -> UIImage? { // Calculate the size of the rotated view's containing box for our drawing space let rotatedViewBox = UIView(frame: CGRect(origin: .zero, size: self.size)) rotatedViewBox.transform = CGAffineTransform(rotationAngle: CGFloat(angle)) let rotatedSize = rotatedViewBox.frame.size UIGraphicsBeginImageContext(rotatedSize) // Create the bitmap context guard let context = UIGraphicsGetCurrentContext() else { return nil } context.translateBy(x: rotatedSize.width / 2.0, y: rotatedSize.height / 2.0) context.rotate(by: CGFloat(angle)) self.draw(in: CGRect(origin: CGPoint(x: -self.size.width / 2, y: -self.size.height / 2), size: self.size)) // Returns an image based on the contents of the current bitmap-based graphics context. let contextImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return contextImage } }
mit
c229abdff6c8b3f85fda6750d33b7489
31.676056
132
0.619828
5.213483
false
false
false
false
ClaudeChey/RSingleTickerView
RSingleTickerView/RSingleTickerView.swift
1
4286
// // RSingleTickerView.swift // RSTickrView // // Created by Claude Chey on 2015. 9. 23.. // Copyright © 2015년 Claude Chey. All rights reserved. // import Foundation import UIKit class RSingleTickerView: UIView { private var mTimerDelay:NSTimer? private var mTimer:NSTimer? private var mLabel:UILabel? private var mMoveInterval:Float = 0.05 private var mLeftMargin:Float = 0 private var mForceAnimate:Bool = false; // true: animating for (text width < view width ) var intervalGap:Float = 1.0 var intervalMilliseconds:Float { get { return mMoveInterval } set (interval) { assert( interval > 0 ) mMoveInterval = interval if mTimer != nil { stop() start() } } } var forceAnimate:Bool { get { return mForceAnimate } set (animate) { mForceAnimate = animate if mTimerDelay == nil && mTimer != nil { stop() start() } } } var leftMargin:Float { get { return mLeftMargin } set (margin) { mLeftMargin = margin if mTimer == nil { mLabel?.leftX += CGFloat(mLeftMargin) } } } var text:String? { get { return mLabel?.text } set (text) { mLabel?.text = text mLabel?.sizeToFit() } } var textColor:UIColor? { get { return mLabel?.textColor } set (color) { mLabel?.textColor = color } } var font:UIFont? { get { return mLabel?.font } set (font) { mLabel?.font = font mLabel?.sizeToFit() } } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override init(frame: CGRect) { super.init(frame: frame) layer.masksToBounds = true initWithLabel() } func initWithLabel() { mLabel = UILabel() mLabel?.textColor = UIColor.blackColor() mLabel?.font = UIFont.systemFontOfSize(12) mLabel?.sizeThatFits(frame.size) addSubview(mLabel!) } func reset() { mLabel?.leftX = CGFloat(mLeftMargin) + 0 } func textSize(text:String, font:UIFont)->CGSize { return (text as NSString).sizeWithAttributes([NSFontAttributeName:font]) } func startWithDelay(DelaySeconds delay:Float) { if mTimerDelay == nil && mTimer == nil { mTimerDelay = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: Selector("start"), userInfo: nil, repeats: false) } } func start() { if mTimerDelay != nil { mTimerDelay?.invalidate() mTimerDelay = nil } if mForceAnimate == false && mLabel?.width < width { return } if mTimer == nil { mTimer = NSTimer.scheduledTimerWithTimeInterval(NSTimeInterval(mMoveInterval), target: self, selector: Selector("tick:"), userInfo: nil, repeats: true) } } func stopWithReset() { stop() reset(); } func stop() { mTimer?.invalidate() mTimer = nil } func tick(timer:NSTimer) { mLabel?.leftX -= CGFloat(intervalGap) if mLabel?.rightX < 0 { mLabel?.leftX = CGFloat(mLeftMargin) + width } } } extension UIView { var leftX:CGFloat { get { return frame.origin.x } set (value) { var frm = frame frm.origin.x = value frame = frm } } var rightX:CGFloat { return frame.origin.x + frame.size.width } var width:CGFloat { return frame.size.width } var height:CGFloat { return frame.size.height } }
mit
cfcb6d5c7ec3ef49af438d44a711f36a
18.120536
163
0.487976
4.595494
false
false
false
false
papr/Dot-Producer
Dot Producer/Document.swift
1
3534
// // Document.swift // Dot Producer // // Created by Pablo Prietz on 27.02.15. // Copyright (c) 2015 Pablo Prietz. All rights reserved. // import Cocoa let SDPTurnFreqChangedNotification = "SDPTurnFreqChangedNotification" class Document: NSDocument { var dots: SDPDots = SDPDots() var turnFreq: NSTimeInterval = 0.25 { didSet { NSNotificationCenter.defaultCenter().postNotificationName(SDPTurnFreqChangedNotification, object: self) } } @IBOutlet var view: SDPDotView! override init() { super.init() // Add your subclass-specific initialization here. } override func windowControllerDidLoadNib(aController: NSWindowController) { super.windowControllerDidLoadNib(aController) } override class func autosavesInPlace() -> Bool { return true } override var windowNibName: String? { // Returns the nib file name of the document // If you need to use a subclass of NSWindowController or if your document supports multiple NSWindowControllers, you should remove this property and override -makeWindowControllers instead. return "Document" } override func dataOfType(typeName: String, error outError: NSErrorPointer) -> NSData? { // Insert code here to write your document to data of the specified type. If outError != nil, ensure that you create and set an appropriate error when returning nil. // You can also choose to override fileWrapperOfType:error:, writeToURL:ofType:error:, or writeToURL:ofType:forSaveOperation:originalContentsURL:error: instead. outError.memory = NSError(domain: NSOSStatusErrorDomain, code: unimpErr, userInfo: nil) return nil } override func readFromData(data: NSData, ofType typeName: String, error outError: NSErrorPointer) -> Bool { // Insert code here to read your document from the given data of the specified type. If outError != nil, ensure that you create and set an appropriate error when returning false. // You can also choose to override readFromFileWrapper:ofType:error: or readFromURL:ofType:error: instead. // If you override either of these, you should also override -isEntireFileLoaded to return NO if the contents are lazily loaded. outError.memory = NSError(domain: NSOSStatusErrorDomain, code: unimpErr, userInfo: nil) return false } @IBAction func export(sender: NSMenuItem) { let op = NSOpenPanel() op.title = "Dot Image Export Folder" op.canChooseDirectories = true op.canChooseFiles = false op.canCreateDirectories = true op.beginWithCompletionHandler { (result: Int) -> Void in if result == NSFileHandlingPanelOKButton { let exportedFileURL = op.URL! let imageRect: NSRect = NSRect( x: 0, y: 0, width: 2000, height: 2000) let viewOff = SDPDotView( frame: imageRect, dots: self, state: false) let viewOn = SDPDotView( frame: imageRect, dots: self, state: true) let imgOff: NSData = viewOff.viewData()! let imgOn : NSData = viewOn.viewData()! self.drawImagesToFiles([imgOff, imgOn], toFolder: exportedFileURL) } } } func drawImagesToFiles(images: [NSData], toFolder folder: NSURL) -> Bool { var success = true for turned in [false, true] { var filename = dots.fileDescription + (turned ? "_on" : "_off") + ".png" var loc = folder.URLByAppendingPathComponent(filename, isDirectory: false) var img = images[turned ? 1 : 0] let writesuc = img.writeToURL(loc, atomically: true) if !writesuc { success = false } } return success } func ShouldSerializeView() -> Bool { return false; } }
mit
15d1eedb49d2f03669743140d3961cb4
31.127273
192
0.72807
3.858079
false
false
false
false
jerrypupu111/LearnDrawingToolSet
SwiftGL-Demo/Source/VisualizationViewController.swift
1
11749
// // VisualizationViewController.swift // SwiftGL // // Created by jerry on 2016/8/14. // Copyright © 2016年 Jerry Chan. All rights reserved. // import UIKit //import Charts class VisualizationViewController:UIViewController { /* weak var delegate:PaintViewController! var graphView = ScrollableGraphView() var currentGraphType = GraphType.dark var graphConstraints = [NSLayoutConstraint]() var label = UILabel() var labelConstraints = [NSLayoutConstraint]() // Data let numberOfDataItems = 100 lazy var data: [Double] = self.generateRandomData(self.numberOfDataItems, max: 50) lazy var labels: [String] = self.generateSequentialLabels(self.numberOfDataItems, text: "FEB") @IBOutlet var barChartView: BarChartView! @IBOutlet var lineChartView: LineChartView! override func viewDidLoad() { /* super.viewDidLoad() graphView = createDarkGraph(self.view.frame) graphView.setData(data, withLabels: labels) self.view.addSubview(graphView) data = self.generateRandomData(self.numberOfDataItems, max: 50) let graphView2 = createDarkGraph(self.view.frame) graphView2.setData(data, withLabels: labels) self.view.addSubview(graphView2) setupConstraints() addLabel(withText: "DARK (TAP HERE)") */ super.viewDidLoad() //setChart(months, values: unitsSold) setArtwork(delegate.paintManager.artwork) } func addDataSet(_ name:String,values: [Double],color:UIColor){ var lineDataEntries:[ChartDataEntry] = [] for i in 0..<values.count { lineDataEntries.append(ChartDataEntry(x: Double(i), y: values[i])) } let lineChartDataSet = LineChartDataSet(values: lineDataEntries, label: name) lineChartDataSet.setColor(color) lineChartDataSet.fillColor = color lineChartDataSet.mode = .cubicBezier lineChartDataSet.drawFilledEnabled = true lineChartDataSet.drawCirclesEnabled = false if((lineChartData) != nil) { lineChartData.addDataSet(lineChartDataSet) } else { lineChartData = LineChartData(dataSet: lineChartDataSet) } lineChartView.data = lineChartData } var lineChartData:LineChartData! func setChart(_ dataPoints: [String], values: [Double]) { //barChartView.noDataTextDescription = "GIVE REASON" var dataEntries: [BarChartDataEntry] = [] var lineDataEntries:[ChartDataEntry] = [] for i in 0..<values.count { // //let dataEntry = BarChartDataEntry(x: values[i], y: Double(i)) //dataEntries.append(dataEntry) lineDataEntries.append(ChartDataEntry(x: Double(i), y: values[i])) } //let chartDataSet = BarChartDataSet(values: dataEntries,label: "Units Sold") //let chartData = BarChartData(dataSet:chartDataSet) //barChartView.data = chartData let lineChartDataSet = LineChartDataSet(values: lineDataEntries, label: "wtf") let lineChartData = LineChartData(dataSet: lineChartDataSet) lineChartView.data = lineChartData lineChartView.gridBackgroundColor = NSUIColor.black lineChartView.backgroundColor = UIColor.gray } func setArtwork(_ artwork:PaintArtwork) { let analyzer = StrokeAnalyzer() analyzer.analyze(artwork.currentClip.strokes) if(analyzer.lengths.count>0) { addDataSet("Force", values: analyzer.briefForces(),color:UIColor.cyan) addDataSet("Speed", values: analyzer.briefSpeeds(),color:UIColor.brown) addDataSet("Length", values: analyzer.briefLength(),color:UIColor.green) } //setChart([], values: ) } func didTap(_ gesture: UITapGestureRecognizer) { currentGraphType.next() self.view.removeConstraints(graphConstraints) graphView.removeFromSuperview() /* switch(currentGraphType) { case .Dark: addLabel(withText: "DARK") graphView = createDarkGraph(self.view.frame) case .Dot: addLabel(withText: "DOT") graphView = createDotGraph(self.view.frame) case .Bar: addLabel(withText: "BAR") graphView = createBarGraph(self.view.frame) case .Pink: addLabel(withText: "PINK") graphView = createPinkMountainGraph(self.view.frame) }*/ graphView.setData(data, withLabels: labels) self.view.insertSubview(graphView, belowSubview: label) setupConstraints() } fileprivate func createDarkGraph(_ frame: CGRect) -> ScrollableGraphView { let graphView = ScrollableGraphView(frame: frame) //graphView.backgroundFillColor = UIColor.colorFromHex("#333333") graphView.backgroundFillColor = UIColor(hue: 0, saturation: 0, brightness: 0, alpha: 0) graphView.lineWidth = 1 graphView.lineColor = UIColor.colorFromHex("#777777") graphView.lineStyle = ScrollableGraphViewLineStyle.smooth graphView.shouldFill = true graphView.fillType = ScrollableGraphViewFillType.gradient graphView.fillColor = UIColor.colorFromHex("#555555") graphView.fillGradientType = ScrollableGraphViewGradientType.linear graphView.fillGradientStartColor = UIColor.colorFromHex("#555555") graphView.fillGradientEndColor = UIColor.colorFromHex("#444444") graphView.dataPointSpacing = 2 graphView.dataPointSize = 1 graphView.dataPointFillColor = UIColor.white graphView.referenceLineLabelFont = UIFont.boldSystemFont(ofSize: 8) graphView.referenceLineColor = UIColor.white.withAlphaComponent(0.2) graphView.referenceLineLabelColor = UIColor.white graphView.numberOfIntermediateReferenceLines = 5 graphView.dataPointLabelColor = UIColor.white.withAlphaComponent(0.5) graphView.shouldAnimateOnStartup = false graphView.shouldAdaptRange = true graphView.adaptAnimationType = ScrollableGraphViewAnimationType.elastic graphView.animationDuration = 0.1 graphView.rangeMax = 50 graphView.shouldRangeAlwaysStartAtZero = true return graphView } fileprivate func setupConstraints() { self.graphView.translatesAutoresizingMaskIntoConstraints = false graphConstraints.removeAll() let topConstraint = NSLayoutConstraint(item: self.graphView, attribute: NSLayoutAttribute.top, relatedBy: NSLayoutRelation.equal, toItem: self.view, attribute: NSLayoutAttribute.top, multiplier: 1, constant: 0) let rightConstraint = NSLayoutConstraint(item: self.graphView, attribute: NSLayoutAttribute.right, relatedBy: NSLayoutRelation.equal, toItem: self.view, attribute: NSLayoutAttribute.right, multiplier: 1, constant: 0) let bottomConstraint = NSLayoutConstraint(item: self.graphView, attribute: NSLayoutAttribute.bottom, relatedBy: NSLayoutRelation.equal, toItem: self.view, attribute: NSLayoutAttribute.bottom, multiplier: 1, constant: 0) let leftConstraint = NSLayoutConstraint(item: self.graphView, attribute: NSLayoutAttribute.left, relatedBy: NSLayoutRelation.equal, toItem: self.view, attribute: NSLayoutAttribute.left, multiplier: 1, constant: 0) //let heightConstraint = NSLayoutConstraint(item: self.graphView, attribute: NSLayoutAttribute.Height, relatedBy: NSLayoutRelation.Equal, toItem: self.view, attribute: NSLayoutAttribute.Height, multiplier: 1, constant: 0) graphConstraints.append(topConstraint) graphConstraints.append(bottomConstraint) graphConstraints.append(leftConstraint) graphConstraints.append(rightConstraint) //graphConstraints.append(heightConstraint) self.view.addConstraints(graphConstraints) } // Adding and updating the graph switching label in the top right corner of the screen. fileprivate func addLabel(withText text: String) { label.removeFromSuperview() label = createLabel(withText: text) label.isUserInteractionEnabled = true let rightConstraint = NSLayoutConstraint(item: label, attribute: NSLayoutAttribute.right, relatedBy: NSLayoutRelation.equal, toItem: self.view, attribute: NSLayoutAttribute.right, multiplier: 1, constant: -20) let topConstraint = NSLayoutConstraint(item: label, attribute: NSLayoutAttribute.top, relatedBy: NSLayoutRelation.equal, toItem: self.view, attribute: NSLayoutAttribute.top, multiplier: 1, constant: 20) let heightConstraint = NSLayoutConstraint(item: label, attribute: NSLayoutAttribute.height, relatedBy: NSLayoutRelation.equal, toItem: nil, attribute: NSLayoutAttribute.notAnAttribute, multiplier: 1, constant: 40) let widthConstraint = NSLayoutConstraint(item: label, attribute: NSLayoutAttribute.width, relatedBy: NSLayoutRelation.equal, toItem: nil, attribute: NSLayoutAttribute.notAnAttribute, multiplier: 1, constant: label.frame.width * 1.5) let tapGestureRecogniser = UITapGestureRecognizer(target: self, action: #selector(didTap)) label.addGestureRecognizer(tapGestureRecogniser) self.view.insertSubview(label, aboveSubview: graphView) self.view.addConstraints([rightConstraint, topConstraint, heightConstraint, widthConstraint]) } fileprivate func createLabel(withText text: String) -> UILabel { let label = UILabel() label.backgroundColor = UIColor.black.withAlphaComponent(0.5) label.text = text label.textColor = UIColor.white label.textAlignment = NSTextAlignment.center label.font = UIFont.boldSystemFont(ofSize: 14) label.layer.cornerRadius = 2 label.clipsToBounds = true label.translatesAutoresizingMaskIntoConstraints = false label.sizeToFit() return label } fileprivate func generateRandomData(_ numberOfItems: Int, max: Double) -> [Double] { var data = [Double]() for _ in 0 ..< numberOfItems { var randomNumber = Double(random()).truncatingRemainder(dividingBy: max) if(random() % 100 < 10) { randomNumber *= 3 } data.append(randomNumber) } return data } fileprivate func generateSequentialLabels(_ numberOfItems: Int, text: String) -> [String] { var labels = [String]() for i in 0 ..< numberOfItems { labels.append("\(text) \(i+1)") } return labels } // The type of the current graph we are showing. enum GraphType { case dark case bar case dot case pink mutating func next() { switch(self) { case .dark: self = GraphType.bar case .bar: self = GraphType.dot case .dot: self = GraphType.pink case .pink: self = GraphType.dark } } } override var prefersStatusBarHidden : Bool { return true } */ }
mit
fa85a5953a0236a29900abf7ba7bdfe6
37.638158
240
0.644815
5.288609
false
false
false
false
slavasemeniuk/SVLoader
SVLoader/Classes/SVLoader.swift
1
3582
// // Loader.swift // Loader // // Created by Slava Semeniuk on 12/12/16. // Copyright © 2016 Slava Semeniuk. All rights reserved. // import UIKit open class SVLoader: NSObject { internal static let sharedLoader = SVLoader() internal var holderView: HolderView! open static fileprivate(set) var animating = false { didSet { sharedLoader.holderView.shouldAnimate = animating } } override init() { super.init() holderView = HolderView(frame: UIScreen.main.bounds) NotificationCenter.default.addObserver(self, selector: #selector(applicationDidBecomeActive), name: NSNotification.Name.UIApplicationDidBecomeActive, object: nil) } //MARK: - Window fileprivate func addHolderView() { guard let window = frontWindow() else { return } SVLoader.animating = true holderView.alpha = 0 window.addSubview(holderView) UIView.animate(withDuration: 0.4, animations: { self.holderView!.alpha = 1 }) } fileprivate func hideHolderView(completion: (()->Void)?) { UIView.animate(withDuration: 0.4, animations: { self.holderView?.alpha = 0 }, completion: { if $0 { SVLoader.animating = false SVLoader.sharedLoader.holderView.resetAllLayers() self.holderView.removeFromSuperview() completion?() } }) } fileprivate func frontWindow() -> UIWindow? { for window in UIApplication.shared.windows.reversed() { let onMainScreen = window.screen == UIScreen.main let windowLevelSupported = window.windowLevel <= UIWindowLevelNormal let windowsIsVisible = !window.isHidden && window.alpha > 0 if onMainScreen && windowsIsVisible && windowLevelSupported { return window } } return nil } //MARK: - Appication actions @objc fileprivate func applicationDidBecomeActive() { guard SVLoader.animating else { return } holderView.animateDots() } //MARK: - Interface open class func showLoaderWith(message: String) { if SVLoader.animating { return } sharedLoader.addHolderView() sharedLoader.holderView.showWith(message) } open class func show() { showLoaderWith(message: SVLoaderSettings.defaultLoadingMessage) } open class func showLoaderWith(messages: [String], changeInA seconds: TimeInterval) { if SVLoader.animating { return } sharedLoader.addHolderView() sharedLoader.holderView.showWith(messages: messages, timeInterval: seconds) } open class func hideWithSuccess(message: String? = nil, completion: (() -> Void)? = nil) { if !SVLoader.animating { completion?() return } var successMessage = "" if let text = message { successMessage = text } else { successMessage = SVLoaderSettings.defaultSuccessMessage } sharedLoader.holderView.hideWithSuccess(message: successMessage, completion: { sharedLoader.hideHolderView(completion: completion) }) } open class func hideLoader(_ completion: (() -> Void)? = nil) { guard SVLoader.animating else { completion?() return } sharedLoader.hideHolderView(completion: completion) } }
mit
2893e0808305cc4b20d3b3b822b7dc83
30.973214
170
0.603183
5.036568
false
false
false
false
vanshg/MacAssistant
Pods/Magnet/Lib/Magnet/HotKey.swift
1
3015
// // HotKey.swift // Magnet // // Created by 古林俊佑 on 2016/03/09. // Copyright © 2016年 Shunsuke Furubayashi. All rights reserved. // import Cocoa import Carbon public final class HotKey: NSObject { // MARK: - Properties public let identifier: String public let keyCombo: KeyCombo public let callback: ((HotKey) -> Void)? public let target: AnyObject? public let action: Selector? public let actionQueue: ActionQueue var hotKeyId: UInt32? var hotKeyRef: EventHotKeyRef? // MARK: - Enum Value public enum ActionQueue { case main case session public func execute(closure: @escaping () -> Void) { switch self { case .main: DispatchQueue.main.async { closure() } case .session: closure() } } } // MARK: - Initialize public init(identifier: String, keyCombo: KeyCombo, target: AnyObject, action: Selector, actionQueue: ActionQueue = .main) { self.identifier = identifier self.keyCombo = keyCombo self.callback = nil self.target = target self.action = action self.actionQueue = actionQueue super.init() } public init(identifier: String, keyCombo: KeyCombo, actionQueue: ActionQueue = .main, handler: @escaping ((HotKey) -> Void)) { self.identifier = identifier self.keyCombo = keyCombo self.callback = handler self.target = nil self.action = nil self.actionQueue = actionQueue super.init() } } // MARK: - Invoke public extension HotKey { public func invoke() { guard let callback = self.callback else { guard let target = self.target as? NSObject, let selector = self.action else { return } guard target.responds(to: selector) else { return } actionQueue.execute { [weak self] in guard let wSelf = self else { return } target.perform(selector, with: wSelf) } return } actionQueue.execute { [weak self] in guard let wSelf = self else { return } callback(wSelf) } } } // MARK: - Register & UnRegister public extension HotKey { @discardableResult public func register() -> Bool { return HotKeyCenter.shared.register(with: self) } public func unregister() { return HotKeyCenter.shared.unregister(with: self) } } // MARK: - override isEqual public extension HotKey { public override func isEqual(_ object: Any?) -> Bool { guard let hotKey = object as? HotKey else { return false } return self.identifier == hotKey.identifier && self.keyCombo == hotKey.keyCombo && self.hotKeyId == hotKey.hotKeyId && self.hotKeyRef == hotKey.hotKeyRef } }
mit
08ea2b3b7e67a9dcb1012fdb75d222f3
27.339623
130
0.574567
4.56535
false
false
false
false
audiokit/AudioKit
Sources/AudioKit/Internals/Hardware/Device.swift
2
2797
// Copyright AudioKit. All Rights Reserved. Revision History at http://github.com/AudioKit/AudioKit/ #if os(macOS) /// DeviceID isan AudioDeviceID on macOS public typealias DeviceID = AudioDeviceID #else /// DeviceID is a string on iOS public typealias DeviceID = String #endif import AVFoundation /// Wrapper for audio device selection public struct Device: Equatable, Hashable { /// The human-readable name for the device. public private(set) var name: String /// Number of input channels public private(set) var nInputChannels: Int? /// Number of output channels public private(set) var nOutputChannels: Int? /// The device identifier. public private(set) var deviceID: DeviceID /// Initialize the device /// /// - Parameters: /// - name: The human-readable name for the device. /// - deviceID: The device identifier. /// - dataSource: String describing data source /// public init(name: String, deviceID: DeviceID, dataSource: String = "") { self.name = name self.deviceID = deviceID #if !os(macOS) if dataSource != "" { self.deviceID = "\(deviceID) \(dataSource)" } #endif } #if os(macOS) /// Initialize the device /// - Parameter deviceID: DeviceID public init(deviceID: DeviceID) { self.init(name: AudioDeviceUtils.name(deviceID), deviceID: deviceID) nInputChannels = AudioDeviceUtils.inputChannels(deviceID) nOutputChannels = AudioDeviceUtils.outputChannels(deviceID) } #endif #if !os(macOS) /// Initialize the device /// /// - Parameters: /// - portDescription: A port description object that describes a single /// input or output port associated with an audio route. /// public init(portDescription: AVAudioSessionPortDescription) { let portData = [portDescription.uid, portDescription.selectedDataSource?.dataSourceName] let deviceID = portData.compactMap { $0 }.joined(separator: " ") self.init(name: portDescription.portName, deviceID: deviceID) } /// Return a port description matching the devices name. var portDescription: AVAudioSessionPortDescription? { return AVAudioSession.sharedInstance().availableInputs?.filter { $0.portName == name }.first } /// Return a data source matching the devices deviceID. var dataSource: AVAudioSessionDataSourceDescription? { let dataSources = portDescription?.dataSources ?? [] return dataSources.filter { deviceID.contains($0.dataSourceName) }.first } #endif } extension Device: CustomDebugStringConvertible { /// Printout for debug public var debugDescription: String { return "<Device: \(name) (\(deviceID))>" } }
mit
211d819c303aafe511ef9ae1e1f07356
32.698795
100
0.672149
4.724662
false
false
false
false
bwitt2/rendezvous
Rendezvous/GooglePlacesAutoComplete.swift
1
4942
// // GooglePlacesAutoComplete.swift // Rendezvous // // Created by Brandon Witt on 2014-11-18. // Copyright (c) 2014 Connor Giles. All rights reserved. // import Foundation import UIKit class GooglePlacesAutoComplete: UITableView, UITableViewDelegate, UITableViewDataSource { private var query: NSString! //the address to be queried var latitude: Int! //latitude of current address var longitude: Int! //longitude of current address private let baseURL: NSString = "https://maps.googleapis.com/maps/api/place/autocomplete/json?" // base URL for Google Maps Geocoding API private let APIKey: NSString = "AIzaSyBW383B23YhA7weSXAPhiwbv5vkv2WP4lA" //our API key private let params: NSArray = ["input=", "key="]//basic params var suggestions: NSMutableArray = NSMutableArray() var mapView: MapViewController! var place: Place = Place() //Table View Stuff func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int{ return suggestions.count } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell{ var cell: UITableViewCell = UITableViewCell(style: UITableViewCellStyle.Subtitle, reuseIdentifier: "Cell") if indexPath.row < suggestions.count{ let place: Place = suggestions.objectAtIndex(indexPath.row) as Place cell.textLabel.text = place.desc! as String } return cell } func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath){ if indexPath.row < suggestions.count && mapView.addressInputField != nil{ let selected: Place = suggestions.objectAtIndex(indexPath.row) as Place mapView.addressInputField.text = selected.desc! as String self.place = selected //getCoordinates(selected) mapView.addressInputField.endEditing(true) } } func search(query: NSString){ println("QUERY: \(query)") if(query == ""){ self.suggestions.removeAllObjects() } var url: NSString = createURL(explode(query) ) makeAPICall(url) self.reloadData() } private func createURL(addressMembers: NSArray) -> String{ var url: NSString = "\(baseURL)\(params[0])" for var i = 0; i<addressMembers.count; ++i{ if(i<addressMembers.count-1){ url = "\(url)\(addressMembers[i])+" }else{ url = "\(url)\(addressMembers[i])" } } url = "\(url)&\(params[1])\(APIKey)" return url } private func explode(string: NSString) -> NSArray{ return string.componentsSeparatedByString(" ") } private func makeAPICall(url: NSString){//make it async let url: NSURL = NSURL(string: url)! let task = NSURLSession.sharedSession().dataTaskWithURL(url) {(data, response, error) in var jsonResult: NSDictionary = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: nil) as NSDictionary if let arr = jsonResult["predictions"] as? [NSDictionary]{ self.suggestions.removeAllObjects() for a in arr{ let desc: String = a["description"] as String let id: String = a["place_id"] as String let place: Place = Place(place_id: id, description: desc) self.suggestions.addObject(place) //println(self.suggestions.lastObject!) } } } task.resume() } func getCoordinates(selected: Place){ let place_id: String = selected.placeID let url: NSURL = NSURL(string:"https://maps.googleapis.com/maps/api/place/details/json?placeid=\(place_id)&key=\(APIKey)")! let task = NSURLSession.sharedSession().dataTaskWithURL(url) {(data, response, error) in var jsonResult: NSDictionary = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: nil) as NSDictionary if(jsonResult["result"] != nil){ var step1: NSDictionary = jsonResult["result"] as NSDictionary var step2 = step1["geometry"] as NSDictionary var step3 = step2["location"] as NSDictionary let lon = step3["lng"] as? Double let lat = step3["lat"] as? Double self.place.location = PFGeoPoint(latitude: lat!, longitude: lon!) self.mapView.addPost(self.place) } } task.resume() } }
mit
5dd8d86300376a939665fd0e8c841187
37.023077
164
0.596317
5.048008
false
false
false
false
neetsdkasu/Paiza-POH-MyAnswers
POH7/NekoMimi/Answer.swift
1
1570
// Try POH // author: Leonardone @ NEETSDKASU // ============================================================= func ti(s :String) -> Int { if let v : Int = Int(s) { return v } else { return 0 } } func gs() -> String { if let s : String = readLine() { return s } else { return "" } } func gi() -> Int { return ti(gs()) } func gss() -> [String] { return gs().characters.split{ $0 == " " }.map{ String($0) } } func gis() -> [Int] { return gss().map(ti) } // [Type] は Array<Type> の糖衣構文的な? func ngt<T>(n :Int, f :() -> T) -> [T] { var a : [T] = [T](); for _ in 1...n { a.append(f()) }; return a } func ngs(n :Int) -> [String] { return ngt(n, f: gs) } func ngi(n :Int) -> [Int] { return ngt(n, f: gi) } func ngss(n :Int) -> [[String]] { return ngt(n, f: gss) } func ngis(n :Int) -> [[Int]] { return ngt(n, f: gis) } func Bv2(a :[Int]) -> (Int, Int, [Int]) { return (a[0], a[1], [Int](a[2..<a.count])) } func Bv3(a :[Int]) -> (Int, Int, Int, [Int]) { return (a[0], a[1], a[2], [Int](a[3..<a.count])) } func Bv4(a :[Int]) -> (Int, Int, Int, Int, [Int]) { return (a[0], a[1], a[2], a[3], [Int](a[4..<a.count])) } func Bv5(a :[Int]) -> (Int, Int, Int, Int, Int, [Int]) { return (a[0], a[1], a[2], a[3], a[4], [Int](a[5..<a.count])) } // ============================================================= func solve() { let s = gs().characters var c = 0 for i in s.startIndex ..< s.endIndex { let sb = String(s[i ..< s.endIndex].prefix(3)) if sb == "cat" { c += 1 } } print(c) } solve()
mit
823cf182dd403fdc7c45aa07c3509d12
38.794872
119
0.450387
2.612795
false
false
false
false
yeti/signals
tests/generators/ios/swift/files/DataModel.swift
1
5433
// // DataModel.swift // // Created by signals on %s. import Foundation import CoreData import RestKit typealias RestKitSuccess = (operation: RKObjectRequestOperation!, result: RKMappingResult!) -> Void typealias RestKitError = (operation: RKObjectRequestOperation!, error: NSError!) -> Void protocol DataModelDelegate { func getBaseURLString() -> String func getAccessToken() -> String } class DataModel: NSObject { var delegate: DataModelDelegate? class func sharedDataModel() -> DataModel { struct Static { static var __sharedDataModel: DataModel? = nil static var onceToken: dispatch_once_t = 0 } dispatch_once(&Static.onceToken) { Static.__sharedDataModel = DataModel.init() } return Static.__sharedDataModel! } func setup(delegate: DataModelDelegate) { // Initialize RestKit let _delegate = delegate self.delegate = delegate let baseURL = NSURL(string: _delegate.getBaseURLString()) let objectManager = RKObjectManager(baseURL: baseURL) // Enable Activity Indicator Spinner AFNetworkActivityIndicatorManager.sharedManager().enabled = true // Initialize managed object store let managedObjectModel = NSManagedObjectModel.mergedModelFromBundles(nil) let managedObjectStore = RKManagedObjectStore(managedObjectModel: managedObjectModel) objectManager.managedObjectStore = managedObjectStore // MARK: RestKit Entity Mappings let loginResponseMapping = RKEntityMapping(forEntityForName: "LoginResponse", inManagedObjectStore: managedObjectStore) loginResponseMapping.addAttributeMappingsFromDictionary([ "client_secret": "clientSecret", "client_id": "clientId" ]) let signUpResponseMapping = RKEntityMapping(forEntityForName: "SignUpResponse", inManagedObjectStore: managedObjectStore) signUpResponseMapping.addAttributeMappingsFromDictionary([ "username": "username", "client_secret": "clientSecret", "fullname": "fullname", "email": "email", "client_id": "clientId" ]) let signUpRequestMapping = RKEntityMapping(forEntityForName: "SignUpRequest", inManagedObjectStore: managedObjectStore) signUpRequestMapping.addAttributeMappingsFromDictionary([ "username": "username", "fullname": "fullname", "password": "password", "email": "email" ]) // MARK: RestKit Entity Relationship Mappings // We place the relationship mappings after the entities so that we don't need to worry about ordering // MARK: RestKit URL Descriptors let signUpPostRequestDescriptor = RKRequestDescriptor(mapping: signUpRequestMapping.inverseMapping(), objectClass: SignUpRequest.self, rootKeyPath: nil, method: RKRequestMethod.POST) objectManager.addRequestDescriptor(signUpPostRequestDescriptor) let signUpPostResponseDescriptor = RKResponseDescriptor(mapping: signUpResponseMapping, method: RKRequestMethod.POST, pathPattern: "sign_up/", keyPath: nil, statusCodes: RKStatusCodeIndexSetForClass(RKStatusCodeClass.Successful)) objectManager.addResponseDescriptor(signUpPostResponseDescriptor) let loginGetResponseDescriptor = RKResponseDescriptor(mapping: loginResponseMapping, method: RKRequestMethod.GET, pathPattern: "login/", keyPath: "results", statusCodes: RKStatusCodeIndexSetForClass(RKStatusCodeClass.Successful)) objectManager.addResponseDescriptor(loginGetResponseDescriptor) /** Complete Core Data stack initialization */ managedObjectStore.createPersistentStoreCoordinator() let storePath = (RKApplicationDataDirectory() as NSString).stringByAppendingPathComponent("TestProject.sqlite") do { try managedObjectStore.addSQLitePersistentStoreAtPath(storePath, fromSeedDatabaseAtPath: nil, withConfiguration: nil, options: nil) } catch { // Problem creating persistent store, wipe it since there was probably a core data change // Causes runtime crash if still unable to create persistant storage try! NSFileManager.defaultManager().removeItemAtPath(storePath) try! managedObjectStore.addSQLitePersistentStoreAtPath(storePath, fromSeedDatabaseAtPath: nil, withConfiguration: nil, options: nil) } // Create the managed object contexts managedObjectStore.createManagedObjectContexts() // Configure a managed object cache to ensure we do not create duplicate objects managedObjectStore.managedObjectCache = RKInMemoryManagedObjectCache(managedObjectContext: managedObjectStore.persistentStoreManagedObjectContext) } // MARK: API Calls func postSignUpWithUsername(username: String, fullname: String, password: String, email: String, success: RestKitSuccess, failure: RestKitError) { let sharedMgr = RKObjectManager.sharedManager() sharedMgr.requestSerializationMIMEType = RKMIMETypeJSON let obj = NSEntityDescription.insertNewObjectForEntityForName("SignUpRequest", inManagedObjectContext: sharedMgr.managedObjectStore.mainQueueManagedObjectContext) as! SignUpRequest obj.username = username obj.fullname = fullname obj.password = password obj.email = email sharedMgr.postObject(obj, path: "sign_up/", parameters: nil, success: success, failure: failure) } func getLoginWithSuccess(success: RestKitSuccess, failure: RestKitError) { let sharedMgr = RKObjectManager.sharedManager() sharedMgr.requestSerializationMIMEType = RKMIMETypeJSON sharedMgr.getObject(nil, path: "login/", parameters: nil, success: success, failure: failure) } }
mit
9102c5b5a6fe812da1540182c4b6b5b1
46.252174
233
0.778575
5.053953
false
false
false
false
hamilyjing/JJSwiftNetwork
Pods/HandyJSON/HandyJSON/Deserializer.swift
3
8544
/* * Copyright 1999-2101 Alibaba Group. * * 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. */ // Created by zhouzhuo on 7/7/16. // import Foundation fileprivate func getSubObject(inside jsonObject: NSObject?, by designatedPath: String?) -> NSObject? { var nodeValue: NSObject? = jsonObject var abort = false if let paths = designatedPath?.components(separatedBy: "."), paths.count > 0 { paths.forEach({ (seg) in if seg.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines) == "" || abort { return } if let next = (nodeValue as? NSDictionary)?.object(forKey: seg) as? NSObject { nodeValue = next } else { abort = true } }) } return abort ? nil : nodeValue } extension _PropertiesMappable { static func _transform(rawPointer: UnsafeMutableRawPointer, property: Property.Description, dict: NSDictionary, mapper: HelpingMapper) { var key = property.key if HandyJSONConfiguration.deserializeOptions.contains(.caseInsensitive) { key = key.lowercased() } let mutablePointer = rawPointer.advanced(by: property.offset) if mapper.propertyExcluded(key: mutablePointer.hashValue) { ClosureExecutor.executeWhenDebug { print("Exclude property: \(key)") } return } if let mappingHandler = mapper.getMappingHandler(key: mutablePointer.hashValue) { // if specific key is set, replace the label if let specifyKey = mappingHandler.mappingName { key = specifyKey } if let transformer = mappingHandler.assignmentClosure { // execute the transform closure transformer(dict[key]) return } } guard let rawValue = dict[key] as? NSObject else { ClosureExecutor.executeWhenDebug { print("Can not find a value from dictionary for property: \(key)") } return } if let transformableType = property.type as? _JSONTransformable.Type { if let sv = transformableType.transform(from: rawValue) { extensions(of: transformableType).write(sv, to: mutablePointer) return } } else { if let sv = extensions(of: property.type).takeValue(from: rawValue) { extensions(of: property.type).write(sv, to: mutablePointer) return } } ClosureExecutor.executeWhenDebug { print("Property: \(property.key) hasn't been written in") } } static func _transform(dict: NSDictionary, toType: _PropertiesMappable.Type) -> _PropertiesMappable? { var instance = toType.init() guard let properties = getProperties(forType: toType) else { ClosureExecutor.executeWhenError { print("Failed when try to get properties from type: \(type(of: toType))") } return nil } let mapper = HelpingMapper() // do user-specified mapping first instance.mapping(mapper: mapper) let rawPointer: UnsafeMutableRawPointer if toType is AnyClass { rawPointer = UnsafeMutableRawPointer(instance.headPointerOfClass()) } else { rawPointer = UnsafeMutableRawPointer(instance.headPointerOfStruct()) } var _dict = dict if HandyJSONConfiguration.deserializeOptions.contains(.caseInsensitive) { let newDict = NSMutableDictionary() dict.allKeys.forEach({ (key) in if let sKey = key as? String { newDict[sKey.lowercased()] = dict[key] } else { newDict[key] = dict[key] } }) _dict = newDict } properties.forEach { (property) in _transform(rawPointer: rawPointer, property: property, dict: _dict, mapper: mapper) } return instance } } public extension HandyJSON { /// Finds the internal NSDictionary in `dict` as the `designatedPath` specified, and converts it to a Model /// `designatedPath` is a string like `result.data.orderInfo`, which each element split by `.` represents key of each layer public static func deserialize(from dict: NSDictionary?, designatedPath: String? = nil) -> Self? { return JSONDeserializer<Self>.deserializeFrom(dict: dict, designatedPath: designatedPath) } /// Finds the internal JSON field in `json` as the `designatedPath` specified, and converts it to a Model /// `designatedPath` is a string like `result.data.orderInfo`, which each element split by `.` represents key of each layer public static func deserialize(from json: String?, designatedPath: String? = nil) -> Self? { return JSONDeserializer<Self>.deserializeFrom(json: json, designatedPath: designatedPath) } } public extension Array where Element: HandyJSON { /// if the JSON field finded by `designatedPath` in `json` is representing a array, such as `[{...}, {...}, {...}]`, /// this method converts it to a Models array public static func deserialize(from json: String?, designatedPath: String? = nil) -> [Element?]? { return JSONDeserializer<Element>.deserializeModelArrayFrom(json: json, designatedPath: designatedPath) } } public class JSONDeserializer<T: HandyJSON> { /// Finds the internal NSDictionary in `dict` as the `designatedPath` specified, and converts it to a Model /// `designatedPath` is a string like `result.data.orderInfo`, which each element split by `.` represents key of each layer, or nil public static func deserializeFrom(dict: NSDictionary?, designatedPath: String? = nil) -> T? { var targetDict = dict if let path = designatedPath { targetDict = getSubObject(inside: targetDict, by: path) as? NSDictionary } if let _dict = targetDict { return T._transform(dict: _dict, toType: T.self) as? T } return nil } /// Finds the internal JSON field in `json` as the `designatedPath` specified, and converts it to a Model /// `designatedPath` is a string like `result.data.orderInfo`, which each element split by `.` represents key of each layer, or nil public static func deserializeFrom(json: String?, designatedPath: String? = nil) -> T? { guard let _json = json else { return nil } do { let jsonObject = try JSONSerialization.jsonObject(with: _json.data(using: String.Encoding.utf8)!, options: .allowFragments) if let jsonDict = jsonObject as? NSDictionary { return self.deserializeFrom(dict: jsonDict, designatedPath: designatedPath) } } catch let error { ClosureExecutor.executeWhenError { print(error) } } return nil } /// if the JSON field finded by `designatedPath` in `json` is representing a array, such as `[{...}, {...}, {...}]`, /// this method converts it to a Models array public static func deserializeModelArrayFrom(json: String?, designatedPath: String? = nil) -> [T?]? { guard let _json = json else { return nil } do { let jsonObject = try JSONSerialization.jsonObject(with: _json.data(using: String.Encoding.utf8)!, options: .allowFragments) if let jsonArray = getSubObject(inside: jsonObject as? NSObject, by: designatedPath) as? NSArray { return jsonArray.map({ (jsonDict) -> T? in return self.deserializeFrom(dict: jsonDict as? NSDictionary) }) } } catch let error { ClosureExecutor.executeWhenError { print(error) } } return nil } }
mit
3441acc4b1945b6973f5ab4b6966e3b0
38.925234
140
0.617275
4.781198
false
false
false
false