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
Jnosh/swift
stdlib/public/core/ASCII.swift
2
2872
//===--- ASCII.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 // //===----------------------------------------------------------------------===// extension Unicode { @_fixed_layout public enum ASCII {} } extension Unicode.ASCII : Unicode.Encoding { public typealias CodeUnit = UInt8 public typealias EncodedScalar = CollectionOfOne<CodeUnit> public static var encodedReplacementCharacter : EncodedScalar { return EncodedScalar(0x1a) // U+001A SUBSTITUTE; best we can do for ASCII } @inline(__always) @_inlineable public static func _isScalar(_ x: CodeUnit) -> Bool { return true } @inline(__always) @_inlineable public static func decode(_ source: EncodedScalar) -> Unicode.Scalar { return Unicode.Scalar(_unchecked: UInt32( source.first._unsafelyUnwrappedUnchecked)) } @inline(__always) @_inlineable public static func encode( _ source: Unicode.Scalar ) -> EncodedScalar? { guard source.value < (1&<<7) else { return nil } return EncodedScalar(UInt8(extendingOrTruncating: source.value)) } @inline(__always) public static func transcode<FromEncoding : Unicode.Encoding>( _ content: FromEncoding.EncodedScalar, from _: FromEncoding.Type ) -> EncodedScalar? { if _fastPath(FromEncoding.self == UTF16.self) { let c = _identityCast(content, to: UTF16.EncodedScalar.self) guard (c._storage & 0xFF80 == 0) else { return nil } return EncodedScalar(CodeUnit(c._storage & 0x7f)) } else if _fastPath(FromEncoding.self == UTF8.self) { let c = _identityCast(content, to: UTF8.EncodedScalar.self) guard (c._storage & 0x80 == 0) else { return nil } return EncodedScalar(CodeUnit(c._storage & 0x7f)) } return encode(FromEncoding.decode(content)) } public struct Parser { public init() { } } public typealias ForwardParser = Parser public typealias ReverseParser = Parser } extension Unicode.ASCII.Parser : Unicode.Parser { public typealias Encoding = Unicode.ASCII /// Parses a single Unicode scalar value from `input`. public mutating func parseScalar<I : IteratorProtocol>( from input: inout I ) -> Unicode.ParseResult<Encoding.EncodedScalar> where I.Element == Encoding.CodeUnit { let n = input.next() if _fastPath(n != nil), let x = n { guard _fastPath(Int8(extendingOrTruncating: x) >= 0) else { return .error(length: 1) } return .valid(Unicode.ASCII.EncodedScalar(x)) } return .emptyInput } }
apache-2.0
ec1f4385a89e452da1d5645c628bc185
31.636364
80
0.656337
4.331825
false
false
false
false
iwantooxxoox/CVCalendar
CVCalendar/CVCalendarWeekContentViewController.swift
8
19866
// // CVCalendarWeekContentViewController.swift // CVCalendar Demo // // Created by Eugene Mozharovsky on 12/04/15. // Copyright (c) 2015 GameApp. All rights reserved. // import UIKit public final class CVCalendarWeekContentViewController: CVCalendarContentViewController { private var weekViews: [Identifier : WeekView] private var monthViews: [Identifier : MonthView] public override init(calendarView: CalendarView, frame: CGRect) { weekViews = [Identifier : WeekView]() monthViews = [Identifier : MonthView]() super.init(calendarView: calendarView, frame: frame) initialLoad(NSDate()) } public init(calendarView: CalendarView, frame: CGRect, presentedDate: NSDate) { weekViews = [Identifier : WeekView]() monthViews = [Identifier : MonthView]() super.init(calendarView: calendarView, frame: frame) presentedMonthView = MonthView(calendarView: calendarView, date: presentedDate) presentedMonthView.updateAppearance(bounds) initialLoad(presentedDate) } public required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: - Load & Reload public func initialLoad(date: NSDate) { monthViews[Previous] = getPreviousMonth(presentedMonthView.date) monthViews[Presented] = presentedMonthView monthViews[Following] = getFollowingMonth(presentedMonthView.date) presentedMonthView.mapDayViews { dayView in if self.matchedDays(dayView.date, Date(date: date)) { self.insertWeekView(dayView.weekView, withIdentifier: self.Presented) self.calendarView.coordinator.flush() self.calendarView.touchController.receiveTouchOnDayView(dayView) dayView.circleView?.removeFromSuperview() } } if let presented = weekViews[Presented] { insertWeekView(getPreviousWeek(presented), withIdentifier: Previous) insertWeekView(getFollowingWeek(presented), withIdentifier: Following) } } public func reloadWeekViews() { for (identifier, weekView) in weekViews { weekView.frame.origin = CGPointMake(CGFloat(indexOfIdentifier(identifier)) * scrollView.frame.width, 0) weekView.removeFromSuperview() scrollView.addSubview(weekView) } } // MARK: - Insertion public func insertWeekView(weekView: WeekView, withIdentifier identifier: Identifier) { let index = CGFloat(indexOfIdentifier(identifier)) weekView.frame.origin = CGPointMake(scrollView.bounds.width * index, 0) weekViews[identifier] = weekView scrollView.addSubview(weekView) } public func replaceWeekView(weekView: WeekView, withIdentifier identifier: Identifier, animatable: Bool) { var weekViewFrame = weekView.frame weekViewFrame.origin.x = weekViewFrame.width * CGFloat(indexOfIdentifier(identifier)) weekView.frame = weekViewFrame weekViews[identifier] = weekView if animatable { scrollView.scrollRectToVisible(weekViewFrame, animated: false) } } // MARK: - Load management public func scrolledLeft() { if let presented = weekViews[Presented], let following = weekViews[Following] { if pageLoadingEnabled { pageLoadingEnabled = false weekViews[Previous]?.removeFromSuperview() replaceWeekView(presented, withIdentifier: Previous, animatable: false) replaceWeekView(following, withIdentifier: Presented, animatable: true) insertWeekView(getFollowingWeek(following), withIdentifier: Following) } } } public func scrolledRight() { if let presented = weekViews[Presented], let previous = weekViews[Previous] { if pageLoadingEnabled { pageLoadingEnabled = false weekViews[Following]?.removeFromSuperview() replaceWeekView(presented, withIdentifier: Following, animatable: false) replaceWeekView(previous, withIdentifier: Presented, animatable: true) insertWeekView(getPreviousWeek(previous), withIdentifier: Previous) } } } // MARK: - Override methods public override func updateFrames(rect: CGRect) { super.updateFrames(rect) for monthView in monthViews.values { monthView.reloadViewsWithRect(rect != CGRectZero ? rect : scrollView.bounds) } reloadWeekViews() if let presented = weekViews[Presented] { scrollView.scrollRectToVisible(presented.frame, animated: false) } } public override func performedDayViewSelection(dayView: DayView) { if dayView.isOut { if dayView.date.day > 20 { let presentedDate = dayView.monthView.date calendarView.presentedDate = Date(date: self.dateBeforeDate(presentedDate)) presentPreviousView(dayView) } else { let presentedDate = dayView.monthView.date calendarView.presentedDate = Date(date: self.dateAfterDate(presentedDate)) presentNextView(dayView) } } } public override func presentPreviousView(view: UIView?) { if presentationEnabled { presentationEnabled = false if let extra = weekViews[Following], let presented = weekViews[Presented], let previous = weekViews[Previous] { UIView.animateWithDuration(0.5, delay: 0, options: UIViewAnimationOptions.CurveEaseInOut, animations: { self.prepareTopMarkersOnWeekView(presented, hidden: false) extra.frame.origin.x += self.scrollView.frame.width presented.frame.origin.x += self.scrollView.frame.width previous.frame.origin.x += self.scrollView.frame.width self.replaceWeekView(presented, withIdentifier: self.Following, animatable: false) self.replaceWeekView(previous, withIdentifier: self.Presented, animatable: false) }) { _ in extra.removeFromSuperview() self.insertWeekView(self.getPreviousWeek(previous), withIdentifier: self.Previous) self.updateSelection() self.presentationEnabled = true for weekView in self.weekViews.values { self.prepareTopMarkersOnWeekView(weekView, hidden: false) } } } } } public override func presentNextView(view: UIView?) { if presentationEnabled { presentationEnabled = false if let extra = weekViews[Previous], let presented = weekViews[Presented], let following = weekViews[Following] { UIView.animateWithDuration(0.5, delay: 0, options: UIViewAnimationOptions.CurveEaseInOut, animations: { self.prepareTopMarkersOnWeekView(presented, hidden: false) extra.frame.origin.x -= self.scrollView.frame.width presented.frame.origin.x -= self.scrollView.frame.width following.frame.origin.x -= self.scrollView.frame.width self.replaceWeekView(presented, withIdentifier: self.Previous, animatable: false) self.replaceWeekView(following, withIdentifier: self.Presented, animatable: false) }) { _ in extra.removeFromSuperview() self.insertWeekView(self.getFollowingWeek(following), withIdentifier: self.Following) self.updateSelection() self.presentationEnabled = true for weekView in self.weekViews.values { self.prepareTopMarkersOnWeekView(weekView, hidden: false) } } } } } public override func updateDayViews(hidden: Bool) { setDayOutViewsVisible(hidden) } private var togglingBlocked = false public override func togglePresentedDate(date: NSDate) { let presentedDate = Date(date: date) if let presentedMonthView = monthViews[Presented], let presentedWeekView = weekViews[Presented], let selectedDate = calendarView.coordinator.selectedDayView?.date { if !matchedDays(selectedDate, Date(date: date)) && !togglingBlocked { if !matchedWeeks(presentedDate, selectedDate) { togglingBlocked = true weekViews[Previous]?.removeFromSuperview() weekViews[Following]?.removeFromSuperview() let currentMonthView = MonthView(calendarView: calendarView, date: date) currentMonthView.updateAppearance(scrollView.bounds) monthViews[Presented] = currentMonthView monthViews[Previous] = getPreviousMonth(date) monthViews[Following] = getFollowingMonth(date) let currentDate = CVDate(date: date) calendarView.presentedDate = currentDate var currentWeekView: WeekView! currentMonthView.mapDayViews { dayView in if self.matchedDays(currentDate, dayView.date) { if let weekView = dayView.weekView { currentWeekView = weekView currentWeekView.alpha = 0 } } } insertWeekView(getPreviousWeek(currentWeekView), withIdentifier: Previous) insertWeekView(currentWeekView, withIdentifier: Presented) insertWeekView(getFollowingWeek(currentWeekView), withIdentifier: Following) UIView.animateWithDuration(0.8, delay: 0, options: UIViewAnimationOptions.CurveEaseInOut, animations: { presentedWeekView.alpha = 0 currentWeekView.alpha = 1 }) { _ in presentedWeekView.removeFromSuperview() self.selectDayViewWithDay(currentDate.day, inWeekView: currentWeekView) self.togglingBlocked = false } } else { if let currentWeekView = weekViews[Presented] { selectDayViewWithDay(presentedDate.day, inWeekView: currentWeekView) } } } } } } // MARK: - WeekView management extension CVCalendarWeekContentViewController { public func getPreviousWeek(presentedWeekView: WeekView) -> WeekView { if let presentedMonthView = monthViews[Presented], let previousMonthView = monthViews[Previous] where presentedWeekView.monthView == presentedMonthView { for weekView in presentedMonthView.weekViews { if weekView.index == presentedWeekView.index - 1 { return weekView } } for weekView in previousMonthView.weekViews { if weekView.index == previousMonthView.weekViews.count - 1 { return weekView } } } else if let previousMonthView = monthViews[Previous] { monthViews[Following] = monthViews[Presented] monthViews[Presented] = monthViews[Previous] monthViews[Previous] = getPreviousMonth(previousMonthView.date) presentedMonthView = monthViews[Previous]! } return getPreviousWeek(presentedWeekView) } public func getFollowingWeek(presentedWeekView: WeekView) -> WeekView { if let presentedMonthView = monthViews[Presented], let followingMonthView = monthViews[Following] where presentedWeekView.monthView == presentedMonthView { for weekView in presentedMonthView.weekViews { for weekView in presentedMonthView.weekViews { if weekView.index == presentedWeekView.index + 1 { return weekView } } for weekView in followingMonthView.weekViews { if weekView.index == 0 { return weekView } } } } else if let followingMonthView = monthViews[Following] { monthViews[Previous] = monthViews[Presented] monthViews[Presented] = monthViews[Following] monthViews[Following] = getFollowingMonth(followingMonthView.date) presentedMonthView = monthViews[Following]! } return getFollowingWeek(presentedWeekView) } } // MARK: - MonthView management extension CVCalendarWeekContentViewController { public func getFollowingMonth(date: NSDate) -> MonthView { let calendarManager = calendarView.manager let firstDate = calendarManager.monthDateRange(date).monthStartDate let components = Manager.componentsForDate(firstDate) components.month += 1 let newDate = NSCalendar.currentCalendar().dateFromComponents(components)! let monthView = MonthView(calendarView: calendarView, date: newDate) let frame = CGRectMake(0, 0, scrollView.bounds.width, scrollView.bounds.height) monthView.updateAppearance(frame) return monthView } public func getPreviousMonth(date: NSDate) -> MonthView { let firstDate = calendarView.manager.monthDateRange(date).monthStartDate let components = Manager.componentsForDate(firstDate) components.month -= 1 let newDate = NSCalendar.currentCalendar().dateFromComponents(components)! let monthView = MonthView(calendarView: calendarView, date: newDate) let frame = CGRectMake(0, 0, scrollView.bounds.width, scrollView.bounds.height) monthView.updateAppearance(frame) return monthView } } // MARK: - Visual preparation extension CVCalendarWeekContentViewController { public func prepareTopMarkersOnWeekView(weekView: WeekView, hidden: Bool) { weekView.mapDayViews { dayView in dayView.topMarker?.hidden = hidden } } public func setDayOutViewsVisible(visible: Bool) { for monthView in monthViews.values { monthView.mapDayViews { dayView in if dayView.isOut { if !visible { dayView.alpha = 0 dayView.hidden = false } UIView.animateWithDuration(0.5, delay: 0, options: UIViewAnimationOptions.CurveEaseInOut, animations: { dayView.alpha = visible ? 0 : 1 }) { _ in if visible { dayView.alpha = 1 dayView.hidden = true dayView.userInteractionEnabled = false } else { dayView.userInteractionEnabled = true } } } } } } public func updateSelection() { let coordinator = calendarView.coordinator if let selected = coordinator.selectedDayView { for (index, monthView) in monthViews { if indexOfIdentifier(index) != 1 { monthView.mapDayViews { dayView in if dayView == selected { dayView.setDeselectedWithClearing(true) coordinator.dequeueDayView(dayView) } } } } } if let presentedWeekView = weekViews[Presented], let presentedMonthView = monthViews[Presented] { self.presentedMonthView = presentedMonthView calendarView.presentedDate = Date(date: presentedMonthView.date) var presentedDate: Date! for dayView in presentedWeekView.dayViews { if !dayView.isOut { presentedDate = dayView.date break } } if let selected = coordinator.selectedDayView where !matchedWeeks(selected.date, presentedDate) { let current = Date(date: NSDate()) if matchedWeeks(current, presentedDate) { selectDayViewWithDay(current.day, inWeekView: presentedWeekView) } else { selectDayViewWithDay(presentedDate.day, inWeekView: presentedWeekView) } } } } public func selectDayViewWithDay(day: Int, inWeekView weekView: WeekView) { let coordinator = calendarView.coordinator weekView.mapDayViews { dayView in if dayView.date.day == day && !dayView.isOut { if let selected = coordinator.selectedDayView where selected != dayView { self.calendarView.didSelectDayView(dayView) } coordinator.performDayViewSingleSelection(dayView) } } } } // MARK: - UIScrollViewDelegate extension CVCalendarWeekContentViewController { public func scrollViewDidScroll(scrollView: UIScrollView) { if scrollView.contentOffset.y != 0 { scrollView.contentOffset = CGPointMake(scrollView.contentOffset.x, 0) } let page = Int(floor((scrollView.contentOffset.x - scrollView.frame.width / 2) / scrollView.frame.width) + 1) if currentPage != page { currentPage = page } lastContentOffset = scrollView.contentOffset.x } public func scrollViewWillBeginDragging(scrollView: UIScrollView) { if let presented = weekViews[Presented] { prepareTopMarkersOnWeekView(presented, hidden: true) } } public func scrollViewDidEndDecelerating(scrollView: UIScrollView) { if pageChanged { switch direction { case .Left: scrolledLeft() case .Right: scrolledRight() default: break } } updateSelection() pageLoadingEnabled = true direction = .None } public func scrollViewDidEndDragging(scrollView: UIScrollView, willDecelerate decelerate: Bool) { if decelerate { let rightBorder = scrollView.frame.width if scrollView.contentOffset.x <= rightBorder { direction = .Right } else { direction = .Left } } for weekView in self.weekViews.values { self.prepareTopMarkersOnWeekView(weekView, hidden: false) } } }
mit
0a0dd040265697ec033c46ebd3cca378
39.794661
172
0.579382
6.404255
false
false
false
false
aipeople/PokeIV
Pods/PGoApi/PGoApi/Classes/Unknown6/subFuncK.swift
1
34717
// // subFuncA.swift // Pods // // Created by PokemonGoSucks on 2016-08-10 // // import Foundation public class subFuncK { public func subFuncK(input_: Array<UInt32>) -> Array<UInt32> { var v = Array<UInt32>(count: 482, repeatedValue: 0) var input = input_ v[0] = ((((input[164] ^ input[200]) ^ input[59]) ^ input[146]) ^ input[20]) v[1] = input[28] v[2] = (v[0] | input[28]) v[3] = (v[0] ^ v[1]) v[4] = ((((input[164] ^ input[200]) ^ input[59]) ^ input[146]) ^ input[20]) v[5] = (input[28] & v[0]) v[6] = (input[28] & v[0]) v[7] = ~input[175] v[8] = (v[0] & v[7]) v[9] = (v[5] & v[7]) v[10] = (v[2] & ~v[1]) v[11] = ((v[1] & ~v[5]) ^ (v[2] & v[7])) let part0 = ((v[0] ^ v[1])) v[12] = (part0 & v[7]) v[13] = input[84] v[14] = (v[10] ^ input[10]) v[15] = (v[12] ^ v[2]) let part1 = (((v[0] ^ v[1]) | input[175])) v[16] = (part1 ^ (v[2] & ~v[1])) v[17] = (v[9] ^ input[28]) v[18] = ((v[0] ^ v[1]) ^ input[175]) v[19] = (v[8] ^ v[2]) let part2 = ((v[12] ^ v[2])) v[20] = (((part2 & ~v[13]) ^ v[8]) ^ v[2]) let part3 = ((v[14] | v[13])) input[10] = (part3 ^ v[18]) v[21] = input[192] let part4 = ((v[11] | v[13])) let part5 = ((part4 ^ v[17])) v[22] = (part5 & v[21]) let part6 = ((v[8] | v[13])) let part7 = ((part6 ^ v[16])) v[23] = (v[21] & ~part7) input[4] = (v[2] & ~v[1]) v[24] = input[175] input[164] = v[2] input[141] = v[20] v[25] = (v[24] | v[4]) v[26] = (v[22] ^ input[10]) input[200] = v[26] let part8 = ((v[24] | v[4])) v[27] = (part8 ^ v[4]) let part9 = ((v[17] ^ (v[13] & ~v[11]))) v[28] = (((v[14] & v[13]) ^ v[18]) ^ (input[192] & ~part9)) v[29] = (v[26] ^ input[35]) let part10 = ((v[23] ^ v[20])) v[30] = (input[12] & ~part10) v[31] = (input[138] & input[59]) v[32] = ((v[4] & ~v[1]) ^ input[92]) v[33] = input[189] input[146] = v[6] v[34] = (v[2] ^ v[33]) let part11 = ((v[10] | input[175])) v[35] = (part11 ^ v[3]) input[186] = (v[8] ^ v[2]) v[36] = (v[29] ^ v[30]) v[37] = v[28] v[38] = input[120] input[174] = v[28] v[39] = (v[31] ^ v[38]) v[40] = input[116] v[41] = input[175] v[42] = v[39] input[116] = v[39] v[43] = v[40] v[44] = (v[2] ^ v[41]) v[45] = (v[9] & ~v[13]) v[46] = v[36] v[47] = ((v[13] & ~v[27]) ^ v[32]) input[54] = v[36] v[48] = (v[35] & v[13]) input[65] = (v[25] ^ v[6]) let part12 = (((v[13] & ~v[8]) ^ v[16])) v[49] = (part12 & input[192]) let part13 = ((v[27] | v[13])) let part14 = ((part13 ^ v[32])) v[50] = (((v[34] & ~v[13]) ^ v[44]) ^ (part14 & input[192])) input[189] = ((v[15] & v[13]) ^ v[19]) v[51] = ((v[9] & v[13]) ^ v[8]) v[52] = input[201] let part15 = ((input[59] | input[31])) v[53] = ((input[125] ^ input[0]) ^ part15) let part16 = ((input[59] | input[180])) v[54] = (part16 ^ input[155]) v[55] = input[30] let part17 = ((v[35] | v[13])) input[90] = (part17 ^ input[65]) v[56] = input[192] input[92] = (v[48] ^ input[65]) let part18 = ((v[45] ^ v[8])) v[57] = (v[56] & ~part18) v[58] = input[192] v[59] = (((v[58] & ~v[47]) ^ v[44]) ^ (v[34] & v[13])) v[60] = ~input[59] v[61] = (input[92] ^ (v[58] & ~v[51])) v[62] = (v[60] & v[52]) let part19 = ((v[49] ^ input[189])) v[63] = ((input[12] & ~part19) ^ input[196]) v[64] = (v[53] & ~input[37]) v[65] = ~input[59] v[66] = (((v[60] & v[55]) ^ input[188]) ^ (input[154] & ~v[54])) v[67] = (input[90] ^ v[57]) v[68] = input[73] v[69] = ((v[50] & input[12]) ^ v[67]) v[70] = ((input[59] & ~v[52]) ^ v[68]) v[71] = ((v[61] ^ input[63]) ^ (v[59] & input[12])) v[72] = (input[59] & ~input[31]) v[73] = input[122] input[126] = v[69] input[158] = v[67] v[74] = (v[64] ^ v[73]) v[75] = (v[37] ^ v[63]) input[53] ^= v[69] v[76] = input[59] v[77] = input[125] input[60] = v[61] v[78] = (v[62] ^ v[68]) v[79] = (v[72] ^ v[77]) input[201] = v[70] v[80] = (v[74] ^ v[66]) v[81] = input[130] v[82] = (v[76] & ~input[30]) input[73] = v[79] v[83] = v[71] input[196] = v[75] v[84] = input[170] input[63] = v[71] input[157] = (v[62] ^ v[68]) v[85] = v[84] v[86] = input[59] input[122] = (v[74] ^ v[66]) v[87] = ((v[85] & v[86]) ^ v[81]) v[88] = input[35] v[89] = (v[87] | v[88]) v[90] = ~v[88] v[91] = v[80] let part20 = (((v[65] & input[45]) ^ input[152])) v[92] = (part20 & input[154]) let part21 = ((v[86] | input[99])) let part22 = ((part21 ^ input[182])) v[93] = (v[78] ^ (part22 & input[154])) let part23 = (((v[79] ^ input[98]) | input[37])) v[94] = ((((v[82] ^ input[162]) ^ input[188]) ^ input[62]) ^ part23) let part24 = ((input[66] | v[80])) v[95] = (part24 ^ input[91]) let part25 = ((input[123] | v[80])) v[96] = ((part25 ^ input[79]) | input[18]) v[97] = (v[80] | input[15]) v[98] = ~input[18] let part26 = ((input[28] | v[80])) v[99] = (part26 ^ input[75]) v[100] = (input[64] ^ (v[98] & input[49])) v[101] = input[72] v[102] = ~v[80] v[103] = (~v[80] & input[191]) v[104] = input[109] v[105] = (v[89] ^ v[43]) input[62] = v[94] v[106] = v[100] v[107] = (v[103] ^ v[104]) v[108] = (~v[80] & v[101]) let part27 = ((v[80] | input[117])) v[109] = (part27 ^ input[117]) v[110] = (input[59] | input[106]) v[111] = (~v[94] & input[101]) v[112] = input[19] v[113] = (input[104] & ~v[111]) v[114] = input[139] let part28 = ((v[94] ^ input[39])) v[115] = (input[104] & ~part28) let part29 = ((v[94] | v[112])) v[116] = (part29 ^ input[101]) v[117] = input[32] v[118] = (v[94] ^ input[97]) v[119] = input[159] v[120] = ~input[104] v[121] = (v[94] | input[76]) v[122] = (v[94] ^ v[119]) v[123] = v[102] v[124] = (v[94] | v[112]) v[125] = input[24] v[126] = (v[94] | v[119]) v[127] = input[70] v[128] = ((~v[94] & v[114]) ^ v[117]) v[129] = input[136] v[130] = (~v[94] & input[133]) v[131] = ((v[129] & v[94]) & v[125]) let part30 = (((~v[94] & v[117]) ^ v[129])) let part31 = ((v[94] | v[127])) v[132] = ((part31 ^ v[114]) ^ (part30 & ~v[125])) v[133] = input[70] v[134] = ((~v[94] & v[133]) ^ input[133]) let part32 = ((v[94] | v[117])) let part33 = ((v[94] | v[117])) let part34 = ((((v[125] & ~part32) ^ part33) ^ v[117])) v[135] = (part34 & v[120]) let part35 = (((~v[94] & v[133]) ^ v[117])) v[136] = (part35 & ~v[125]) let part36 = ((v[94] | v[117])) v[137] = ((v[131] ^ part36) ^ v[117]) let part37 = ((v[94] | v[127])) let part38 = ((part37 ^ input[8])) let part39 = ((v[94] | input[68])) v[138] = ((part39 ^ v[133]) ^ (part38 & ~v[125])) let part40 = ((v[94] | input[153])) let part41 = ((part40 ^ v[117])) let part42 = ((v[94] | input[183])) v[139] = ((input[68] ^ part42) ^ (part41 & ~v[125])) let part43 = ((v[94] | v[117])) let part44 = ((part43 ^ v[117])) v[140] = ((v[128] ^ (part44 & ~v[125])) | input[104]) v[141] = input[8] let part45 = ((v[94] | v[117])) let part46 = ((v[94] | v[117])) let part47 = ((part45 ^ v[117])) v[142] = ((part47 & v[125]) ^ part46) let part48 = ((v[94] | v[117])) v[143] = (part48 ^ v[141]) v[144] = ((v[141] & ~v[94]) | v[125]) v[145] = (v[130] & v[125]) let part49 = (((v[130] ^ input[8]) | v[125])) v[146] = (((v[117] ^ input[112]) ^ (input[68] & ~v[94])) ^ part49) v[147] = (v[134] & v[125]) let part50 = ((v[128] | v[125])) v[148] = (part50 ^ v[117]) let part51 = ((v[94] | v[117])) let part52 = ((v[94] | v[117])) let part53 = (((part51 ^ v[117]) | input[104])) v[149] = ((part53 ^ part52) ^ v[117]) let part54 = ((v[94] | v[117])) let part55 = ((part54 ^ input[202])) v[150] = (((((v[120] & part55) ^ input[136]) ^ input[134]) ^ input[41]) ^ v[130]) v[151] = ~input[16] v[152] = ((v[149] ^ v[147]) | input[16]) let part56 = (((v[137] ^ v[135]) | input[16])) let part57 = ((v[94] | v[127])) v[153] = ((((((v[138] & v[120]) ^ input[183]) ^ input[102]) ^ part57) ^ v[144]) ^ part56) let part58 = ((v[145] ^ v[140])) let part59 = ((v[132] | input[104])) v[154] = ((v[146] ^ part59) ^ (part58 & v[151])) let part60 = (((v[142] & v[120]) ^ v[148])) let part61 = ((v[139] | input[104])) v[155] = ((((v[143] ^ input[13]) ^ v[136]) ^ part61) ^ (part60 & v[151])) v[156] = ((((input[71] & v[65]) ^ input[167]) ^ input[45]) | input[37]) input[112] = v[154] v[157] = v[155] input[13] = v[155] v[158] = v[154] input[167] = v[156] v[159] = (v[150] ^ v[152]) v[160] = (v[154] | v[46]) v[161] = (v[46] & ~v[154]) v[162] = input[59] input[41] = v[159] input[0] = v[161] v[163] = v[161] v[164] = (v[162] & input[118]) v[165] = input[71] input[130] = v[163] v[166] = input[37] v[167] = v[164] v[168] = (v[165] & input[59]) v[169] = input[45] input[118] = v[164] v[170] = input[74] v[171] = (((v[168] ^ v[169]) ^ v[92]) | v[166]) v[172] = v[160] v[173] = (v[121] ^ input[76]) v[174] = input[104] input[15] = v[160] v[175] = (v[122] & v[174]) v[176] = input[97] v[177] = (v[170] | input[59]) v[178] = input[120] input[102] = v[153] v[179] = ~input[149] let part62 = ((input[168] ^ (input[59] & input[77]))) let part63 = ((((part62 & v[90]) ^ v[177]) ^ v[178])) v[180] = ((v[105] ^ input[46]) ^ (part63 & v[179])) v[181] = (v[94] | input[97]) v[182] = ((v[93] ^ input[58]) ^ v[171]) v[183] = (v[182] & input[5]) v[184] = (~v[94] & input[97]) v[185] = (v[181] ^ input[97]) v[186] = (v[182] & ~input[142]) v[187] = (input[21] ^ input[128]) let part64 = (((input[104] & ~v[116]) ^ v[121])) let part65 = ((v[115] ^ v[118])) let part66 = ((((v[111] ^ input[50]) ^ v[113]) ^ (part65 & ~v[180]))) v[188] = (((((input[119] & ~part66) ^ v[122]) ^ input[184]) ^ input[80]) ^ (part64 & ~v[180])) v[189] = (input[7] ^ input[67]) v[190] = (v[182] & input[172]) v[191] = (input[57] ^ input[2]) v[192] = (v[182] & ~input[144]) v[193] = (v[182] | input[5]) v[194] = (v[182] & input[93]) v[195] = (input[115] ^ input[43]) v[196] = (v[182] & ~input[5]) let part67 = (((v[175] ^ input[159]) | v[180])) v[197] = (((v[181] ^ input[177]) ^ (v[173] & input[104])) ^ part67) let part68 = ((v[126] ^ v[176])) let part69 = ((((v[124] ^ input[97]) ^ (part68 & input[104])) | v[180])) v[198] = ((((input[39] ^ input[9]) ^ v[184]) ^ (input[104] & ~v[185])) ^ part69) v[199] = (v[182] & input[5]) v[200] = (v[197] & input[119]) input[58] = v[182] v[201] = (v[182] & ~v[199]) v[202] = input[29] input[21] = (v[186] ^ v[187]) v[203] = ~v[202] v[204] = (~v[202] & v[196]) v[205] = (v[190] ^ v[189]) input[7] = v[205] v[206] = (v[191] ^ v[194]) input[57] = (v[191] ^ v[194]) v[207] = v[195] v[208] = (~v[182] & v[193]) let part70 = ((v[201] | input[29])) v[209] = (part70 ^ v[208]) v[210] = (v[207] ^ v[192]) input[115] = (v[207] ^ v[192]) v[211] = v[209] v[212] = input[59] input[136] = v[209] v[213] = (v[198] ^ v[200]) v[214] = input[140] v[215] = v[213] v[216] = (v[204] ^ v[193]) input[45] = (v[204] ^ v[193]) v[217] = v[212] v[218] = input[94] v[219] = ((v[212] & v[214]) ^ input[82]) v[220] = input[181] v[221] = input[35] v[222] = v[215] input[9] = v[215] v[223] = ((v[217] & v[218]) ^ v[220]) v[224] = (v[219] | v[221]) v[225] = v[188] v[226] = input[59] v[227] = (v[110] ^ input[170]) input[80] = v[188] let part71 = (((v[226] & ~input[86]) ^ input[61])) let part72 = (((part71 & v[90]) ^ v[223])) v[228] = (((input[6] ^ v[227]) ^ v[224]) ^ (part72 & v[179])) v[229] = input[119] v[230] = v[228] v[231] = (v[228] | v[229]) let part73 = ((v[228] | v[229])) v[232] = (~v[228] & part73) v[233] = (~v[228] & input[119]) v[234] = (v[228] ^ v[229]) v[235] = (v[233] ^ ((v[98] & ~v[229]) & v[228])) v[236] = (v[233] & v[98]) v[237] = (input[177] & ~v[94]) v[238] = input[18] v[239] = (v[232] | v[238]) v[240] = ~input[97] let part74 = ((v[232] ^ v[238])) v[241] = (part74 & v[240]) v[242] = v[121] let part75 = ((v[181] ^ input[171])) let part76 = (((part75 & input[104]) ^ v[184])) let part77 = ((((((input[19] & input[104]) & ~v[94]) ^ v[124]) ^ input[50]) ^ (part76 & ~v[180]))) let part78 = ((v[237] ^ input[97])) let part79 = ((v[94] | input[39])) let part80 = ((v[124] ^ input[159])) let part81 = ((((part80 & v[120]) ^ v[185]) | v[180])) v[243] = (((((part81 ^ input[59]) ^ part79) ^ input[171]) ^ (input[104] & ~part78)) ^ (input[119] & ~part77)) let part82 = ((v[228] | v[229])) let part83 = ((v[233] ^ (part82 & v[98]))) let part84 = (((((part83 & input[97]) ^ v[239]) ^ v[228]) | input[22])) v[244] = (((v[241] ^ v[235]) ^ input[51]) ^ part84) v[245] = input[19] v[246] = (v[126] ^ v[245]) v[247] = (input[11] ^ v[245]) v[248] = input[104] v[249] = ((v[247] ^ v[111]) ^ (v[246] & input[104])) let part85 = (((v[98] & v[234]) ^ input[119])) let part86 = (((v[236] ^ v[231]) ^ (part85 & v[240]))) v[250] = (v[244] ^ (input[14] & ~part86)) let part87 = ((v[126] ^ input[101])) let part88 = ((v[184] ^ input[171])) let part89 = ((((v[94] ^ input[101]) ^ (part88 & input[104])) | v[180])) v[251] = (((part89 ^ v[242]) ^ input[159]) ^ (v[248] & ~part87)) v[252] = (v[250] ^ v[243]) let part90 = ((v[237] ^ input[177])) let part91 = (((part90 & v[248]) ^ v[118])) v[253] = (v[249] ^ (~v[180] & part91)) let part92 = ((((v[107] & v[98]) ^ v[108]) ^ input[176])) v[254] = (((((v[123] & input[117]) ^ input[135]) ^ (v[109] & v[98])) ^ input[3]) ^ (v[230] & ~part92)) let part93 = ((v[250] ^ v[243])) v[255] = (v[158] & ~part93) v[256] = ((v[91] ^ input[36]) ^ (v[95] & v[98])) v[257] = input[23] v[258] = (v[95] | input[18]) v[259] = (v[158] & v[46]) let part94 = ((v[91] | input[192])) v[260] = (part94 ^ input[88]) let part95 = ((v[106] & v[123])) v[261] = ((((input[88] ^ input[166]) ^ input[197]) ^ (v[91] & ~input[47])) ^ (v[230] & ~part95)) v[262] = ((input[119] & ~v[251]) ^ v[253]) v[263] = ((v[250] ^ v[243]) ^ v[158]) v[264] = (((input[27] & v[123]) ^ input[111]) ^ v[96]) let part96 = ((v[99] | input[18])) v[265] = (((input[34] ^ input[17]) ^ v[97]) ^ part96) let part97 = ((v[163] ^ v[46])) input[75] = ((v[254] & ~v[262]) & ~part97) v[266] = (v[256] ^ v[257]) input[133] = ((v[254] & ~v[172]) | v[262]) input[11] = v[262] v[267] = (~v[254] & v[75]) input[49] = (v[157] & v[261]) input[166] = (v[157] & v[261]) input[139] = (v[157] & v[261]) let part98 = ((v[250] ^ v[243])) let part99 = ((v[158] & ~part98)) let part100 = (((((~v[250] & v[243]) & v[158]) ^ v[250]) ^ (v[46] & ~part99))) let part101 = ((v[250] & v[243])) v[268] = ((((~part101 & v[158]) & v[46]) ^ v[263]) ^ (v[261] & ~part100)) input[36] = v[243] v[269] = (v[265] ^ (v[230] & ~v[264])) input[47] = (~v[205] & v[225]) v[270] = input[51] input[3] = v[254] v[271] = (v[267] ^ v[75]) v[272] = input[59] v[273] = input[138] let part102 = ((v[258] ^ v[260])) input[23] = (v[266] ^ (part102 & v[230])) v[274] = ((v[272] & ~v[273]) ^ v[270]) v[275] = input[5] v[276] = input[119] input[138] = v[274] input[35] = ((v[274] & v[90]) ^ v[42]) let part103 = ((v[225] | v[205])) input[159] = (part103 ^ v[225]) v[277] = (v[230] & v[276]) v[278] = (v[182] ^ v[275]) v[279] = input[29] let part104 = ((v[46] ^ v[158])) input[19] = (v[254] & ~part104) v[280] = (v[278] & v[203]) input[162] = (v[225] | v[205]) input[98] = (v[225] | v[205]) v[281] = (v[182] | v[279]) input[197] = v[261] v[282] = (v[182] & v[203]) input[140] = v[250] v[283] = ((v[182] & v[203]) ^ v[182]) v[284] = ((v[230] & v[276]) & v[98]) v[285] = input[5] input[61] = v[268] v[286] = (v[204] ^ v[196]) input[17] = v[269] input[88] = (v[267] ^ v[75]) v[287] = input[29] v[288] = (v[183] ^ input[131]) v[289] = (v[278] | v[287]) let part105 = ((v[208] | v[287])) v[290] = (part105 ^ (~v[182] & v[285])) let part106 = (((input[194] & input[59]) ^ input[69])) v[291] = ((part106 & v[90]) ^ v[167]) v[292] = input[149] let part107 = ((v[182] | v[279])) v[293] = (v[208] ^ part107) v[294] = (v[183] & v[203]) let part108 = ((v[291] | v[292])) v[295] = ((part108 ^ input[35]) ^ input[56]) let part109 = ((v[193] ^ v[279])) v[296] = (v[295] & ~part109) let part110 = ((v[291] | v[292])) v[297] = ((part110 ^ input[35]) ^ input[56]) v[298] = ((v[193] & ~v[203]) & v[295]) v[299] = ~v[295] v[300] = (v[230] & ~v[277]) v[301] = (v[283] & ~v[295]) let part111 = ((v[250] ^ v[243])) v[302] = (part111 & v[158]) v[303] = (v[230] & ~v[98]) v[304] = ((v[289] ^ input[25]) ^ v[201]) v[305] = ((v[280] ^ v[183]) | v[297]) v[306] = ((v[294] ^ v[182]) ^ v[301]) let part112 = ((v[284] | input[97])) v[307] = (part112 ^ v[230]) v[308] = v[297] v[309] = (v[290] | v[297]) v[310] = (v[298] ^ v[283]) let part113 = ((v[296] ^ v[293])) v[311] = (input[113] & ~part113) v[312] = (v[250] | v[243]) let part114 = ((v[301] ^ v[283])) v[313] = (part114 & input[113]) v[314] = ((input[18] ^ input[83]) ^ input[33]) let part115 = ((v[204] ^ v[196])) v[315] = (part115 & v[299]) v[316] = (input[110] ^ input[145]) v[317] = input[18] input[194] = ((v[288] & v[299]) ^ v[183]) v[318] = (v[277] | v[317]) v[319] = (v[304] ^ v[309]) v[320] = (~v[243] & v[158]) v[321] = (~v[243] & v[250]) let part116 = ((v[300] | input[18])) v[322] = (v[307] ^ part116) let part117 = ((v[250] ^ v[302])) v[323] = ((((~v[250] & v[243]) & v[158]) ^ (v[250] & v[243])) ^ (part117 & v[46])) v[324] = (v[313] ^ input[194]) v[325] = (v[182] ^ input[29]) v[326] = (input[113] & ~v[306]) v[327] = (v[314] ^ v[234]) let part118 = ((v[315] ^ v[293])) input[131] = ((v[325] ^ v[305]) ^ (part118 & input[113])) let part119 = ((v[250] & v[243])) v[328] = (~part119 & v[250]) v[329] = (v[320] ^ v[243]) v[330] = (v[321] ^ (v[243] & v[158])) v[331] = (v[243] ^ v[158]) v[332] = input[195] let part120 = ((v[250] | v[243])) v[333] = (part120 & v[158]) let part121 = ((v[310] ^ v[311])) v[334] = (v[332] & ~part121) v[335] = (v[319] ^ v[326]) let part122 = ((v[250] | v[243])) v[336] = (v[320] ^ part122) v[337] = (v[255] ^ (~v[250] & v[312])) let part123 = (((input[97] & ~v[318]) ^ (v[303] & ~input[22]))) v[338] = ((v[327] ^ (v[322] & ~input[22])) ^ (input[14] & ~part123)) v[339] = (v[231] | input[18]) v[340] = ((v[231] ^ v[316]) | input[22]) v[341] = (v[331] & ~v[250]) let part124 = ((v[320] ^ v[252])) v[342] = (v[330] ^ (v[46] & part124)) v[343] = ((v[332] & ~v[324]) ^ input[131]) let part125 = ((~v[250] & v[312])) v[344] = (v[158] & ~part125) input[2] = v[343] let part126 = ((v[333] ^ v[252])) v[345] = ((part126 & v[46]) ^ v[337]) v[346] = (v[328] ^ (~v[250] & v[158])) let part127 = (((~v[250] & v[158]) ^ v[252])) v[347] = (v[46] & ~part127) v[348] = (v[335] ^ v[334]) v[349] = v[158] v[350] = v[338] v[351] = (v[235] ^ v[340]) v[352] = ((v[321] & v[349]) ^ v[312]) let part128 = ((v[329] | v[46])) v[353] = ((part128 ^ v[349]) ^ (v[323] & v[261])) v[354] = (v[46] & ~v[329]) v[355] = (v[342] & v[261]) v[356] = ((v[46] & ~v[302]) ^ v[341]) v[357] = (v[250] ^ (v[250] & v[349])) input[149] ^= input[2] v[358] = (v[333] ^ v[321]) v[359] = ((((v[336] & ~v[46]) ^ v[263]) ^ v[308]) ^ (v[261] & ~v[345])) let part129 = ((v[250] & v[349])) v[360] = (v[46] & ~part129) v[361] = (input[105] ^ v[277]) let part130 = ((v[335] ^ v[334])) v[362] = (part130 & v[269]) v[363] = (v[356] ^ v[355]) v[364] = (v[354] ^ v[336]) v[365] = (((v[357] & v[46]) ^ v[328]) ^ v[302]) v[366] = (v[269] & ~v[362]) v[367] = ~input[149] v[368] = (v[363] & v[367]) let part131 = ((v[346] ^ v[347])) let part132 = ((v[364] ^ (v[261] & ~part131))) let part133 = (((v[321] & v[349]) ^ v[321])) let part134 = (((part133 & ~v[46]) ^ v[357])) let part135 = ((v[344] ^ v[250])) v[369] = ((((v[358] ^ v[180]) ^ (v[46] & ~part135)) ^ (v[261] & ~part134)) ^ (part132 & v[367])) let part136 = (((v[361] ^ v[239]) | input[22])) v[370] = ((((v[318] ^ (v[231] & v[240])) ^ input[154]) ^ v[300]) ^ part136) v[371] = ((v[335] ^ v[334]) ^ v[269]) let part137 = ((v[254] | (v[350] ^ v[75]))) v[372] = ((part137 ^ v[350]) ^ v[75]) v[373] = (v[368] ^ v[230]) let part138 = ((v[349] ^ v[250])) let part139 = ((v[352] ^ (part138 & v[46]))) v[374] = (((v[261] & ~part139) ^ v[365]) | input[149]) let part140 = ((v[352] ^ v[259])) v[375] = (((v[360] ^ v[4]) ^ v[337]) ^ (part140 & v[261])) let part141 = (((v[284] ^ v[230]) | input[97])) v[376] = (part141 & input[14]) let part142 = (((((v[318] & v[240]) ^ v[236]) ^ input[119]) | input[22])) let part143 = ((v[339] ^ v[231])) let part144 = ((v[351] ^ (v[240] & part143))) v[377] = ((((((input[14] & ~part144) ^ part142) ^ input[55]) ^ input[97]) ^ v[239]) ^ v[230]) let part145 = ((v[348] | v[269])) v[378] = (part145 & ~v[222]) let part146 = ((v[353] | input[149])) v[379] = (v[359] ^ part146) v[380] = (v[373] ^ v[268]) input[6] = (v[373] ^ v[268]) input[168] = v[379] input[111] = ~v[379] input[46] = v[369] input[110] = (v[210] & v[377]) let part147 = ((v[75] | v[350])) let part148 = ((v[75] | v[350])) let part149 = (((part147 & ~v[75]) | v[254])) v[381] = (part149 ^ (part148 & ~v[75])) let part150 = ((v[348] & v[269])) let part151 = ((v[222] | v[269])) let part152 = ((part151 ^ (v[269] & ~part150))) v[382] = (((v[348] ^ v[269]) ^ v[222]) ^ (part152 & v[83])) v[383] = (v[375] ^ v[374]) input[20] = (v[375] ^ v[374]) v[384] = (v[370] ^ v[376]) v[385] = input[29] let part153 = ((v[254] | (v[350] ^ v[75]))) v[386] = ((part153 ^ v[350]) ^ (~v[348] & v[372])) input[55] = v[377] let part154 = ((v[348] | v[269])) v[387] = ((part154 & ~v[269]) ^ v[378]) let part155 = ((v[208] ^ input[29])) v[388] = (part155 & v[299]) v[389] = input[29] input[25] = v[348] input[70] = (v[348] & v[269]) v[390] = input[113] input[33] = v[350] input[135] = v[384] input[56] = v[308] let part156 = ((v[348] & v[269])) input[76] = (v[269] & ~part156) v[391] = input[173] input[74] = v[381] input[120] = (v[348] ^ v[269]) input[128] = v[386] input[93] = (v[348] | v[269]) let part157 = ((v[308] | v[389])) let part158 = (((v[281] ^ v[193]) ^ part157)) v[392] = (part158 & input[113]) input[71] = v[387] input[109] = v[382] let part159 = ((v[350] ^ v[75])) v[393] = (part159 & ~v[254]) v[394] = (v[350] ^ v[254]) let part160 = ((v[350] & v[75])) v[395] = ((v[75] & ~part160) | v[254]) let part161 = (((v[196] ^ v[385]) ^ (v[293] & v[299]))) let part162 = ((((v[293] & v[299]) ^ v[325]) ^ (v[390] & ~part161))) v[396] = ((((((part162 & input[195]) ^ v[392]) ^ v[391]) ^ input[5]) ^ v[282]) ^ v[388]) let part163 = ((v[350] | v[254])) v[397] = (part163 ^ v[350]) let part164 = ((v[75] | v[254])) v[398] = (v[350] ^ part164) let part165 = ((v[75] | v[254])) v[399] = (part165 ^ v[75]) v[400] = ((v[350] & ~v[75]) & ~v[254]) v[401] = (v[348] & ~v[269]) let part166 = ((v[350] ^ v[254])) v[402] = ((v[348] & ~part166) & ~v[159]) let part167 = ((v[350] | v[254])) let part168 = (((v[350] ^ v[75]) ^ part167)) v[403] = (part168 & ~v[348]) let part169 = ((v[350] | v[254])) let part170 = ((v[75] | v[350])) let part171 = (((part170 & ~v[75]) ^ part169)) v[404] = (v[395] ^ (~v[348] & part171)) v[405] = ((v[75] | v[350]) | v[254]) v[406] = (input[104] ^ v[398]) v[407] = (v[182] ^ input[44]) let part172 = ((v[350] | v[254])) v[408] = (((part172 & ~v[348]) ^ v[393]) ^ v[75]) input[144] = (~v[348] & v[269]) let part173 = (((v[348] | v[75]) | v[254])) let part174 = (((v[348] | v[75]) | v[254])) let part175 = ((part174 ^ v[397])) v[409] = ((v[381] ^ part173) ^ (part175 & ~v[159])) v[410] = (v[396] & ~v[384]) v[411] = (v[394] ^ input[14]) v[412] = (v[386] ^ v[402]) v[413] = (v[404] ^ v[75]) v[414] = (v[398] ^ input[192]) v[415] = (v[308] & ~v[407]) let part176 = ((v[293] | v[308])) v[416] = (part176 ^ v[293]) v[417] = (v[348] & ~v[222]) v[418] = (v[348] | v[393]) let part177 = ((v[348] | v[398])) v[419] = ((v[393] ^ v[350]) ^ part177) v[420] = ((v[348] | v[269]) | v[222]) v[421] = (input[144] & ~v[222]) let part178 = ((v[348] | v[222])) v[422] = (v[401] ^ part178) v[423] = (v[384] & ~v[205]) let part179 = ((v[396] & ~v[384])) v[424] = (v[396] & ~part179) v[425] = (v[384] & ~v[396]) v[426] = (v[315] ^ v[216]) v[427] = (v[286] | v[308]) v[428] = (v[411] ^ (v[348] & ~v[372])) let part180 = ((v[75] | v[350])) let part181 = ((v[405] ^ part180)) v[429] = (~v[348] & part181) let part182 = (((v[395] ^ v[350]) | v[348])) v[430] = ((v[406] ^ v[403]) ^ (part182 & ~v[159])) v[431] = (v[416] & input[113]) v[432] = (v[415] ^ v[288]) let part183 = ((v[408] | v[159])) let part184 = ((v[348] | v[399])) v[433] = ((part184 ^ v[267]) ^ part183) v[434] = ((v[400] & v[348]) ^ v[397]) let part185 = ((v[378] ^ v[348])) v[435] = (v[83] & ~part185) v[436] = input[144] let part186 = ((v[348] | v[269])) let part187 = ((part186 ^ v[222])) v[437] = (part187 & v[83]) let part188 = ((v[348] | v[269])) let part189 = ((v[378] ^ part188)) v[438] = (v[83] & ~part189) input[43] = (v[418] ^ v[271]) let part190 = ((v[348] | v[269])) input[68] = ((v[348] & ~v[222]) ^ part190) v[439] = (v[436] ^ v[420]) v[440] = (v[419] & ~v[159]) v[441] = (v[420] ^ v[348]) input[83] = (v[421] ^ v[366]) let part191 = ((v[366] | v[222])) let part192 = ((part191 ^ v[366])) v[442] = (part192 & v[83]) v[443] = (v[269] ^ v[222]) v[444] = (v[348] ^ (~v[222] & v[269])) v[445] = (v[83] & ~v[422]) v[446] = (v[422] | v[83]) v[447] = (v[83] | v[269]) v[448] = (v[417] ^ v[269]) v[449] = ((v[396] ^ v[384]) | v[205]) input[106] = (v[211] ^ v[427]) v[450] = (v[428] ^ (v[412] & v[206])) let part193 = ((v[75] | v[350])) let part194 = (((v[395] ^ part193) | v[348])) v[451] = (((part194 ^ v[395]) ^ v[350]) | v[159]) v[452] = ((v[414] ^ (v[348] & ~v[271])) ^ (v[413] & ~v[159])) v[453] = (input[113] & ~v[432]) v[454] = (v[206] & ~v[433]) input[104] = (v[430] ^ (v[206] & ~v[409])) v[455] = (v[434] | v[159]) v[456] = (v[438] ^ input[68]) v[457] = (input[43] ^ input[5]) v[458] = (v[440] ^ v[429]) v[459] = (v[437] ^ input[68]) v[460] = (v[83] & ~v[439]) v[461] = (v[435] ^ input[83]) let part195 = ((v[348] | v[222])) v[462] = (v[362] ^ part195) let part196 = ((v[348] | v[222])) v[463] = (part196 ^ v[348]) v[464] = (v[83] & ~v[444]) let part197 = ((v[348] ^ v[222])) v[465] = (part197 & v[83]) v[466] = ((~v[222] & v[83]) & v[401]) v[467] = v[441] v[468] = (v[222] & ~v[83]) v[469] = (v[417] & v[83]) let part198 = ((v[423] ^ v[384])) v[470] = (~v[225] & part198) input[86] = (v[424] ^ v[449]) v[471] = (v[451] ^ v[450]) let part199 = ((v[426] ^ v[431])) v[472] = (input[195] & part199) input[44] = (input[106] ^ v[453]) v[473] = (v[462] ^ v[83]) v[474] = ((v[448] ^ v[446]) | v[350]) let part200 = ((v[410] | v[205])) input[134] = (part200 ^ (v[396] & v[384])) v[475] = input[86] input[173] = v[396] v[476] = ((v[449] ^ v[396]) ^ v[384]) v[477] = (v[475] & v[225]) v[478] = input[44] input[14] = v[471] input[192] = (v[452] ^ v[454]) input[82] = (v[472] ^ v[478]) input[183] = ~input[104] input[188] = ((v[456] & ~v[350]) ^ v[382]) input[180] = (v[466] ^ v[371]) input[5] = ((v[457] ^ v[455]) ^ (v[206] & ~v[458])) let part201 = ((v[461] | v[350])) input[181] = ((v[460] ^ v[387]) ^ part201) let part202 = ((v[459] | v[350])) input[172] = ((v[463] ^ v[464]) ^ part202) let part203 = ((v[467] ^ v[442])) input[177] = (v[473] ^ (part203 & ~v[350])) let part204 = ((v[350] | v[468])) input[117] = ((v[466] ^ v[371]) ^ part204) let part205 = ((v[445] ^ v[443])) input[79] = ((v[465] ^ v[417]) ^ (part205 & ~v[350])) let part206 = ((v[447] ^ v[417])) input[27] = ((part206 & ~v[350]) ^ v[448]) v[479] = ((v[452] ^ v[454]) | v[383]) input[145] = ((v[469] ^ v[443]) ^ v[474]) input[101] = ((v[452] ^ v[454]) ^ v[383]) input[31] = v[479] input[161] = v[479] let part207 = ((v[452] ^ v[454])) input[50] = (part207 & ~v[383]) input[64] = v[479] v[480] = input[134] input[72] = (v[380] & ~v[471]) input[94] = (v[471] & ~v[380]) let part208 = ((v[410] | v[205])) input[30] = (v[205] ^ (v[225] & ~part208)) v[481] = input[86] let part209 = ((v[410] | v[205])) input[184] = ((v[470] ^ v[384]) ^ part209) input[202] = (v[410] ^ v[205]) let part210 = ((v[424] | v[205])) let part211 = (((part210 ^ v[396]) | v[225])) input[142] = ((part211 ^ v[410]) ^ v[205]) input[34] = ((v[410] & v[205]) ^ (~v[225] & v[384])) input[105] = (v[480] ^ v[470]) input[67] = (v[476] & v[225]) input[66] = ((v[477] ^ v[410]) ^ v[205]) let part212 = ((v[410] | v[205])) let part213 = (((v[396] ^ v[384]) ^ part212)) input[52] = (v[481] ^ (part213 & ~v[225])) input[170] = (v[396] | v[205]) let part214 = (((v[425] & ~v[205]) ^ v[425])) input[153] = (part214 & ~v[225]) let part215 = ((v[396] | v[205])) let part216 = (((v[425] & ~v[205]) ^ (v[396] & v[384]))) input[123] = ((part216 & ~v[225]) ^ part215) let part217 = ((v[410] | v[205])) input[171] = ((v[425] ^ part217) ^ ((v[396] & v[205]) & ~v[225])) input[77] = ((v[396] & v[205]) | v[225]) let part218 = ((v[396] ^ v[384])) input[91] = ((v[396] ^ (~v[225] & v[423])) ^ (part218 & ~v[205])) let part219 = ((v[423] | v[225])) let part220 = (((v[384] | v[205]) | v[396])) input[176] = (((part220 ^ v[396]) ^ v[384]) ^ part219) return input } }
gpl-3.0
f0666f65105c9f13a6c57a45d954628e
39.558411
117
0.401936
2.475542
false
false
false
false
jessemillar/zombits
Rytsar/Rytsar/MapViewController.swift
2
13116
// // MapViewController.swift // Rytsar // // Created by Jesse Millar on 1/24/16. // Copyright © 2016 Jesse Millar. All rights reserved. // import UIKit import MapKit import CoreLocation import CoreMotion import AVFoundation import AudioToolbox struct Globals { static var maxAmmo = 3 static var ammo = maxAmmo } class Enemy: NSObject { // Used to make an array of enemies from the database var id : Int = 0 // Initialize to a "null" value that shouldn't ever be a valid ID on the server var latitude : Double = 0.0 // Initialize to a "null" double var longitude : Double = 0.0 } class MapViewController: UIViewController, MKMapViewDelegate, CLLocationManagerDelegate { @IBOutlet weak var mapView: MKMapView! var enemies = [Enemy]() let baseURL = "http://woodsman.jessemillar.com:33333" let enemyRadius = 1.0 // Kilometers let shootRadius = 150.0 // In meters var enemiesLoaded = false var canShoot = true var canReload = true let reloadTime = 1.5 // In seconds (needs to be a double) var userLatitude = 0.0 var userLongitude = 0.0 var shootOrientation = true // Make sure we're in gun orientation before allowing a shot var enemyAimedAtID = 0 var crossbowShoot = AVAudioPlayer() var crossbowCock = AVAudioPlayer() var crossbowEmpty = AVAudioPlayer() let locationManager = CLLocationManager() let motionManager = CMMotionManager() override func viewDidLoad() { super.viewDidLoad() let crossbowShootFile = NSBundle.mainBundle().URLForResource("shoot", withExtension: "wav") do { try crossbowShoot = AVAudioPlayer(contentsOfURL: crossbowShootFile!, fileTypeHint: nil) } catch { print(error) } let crossbowCockFile = NSBundle.mainBundle().URLForResource("cock", withExtension: "wav") do { try crossbowCock = AVAudioPlayer(contentsOfURL: crossbowCockFile!, fileTypeHint: nil) } catch { print(error) } let crossbowEmptyFile = NSBundle.mainBundle().URLForResource("empty", withExtension: "wav") do { try crossbowEmpty = AVAudioPlayer(contentsOfURL: crossbowEmptyFile!, fileTypeHint: nil) } catch { print(error) } self.locationManager.delegate = self self.locationManager.desiredAccuracy = kCLLocationAccuracyBest self.locationManager.requestWhenInUseAuthorization() // Only use location services when the app is in use self.locationManager.startUpdatingLocation() // Watch the GPS self.locationManager.startUpdatingHeading() // Watch the compass self.mapView.showsUserLocation = true self.mapView.rotateEnabled = true // if motionManager.accelerometerAvailable{ // motionManager.startAccelerometerUpdatesToQueue(NSOperationQueue()) { (data: CMAccelerometerData?, error: NSError?) in // guard data != nil else { // print("There was an error: \(error)") // return // } // // let cone = 0.1 // // if abs(data!.acceleration.x) > (0.9 - cone) && abs(data!.acceleration.x) < (0.9 + cone){ // self.shootOrientation = true // } else { // self.shootOrientation = false // } // } // } else { // print("Accelerometer is not available") // } if motionManager.accelerometerAvailable{ motionManager.startGyroUpdatesToQueue(NSOperationQueue()) { (data: CMGyroData?, error: NSError?) in guard data != nil else { print("There was an error: \(error)") return } if data!.rotationRate.y < -15{ if self.canReload { Globals.ammo = Globals.maxAmmo self.crossbowCock.play() print("RELOAD") } } if data!.rotationRate.z < -8{ self.shoot() } } } else { print("Accelerometer is not available") } } func shoot() { if self.canShoot && Globals.ammo > 0 { Globals.ammo-- self.canShoot = false self.canReload = false // Don't allow reloading RIGHT after firing self.crossbowShoot.play() // Play a crossbow firing sound self.shootEnemy() let date = NSDate().dateByAddingTimeInterval(self.reloadTime) let timer = NSTimer(fireDate: date, interval: 0, target: self, selector: "canShootEnable", userInfo: nil, repeats: false) NSRunLoop.mainRunLoop().addTimer(timer, forMode: NSRunLoopCommonModes) } else if Globals.ammo == 0 && self.canShoot { print("Playing empty sound") self.canShoot = false self.canReload = false // Don't allow reloading RIGHT after firing self.crossbowCock.play() let date = NSDate().dateByAddingTimeInterval(self.reloadTime) let timer = NSTimer(fireDate: date, interval: 0, target: self, selector: "canShootEnable", userInfo: nil, repeats: false) NSRunLoop.mainRunLoop().addTimer(timer, forMode: NSRunLoopCommonModes) } } func canShootEnable() { self.canShoot = true // Allows firing for real and when we're out of ammo (just to play the empty sound) self.canReload = true } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // Location delegate methods func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { let location = locations.last userLatitude = location!.coordinate.latitude userLongitude = location!.coordinate.longitude mapView.setUserTrackingMode(MKUserTrackingMode.FollowWithHeading, animated: true) let overlays = mapView.overlays // Remove previous range circles so we don't get duplicates mapView.removeOverlays(overlays) let tempLocation = CLLocation(latitude: userLatitude as CLLocationDegrees, longitude: userLongitude as CLLocationDegrees) addRadiusCircle(tempLocation) if !enemiesLoaded { enemiesLoaded = true getEnemies() } } // MARK: MapView delegate for drawing annotations (mainly the shooting radius) func addRadiusCircle(location: CLLocation){ self.mapView.delegate = self let circle = MKCircle(centerCoordinate: location.coordinate, radius: shootRadius as CLLocationDistance) self.mapView.addOverlay(circle) } func mapView(mapView: MKMapView!, rendererForOverlay overlay: MKOverlay!) -> MKOverlayRenderer! { if overlay is MKCircle { let circle = MKCircleRenderer(overlay: overlay) circle.strokeColor = UIColor(red:0.94, green:0.55, blue:0.23, alpha:0.5) // rgb(239, 139, 59) circle.fillColor = UIColor(red:0.94, green:0.55, blue:0.23, alpha:0.25) // rgb(239, 139, 59) circle.lineWidth = 1 return circle } else { return nil } } // MARK: Track compass heading and detect aiming func locationManager(manager: CLLocationManager, didUpdateHeading newHeading: CLHeading) { for enemy in enemies { let distance = distanceTo(enemy.latitude, longitude: enemy.longitude) let heading = newHeading.magneticHeading let angle = angleTo(userLatitude, lon1: userLongitude, lat2: enemy.latitude, lon2: enemy.longitude) let halfCone = 8.0 // Make the aiming cone match up with the default compass cone var leftCone = angle - halfCone*4 // Not sure why I have to do this to get the cone to the right size... var rightCone = angle + halfCone if leftCone < 0 { leftCone += 360 } if rightCone > 360 { rightCone -= 360 } if heading > leftCone && heading < rightCone && distance < shootRadius { AudioServicesPlayAlertSound(SystemSoundID(kSystemSoundID_Vibrate)) enemyAimedAtID = enemy.id break } else { enemyAimedAtID = 0 } } } func locationManager(manager: CLLocationManager, didFailWithError error: NSError) { print("Errors: " + error.localizedDescription) } func angleTo(lat1: Float64, lon1: Float64, lat2: Float64, lon2: Float64) -> Float64 { var angle = toDegrees(atan2(sin(toRadians(lon2-lon1))*cos(toRadians(lat2)), cos(toRadians(lat1))*sin(toRadians(lat2))-sin(toRadians(lat1))*cos(toRadians(lat2))*cos(toRadians(lon2-lon1)))) if angle < 0 { angle = angle + 360 } return angle } func distanceTo(latitude: Float64, longitude: Float64) -> Float64 { let from = CLLocation(latitude: userLatitude, longitude: userLongitude) let to = CLLocation(latitude: latitude, longitude: longitude) let distance = from.distanceFromLocation(to) return distance } func toDegrees(number: Float64) -> Float64 { let PI = 3.14159 return number*180/PI } func toRadians(number: Float64) -> Float64 { let PI = 3.14159 return number*PI/180 } func getEnemies() { let latitude = "\(userLatitude)" let longitude = "\(userLongitude)" let radius = "\(enemyRadius)" var apiURL = baseURL apiURL += "/database/" apiURL += latitude + "/" apiURL += longitude + "/" + radius let url = NSURL(string: apiURL) let task = NSURLSession.sharedSession().dataTaskWithURL(url!) {(data, response, error) in do { let json = try NSJSONSerialization.JSONObjectWithData(data!, options: .AllowFragments) if let coordinates = json as? [[String: AnyObject]] { for cursor in coordinates { let newEnemy : Enemy = Enemy() if let id = cursor["id"] as? String { newEnemy.id = Int(id)! } if let latitude = cursor["latitude"] as? String { newEnemy.latitude = Double(latitude)! } if let longitude = cursor["longitude"] as? String { newEnemy.longitude = Double(longitude)! } self.enemies.append(newEnemy) } } } catch { print("Error serializing JSON: \(error)") } for enemy in self.enemies { let pin = EnemyPin(coordinate: CLLocationCoordinate2D(latitude: enemy.latitude, longitude: enemy.longitude)) self.mapView.addAnnotation(pin) } } task.resume() } func shootEnemy() { if enemyAimedAtID > 0 { let enemyID = "\(enemyAimedAtID)" let endpoint: String = baseURL + "/delete/" + enemyID let endpointRequest = NSMutableURLRequest(URL: NSURL(string: endpoint)!) endpointRequest.HTTPMethod = "DELETE" let config = NSURLSessionConfiguration.defaultSessionConfiguration() let session = NSURLSession(configuration: config) let task = session.dataTaskWithRequest(endpointRequest, completionHandler: { (data, response, error) in guard let _ = data else { print("Error shooting enemy") return } // Run the following as an asynchronous process so the UI can update dispatch_async(dispatch_get_main_queue(), { // Kill all the enemy pins and repopulate with the updates from the database let allAnnotations = self.mapView.annotations self.mapView.removeAnnotations(allAnnotations) self.enemies.removeAll() // Wipe the local array so we don't get duplicate pins self.getEnemies() }) }) task.resume() } } }
mit
d10e7e270831432d15c2e6bec9a8afff
37.236152
195
0.565154
5.063707
false
false
false
false
SunghanKim/firefox-ios
Client/Frontend/Widgets/AutocompleteTextField.swift
1
6476
/* 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/. */ // This code is loosely based on https://github.com/Antol/APAutocompleteTextField import UIKit import Shared /// Delegate for the text field events. Since AutocompleteTextField owns the UITextFieldDelegate, /// callers must use this instead. protocol AutocompleteTextFieldDelegate: class { func autocompleteTextField(autocompleteTextField: AutocompleteTextField, didEnterText text: String) func autocompleteTextFieldShouldReturn(autocompleteTextField: AutocompleteTextField) -> Bool func autocompleteTextFieldShouldClear(autocompleteTextField: AutocompleteTextField) -> Bool func autocompleteTextFieldDidBeginEditing(autocompleteTextField: AutocompleteTextField) } private struct AutocompleteTextFieldUX { static let HighlightColor = UIColor(rgb: 0xccdded) } class AutocompleteTextField: UITextField, UITextFieldDelegate { var autocompleteDelegate: AutocompleteTextFieldDelegate? private var completionActive = false private var enteredTextLength = 0 private var notifyTextChanged: (() -> ())? = nil override init(frame: CGRect) { super.init(frame: frame) commonInit() } required init(coder aDecoder: NSCoder) { super.init(coder: aDecoder) commonInit() } private func commonInit() { super.delegate = self notifyTextChanged = debounce(0.1, { if self.editing { self.autocompleteDelegate?.autocompleteTextField(self, didEnterText: self.text) } }) } func highlightAll() { if !text.isEmpty { let attributedString = NSMutableAttributedString(string: text) attributedString.addAttribute(NSBackgroundColorAttributeName, value: AutocompleteTextFieldUX.HighlightColor, range: NSMakeRange(0, count(text))) attributedText = attributedString enteredTextLength = 0 completionActive = true } selectedTextRange = textRangeFromPosition(beginningOfDocument, toPosition: beginningOfDocument) } /// Commits the completion by setting the text and removing the highlight. private func applyCompletion() { if completionActive { self.attributedText = NSAttributedString(string: text) completionActive = false } } /// Removes the autocomplete-highlighted text from the field. private func removeCompletion() { if completionActive { let enteredText = text.substringToIndex(advance(text.startIndex, enteredTextLength, text.endIndex)) // Workaround for stuck highlight bug. if enteredTextLength == 0 { attributedText = NSAttributedString(string: " ") } attributedText = NSAttributedString(string: enteredText) completionActive = false } } func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool { if completionActive && string.isEmpty { // Characters are being deleted, so clear the autocompletion, but don't change the text. removeCompletion() return false } return true } func setAutocompleteSuggestion(suggestion: String?) { if let suggestion = suggestion where editing { // Check that the length of the entered text is shorter than the length of the suggestion. // This ensures that completionActive is true only if there are remaining characters to // suggest (which will suppress the caret). if suggestion.startsWith(text) && count(text) < count(suggestion) { let endingString = suggestion.substringFromIndex(advance(suggestion.startIndex, count(self.text))) let completedAndMarkedString = NSMutableAttributedString(string: suggestion) completedAndMarkedString.addAttribute(NSBackgroundColorAttributeName, value: AutocompleteTextFieldUX.HighlightColor, range: NSMakeRange(enteredTextLength, count(endingString))) attributedText = completedAndMarkedString completionActive = true } } } func textFieldDidBeginEditing(textField: UITextField) { autocompleteDelegate?.autocompleteTextFieldDidBeginEditing(self) } func textFieldShouldEndEditing(textField: UITextField) -> Bool { applyCompletion() return true } func textFieldShouldReturn(textField: UITextField) -> Bool { return autocompleteDelegate?.autocompleteTextFieldShouldReturn(self) ?? true } func textFieldShouldClear(textField: UITextField) -> Bool { removeCompletion() return autocompleteDelegate?.autocompleteTextFieldShouldClear(self) ?? true } override func setMarkedText(markedText: String!, selectedRange: NSRange) { // Clear the autocompletion if any provisionally inserted text has been // entered (e.g., a partial composition from a Japanese keyboard). removeCompletion() super.setMarkedText(markedText, selectedRange: selectedRange) } override func insertText(text: String) { removeCompletion() super.insertText(text) enteredTextLength = count(self.text) notifyTextChanged?() } override func caretRectForPosition(position: UITextPosition!) -> CGRect { return completionActive ? CGRectZero : super.caretRectForPosition(position) } override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) { if !completionActive { super.touchesBegan(touches, withEvent: event) } } override func touchesMoved(touches: Set<NSObject>, withEvent event: UIEvent) { if !completionActive { super.touchesMoved(touches, withEvent: event) } } override func touchesEnded(touches: Set<NSObject>, withEvent event: UIEvent) { if !completionActive { super.touchesEnded(touches, withEvent: event) } else { applyCompletion() // Set the current position to the end of the text. selectedTextRange = textRangeFromPosition(endOfDocument, toPosition: endOfDocument) } } }
mpl-2.0
d0716684ef3e31c91611b7fbb9f755da
37.319527
192
0.685608
5.802867
false
false
false
false
LQJJ/demo
86-DZMeBookRead-master/DZMeBookRead/DZMeBookRead/controller/DZMReadAuxiliary.swift
1
10236
// // DZMReadAuxiliary.swift // DZMeBookRead // // Created by 邓泽淼 on 2017/12/7. // Copyright © 2017年 DZM. All rights reserved. // import UIKit class DZMReadAuxiliary: NSObject { /// 获得触摸位置文字的Location /// /// - Parameters: /// - point: 触摸位置 /// - frameRef: CTFrame /// - Returns: 触摸位置的Index @objc class func GetTouchLocation(point:CGPoint, frameRef:CTFrame?) ->CFIndex { var location:CFIndex = -1 let line = GetTouchLine(point: point, frameRef: frameRef) if line != nil { location = CTLineGetStringIndexForPosition(line!, point) } return location } /// 获得触摸位置那一行文字的Range /// /// - Parameters: /// - point: 触摸位置 /// - frameRef: CTFrame /// - Returns: CTLine @objc class func GetTouchLineRange(point:CGPoint, frameRef:CTFrame?) ->NSRange { var range:NSRange = NSMakeRange(NSNotFound, 0) let line = GetTouchLine(point: point, frameRef: frameRef) if line != nil { let lineRange = CTLineGetStringRange(line!) range = NSMakeRange(lineRange.location == kCFNotFound ? NSNotFound : lineRange.location, lineRange.length) } return range } /// 获得触摸位置在哪一行 /// /// - Parameters: /// - point: 触摸位置 /// - frameRef: CTFrame /// - Returns: CTLine @objc class func GetTouchLine(point:CGPoint, frameRef:CTFrame?) ->CTLine? { var line:CTLine? = nil if frameRef == nil { return line } let frameRef:CTFrame = frameRef! let path:CGPath = CTFrameGetPath(frameRef) let bounds:CGRect = path.boundingBox let lines:[CTLine] = CTFrameGetLines(frameRef) as! [CTLine] if lines.isEmpty { return line } let lineCount = lines.count let origins = malloc(lineCount * MemoryLayout<CGPoint>.size).assumingMemoryBound(to: CGPoint.self) CTFrameGetLineOrigins(frameRef, CFRangeMake(0, 0), origins) for i in 0..<lineCount { let origin:CGPoint = origins[i] let tempLine:CTLine = lines[i] var lineAscent:CGFloat = 0 var lineDescent:CGFloat = 0 var lineLeading:CGFloat = 0 CTLineGetTypographicBounds(tempLine, &lineAscent, &lineDescent, &lineLeading) let lineWidth:CGFloat = bounds.width let lineheight:CGFloat = lineAscent + lineDescent + lineLeading var lineFrame = CGRect(x: origin.x, y: bounds.height - origin.y - lineAscent, width: lineWidth, height: lineheight) lineFrame = lineFrame.insetBy(dx: -DZMSpace_1, dy: -DZMSpace_6) if lineFrame.contains(point) { line = tempLine break } } free(origins) return line } /// 通过 range 返回字符串所覆盖的位置 [CGRect] /// /// - Parameter range: NSRange /// - Parameter frameRef: CTFrame /// - Parameter content: 内容字符串(有值则可以去除选中每一行区域内的 开头空格 - 尾部换行符 - 所占用的区域,不传默认返回每一行实际占用区域) /// - Returns: 覆盖位置 @objc class func GetRangeRects(range:NSRange, frameRef:CTFrame?, content:String? = nil) -> [CGRect] { var rects:[CGRect] = [] if frameRef == nil { return rects } if range.length == 0 || range.location == NSNotFound { return rects } let frameRef = frameRef! let lines:[CTLine] = CTFrameGetLines(frameRef) as! [CTLine] if lines.isEmpty { return rects } let lineCount:Int = lines.count let origins = malloc(lineCount * MemoryLayout<CGPoint>.size).assumingMemoryBound(to: CGPoint.self) CTFrameGetLineOrigins(frameRef, CFRangeMake(0, 0), origins) for i in 0..<lineCount { let line:CTLine = lines[i] let lineCFRange = CTLineGetStringRange(line) let lineRange = NSMakeRange(lineCFRange.location == kCFNotFound ? NSNotFound : lineCFRange.location, lineCFRange.length) var contentRange:NSRange = NSMakeRange(NSNotFound, 0) if (lineRange.location + lineRange.length) > range.location && lineRange.location < (range.location + range.length) { contentRange.location = max(lineRange.location, range.location) let end = min(lineRange.location + lineRange.length, range.location + range.length) contentRange.length = end - contentRange.location } if contentRange.length > 0 { // 去掉 -> 开头空格 - 尾部换行符 - 所占用的区域 if content != nil && !content!.isEmpty { let tempContent:String = content!.substring(contentRange) let spaceRanges:[NSTextCheckingResult] = tempContent.matches(pattern: "\\s\\s") if !spaceRanges.isEmpty { let spaceRange = spaceRanges.first!.range contentRange = NSMakeRange(contentRange.location + spaceRange.length, contentRange.length - spaceRange.length) } let enterRanges:[NSTextCheckingResult] = tempContent.matches(pattern: "\\n") if !enterRanges.isEmpty { let enterRange = enterRanges.first!.range contentRange = NSMakeRange(contentRange.location, contentRange.length - enterRange.length) } } // 正常使用(如果不需要排除段头空格跟段尾换行符可将上面代码删除) let xStart:CGFloat = CTLineGetOffsetForStringIndex(line, contentRange.location, nil) let xEnd:CGFloat = CTLineGetOffsetForStringIndex(line, contentRange.location + contentRange.length, nil) let origin:CGPoint = origins[i] var lineAscent:CGFloat = 0 var lineDescent:CGFloat = 0 var lineLeading:CGFloat = 0 CTLineGetTypographicBounds(line, &lineAscent, &lineDescent, &lineLeading) let contentRect:CGRect = CGRect(x: origin.x + xStart, y: origin.y - lineDescent, width: fabs(xEnd - xStart), height: lineAscent + lineDescent + lineLeading) rects.append(contentRect) } } free(origins) return rects } /// 通过 range 获得合适的 MenuRect /// /// - Parameter rects: [CGRect] /// - Parameter frameRef: CTFrame /// - Parameter viewFrame: 目标ViewFrame /// - Parameter content: 内容字符串 /// - Returns: MenuRect @objc class func GetMenuRect(range:NSRange, frameRef:CTFrame?, viewFrame:CGRect, content:String? = nil) ->CGRect { let rects = GetRangeRects(range: range, frameRef: frameRef, content: content) return GetMenuRect(rects: rects, viewFrame: viewFrame) } /// 通过 [CGRect] 获得合适的 MenuRect /// /// - Parameter rects: [CGRect] /// - Parameter viewFrame: 目标ViewFrame /// - Returns: MenuRect @objc class func GetMenuRect(rects:[CGRect], viewFrame:CGRect) ->CGRect { var menuRect:CGRect = CGRect.zero if rects.isEmpty { return menuRect } if rects.count == 1 { menuRect = rects.first! }else{ menuRect = rects.first! let count = rects.count for i in 1..<count { let rect = rects[i] let minX = min(menuRect.origin.x, rect.origin.x) let maxX = max(menuRect.origin.x + menuRect.size.width, rect.origin.x + rect.size.width) let minY = min(menuRect.origin.y, rect.origin.y) let maxY = max(menuRect.origin.y + menuRect.size.height, rect.origin.y + rect.size.height) menuRect.origin.x = minX menuRect.origin.y = minY menuRect.size.width = maxX - minX menuRect.size.height = maxY - minY } } menuRect.origin.y = viewFrame.height - menuRect.origin.y - menuRect.size.height return menuRect } /// 获取行高 /// /// - Parameter line: CTLine /// - Returns: 行高 @objc class func GetLineHeight(frameRef:CTFrame?) ->CGFloat { if frameRef == nil { return 0 } let frameRef:CTFrame = frameRef! let lines:[CTLine] = CTFrameGetLines(frameRef) as! [CTLine] if lines.isEmpty { return 0 } return GetLineHeight(line: lines.first) } /// 获取行高 /// /// - Parameter line: CTLine /// - Returns: 行高 @objc class func GetLineHeight(line:CTLine?) ->CGFloat { if line == nil { return 0 } var lineAscent:CGFloat = 0 var lineDescent:CGFloat = 0 var lineLeading:CGFloat = 0 CTLineGetTypographicBounds(line!, &lineAscent, &lineDescent, &lineLeading) return lineAscent + lineDescent + lineLeading } }
apache-2.0
4269edf61cd048436ff56d3fa2ea8704
30.215873
172
0.526289
4.702535
false
false
false
false
NicholasTD07/SwiftDailyAPI
SwiftDailyAPITests/Specs/ExtensionSpecs.swift
1
1559
// // ExtensionSpecs.swift // SwiftDailyAPI // // Created by Nicholas Tian on 16/06/2015. // Copyright © 2015 nickTD. All rights reserved. // import Quick import Nimble import SwiftDailyAPI class ExtensionSpecs: QuickSpec { override func spec() { describe("NSDate.init(_ year:month:day:)") { it("returns the correct date") { let date = NSDate.dateAt(year: 2015, month: 5, day: 25)! let components = NSDateComponents() components.year = 2015 components.month = 5 components.day = 25 let theDate = NSCalendar.currentCalendar().dateFromComponents(components)! expect(date.compare(theDate)).to(equal(NSComparisonResult.OrderedSame)) let dateFormatter = NSDateFormatter() dateFormatter.dateFormat = "yyyyMMdd" expect(dateFormatter.stringFromDate(date)).to(equal("20150525")) } } describe("NSDate.daysBefore") { it("returns date before the date") { let today = NSDate() let dayBeforeToday = today.daysBefore(1) expect(dayBeforeToday.compare(today)).to(equal(NSComparisonResult.OrderedAscending)) } } describe("NSDate.dayslater") { it("returns date after the date") { let today = NSDate() let dayAfterToday = today.daysAfter(1) expect(dayAfterToday.compare(today)).to(equal(NSComparisonResult.OrderedDescending)) } } it("is comparable") { let today = NSDate() expect(today) < today.dayAfter() expect(today) > today.dayBefore() } } }
mit
1611e567db8e85541f793e66ae2a762d
26.333333
92
0.644416
4.199461
false
false
false
false
Syject/MyLessPass-iOS
LessPass/Model/Generator/Template.swift
1
354
// // Template.swift // LessPass // // Created by Dan Slupskiy on 11.01.17. // Copyright © 2017 Syject. All rights reserved. // import Foundation class Template { var hasLowerCaseLetters = true var hasUpperCaseLetters = true var hasNumbers = true var hasSymbols = true var length = 16 var keylen = 32 var counter = 1 }
gpl-3.0
300e9e192b6ae434e76081a1cc410633
17.578947
49
0.660057
3.602041
false
false
false
false
cinco-interactive/BluetoothKit
Source/BKConnectionPool.swift
1
7473
// // BluetoothKit // // Copyright (c) 2015 Rasmus Taulborg Hummelmose - https://github.com/rasmusth // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import Foundation import CoreBluetooth internal protocol BKConnectionPoolDelegate: class { func connectionPool(connectionPool: BKConnectionPool, remotePeripheralDidDisconnect remotePeripheral: BKRemotePeripheral) } internal class BKConnectionPool: BKCBCentralManagerConnectionDelegate { // MARK: Enums internal enum Error: ErrorType { case NoCentralManagerSet case AlreadyConnected case AlreadyConnecting case NoSupportForPeripheralEntitiesWithoutPeripheralsYet case Interrupted case NoConnectionAttemptForRemotePeripheral case NoConnectionForRemotePeripheral case TimeoutElapsed case Internal(underlyingError: ErrorType?) } // MARK: Properties internal weak var delegate: BKConnectionPoolDelegate? internal var centralManager: CBCentralManager! internal var connectedRemotePeripherals = [BKRemotePeripheral]() private var connectionAttempts = [BKConnectionAttempt]() // MARK: Internal Functions internal func connectWithTimeout(timeout: NSTimeInterval, remotePeripheral: BKRemotePeripheral, completionHandler: ((peripheralEntity: BKRemotePeripheral, error: Error?) -> Void)) throws { guard centralManager != nil else { throw Error.NoCentralManagerSet } guard !connectedRemotePeripherals.contains(remotePeripheral) else { throw Error.AlreadyConnected } guard !connectionAttempts.map({ connectionAttempt in return connectionAttempt.remotePeripheral }).contains(remotePeripheral) else { throw Error.AlreadyConnecting } guard remotePeripheral.peripheral != nil else { throw Error.NoSupportForPeripheralEntitiesWithoutPeripheralsYet } let timer = NSTimer.scheduledTimerWithTimeInterval(timeout, target: self, selector: #selector(BKConnectionPool.timerElapsed(_:)), userInfo: nil, repeats: false) remotePeripheral.prepareForConnection() connectionAttempts.append(BKConnectionAttempt(remotePeripheral: remotePeripheral, timer: timer, completionHandler: completionHandler)) centralManager!.connectPeripheral(remotePeripheral.peripheral!, options: nil) } internal func interruptConnectionAttemptForRemotePeripheral(remotePeripheral: BKRemotePeripheral) throws { let connectionAttempt = connectionAttemptForRemotePeripheral(remotePeripheral) guard connectionAttempt != nil else { throw Error.NoConnectionAttemptForRemotePeripheral } failConnectionAttempt(connectionAttempt!, error: .Interrupted) } internal func disconnectRemotePeripheral(remotePeripheral: BKRemotePeripheral) throws { let connectedRemotePeripheral = connectedRemotePeripherals.filter({ $0 == remotePeripheral }).last guard connectedRemotePeripheral != nil else { throw Error.NoConnectionForRemotePeripheral } connectedRemotePeripheral?.unsubscribe() centralManager.cancelPeripheralConnection(connectedRemotePeripheral!.peripheral!) } internal func reset() { for connectionAttempt in connectionAttempts { failConnectionAttempt(connectionAttempt, error: .Interrupted) } connectionAttempts.removeAll() for remotePeripheral in connectedRemotePeripherals { delegate?.connectionPool(self, remotePeripheralDidDisconnect: remotePeripheral) } connectedRemotePeripherals.removeAll() } // MARK: Private Functions private func connectionAttemptForRemotePeripheral(remotePeripheral: BKRemotePeripheral) -> BKConnectionAttempt? { return connectionAttempts.filter({ $0.remotePeripheral == remotePeripheral }).last } private func connectionAttemptForTimer(timer: NSTimer) -> BKConnectionAttempt? { return connectionAttempts.filter({ $0.timer == timer }).last } private func connectionAttemptForPeripheral(peripheral: CBPeripheral) -> BKConnectionAttempt? { return connectionAttempts.filter({ $0.remotePeripheral.peripheral == peripheral }).last } @objc private func timerElapsed(timer: NSTimer) { failConnectionAttempt(connectionAttemptForTimer(timer)!, error: .TimeoutElapsed) } private func failConnectionAttempt(connectionAttempt: BKConnectionAttempt, error: Error) { connectionAttempts.removeAtIndex(connectionAttempts.indexOf(connectionAttempt)!) connectionAttempt.timer.invalidate() if let peripheral = connectionAttempt.remotePeripheral.peripheral { centralManager.cancelPeripheralConnection(peripheral) } connectionAttempt.completionHandler(peripheralEntity: connectionAttempt.remotePeripheral, error: error) } private func succeedConnectionAttempt(connectionAttempt: BKConnectionAttempt) { connectionAttempt.timer.invalidate() connectionAttempts.removeAtIndex(connectionAttempts.indexOf(connectionAttempt)!) connectedRemotePeripherals.append(connectionAttempt.remotePeripheral) connectionAttempt.remotePeripheral.discoverServices() connectionAttempt.completionHandler(peripheralEntity: connectionAttempt.remotePeripheral, error: nil) } // MARK: CentralManagerConnectionDelegate internal func centralManager(central: CBCentralManager, didConnectPeripheral peripheral: CBPeripheral) { succeedConnectionAttempt(connectionAttemptForPeripheral(peripheral)!) } internal func centralManager(central: CBCentralManager, didFailToConnectPeripheral peripheral: CBPeripheral, error: NSError?) { failConnectionAttempt(connectionAttemptForPeripheral(peripheral)!, error: .Internal(underlyingError: error)) } internal func centralManager(central: CBCentralManager, didDisconnectPeripheral peripheral: CBPeripheral, error: NSError?) { if let remotePeripheral = connectedRemotePeripherals.filter({ $0.peripheral == peripheral }).last { connectedRemotePeripherals.removeAtIndex(connectedRemotePeripherals.indexOf(remotePeripheral)!) delegate?.connectionPool(self, remotePeripheralDidDisconnect: remotePeripheral) } } }
mit
132d9fdd0969fdd8d1741cb9faaad661
46.903846
192
0.744815
5.652799
false
false
false
false
apple/swift
test/Concurrency/where_clause_main_resolution.swift
7
2493
// RUN: %target-swift-frontend -disable-availability-checking -D CONFIG1 -dump-ast -parse-as-library %s | %FileCheck %s --check-prefixes=CHECK,CHECK-CONFIG1 // RUN: %target-swift-frontend -disable-availability-checking -D CONFIG2 -dump-ast -parse-as-library %s | %FileCheck %s --check-prefixes=CHECK,CHECK-CONFIG2 // RUN: %target-swift-frontend -disable-availability-checking -D CONFIG3 -dump-ast -parse-as-library %s | %FileCheck %s --check-prefixes=CHECK,CHECK-CONFIG3 // REQUIRES: concurrency protocol AppConfiguration { } struct Config1: AppConfiguration {} struct Config2: AppConfiguration {} struct Config3: AppConfiguration {} protocol App { associatedtype Configuration: AppConfiguration } // Load in the source file name and grab line numbers for default main funcs // CHECK: (source_file "[[SOURCE_FILE:[^"]+]]" // CHECK: (extension_decl range={{\[}}[[SOURCE_FILE]]:{{[0-9]+}}:{{[0-9]+}} - line:{{[0-9]+}}:{{[0-9]+}}{{\]}} App where // CHECK: (extension_decl range={{\[}}[[SOURCE_FILE]]:{{[0-9]+}}:{{[0-9]+}} - line:{{[0-9]+}}:{{[0-9]+}}{{\]}} App where // CHECK: (extension_decl range={{\[}}[[SOURCE_FILE]]:{{[0-9]+}}:{{[0-9]+}} - line:{{[0-9]+}}:{{[0-9]+}}{{\]}} App where // CHECK: (extension_decl range={{\[}}[[SOURCE_FILE]]:{{[0-9]+}}:{{[0-9]+}} - line:{{[0-9]+}}:{{[0-9]+}}{{\]}} // CHECK-NOT: where // CHECK-NEXT: (func_decl range={{\[}}[[SOURCE_FILE]]:[[DEFAULT_ASYNCHRONOUS_MAIN_LINE:[0-9]+]]:{{[0-9]+}} - line:{{[0-9]+}}:{{[0-9]+}}{{\]}} "main()" // CHECK-SAME: interface type='<Self where Self : App> (Self.Type) -> () async -> ()' extension App where Configuration == Config1 { // CHECK-CONFIG1: (func_decl implicit "$main()" interface type='(MainType.Type) -> () -> ()' // CHECK-CONFIG1: [[SOURCE_FILE]]:[[# @LINE+1 ]] static func main() { } } extension App where Configuration == Config2 { // CHECK-CONFIG2: (func_decl implicit "$main()" interface type='(MainType.Type) -> () async -> ()' // CHECK-CONFIG2: [[SOURCE_FILE]]:[[# @LINE+1 ]] static func main() async { } } extension App where Configuration == Config3 { // CHECK-CONFIG3-ASYNC: (func_decl implicit "$main()" interface type='(MainType.Type) -> () async -> ()' // CHECK-CONFIG3-ASYNC: [[SOURCE_FILE]]:[[DEFAULT_ASYNCHRONOUS_MAIN_LINE]] } extension App { static func main() async { } } @main struct MainType : App { #if CONFIG1 typealias Configuration = Config1 #elseif CONFIG2 typealias Configuration = Config2 #elseif CONFIG3 typealias Configuration = Config3 #endif }
apache-2.0
bd11a22aacab607ca424078c63725b1f
41.982759
156
0.636181
3.301987
false
true
false
false
muriarte/swift-semana-2
swift semana 2.swift
1
366
//: Playground - noun: a place where people can play import UIKit var rango = 0...100 for valor in rango { if valor % 5 == 0 { print("\(valor) Bingo!!!") } if valor % 2 == 0 { print("\(valor) par!!!") } else { print("\(valor) impar!!!") } if valor>=30 && valor<=40 { print("\(valor) Viva Swift!!!") } }
mit
f7d82911970c2f8a2f0db1f9fd18f68e
18.263158
52
0.480874
3.553398
false
false
false
false
Infinisil/ScriptKit
Source/Hotkey.swift
1
3845
// // Hotkey.swift // ScriptKit // // Created by Silvan Mosberger on 21/07/16. // // import Cocoa import Carbon /** Represents a hotkey, composed of a combination of modifiers and a single key You can create this struct be either using the initializer or the combining operators: Hotkey(modifiers: [.Command, .Shift], key: .ANSI_A) Hotkey(modifiers: .Control, key: .F5) [.Control, .Option] - .ANSI_1 .Shift + .ANSI_P */ public struct Hotkey : CustomStringConvertible, Hashable { public let modifiers : Modifiers public let key : Key public var description: String { if modifiers.isEmpty { return "\(key)" } else { return "\(modifiers) + \(key)" } } public var hashValue: Int { return Int(id) } /// Initializes a new hotkey with the specified modifier and key public init(modifiers: Modifiers, key: Key) { self.modifiers = modifiers self.key = key } } extension Hotkey { /** A set of key modifiers. Available modifiers are : - Control - Shift - Option - Command The bit representation is the same as those defined in `Carbon.HIToolbox.Events.h` (`controlKey`, etc.) */ public struct Modifiers : OptionSet, CustomStringConvertible, Equatable { public let rawValue: UInt32 public init(rawValue: UInt32) { self.rawValue = rawValue } public static let Control = Modifiers(rawValue: UInt32(controlKey)) public static let Shift = Modifiers(rawValue: UInt32(shiftKey)) public static let Option = Modifiers(rawValue: UInt32(optionKey)) public static let Command = Modifiers(rawValue: UInt32(cmdKey)) public var description: String { var strings : [String] = [] func add(_ modifier: Modifiers, _ description: String) { if contains(modifier) { strings.append(description) } } add(.Control, "Control") add(.Shift, "Shift") add(.Option, "Option") add(.Command, "Command") return "[\(strings.joined(separator: ", "))]" } } } extension CGEventFlags { /// `Hotkey.Modifiers` equivalent of this `GCEventFlags` /// - Note: Even though `CGEventFlags` is declared as an enum, it should actually be an `OptionSetType` and can therefore represent combination of the declared cases var modifiers : Hotkey.Modifiers { var mods : Hotkey.Modifiers = [] if CGEventFlags.maskControl.rawValue & rawValue > 0 { mods.formUnion(.Control) } if CGEventFlags.maskShift.rawValue & rawValue > 0 { mods.formUnion(.Shift) } if CGEventFlags.maskAlternate.rawValue & rawValue > 0 { mods.formUnion(.Option) } if CGEventFlags.maskCommand.rawValue & rawValue > 0 { mods.formUnion(.Command) } return mods } } public func ==(lhs: Hotkey, rhs: Hotkey) -> Bool { return lhs.modifiers == rhs.modifiers && lhs.key == rhs.key } extension Hotkey { /// An id representing this hotkey /// - Note: Since modifiers is always only using 16 bytes max and the key codes have a range of 0..<256, this representation is unique var id : UInt32 { return modifiers.rawValue << 16 | key.rawValue } /// Initializes a hotkey with the given id /// - Returns: A hotkey or nil if the least significant two bytes don't represent a valid key code init?(id: UInt32) { modifiers = Modifiers(rawValue: id >> 16) if let key = Key(rawValue: id & 0xFFFF) { self.key = key } else { return nil } } } // Creates a new hotkey with the given modifiers and key. Equivalent to using the `-` operator public func +(modifiers: Hotkey.Modifiers, key: Hotkey.Key) -> Hotkey { return Hotkey(modifiers: modifiers, key: key) } // Creates a new hotkey with the given modifiers and key. Equivalent to using the `+` operator public func -(modifiers: Hotkey.Modifiers, key: Hotkey.Key) -> Hotkey { return Hotkey(modifiers: modifiers, key: key) }
mit
f810fb88e01c290d56f4778345604d53
29.039063
166
0.678023
3.788177
false
false
false
false
yuhaifei123/WeiBo_Swift
WeiBo_Swift/WeiBo_Swift/class/Home(主页)/model/User.swift
1
2175
// // User.swift // WeiBo_Swift // // Created by 虞海飞 on 2016/12/22. // Copyright © 2016年 虞海飞. All rights reserved. // import UIKit class User: NSObject { /// 用户ID var id: Int = 0 /// 友好显示名称 var name: String? /// 用户头像地址(中图),50×50像素 var profile_image_url: String? /// 时候是认证, true是, false不是 var verified: Bool = false /// 用户的认证类型,-1:没有认证,0,认证用户,2,3,5: 企业认证,220: 达人 var verified_type: Int = -1; /// 用户的认证类型 图片 var verifiedImage : UIImage?; init(dic : [String : AnyObject]) { super.init(); id = dic["id"] as! Int; name = dic["name"] as? String; profile_image_url = dic["profile_image_url"] as! String? verified = (dic["verified"] != nil) verified_type = dic["verified_type"] as! Int switch verified_type{ case 0: verifiedImage = UIImage(named: "avatar_vip") case 2, 3, 5: verifiedImage = UIImage(named: "avatar_enterprise_vip") case 220: verifiedImage = UIImage(named: "avatar_grassroot") default: verifiedImage = nil } } /// 防止setValuesForKeys 有一些属性没有数据,报错,只要重写这个方法就可以 /// - Parameters: /// - value: <#value description#> /// - key: <#key description#> override func setValue(_ value: Any?, forUndefinedKey key: String) { } /// setValuesForKeys内部会调用以下方法 /// /// - Parameters: /// - value: <#value description#> /// - key: <#key description#> override func setValue(_ value: Any?, forKey key: String) { } /// 这个是调用,model 是打印数据 let dicdescription = ["id", "name", "profile_image_url", "verified", "verified_type"]; override var description: String{ let dic = self.dictionaryWithValues(forKeys: dicdescription); return "\(dic)"; } }
apache-2.0
20e5776c491052022acd5abcfb206682
25.534247
90
0.537945
3.761165
false
false
false
false
EasySwift/EasySwift
Carthage/Checkouts/SwiftString/SwiftString_iOS/StringExtensions.swift
2
10669
// // SwiftString.swift // SwiftString // // Created by Andrew Mayne on 30/01/2016. // Copyright © 2016 Red Brick Labs. All rights reserved. // import Foundation public extension String { /// Finds the string between two bookend strings if it can be found. /// /// - parameter left: The left bookend /// - parameter right: The right bookend /// /// - returns: The string between the two bookends, or nil if the bookends cannot be found, the bookends are the same or appear contiguously. func between(_ left: String, _ right: String) -> String? { guard let leftRange = range(of:left), let rightRange = range(of: right, options: .backwards), left != right && leftRange.upperBound != rightRange.lowerBound else { return nil } return self[leftRange.upperBound...index(before: rightRange.lowerBound)] } // https://gist.github.com/stevenschobert/540dd33e828461916c11 func camelize() -> String { let source = clean("", allOf: "-", "_") if source.characters.contains(" ") { let first = self[self.startIndex...self.index(after: startIndex)] //source.substringToIndex(source.index(after: startIndex)) let cammel = NSString(format: "%@", (source as NSString).capitalized.replacingOccurrences(of: " ", with: "")) as String let rest = String(cammel.characters.dropFirst()) return "\(first)\(rest)" } else { let first = source[self.startIndex...self.index(after: startIndex)].lowercased() let rest = String(source.characters.dropFirst()) return "\(first)\(rest)" } } func capitalize() -> String { return capitalized } // func contains(_ substring: String) -> Bool { // return range(of: substring) != nil // } func chompLeft(_ prefix: String) -> String { if let prefixRange = range(of: prefix) { if prefixRange.upperBound >= endIndex { return self[startIndex..<prefixRange.lowerBound] } else { return self[prefixRange.upperBound..<endIndex] } } return self } func chompRight(_ suffix: String) -> String { if let suffixRange = range(of: suffix, options: .backwards) { if suffixRange.upperBound >= endIndex { return self[startIndex..<suffixRange.lowerBound] } else { return self[suffixRange.upperBound..<endIndex] } } return self } func collapseWhitespace() -> String { let thecomponents = components(separatedBy: CharacterSet.whitespacesAndNewlines).filter { !$0.isEmpty } return thecomponents.joined(separator: " ") } func clean(_ with: String, allOf: String...) -> String { var string = self for target in allOf { string = string.replacingOccurrences(of: target, with: with) } return string } func count(_ substring: String) -> Int { return components(separatedBy: substring).count-1 } func endsWith(_ suffix: String) -> Bool { return hasSuffix(suffix) } func ensureLeft(_ prefix: String) -> String { if startsWith(prefix) { return self } else { return "\(prefix)\(self)" } } func ensureRight(_ suffix: String) -> String { if endsWith(suffix) { return self } else { return "\(self)\(suffix)" } } func indexOf(_ substring: String) -> Int? { if let range = range(of: substring) { return self.distance(from: startIndex, to: range.lowerBound) // return startIndex.distanceTo(range.lowerBound) } return nil } func initials() -> String { let words = self.components(separatedBy: " ") return words.reduce(""){$0 + $1[startIndex...startIndex]} // return words.reduce(""){$0 + $1[0...0]} } func initialsFirstAndLast() -> String { let words = self.components(separatedBy: " ") return words.reduce("") { ($0 == "" ? "" : $0[startIndex...startIndex]) + $1[startIndex...startIndex]} } func isAlpha() -> Bool { for chr in characters { if (!(chr >= "a" && chr <= "z") && !(chr >= "A" && chr <= "Z") ) { return false } } return true } func isAlphaNumeric() -> Bool { let alphaNumeric = CharacterSet.alphanumerics let output = self.unicodeScalars.split { !alphaNumeric.contains($0)}.map(String.init) if output.count == 1 { if output[0] != self { return false } } return output.count == 1 // return componentsSeparatedByCharactersInSet(alphaNumeric).joinWithSeparator("").length == 0 } func isEmpty() -> Bool { return self.trimmingCharacters(in: .whitespacesAndNewlines).length == 0 } func isNumeric() -> Bool { if let _ = defaultNumberFormatter().number(from: self) { return true } return false } fileprivate func join<S: Sequence>(_ elements: S) -> String { return elements.map{String(describing: $0)}.joined(separator: self) } func latinize() -> String { return self.folding(options: .diacriticInsensitive, locale: .current) // stringByFoldingWithOptions(.DiacriticInsensitiveSearch, locale: NSLocale.currentLocale()) } func lines() -> [String] { return self.components(separatedBy: CharacterSet.newlines) } var length: Int { get { return self.characters.count } } func pad(_ n: Int, _ string: String = " ") -> String { return "".join([string.times(n), self, string.times(n)]) } func padLeft(_ n: Int, _ string: String = " ") -> String { return "".join([string.times(n), self]) } func padRight(_ n: Int, _ string: String = " ") -> String { return "".join([self, string.times(n)]) } func slugify(withSeparator separator: Character = "-") -> String { let slugCharacterSet = CharacterSet(charactersIn: "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789\(separator)") return latinize() .lowercased() .components(separatedBy: slugCharacterSet.inverted) .filter { $0 != "" } .joined(separator: String(separator)) } func split(_ separator: Character = " ") -> [String] { return characters.split{$0 == separator}.map(String.init) } func startsWith(_ prefix: String) -> Bool { return hasPrefix(prefix) } func stripPunctuation() -> String { return components(separatedBy: .punctuationCharacters) .joined(separator: "") .components(separatedBy: " ") .filter { $0 != "" } .joined(separator: " ") } func times(_ n: Int) -> String { return (0..<n).reduce("") { $0.0 + self } } func toFloat() -> Float? { if let number = defaultNumberFormatter().number(from: self) { return number.floatValue } return nil } func toInt() -> Int? { if let number = defaultNumberFormatter().number(from: self) { return number.intValue } return nil } func toBool() -> Bool? { let trimmed = self.trimmed().lowercased() return (trimmed as NSString).boolValue } func toDate(_ format: String = "yyyy-MM-dd") -> Date? { return dateFormatter(format).date(from: self) as Date? } func toDateTime(_ format: String = "yyyy-MM-dd HH:mm:ss") -> Date? { return toDate(format) } func trimmedLeft() -> String { if let range = rangeOfCharacter(from: CharacterSet.whitespacesAndNewlines.inverted) { return self[range.lowerBound..<endIndex] } return self } func trimmedRight() -> String { if let range = rangeOfCharacter(from: CharacterSet.whitespacesAndNewlines.inverted, options: NSString.CompareOptions.backwards) { return self[startIndex..<range.upperBound] } return self } func trimmed() -> String { return self.trimmingCharacters(in: .whitespacesAndNewlines) } subscript(r: Range<Int>) -> String { get { let startIndex = self.characters.index(self.startIndex, offsetBy: r.lowerBound) let endIndex = self.characters.index(self.startIndex, offsetBy: r.upperBound - r.lowerBound) return self[startIndex..<endIndex] } } func substring(_ startIndex: Int, length: Int) -> String { let start = self.characters.index(self.startIndex, offsetBy: startIndex) let end = self.characters.index(self.startIndex, offsetBy: startIndex + length) return self[start..<end] } subscript(i: Int) -> Character { get { let index = self.characters.index(self.startIndex, offsetBy: i) return self[index] } } } private enum ThreadLocalIdentifier { case dateFormatter(String) case defaultNumberFormatter case localeNumberFormatter(Locale) var objcDictKey: String { switch self { case .dateFormatter(let format): return "SS\(self)\(format)" case .localeNumberFormatter(let l): return "SS\(self)\(l.identifier)" default: return "SS\(self)" } } } private func threadLocalInstance<T: AnyObject>(_ identifier: ThreadLocalIdentifier, initialValue: @autoclosure () -> T) -> T { let storage = Thread.current.threadDictionary let k = identifier.objcDictKey let instance: T = storage[k] as? T ?? initialValue() if storage[k] == nil { storage[k] = instance } return instance } private func dateFormatter(_ format: String) -> DateFormatter { return threadLocalInstance(.dateFormatter(format), initialValue: { let df = DateFormatter() df.dateFormat = format return df }()) } private func defaultNumberFormatter() -> NumberFormatter { return threadLocalInstance(.defaultNumberFormatter, initialValue: NumberFormatter()) } private func localeNumberFormatter(_ locale: NSLocale) -> NumberFormatter { return threadLocalInstance(ThreadLocalIdentifier.localeNumberFormatter(locale as Locale), initialValue: { let nf = NumberFormatter() nf.locale = locale as Locale! return nf }()) }
apache-2.0
55c2bf165566a324418e26ded7124218
30.75
146
0.588489
4.543441
false
false
false
false
KosyanMedia/Aviasales-iOS-SDK
AviasalesSDKTemplate/Source/HotelsSource/HotelDetails/Cells/HLHotelDetailsPriceTableCell.swift
1
1523
class HLHotelDetailsPriceTableCell: HLPriceTableViewCell { @IBOutlet weak var backgroundBottomConstraint: NSLayoutConstraint! @IBOutlet weak var highlightView: UIView! var forceTouchAdded = false override var last: Bool { didSet { backgroundBottomConstraint.constant = last ? 15.0 : 10.0 setNeedsLayout() } } override func setHighlighted(_ highlighted: Bool, animated: Bool) { highlightView.isHidden = !highlighted } override func awakeFromNib() { super.awakeFromNib() separatorView.attachToView(self, edge: .bottom, insets: UIEdgeInsets(top: 0, left: 15, bottom: 0, right: 15)) separatorView.isHidden = true } func configure(for room: HDKRoom, currency: HDKCurrency, duration: Int, shouldShowSeparator: Bool) { super.configure(for: room, currency: currency, duration: duration) separatorView.isHidden = !shouldShowSeparator } override var canHighlightDiscount: Bool { return false } override class func logoTopOffset() -> CGFloat { return 14.0 } override class func commonLeftOffset() -> CGFloat { return 30.0 } override class func contentBottomOffset() -> CGFloat { return 25.0 } class func calculateCellHeight(_ tableWidth: CGFloat, room: HDKRoom, currency: HDKCurrency, last: Bool) -> CGFloat { return super.calculateCellHeight(tableWidth, room: room, currency: currency) + (last ? 5.0 : 0.0) } }
mit
1a11d183141d6c2486f2193c3764c84c
30.729167
120
0.664478
4.671779
false
false
false
false
rcarvalhosilva/RCAlertController
RCAlertController/Classes/AlertController.swift
1
16280
// // AlertController.swift // AlertController // // Copyright (c) 2016 Rodrigo Silva // // 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 //MARK: Alert Action /// Defines actions to be presented in the alert controller. Initialize it with a name and a command. /// /// An action will be presented as a button in the alert. You create an alert passing a name and a command /// block with no parameters or return values. When a button on the alert is pressed the corresponding action /// will be called. Use the addAction(:) method to add a action you created to the alert. public class AlertAction { public typealias AlertActionCommand = () -> Void fileprivate var action: AlertActionCommand fileprivate var actionName: String public init(named name: String, withCommand command: @escaping AlertActionCommand) { actionName = name action = command } fileprivate func execute() { // execute the action in the main queue let mainQueue = DispatchQueue.main mainQueue.async { self.action() } } } //MARK: Alert Controller /// A custom alert controller highly customizable. To see more details see the /// init(title: message: style:) documentation. @available(iOS 9.0, *) public class AlertController: UIViewController, AlertViewDelegate { //MARK: Private properties private var alertView: AlertView! private var transitionDelegate = AlertTransitioningDelegate() // Alert view related properties private var alertTitle: String! private var message: String? private var style: AlertControllerStyle! private var actions = [AlertAction]() //MARK: Initialization required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) fatalError("Storyboard not supported. You should use init(title: message:)") } private func commonInit() { self.modalPresentationStyle = .custom self.transitioningDelegate = transitionDelegate } //MARK: Life Cycle override public func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) configureAlertView() } //MARK: Private Methods private func setConstraints() { alertView.translatesAutoresizingMaskIntoConstraints = false var allConstraints = [NSLayoutConstraint]() // center X let centerHorizontallyConstraint = NSLayoutConstraint(item: alertView, attribute: .centerX, relatedBy: .equal, toItem: self.view, attribute: .centerX, multiplier: 1, constant: 0) allConstraints.append(centerHorizontallyConstraint) // center Y let centerVerticallyConstraint = NSLayoutConstraint(item: alertView, attribute: .centerY, relatedBy: .equal, toItem: self.view, attribute: .centerY, multiplier: 1, constant: 0) allConstraints.append(centerVerticallyConstraint) // fixed width let widthConstraint = NSLayoutConstraint(item: alertView, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: 270) allConstraints.append(widthConstraint) // flexible height let heightConstraint = NSLayoutConstraint(item: alertView, attribute: .height, relatedBy: .lessThanOrEqual, toItem: self.view, attribute: .height, multiplier: 0.8, constant: 0) allConstraints.append(heightConstraint) NSLayoutConstraint.activate(allConstraints) } private func configureAlertView() { if let appearance = appearance { self.alertView = AlertView(appearance: appearance) } else { self.alertView = AlertView(appearance: AlertAppearance()) } self.alertView.delegate = self self.view.addSubview(alertView) setConstraints() //set alert view propeties alertView.title = alertTitle alertView.message = message alertView.style = style alertView.actions = actions // must be set after the style alertView.customView = customView // must be set after the title and message } internal func fireAction(for button: UIButton) { // find button's action guard let index = actions.index(where: { (action) -> Bool in action.actionName == button.title(for: .normal) }) else { self.dismiss(animated: true, completion: nil) return } self.dismiss(animated: true) { [unowned self] in self.actions[index].execute() } } //MARK: Public API /// A custom view to be desplayed on the alert. /// /// This view will appear after the title and message, if any exists, and before the buttons. /// The width of the view is limited by the width of the alert. Its height will be preserved /// until the alert reaches 80% of the presenting view controller height. public var customView: UIView? /// Defines the appearance of the alert controller. /// /// Use it to set a custom appearance to the alert. You can make modifications taking as base /// the standard aprearence. Or you can create your own appearance implementing /// the AlertAppearanceProtocol. public var appearance: AlertAppearanceProtocol? /// Create an Alert Controller to be presented. /// /// You can set the title and message that will be presented in the alert. Additionally you can set the style /// of the alert that will be presented. There are two styles: 'standard' and 'actionAlert'. /// /// To costumize the appearance of the alert use the appearance property. You can create your own /// appearance using the AlertAppearance struct and set it to the alert. /// /// To add actions create an AlertAction and use the addAction(:) method to add them. /// /// - parameter title: A String that will be presented as the alert title. /// - parameter message: An optional String message to be displayed on the alert. /// - parameter style: The alert layout style. You can choose between 'standard' and 'actionAlert'. /// See more in AlertControllerStyle. /// /// - returns: The AlertController to be presented. public init(title: String, message: String?, style: AlertControllerStyle = .standard) { super.init(nibName: nil, bundle: nil) commonInit() self.alertTitle = title self.message = message self.style = style } /// Add an alert action to the alert view. /// /// This action will be represented with a button on the alert view with the name of the action. /// The order of the buttons will be given by the order the actions /// are added. If there any other actions already in the alert they will be presented after those. /// /// - note: In the 'standard' style the number of actions is limited to two. Any actions added after /// this limit has been reached will be discarted. /// /// - parameter action: An AlertAction that will be added to the alert view. public func addAction(action: AlertAction) { if style == .standard { guard actions.count < 2 else { return } actions.append(action) } else { actions.append(action) } } /// Adds to the alert view the list of actions passed. /// /// Those actions will be presented in the order /// they appear in the array as buttons with title equal to the name of the actions. If there any other /// actions already in the alert they will be presented after those. /// /// - note: In the 'standard' style the number of actions is limited to two. Any actions added after /// this limit has been reached will be discarted. /// /// - parameter actions: An array of actions to be added to the alert view public func addActions(actions: [AlertAction]) { for action in actions { addAction(action: action) } } } //MARK: Alert View Delegate fileprivate protocol AlertViewDelegate: class { func fireAction(for button: UIButton) } //MARK: Alert View @available(iOS 9.0, *) fileprivate class AlertView: UIView { // MARK: Private properties /// The title label from the alert view private var titleLabel = UILabel() /// The main text view from the alert view private var textLabel: UILabel? /// The action buttons from the alert view. Each button will be linked to an action added by the caller. private var actionButtons = [UIButton]() /// A container view that will contain all the labels and textViews of the alert. private var textConteinerView = UIStackView(frame: CGRect.zero) /// A container view for a custom view given by the user private var customContainerView = UIStackView(frame: CGRect.zero) /// A container view that will contain all the buttons of the alert. private var buttonsConteinerView = UIStackView(frame: CGRect.zero) //MARK: Fileprivate properties /// A reference to the view controller fileprivate weak var delegate: AlertViewDelegate! fileprivate var title: String! { didSet{ titleLabel.text = title titleLabel.textColor = appearance.titleColor titleLabel.font = appearance.titleFont } } fileprivate var message: String? { didSet { guard let text = message else { return } textLabel = UILabel(frame: .zero) textLabel!.translatesAutoresizingMaskIntoConstraints = false textLabel!.text = text textLabel!.font = appearance.messageFont textLabel!.textColor = appearance.messageColor textLabel!.numberOfLines = 0 textLabel!.textAlignment = .center textConteinerView.addArrangedSubview(textLabel!) } } fileprivate var actions: [AlertAction]? { didSet { if let actions = actions, actions.count > 0 { // if there are any actions to be displayed add them for action in actions { addButton(for: action) } } else { // if not add the default button that does nothig let action = AlertAction(named: "OK", withCommand: { }) addButton(for: action) } } } fileprivate var style: AlertControllerStyle = .standard { didSet { // change the buttons layout distribution acording to the sytle setted switch style { case .standard: buttonsConteinerView.axis = .horizontal case .actionAlert: buttonsConteinerView.axis = .vertical } } } fileprivate var customView: UIView? { willSet { guard let view = newValue else { return } guard customView == nil else { return } view.translatesAutoresizingMaskIntoConstraints = false self.customContainerView.addArrangedSubview(view) let heightConstraint = NSLayoutConstraint(item: view, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 0, constant: view.frame.height) // constraint with low priority so that if the view is to big // it's shortened keeping the other elements aspect heightConstraint.priority = 250 NSLayoutConstraint.activate([heightConstraint]) } } fileprivate var appearance: AlertAppearanceProtocol! // MARK: Initialization fileprivate init(appearance: AlertAppearanceProtocol) { super.init(frame: CGRect.zero) self.appearance = appearance commonInit() } fileprivate required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) fatalError("init(coder:) has not been implemented") } private func commonInit() { addContainerViews() // Configure view appearance self.backgroundColor = appearance.viewBackgroundColor self.layer.cornerRadius = appearance.viewCornerRadius self.clipsToBounds = true } // MARK: Private methods /// Set the constraints of the container views. private func configureContainerViewsConstraints() { textConteinerView.translatesAutoresizingMaskIntoConstraints = false buttonsConteinerView.translatesAutoresizingMaskIntoConstraints = false customContainerView.translatesAutoresizingMaskIntoConstraints = false // views dictionary that holds string representations of views to resolve inside the format string. The string keys inside the views dictionary must match the view strings inside the format string. let views = ["textConteinerView": textConteinerView, "buttonsConteinerView": buttonsConteinerView, "customContainerView": customContainerView] var allConstraints = [NSLayoutConstraint]() // Each container view is spaced by 8 points. let bottomSpace = appearance.spaceToBottomMargin let containersVerticalConstraints = NSLayoutConstraint.constraints(withVisualFormat: "V:|-[textConteinerView]-8-[customContainerView]-8-[buttonsConteinerView]-\(bottomSpace)-|", options: [], metrics: nil, views: views) allConstraints += containersVerticalConstraints // Both containers has standard horizontal space to superview let buttonsHorizSpace = appearance.buttonsSpaceToHorizontalMargins let textHorizSpace = appearance.textSpaceToHorizontalMargins let customHorizSpace = appearance.customViewSpaceToHorizontalMargins let horizontalTextContainerConstraints = NSLayoutConstraint.constraints(withVisualFormat: "H:|-\(textHorizSpace)-[textConteinerView]-\(textHorizSpace)-|", options: [], metrics: nil, views: views) let hozizontalButtonsContainerConstraints = NSLayoutConstraint.constraints(withVisualFormat: "H:|-\(buttonsHorizSpace)-[buttonsConteinerView]-\(buttonsHorizSpace)-|", options: [], metrics: nil, views: views) let horizontalCustomContainerConstraints = NSLayoutConstraint.constraints(withVisualFormat: "H:|-\(customHorizSpace)-[customContainerView]-\(customHorizSpace)-|", options: [], metrics: nil, views: views) allConstraints += horizontalTextContainerConstraints + hozizontalButtonsContainerConstraints + horizontalCustomContainerConstraints NSLayoutConstraint.activate(allConstraints) } /// Adds the container view and call the configurations methods to each one private func addContainerViews() { // Add containers self.addSubview(textConteinerView) self.addSubview(customContainerView) self.addSubview(buttonsConteinerView) configureContainerViewsConstraints() configureTextContainerView() configureButtonsContainerView() } // standard configuration private func configureTextContainerView() { // set stack view axis to vertical textConteinerView.axis = .vertical textConteinerView.spacing = 8.0 // add title label titleLabel.textAlignment = .center titleLabel.numberOfLines = 0 titleLabel.font = appearance.titleFont titleLabel.textColor = appearance.titleColor titleLabel.translatesAutoresizingMaskIntoConstraints = false textConteinerView.addArrangedSubview(titleLabel) } // standard configuration private func configureButtonsContainerView() { // configure the stack view distribution constraints buttonsConteinerView.axis = .horizontal buttonsConteinerView.spacing = appearance.buttonsSpacing buttonsConteinerView.distribution = .fillEqually } @objc private func actionButtonTapped(sender: UIButton) { delegate.fireAction(for: sender) } private func addButton(for action: AlertAction) { let actionButton = UIButton() actionButton.translatesAutoresizingMaskIntoConstraints = false actionButton.setTitle(action.actionName, for: .normal) actionButton.addTarget(self, action: #selector(actionButtonTapped), for: .touchUpInside) actionButton.contentEdgeInsets = UIEdgeInsets(top: 10, left: 8, bottom: 10, right: 8) // set appearance actionButton.backgroundColor = appearance.buttonsBackgroundColor actionButton.setTitleColor(appearance.buttonsTextColor, for: .normal) actionButton.titleLabel?.font = appearance.buttonsFont actionButton.layer.cornerRadius = appearance.buttonsCornerRadius actionButton.titleLabel?.adjustsFontSizeToFitWidth = true buttonsConteinerView.addArrangedSubview(actionButton) } }
mit
73be7425c82ec9dc3d4b358276c4b7e8
36.254005
220
0.751781
4.310299
false
false
false
false
eebean2/DevTools
DevTools/Classes/UIThemeProfile.swift
1
20199
/* * UIThemeProfile * * Created by Erik Bean on 2/8/18 * Copyright © 2018 Erik Bean */ import UIKit // MARK: -UIThemeProfileType public enum UIThemeProfileType { /// UIView case view /// UILabel case label /// UIButton case button /// UITextField case textfield /// UISlider case slider /// UISwitch case `switch` /// UIActivityIndicatorView case activityindicator /// UIProgressBar case progressbar /// UIPageControl case pagecontrol /// UIStepper case stepper /// UISegmentedController case segmentedcontroller /// UITableView case tableview /// UITableViewCell case tableviewcell /// UIImageView case imageview /// UICollectionView case collectionview /// UICollectionViewCell case collectionviewcell /// UITextView case textview /// UIScrollView case scrollview /// UIDatePicker case datepicker /// UIPickerView case pickerview /// UINavigationBar case navigationbar /// UIToolBar case toolbar /// UIBarButtonItem case barbuttonitem /// UITabBar case tabbar /// UITabBarItem case tabbaritem /// UISearchBar case searchbar /// Unsupported item, will require manual theme support case other /// Data uninitilized, will require initilization to work case uninit } // MARK: -UIThemeProfile @objc public class UIThemeProfile: NSObject { /// The element which is being themed public var elementType: UIThemeProfileType = .uninit /// Animate the status bar /// - note: Default = false public var statusBar: Bool = false /// Time to animate public var animateTime: TimeInterval = 0.5 // MARK: -View public class view: UIThemeProfile { public var defaultBackground: UIColor? public var themeBackground: UIColor? public var defaultTint: UIColor? public var themeTint: UIColor? public init(defaultBackground: UIColor, themeBackground: UIColor) { super.init() super.elementType = .view self.defaultBackground = defaultBackground self.themeBackground = themeBackground } } // MARK: -Label public class label: view { public var defaultText: String? public var themeText: String? public var defaultTextColor: UIColor? public var themeTextColor: UIColor? public var defaultShadow: UIColor? public var themeShadow: UIColor? public var defaultHighlight: UIColor? public var themeHighlight: UIColor? public var defaultAttributedText: NSMutableAttributedString? public var themeAttributedText: NSMutableAttributedString? public init(defaultTextColor: UIColor, themeTextColor: UIColor) { super.init(defaultBackground: .clear, themeBackground: .clear) self.defaultTextColor = defaultTextColor self.themeTextColor = themeTextColor super.elementType = .label } } // MARK: -Button public class button: view { public var defaultTitle: [String: UIControlState]? public var themeTitle: [String: UIControlState]? public var defaultImage: [UIImage: UIControlState]? public var themeImage: [UIImage: UIControlState]? public var defaultTitleColor: [UIColor: UIControlState]? public var themeTitleColor: [UIColor: UIControlState]? public var defaultAttributedTitle: [NSMutableAttributedString: UIControlState]? public var themeAttributedTitle: [NSMutableAttributedString: UIControlState]? public var defaultBackgroundImage: [UIImage: UIControlState]? public var themeBackgroundImage: [UIImage: UIControlState]? public var defaultTitleShadowColor: [UIColor: UIControlState]? public var themeTitleShadowColor: [UIColor: UIControlState]? override public init(defaultBackground: UIColor = .clear, themeBackground: UIColor = .clear) { super.init(defaultBackground: defaultBackground, themeBackground: themeBackground) super.elementType = .button } } // MARK: -Textfield public class textfield: view { public var defaultTextColor: UIColor? public var themeTextColor: UIColor? public var defaultAttributedText: NSMutableAttributedString? public var themeAttributedText: NSMutableAttributedString? public var defaultBackgroundImage: UIImage? public var themeBackgroundImage: UIImage? override public init(defaultBackground: UIColor = .clear, themeBackground: UIColor = .clear) { super.init(defaultBackground: defaultBackground, themeBackground: themeBackground) super.elementType = .textfield } } // MARK: -Slider public class slider: view { public var defaultThumbImage: [UIImage: UIControlState]? public var themeThumbImage: [UIImage: UIControlState]? public var defaultMinTrackImage: [UIImage: UIControlState]? public var themeMinTrackImage: [UIImage: UIControlState]? public var defaultMaxTrackImage: [UIImage: UIControlState]? public var themeMaxTrackImage: [UIImage: UIControlState]? public var defaultMinTrackColor: UIColor? public var themeMinTrackColor: UIColor? public var defaultMaxTrackColor: UIColor? public var themeMaxTrackColor: UIColor? public var defaultThumbTint: UIColor? public var themeThumbTint: UIColor? override public init(defaultBackground: UIColor = .clear, themeBackground: UIColor = .clear) { super.init(defaultBackground: defaultBackground, themeBackground: themeBackground) super.elementType = .slider } } public class activityindicator: view { public var defaultStyle: UIActivityIndicatorViewStyle? public var themeStyle: UIActivityIndicatorViewStyle? public var defaultColor: UIColor? public var themeColor: UIColor? override public init(defaultBackground: UIColor = .clear, themeBackground: UIColor = .clear) { super.init(defaultBackground: defaultBackground, themeBackground: themeBackground) super.elementType = .activityindicator } } // MARK: -Switch public class `switch`: view { public var defaultOnTint: UIColor? public var themeOnTint: UIColor? public var defaultOnImage: UIImage? public var themeOnImage: UIImage? override public init(defaultBackground: UIColor = .clear, themeBackground: UIColor = .clear) { super.init(defaultBackground: defaultBackground, themeBackground: themeBackground) super.elementType = .switch } } // MARK: -Progress Bar public class progressbar: view { public var defaultProgressTint: UIColor? public var themeProgressTint: UIColor? public var defaultTrackTink: UIColor? public var themeTrackTint: UIColor? public var defaultProgressImage: UIImage? public var themeProgressImage: UIImage? public var defaultTrackImage: UIImage? public var themeTrackImage: UIImage? override public init(defaultBackground: UIColor = .clear, themeBackground: UIColor = .clear) { super.init(defaultBackground: defaultBackground, themeBackground: themeBackground) super.elementType = .progressbar } } // MARK: -Page Control public class pagecontrol: view { public var defaultPagesColor: UIColor? public var themePagesColor: UIColor? public var defaultCurrentPageColor: UIColor? public var themeCurrentPageColor: UIColor? override public init(defaultBackground: UIColor = .clear, themeBackground: UIColor = .clear) { super.init(defaultBackground: defaultBackground, themeBackground: themeBackground) super.elementType = .pagecontrol } convenience public init(defaultPagesColor: UIColor, themePagesColor: UIColor, defaultCurrentPageColor: UIColor, themeCurrentPageColor: UIColor) { self.init() self.defaultPagesColor = defaultPagesColor self.themePagesColor = themePagesColor self.defaultCurrentPageColor = defaultCurrentPageColor self.themeCurrentPageColor = themeCurrentPageColor } } // MARK: -Stepper public class stepper: view { override public init(defaultBackground: UIColor = .clear, themeBackground: UIColor = .clear) { super.init(defaultBackground: defaultBackground, themeBackground: themeBackground) super.elementType = .stepper } } public class segmentedcontroller: view { override public init(defaultBackground: UIColor = .clear, themeBackground: UIColor = .clear) { super.init(defaultBackground: defaultBackground, themeBackground: themeBackground) super.elementType = .segmentedcontroller } } // MARK: -TableView public class tableview: view { override public init(defaultBackground: UIColor, themeBackground: UIColor = .clear) { super.init(defaultBackground: defaultBackground, themeBackground: themeBackground) super.elementType = .tableview } } // MARK: -TableView Cell public class tableviewcell: view { override public init(defaultBackground: UIColor, themeBackground: UIColor = .clear) { super.init(defaultBackground: defaultBackground, themeBackground: themeBackground) super.elementType = .tableviewcell } } // MARK: -Image View public class imageview: view { public var defaultImage: UIImage? public var themeImage: UIImage? public var defaultHighlight: UIImage? public var themeHighlight: UIImage? override public init(defaultBackground: UIColor = .clear, themeBackground: UIColor = .clear) { super.init(defaultBackground: defaultBackground, themeBackground: themeBackground) super.elementType = .imageview } } // MARK: -Collection View public class collectionview: view { override public init(defaultBackground: UIColor = .clear, themeBackground: UIColor = .clear) { super.init(defaultBackground: defaultBackground, themeBackground: themeBackground) super.elementType = .collectionview } } // MARK: -Collection View Cell public class collectionviewcell: view { override public init(defaultBackground: UIColor = .clear, themeBackground: UIColor = .clear) { super.init(defaultBackground: defaultBackground, themeBackground: themeBackground) super.elementType = .collectionviewcell } } // MARK: -Textview public class textview: view { public var defaultTextColor: UIColor? public var themeTextColor: UIColor? public var defaultAttributedText: NSMutableAttributedString? public var themeAttributedText: NSMutableAttributedString? override public init(defaultBackground: UIColor = .clear, themeBackground: UIColor = .clear) { super.init(defaultBackground: defaultBackground, themeBackground: themeBackground) super.elementType = .textview } } // MARK: -Scrollview public class scrollview: view { override public init(defaultBackground: UIColor = .clear, themeBackground: UIColor = .clear) { super.init(defaultBackground: defaultBackground, themeBackground: themeBackground) super.elementType = .scrollview } } // MARK: -Datepicker public class datepicker: view { override public init(defaultBackground: UIColor = .clear, themeBackground: UIColor = .clear) { super.init(defaultBackground: defaultBackground, themeBackground: themeBackground) super.elementType = .datepicker } } // MARK: -Pickerview public class pickerview: view { override public init(defaultBackground: UIColor = .clear, themeBackground: UIColor = .clear) { super.init(defaultBackground: defaultBackground, themeBackground: themeBackground) super.elementType = .pickerview } } // Navigation Bar is very intensive, and the last objective // MARK: -Navigation Bar public class navigationbar: view { public var defaultBackgroundImageWithPosition: (image: UIImage, position: UIBarPosition, metrics: UIBarMetrics)? public var themeBackgroundImageWithPosition: (image: UIImage, position: UIBarPosition, metrics: UIBarMetrics)? public var defaultBackgroundImage: [UIImage: UIBarMetrics]? public var themeBackgroundImage: [UIImage: UIBarMetrics]? public var defaultItems: [UINavigationItem]? public var themeItems: [UINavigationItem]? public var defaultBarStyle: UIBarStyle? public var themeBarStyle: UIBarStyle? public var defaultIsTranslucent: Bool = true public var themeIsTranslucent: Bool = false public var defaultBarTint: UIColor? public var themeBarTint: UIColor? public var defaultShadowImage: UIImage? public var themeShadowImage: UIImage? public var defaultBackImage: UIImage? public var themeBackImage: UIImage? public var defaultTitleTextAttributes: [NSAttributedStringKey: Any]? public var themeTitleTextAttributes: [NSAttributedStringKey: Any]? public var defaultLargeTitleTextAttributes: [NSAttributedStringKey: Any]? public var themeLargeTitleTextAttributes: [NSAttributedStringKey: Any]? override public init(defaultBackground: UIColor = .clear, themeBackground: UIColor = .clear) { super.init(defaultBackground: defaultBackground, themeBackground: themeBackground) super.elementType = .navigationbar } } // MARK: -Toolbar public class toolbar: view { public var defaultBarStyle: UIBarStyle = .default public var themeBarStyle: UIBarStyle = .default public var defaultIsTranslucent: Bool = true public var themeIsTranslucent: Bool = true public var defaultBarTint: UIColor? public var themeBarTint: UIColor? override public init(defaultBackground: UIColor = .clear, themeBackground: UIColor = .clear) { super.init(defaultBackground: defaultBackground, themeBackground: themeBackground) super.elementType = .toolbar } } // MARK: -Bar Button Item public class barbuttonitem: UIThemeProfile { public var defaultBackgroundImageWithStyle: [(image: UIImage, controlState: UIControlState, style: UIBarButtonItemStyle, metrics: UIBarMetrics)]? public var themeBackgroundImageWithStyle: [(image: UIImage, controlState: UIControlState, style: UIBarButtonItemStyle, metrics: UIBarMetrics)]? public var defaultBackgroundImage: [(image: UIImage, controlState: UIControlState, metrics: UIBarMetrics)]? public var themeBackgroundImage: [(image: UIImage, controlState: UIControlState, metrics: UIBarMetrics)]? public var defaultBackButtonBackgroundImage: [(image: UIImage, controlState: UIControlState, metrics: UIBarMetrics)]? public var themeBackButtonBackgroundImage: [(image: UIImage, controlState: UIControlState, metrics: UIBarMetrics)]? public var defaultTitleTextAttributes: [(attributes: [NSAttributedStringKey: Any], controlState: UIControlState)]? public var themeTitleTextAttributes: [(attributes: [NSAttributedStringKey: Any], controlState: UIControlState)]? public var defaultBarStyle: UIBarButtonItemStyle? public var themeBarStyle: UIBarButtonItemStyle? public var defaultTint: UIColor? public var themeTint: UIColor? public var defaultImage: UIImage? public var themeImage: UIImage? public var defaultLandscapeImage: UIImage? public var themeLandscapeImage: UIImage? public var defaultLargeContentImage: UIImage? public var themeLargeContentImage: UIImage? public override init() { super.init() super.elementType = .barbuttonitem } } // MARK: -Tab Bar public class tabbar: view { public var defaultBackgroundImage: UIImage? public var themeBackgroundImage: UIImage? public var defaultShadowImage: UIImage? public var themeShadowImage: UIImage? public var defaultSelectionImage: UIImage? public var themeSelectionImage: UIImage? public var defaultBarStyle: UIBarStyle = .default public var themeBarStyle: UIBarStyle = .default public var defaultIsTranslucent: Bool = true public var themeIsTranslucent: Bool = true public var defaultBarTint: UIColor? public var themeBarTint: UIColor? override public init(defaultBackground: UIColor = .clear, themeBackground: UIColor = .clear) { super.init(defaultBackground: defaultBackground, themeBackground: themeBackground) super.elementType = .tabbar } } // MARK: -Tab Bar Item public class tabbaritem: UIThemeProfile { public var defaultBadge: UIColor? public var themeBadge: UIColor? public var defaultSelectedImage: UIImage? public var themeSelectedImage: UIImage? public var defaultImage: UIImage? public var themeImage: UIImage? public var defaultLandscapeImage: UIImage? public var themeLandscapeImage: UIImage? public var defaultLargeContentImage: UIImage? public var themeLargeContentImage: UIImage? public override init() { super.init() super.elementType = .tabbaritem } } // MARK: -Search Bar public class searchbar: view { public var defaultImage: [(iconImage: UIImage, icon: UISearchBarIcon, controlState: UIControlState)]? public var themeImage: [(iconImage: UIImage, icon: UISearchBarIcon, controlState: UIControlState)]? public var defaultBackgroundImage: (image: UIImage, position: UIBarPosition, metrics: UIBarMetrics)? public var themeBackgroundImage: (image: UIImage, position: UIBarPosition, metrics: UIBarMetrics)? public var defaultSearchFieldBackgroundImage: [UIImage: UIControlState]? public var themeSearchFieldBackgroundImage: [UIImage: UIControlState]? public var defaultScopeBarButtonBackground: [UIImage: UIControlState]? public var themeScopeBarButtonBackground: [UIImage: UIControlState]? public var defaultScopeBarButtonTitleAttributes: [(attributes: [String: Any], controlState: UIControlState)]? public var themeScopeBarButtonTitleAttributes: [(attributes: [String: Any], controlState: UIControlState)]? public var defaultScopeBarButtonDivider: [(image: UIImage, leftSegmentState: UIControlState, rightSegmentState: UIControlState)]? public var themeScopeBarButtonDivider: [(image: UIImage, leftSegmentState: UIControlState, rightSegmentState: UIControlState)]? public var defaultSearchBarStyle: UISearchBarStyle? public var themeSearchBarStyle: UISearchBarStyle? public var defaultBarStyle: UIBarStyle? public var themeBarStyle: UIBarStyle? public var defaultIsTranslucent: Bool = true public var themeIsTranslucent: Bool = true public var defaultBarTint: UIColor? public var themeBarTint: UIColor? override public init(defaultBackground: UIColor = .clear, themeBackground: UIColor = .clear) { super.init(defaultBackground: defaultBackground, themeBackground: themeBackground) super.elementType = .textfield } } }
mit
04ef36c869c8c7afc3119a0d9e274952
41.343816
153
0.681899
5.565721
false
false
false
false
rodrigo196/ios-samples
CalculoNumerico.playground/Contents.swift
1
714
//: Playground - noun: a place where people can play import UIKit let errorMargin = 1E-4 func f(x:Double) -> Double{ return sin(2*x*x) - cos(x) + 3 } func derivada(x:Double) -> Double{ var result:Double = 0.0 var lastResult:Double = 0.0 var delta:Double = 0.5 var error:Double = 1E10 var lastError:Double = error repeat { lastResult = result lastError = error delta = delta / 2 result = (f(x + delta*x) - f(x - delta*x))/(2*delta*x) error = fabs(result - lastResult) }while ( error > errorMargin && lastError >= error) return result } let x:Double = 1.25 f(x) derivada(x) for i in 1...5000{ print (derivada(Double(i))) }
bsd-2-clause
f00da1b3a4410b7c07d70b22dd0c33ef
18.833333
62
0.593838
3.104348
false
false
false
false
GoogleCloudPlatform/ios-docs-samples
speech-to-speech/SpeechToSpeech/AppDelegate.swift
1
9459
// // Copyright 2019 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // import UIKit import UserNotifications import Firebase import AuthLibrary @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? let gcmMessageIDKey = "gcm.message_id" var voiceLists: [FormattedVoice]? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions:[UIApplication.LaunchOptionsKey :Any]? = nil) -> Bool { FirebaseApp.configure() // [START set_messaging_delegate] Messaging.messaging().delegate = self // [END set_messaging_delegate] // Register for remote notifications. This shows a permission dialog on first run, to // show the dialog at a more appropriate time move this registration accordingly. // [START register_for_notifications] if #available(iOS 10.0, *) { // For iOS 10 display notification (sent via APNS) UNUserNotificationCenter.current().delegate = self let authOptions: UNAuthorizationOptions = [.alert, .badge, .sound] UNUserNotificationCenter.current().requestAuthorization( options: authOptions, completionHandler: {_, _ in }) } else { let settings: UIUserNotificationSettings = UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil) application.registerUserNotificationSettings(settings) } application.registerForRemoteNotifications() if voiceLists == nil || (voiceLists?.isEmpty ?? true) { TextToSpeechRecognitionService.sharedInstance.voiceListDelegate = self TextToSpeechRecognitionService.sharedInstance.getVoiceLists () } return true } func fetchToken() { SpeechRecognitionService.sharedInstance.getDeviceID { (deviceID) in // authenticate using an authorization token (obtained using OAuth) FCMTokenProvider.getToken(deviceID: deviceID) { (shouldWait, token, error) in print("shouldWait: \(shouldWait), token: \(String(describing: token)), error: \(error?.localizedDescription ?? "")") } } } // [START receive_message] func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any]) { // If you are receiving a notification message while your app is in the background, // this callback will not be fired till the user taps on the notification launching the application. // TODO: Handle data of notification // With swizzling disabled you must let Messaging know about the message, for Analytics Messaging.messaging().appDidReceiveMessage(userInfo) // Print message ID. if let messageID = userInfo[gcmMessageIDKey] { print("Message ID: \(messageID)") } if let aps = userInfo["aps"] as? [String: Any], let alert = aps["alert"] as? [String: Any], let token = alert["body"] as? String , let expiryTime = alert["title"] as? String { let tokenData = [ApplicationConstants.accessToken: token, ApplicationConstants.expireTime: expiryTime] FCMTokenProvider.tokenFromAppDelegate(tokenDict: tokenData) NotificationCenter.default.post(name: NSNotification.Name(ApplicationConstants.tokenReceived), object: tokenData) } // Print full message. print(userInfo) } func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) { // If you are receiving a notification message while your app is in the background, // this callback will not be fired till the user taps on the notification launching the application. // TODO: Handle data of notification // With swizzling disabled you must let Messaging know about the message, for Analytics Messaging.messaging().appDidReceiveMessage(userInfo) // Print message ID. if let messageID = userInfo[gcmMessageIDKey] { print("Message ID: \(messageID)") } guard let tokenData = userInfo as? [String: Any] else {return} NotificationCenter.default.post(name: NSNotification.Name(ApplicationConstants.tokenReceived), object: tokenData) // Print full message. print(userInfo) } // [END receive_message] func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) { print("Unable to register for remote notifications: \(error.localizedDescription)") } // This function is added here only for debugging purposes, and can be removed if swizzling is enabled. // If swizzling is disabled then this function must be implemented so that the APNs token can be paired to // the FCM registration token. func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) { print("APNs token retrieved: \(deviceToken)") //Call firebase function to store device token in the data base. // With swizzling disabled you must set the APNs token here. let deviceTokenString = deviceToken.base64EncodedString() Messaging.messaging().apnsToken = deviceToken fetchToken() //fetchVoiceList() } func fetchVoiceList() { if voiceLists == nil || (voiceLists?.isEmpty ?? true) { TextToSpeechRecognitionService.sharedInstance.voiceListDelegate = self TextToSpeechRecognitionService.sharedInstance.getVoiceLists () } } } // [START ios_10_message_handling] @available(iOS 10, *) extension AppDelegate : UNUserNotificationCenterDelegate { // Receive displayed notifications for iOS 10 devices. func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) { let userInfo = notification.request.content.userInfo // With swizzling disabled you must let Messaging know about the message, for Analytics Messaging.messaging().appDidReceiveMessage(userInfo) // Print message ID. if let messageID = userInfo[gcmMessageIDKey], let aps = userInfo["aps"] as? [String: Any], let alert = aps["alert"] as? [String: Any], let token = alert["body"] as? String , let expiryTime = alert["title"] as? String { print("Message ID: \(messageID)") let tokenData = [ApplicationConstants.accessToken: token, ApplicationConstants.expireTime: expiryTime] //UserDefaults.standard.set(tokenData, forKey: ApplicationConstants.token) FCMTokenProvider.tokenFromAppDelegate(tokenDict: tokenData) NotificationCenter.default.post(name: NSNotification.Name(ApplicationConstants.tokenReceived), object: tokenData) } // Print full message. print(userInfo) // Change this to your preferred presentation option completionHandler([]) } func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) { let userInfo = response.notification.request.content.userInfo // Print message ID. if let messageID = userInfo[gcmMessageIDKey], let aps = userInfo["aps"] as? [String: Any], let alert = aps["alert"] as? [String: Any], let token = alert["body"] as? String , let expiryTime = alert["title"] as? String { print("Message ID: \(messageID)") let tokenData = [ApplicationConstants.accessToken: token, ApplicationConstants.expireTime: expiryTime] NotificationCenter.default.post(name: NSNotification.Name(ApplicationConstants.tokenReceived), object: tokenData) } // Print full message. print(userInfo) completionHandler() } } // [END ios_10_message_handling] extension AppDelegate : MessagingDelegate { // [START refresh_token] func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String) { print("Firebase registration token: \(fcmToken)") let dataDict:[String: String] = ["token": fcmToken] NotificationCenter.default.post(name: Notification.Name("FCMToken"), object: nil, userInfo: dataDict) // TODO: If necessary send token to application server. // Note: This callback is fired at each app startup and whenever a new token is generated. } // [END refresh_token] } extension AppDelegate: VoiceListProtocol { func didReceiveVoiceList(voiceList: [FormattedVoice]?, errorString: String?) { if let errorString = errorString { let alertVC = UIAlertController(title: "Error", message: errorString, preferredStyle: .alert) alertVC.addAction(UIAlertAction(title: "OK", style: .default)) self.window?.rootViewController?.present(alertVC, animated: true) } self.voiceLists = voiceList NotificationCenter.default.post(name: Notification.Name("FetchVoiceList"), object: nil) } }
apache-2.0
ad37511dd0250534ae5ed36f3007187c
47.015228
222
0.725341
4.952356
false
false
false
false
kublaios/kublaiOSToolbox
Utilities.swift
1
1951
// // Utilities.swift // kublaiOSToolbox // // Created by Kubilay Erdogan on 13/06/15. // Copyright (c) 2015 Kubilay Erdogan // import Foundation class Utilities { static func JSONDataFromURL(url: String) -> NSDictionary { var err: NSError var errPointer: NSErrorPointer = NSErrorPointer() var request: NSURLRequest = NSURLRequest(URL: NSURL(string: url) as NSURL!) var response: AutoreleasingUnsafeMutablePointer<NSURLResponse?>=nil var dataVal: NSData = NSURLConnection.sendSynchronousRequest(request, returningResponse: response, error:errPointer)! if let retDict: AnyObject = NSJSONSerialization.JSONObjectWithData(dataVal, options: NSJSONReadingOptions.MutableContainers, error: errPointer) { return retDict as! NSDictionary } else { return NSDictionary() } } static func formatURL(url: String, param1: String?, param2: String?) -> String { if param1 != nil { if param2 != nil { return NSString(format: url, param1 as NSString!, param2 as NSString!) as String } else { return NSString(format: url, param1 as NSString!) as String } } else { return "" } } static func Log(log: String!) { if true { println(log) } } static func t(string: String) -> String { // TODO: Implement localization return string } static func isHostReachable() -> Bool { // TODO: Implement Reachability dependency // return (Reachability(hostName: "google.com").currentReachabilityStatus() != NetworkStatus.NotReachable) return true } static func viewController(name: String, inStoryboard: UIStoryboard) -> UIViewController { return inStoryboard.instantiateViewControllerWithIdentifier(name) as! UIViewController } }
mit
677b94cc83a20e97eada5db916ed037e
32.084746
153
0.629933
4.964377
false
false
false
false
firebase/quickstart-ios
database/DatabaseExampleSwiftUI/DatabaseExample/Shared/Views/NewPostsView.swift
1
2599
// // Copyright (c) 2021 Google 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 SwiftUI struct NewPostsView: View { @ObservedObject var postList = PostListViewModel() @Binding var isPresented: Bool @State private var newPostTitle: String = "" @State private var newPostBody: String = "" var body: some View { HStack { Button(action: { isPresented = false }) { Image(systemName: "chevron.left") } Spacer() Button(action: { isPresented = false postList.didTapPostButton( title: newPostTitle, body: newPostBody ) }) { Text("Post") } } .padding(20) VStack { // post title let postTitleInput = TextField("Add a title", text: $newPostTitle) .font(.largeTitle) .padding() #if os(iOS) || os(tvOS) postTitleInput .frame( width: ScreenDimensions.width * 0.88, height: ScreenDimensions.height * 0.08, alignment: .leading ) #elseif os(macOS) postTitleInput .frame(minWidth: 400) #endif // post body #if os(iOS) || os(macOS) let postBodyInput = TextEditor(text: $newPostBody) .padding() #elseif os(tvOS) let postBodyInput = TextField("Say something...", text: $newPostBody) .padding() #endif #if os(iOS) || os(tvOS) postBodyInput .frame( width: ScreenDimensions.width * 0.88, alignment: .leading ) #elseif os(macOS) postBodyInput .frame(minWidth: 300, minHeight: 300) #endif } .alert(isPresented: $postList.alert, content: { Alert( title: Text("Message"), message: Text(postList.alertMessage), dismissButton: .destructive(Text("Ok")) ) }) .navigationTitle("New Post") } } struct NewPostsView_Previews: PreviewProvider { static var previews: some View { NewPostsView(isPresented: .constant(true)) } }
apache-2.0
3656a9f983240a62fc716002db1b535e
25.793814
77
0.597538
4.185185
false
false
false
false
wireapp/wire-ios-sync-engine
Source/Synchronization/Strategies/ProxiedRequestStrategy.swift
1
3241
// // Wire // Copyright (C) 2016 Wire Swiss GmbH // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see http://www.gnu.org/licenses/. // import Foundation import WireTransport extension ProxiedRequestType { var basePath: String { switch self { case .giphy: return "/giphy" case .soundcloud: return "/soundcloud" case .youTube: return "/youtube" @unknown default: fatal("unknown ProxiedRequestType") } } } /// Perform requests to the Giphy search API public final class ProxiedRequestStrategy: AbstractRequestStrategy { static fileprivate let BasePath = "/proxy" /// The requests to fulfill fileprivate weak var requestsStatus: ProxiedRequestsStatus? /// Requests fail after this interval if the network is unreachable fileprivate static let RequestExpirationTime: TimeInterval = 20 @available (*, unavailable, message: "use `init(withManagedObjectContext:applicationStatus:requestsStatus:)` instead") override init(withManagedObjectContext moc: NSManagedObjectContext, applicationStatus: ApplicationStatus) { fatalError() } public init(withManagedObjectContext moc: NSManagedObjectContext, applicationStatus: ApplicationStatus, requestsStatus: ProxiedRequestsStatus) { self.requestsStatus = requestsStatus super.init(withManagedObjectContext: moc, applicationStatus: applicationStatus) } public override func nextRequestIfAllowed(for apiVersion: APIVersion) -> ZMTransportRequest? { guard let status = self.requestsStatus else { return nil } if let proxyRequest = status.pendingRequests.popFirst() { let fullPath = ProxiedRequestStrategy.BasePath + proxyRequest.type.basePath + proxyRequest.path let request = ZMTransportRequest(path: fullPath, method: proxyRequest.method, payload: nil, apiVersion: apiVersion.rawValue) if proxyRequest.type == .soundcloud { request.doesNotFollowRedirects = true } request.expire(afterInterval: ProxiedRequestStrategy.RequestExpirationTime) request.add(ZMCompletionHandler(on: self.managedObjectContext.zm_userInterface, block: { response in proxyRequest.callback?(response.rawData, response.rawResponse, response.transportSessionError as NSError?) })) request.add(ZMTaskCreatedHandler(on: self.managedObjectContext, block: { taskIdentifier in self.requestsStatus?.executedRequests[proxyRequest] = taskIdentifier })) return request } return nil } }
gpl-3.0
5101ccf8deb6966aedce7373848ff73f
39.012346
148
0.704721
5.136292
false
false
false
false
WilliamHester/Breadit-iOS
Breadit/ViewControllers/YouTubePreviewViewController.swift
1
2024
// // YouTubePreviewViewController.swift // Breadit // // Created by William Hester on 5/12/16. // Copyright © 2016 William Hester. All rights reserved. // import UIKit import youtube_ios_player_helper class YouTubePreviewViewController: UIViewController, YTPlayerViewDelegate { private var playerView: YTPlayerView! var link: Link! override func loadView() { uiView { v in v.backgroundColor = UIColor.blackColor() v.uiStackView { v in v.axis = .Vertical self.playerView = YTPlayerView() self.playerView.delegate = self self.playerView.hidden = true v.addChild(self.playerView) }.constrain { v in v.leftAnchor.constraintEqualToAnchor(self.view.leftAnchor).active = true v.rightAnchor.constraintEqualToAnchor(self.view.rightAnchor).active = true v.topAnchor.constraintEqualToAnchor(self.view.topAnchor).active = true v.bottomAnchor.constraintEqualToAnchor(self.view.bottomAnchor).active = true } } } override func viewDidLoad() { super.viewDidLoad() title = "YouTube" playerView.topAnchor.constraintEqualToAnchor(topLayoutGuide.bottomAnchor) let doneButtom = UIBarButtonItem(barButtonSystemItem: .Done, target: self, action: #selector(YouTubePreviewViewController.done(_:))) navigationItem.leftBarButtonItem = doneButtom playerView.loadWithVideoId(link.id!) } func done(obj: AnyObject) { dismissViewControllerAnimated(true, completion: nil) } override func preferredStatusBarStyle() -> UIStatusBarStyle { return .LightContent } func playerViewDidBecomeReady(playerView: YTPlayerView) { playerView.hidden = false } func playerViewPreferredWebViewBackgroundColor(playerView: YTPlayerView) -> UIColor { return UIColor.clearColor() } }
apache-2.0
d8fe3239124feb1903466631bb81b13d
30.123077
92
0.651013
5.173913
false
false
false
false
DNESS/SBTween
SBTween/ease/Ease.swift
3
5928
// // Ease.swift // GTween // // Created by Goon Nguyen on 10/10/14. // Copyright (c) 2014 Goon Nguyen. All rights reserved. // import Foundation struct Ease { /*static var Linear:String = "Linear" static var Back:String = "Back" static var Elastic:String = "Elastic" static var Quint:String = "Quint" static var Sine:String = "Sine" static var Bounce:String = "Bounce" static var Expo:String = "Expo" static var Circ:String = "Circ" static var Cubic:String = "Cubic" static var Quad:String = "Quad" static var Quart:String = "Quart"*/ static var linearMode:ModeLinear = ModeLinear() static var backMode:ModeBack = ModeBack() static var quintMode:ModeQuint = ModeQuint() static var elasticMode:ModeElastic = ModeElastic() static var bounceMode:ModeBounce = ModeBounce() static var sineMode:ModeSine = ModeSine() static var expoMode:ModeExpo = ModeExpo() static var circMode:ModeCirc = ModeCirc() static var cubicMode:ModeCubic = ModeCubic() static var quartMode:ModeQuart = ModeQuart() static var quadMode:ModeQuad = ModeQuad() static func getEaseNumber(type:String, time:Float)->Float { var result:Float; switch(type){ case Back.easeOut: Ease.backMode.time = time result = Ease.backMode.easeOutNumber break case Back.easeIn: Ease.backMode.time = time result = Ease.backMode.easeInNumber break case Back.easeInOut: Ease.backMode.time = time result = Ease.backMode.easeInOutNumber break case Elastic.easeOut: Ease.elasticMode.time = time result = Ease.elasticMode.easeOutNumber break case Elastic.easeIn: Ease.elasticMode.time = time result = Ease.elasticMode.easeInNumber break case Elastic.easeInOut: Ease.elasticMode.time = time result = Ease.elasticMode.easeInOutNumber break case Bounce.easeOut: Ease.bounceMode.time = time result = Ease.bounceMode.easeOutNumber break case Bounce.easeIn: Ease.bounceMode.time = time result = Ease.bounceMode.easeInNumber break case Bounce.easeInOut: Ease.bounceMode.time = time result = Ease.bounceMode.easeInOutNumber break case Sine.easeOut: Ease.sineMode.time = time result = Ease.sineMode.easeOutNumber break case Sine.easeIn: Ease.sineMode.time = time result = Ease.sineMode.easeInNumber break case Sine.easeInOut: Ease.sineMode.time = time result = Ease.sineMode.easeInOutNumber break case Expo.easeOut: Ease.expoMode.time = time result = Ease.expoMode.easeOutNumber break case Expo.easeIn: Ease.expoMode.time = time result = Ease.expoMode.easeInNumber break case Expo.easeInOut: Ease.expoMode.time = time result = Ease.expoMode.easeInOutNumber break case Circ.easeOut: Ease.circMode.time = time result = Ease.circMode.easeOutNumber break case Circ.easeIn: Ease.circMode.time = time result = Ease.circMode.easeInNumber break case Circ.easeInOut: Ease.circMode.time = time result = Ease.circMode.easeInOutNumber break case Cubic.easeOut: Ease.cubicMode.time = time result = Ease.cubicMode.easeOutNumber break case Cubic.easeIn: Ease.cubicMode.time = time result = Ease.cubicMode.easeInNumber break case Cubic.easeInOut: Ease.cubicMode.time = time result = Ease.cubicMode.easeInOutNumber break case Quad.easeOut: Ease.quadMode.time = time result = Ease.quadMode.easeOutNumber break case Quad.easeIn: Ease.quadMode.time = time result = Ease.quadMode.easeInNumber break case Quad.easeInOut: Ease.quadMode.time = time result = Ease.quadMode.easeInOutNumber break case Quart.easeOut: Ease.quartMode.time = time result = Ease.quartMode.easeOutNumber break case Quart.easeIn: Ease.quartMode.time = time result = Ease.quartMode.easeInNumber break case Quart.easeInOut: Ease.quartMode.time = time result = Ease.quartMode.easeInOutNumber break case Quint.easeOut: Ease.quintMode.time = time result = Ease.quintMode.easeOutNumber break case Quint.easeIn: Ease.quintMode.time = time result = Ease.quintMode.easeInNumber break case Quint.easeInOut: Ease.quintMode.time = time result = Ease.quintMode.easeInOutNumber break default: Ease.linearMode.time = time result = Ease.linearMode.easeNoneNumber break } return result } }
mit
0a1173975026cef6fb926d25003bc020
28.79397
63
0.531039
4.998314
false
false
false
false
Laptopmini/SwiftyArtik
Source/DeviceStatus.swift
1
2404
// // DeviceStatus.swift // SwiftyArtik // // Created by Paul-Valentin Mini on 6/2/17. // Copyright © 2017 Paul-Valentin Mini. All rights reserved. // import Foundation import ObjectMapper import PromiseKit open class DeviceStatus: Mappable, AccessibleArtikInstance { public var did: String? public var lastMessageTs: ArtikTimestamp? public var lastActionTs: ArtikTimestamp? public var lastTimeOnline: ArtikTimestamp? public var availability: DeviceStatusAvailability? public var snapshot: [String:Any]? public enum DeviceStatusAvailability: String { case online = "online" case offline = "offline" case unknown = "unknown" } public init() {} required public init?(map: Map) {} public func mapping(map: Map) { did <- map["did"] lastMessageTs <- map["data.lastMessageTs"] lastActionTs <- map["data.lastActionTs"] lastTimeOnline <- map["data.lastTimeOnline"] availability <- map["data.availability"] snapshot <- map["data.snapshot"] } // MARK: - AccessibleArtikInstance public func updateOnArtik() -> Promise<Void> { let promise = Promise<Void>.pending() if let did = did { if let availability = availability { DevicesAPI.updateStatus(id: did, to: availability).then { _ -> Void in promise.fulfill(()) }.catch { error -> Void in promise.reject(error) } } else { promise.reject(ArtikError.missingValue(reason: .noAvailability)) } } else { promise.reject(ArtikError.missingValue(reason: .noID)) } return promise.promise } public func pullFromArtik() -> Promise<Void> { let promise = Promise<Void>.pending() if let did = did { DevicesAPI.getStatus(id: did).then { status -> Void in self.mapping(map: Map(mappingType: .fromJSON, JSON: status.toJSON(), toObject: true, context: nil, shouldIncludeNilValues: true)) promise.fulfill(()) }.catch { error -> Void in promise.reject(error) } } else { promise.reject(ArtikError.missingValue(reason: .noID)) } return promise.promise } }
mit
8050034b7c9abc966750169276811978
30.207792
145
0.583021
4.585878
false
false
false
false
mchirico/SwiftCharts
SwiftCharts/Chart.swift
7
2393
// // Chart.swift // SwiftCharts // // Created by ischuetz on 25/04/15. // Copyright (c) 2015 ivanschuetz. All rights reserved. // import UIKit public class ChartSettings { public var leading: CGFloat = 0 public var top: CGFloat = 0 public var trailing: CGFloat = 0 public var bottom: CGFloat = 0 public var labelsSpacing: CGFloat = 5 public var labelsToAxisSpacingX: CGFloat = 5 public var labelsToAxisSpacingY: CGFloat = 5 public var spacingBetweenAxesX: CGFloat = 15 public var spacingBetweenAxesY: CGFloat = 15 public var axisTitleLabelsToLabelsSpacing: CGFloat = 5 public var axisStrokeWidth: CGFloat = 1.0 public init() {} } public class Chart { public let view: ChartBaseView private let layers: [ChartLayer] convenience public init(frame: CGRect, layers: [ChartLayer]) { self.init(view: ChartBaseView(frame: frame), layers: layers) } public init(view: ChartBaseView, layers: [ChartLayer]) { self.layers = layers self.view = view self.view.chart = self for layer in self.layers { layer.chartInitialized(chart: self) } self.view.setNeedsDisplay() } public required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } public func addSubview(view: UIView) { self.view.addSubview(view) } public var frame: CGRect { return self.view.frame } public var bounds: CGRect { return self.view.bounds } public func clearView() { self.view.removeFromSuperview() } private func drawRect(rect: CGRect) { let context = UIGraphicsGetCurrentContext() for layer in self.layers { layer.chartViewDrawing(context: context, chart: self) } } } public class ChartBaseView: UIView { weak var chart: Chart? override public init(frame: CGRect) { super.init(frame: frame) self.sharedInit() } required public init(coder aDecoder: NSCoder) { super.init(coder: aDecoder) self.sharedInit() } func sharedInit() { self.backgroundColor = UIColor.clearColor() } override public func drawRect(rect: CGRect) { self.chart?.drawRect(rect) } }
apache-2.0
a7d910798a94a18f184d63c8fef6909f
22.94
68
0.619724
4.489681
false
false
false
false
swillsea/DailyDiary
DailyDiary/GridCell.swift
1
786
// // GridCell.swift // Quotidian // // Created by Sam on 5/9/16. // Copyright © 2016 Sam Willsea, Pei Xiong, and Michael Merrill. All rights reserved. // import UIKit class GridCell: UICollectionViewCell { @IBOutlet weak var imageView: UIImageView! weak var entry : Entry?{ didSet { if entry?.imageData != nil{ imageView.image = UIImage(data: (entry?.imageData!)!) } else { imageView.image = nil; imageView.backgroundColor = UIColor.init(colorLiteralRed: 200/255, green: 200/255, blue: 200/255, alpha: 1.0) } self.imageView.layer.cornerRadius = 4 self.imageView.clipsToBounds = true } } }
mit
1635f50c3b72d02cd77831cfbe9a5d77
25.166667
125
0.549045
4.410112
false
false
false
false
tromg/PeriscommentView
PeriscommentView/PeriscommentView.swift
2
2355
// // PeriscommentView.swift // PeriscommentView // // Created by Takuma Yoshida on 2015/04/08. // Copyright (c) 2015 Uniface, Inc. All rights reserved. // import UIKit public class PeriscommentView: UIView { private var visibleCells: [PeriscommentCell] = [] private var config: PeriscommentConfig convenience override init(frame: CGRect) { let config = PeriscommentConfig() self.init(frame: frame, config: config) } required public init(coder aDecoder: NSCoder) { self.config = PeriscommentConfig() super.init(coder: aDecoder) } init(frame: CGRect, config: PeriscommentConfig) { self.config = config super.init(frame: frame) } override public func willMoveToSuperview(newSuperview: UIView?) { super.willMoveToSuperview(newSuperview) setupView() } private func setupView() { self.backgroundColor = config.layout.backgroundColor } public func addCell(cell: PeriscommentCell) { cell.frame = CGRect(origin: CGPoint(x: 0, y: self.frame.height), size: cell.frame.size) visibleCells.append(cell) self.addSubview(cell) UIView.animateWithDuration(self.config.appearDuration, delay: 0, options: UIViewAnimationOptions.CurveEaseOut, animations: { () -> Void in let dy = cell.frame.height + self.config.layout.cellSpace for c in self.visibleCells { let origin = c.transform let transform = CGAffineTransformMakeTranslation(0, -dy) c.transform = CGAffineTransformConcat(origin, transform) } }, completion: nil) UIView.animateWithDuration(self.config.disappearDuration, delay: self.config.appearDuration, options: UIViewAnimationOptions.CurveEaseIn, animations: { () -> Void in cell.alpha = 0.0 }) { (Bool) -> Void in cell.removeFromSuperview() self.visibleCells.removeAtIndex(self.visibleCells.indexOf(cell)!) } } public func addCell(profileImage: UIImage, name: String, comment: String) { let rect = CGRect.zeroRect let cell = PeriscommentCell(frame: rect, profileImage: profileImage, name: name, comment: comment, config: self.config) self.addCell(cell) } }
mit
74155827366d62e1efcd07699a4cecef
32.642857
173
0.644161
4.520154
false
true
false
false
turingcorp/gattaca
gattaca/Model/Home/Strategy/MHomeStrategyFactory.swift
1
973
import Foundation extension MHomeStrategy { //MARK: private private class func strategyMap() -> [MHome.Status:MHomeStrategy.Type] { let map:[MHome.Status:MHomeStrategy.Type] = [ MHome.Status.new:MHomeStrategyNew.self, MHome.Status.authLocation:MHomeStrategyAuthLocation.self, MHome.Status.ready:MHomeStrategyReady.self] return map } //MARK: internal class func factoryStrategy(controller:CHome) -> MHomeStrategy? { let map:[MHome.Status:MHomeStrategy.Type] = strategyMap() let currentStatus:MHome.Status = controller.model.status guard let strategyType:MHomeStrategy.Type = map[currentStatus] else { return nil } let strategy:MHomeStrategy = strategyType.init( controller:controller) return strategy } }
mit
97411d347d364c50c8fc5a85bef3a667
24.605263
73
0.583762
4.939086
false
false
false
false
michaelgwelch/pandemic
Pandemic/Graph/UnweightedEdge.swift
1
1957
// // UnweightedEdge.swift // SwiftGraph // // Copyright (c) 2014-2015 David Kopec // // 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. /// A basic unweighted edge. public class UnweightedEdge: Edge, Equatable, CustomStringConvertible { public var u: Int public var v: Int public var weighted: Bool { return false } public let directed: Bool public var reversed:Edge { return UnweightedEdge(u: v, v: u, directed: directed) } public init(u: Int, v: Int, directed: Bool) { self.u = u self.v = v self.directed = directed } //Implement Printable protocol public var description: String { if directed { return "\(u) -> \(v)" } return "\(u) <-> \(v)" } } public func ==(lhs: UnweightedEdge, rhs: UnweightedEdge) -> Bool { return lhs.u == rhs.u && lhs.v == rhs.v && lhs.directed == rhs.directed }
mit
045e156956dc18c3929edba6bf5e1681
36.653846
82
0.682678
4.181624
false
false
false
false
BeitIssieShapiro/IssieBoard
IssieBoard.xcodeproj/ConfigurableKeyboard/KeyboardViewController.swift
3
31997
// // KeyboardViewController.swift // Keyboard // // Created by Alexei Baboulevitch on 6/9/14. // Copyright (c) 2014 Apple. All rights reserved. // import UIKit import AudioToolbox let metrics: [String:Double] = [ "topBanner": 30 ] func metric(name: String) -> CGFloat { return CGFloat(metrics[name]!) } class KeyboardViewController: UIInputViewController { let backspaceDelay: NSTimeInterval = 0.5 let backspaceRepeat: NSTimeInterval = 0.07 var keyboard: Keyboard! var forwardingView: ForwardingView! var layout: KeyboardLayout? var heightConstraint: NSLayoutConstraint? var settingsView: ExtraView? var currentMode: Int { didSet { if oldValue != currentMode { setMode(currentMode) } } } var backspaceActive: Bool { get { return (backspaceDelayTimer != nil) || (backspaceRepeatTimer != nil) } } var backspaceDelayTimer: NSTimer? var backspaceRepeatTimer: NSTimer? enum AutoPeriodState { case NoSpace case FirstSpace } var autoPeriodState: AutoPeriodState = .NoSpace var lastCharCountInBeforeContext: Int = 0 var keyboardHeight: CGFloat { get { if let constraint = self.heightConstraint { return constraint.constant } else { return 0 } } set { self.setHeight(newValue) } } // TODO: why does the app crash if this isn't here? convenience init() { self.init(nibName: nil, bundle: nil) } override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) { self.keyboard = standardKeyboard() self.currentMode = 0 super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) self.forwardingView = ForwardingView(frame: CGRectZero) self.view.addSubview(self.forwardingView) NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("defaultsChanged:"), name: NSUserDefaultsDidChangeNotification, object: nil) } required init(coder: NSCoder) { fatalError("NSCoding not supported") } deinit { backspaceDelayTimer?.invalidate() backspaceRepeatTimer?.invalidate() NSNotificationCenter.defaultCenter().removeObserver(self) } func defaultsChanged(notification: NSNotification) { var defaults = notification.object as! NSUserDefaults defaults.synchronize() defaults = NSUserDefaults.standardUserDefaults() var i : Int = defaults.integerForKey("defaultBackgroundColor") defaults.synchronize() } // without this here kludge, the height constraint for the keyboard does not work for some reason var kludge: UIView? func setupKludge() { if self.kludge == nil { var kludge = UIView() self.view.addSubview(kludge) kludge.setTranslatesAutoresizingMaskIntoConstraints(false) kludge.hidden = true let a = NSLayoutConstraint(item: kludge, attribute: NSLayoutAttribute.Left, relatedBy: NSLayoutRelation.Equal, toItem: self.view, attribute: NSLayoutAttribute.Left, multiplier: 1, constant: 0) let b = NSLayoutConstraint(item: kludge, attribute: NSLayoutAttribute.Right, relatedBy: NSLayoutRelation.Equal, toItem: self.view, attribute: NSLayoutAttribute.Left, multiplier: 1, constant: 0) let c = NSLayoutConstraint(item: kludge, attribute: NSLayoutAttribute.Top, relatedBy: NSLayoutRelation.Equal, toItem: self.view, attribute: NSLayoutAttribute.Top, multiplier: 1, constant: 0) let d = NSLayoutConstraint(item: kludge, attribute: NSLayoutAttribute.Bottom, relatedBy: NSLayoutRelation.Equal, toItem: self.view, attribute: NSLayoutAttribute.Top, multiplier: 1, constant: 0) self.view.addConstraints([a, b, c, d]) self.kludge = kludge } } /* BUG NOTE For some strange reason, a layout pass of the entire keyboard is triggered whenever a popup shows up, if one of the following is done: a) The forwarding view uses an autoresizing mask. b) The forwarding view has constraints set anywhere other than init. On the other hand, setting (non-autoresizing) constraints or just setting the frame in layoutSubviews works perfectly fine. I don't really know what to make of this. Am I doing Autolayout wrong, is it a bug, or is it expected behavior? Perhaps this has to do with the fact that the view's frame is only ever explicitly modified when set directly in layoutSubviews, and not implicitly modified by various Autolayout constraints (even though it should really not be changing). */ var constraintsAdded: Bool = false func setupLayout() { if !constraintsAdded { self.layout = self.dynamicType.layoutClass(model: self.keyboard, superview: self.forwardingView, layoutConstants: self.dynamicType.layoutConstants, globalColors: self.dynamicType.globalColors/*, darkMode: self.darkMode(), solidColorMode: self.solidColorMode()*/) self.layout?.initialize() self.setMode(0) self.setupKludge() self.addInputTraitsObservers() self.constraintsAdded = true } } var lastLayoutBounds: CGRect? override func viewDidLayoutSubviews() { if view.bounds == CGRectZero { return } self.setupLayout() let orientationSavvyBounds = CGRectMake(0, 0, self.view.bounds.width, self.heightForOrientation(self.interfaceOrientation, withTopBanner: false)) if (lastLayoutBounds != nil && lastLayoutBounds == orientationSavvyBounds) { // do nothing } else { // let uppercase = self.shiftState.uppercase() // let characterUppercase = (NSUserDefaults.standardUserDefaults().boolForKey(kSmallLowercase) ? uppercase : true) self.forwardingView.frame = orientationSavvyBounds self.layout?.layoutKeys(self.currentMode)//, uppercase: uppercase, characterUppercase: characterUppercase, shiftState: self.shiftState) self.lastLayoutBounds = orientationSavvyBounds self.setupKeys() } // self.bannerView?.frame = CGRectMake(0, 0, self.view.bounds.width, metric("topBanner")) let newOrigin = CGPointMake(0, self.view.bounds.height - self.forwardingView.bounds.height) self.forwardingView.frame.origin = newOrigin } override func loadView() { super.loadView() } override func viewWillAppear(animated: Bool) { // self.bannerView?.hidden = false self.keyboardHeight = self.heightForOrientation(self.interfaceOrientation, withTopBanner: true) } override func willRotateToInterfaceOrientation(toInterfaceOrientation: UIInterfaceOrientation, duration: NSTimeInterval) { self.forwardingView.resetTrackedViews() // self.shiftStartingState = nil // self.shiftWasMultitapped = false // optimization: ensures smooth animation if let keyPool = self.layout?.keyPool { for view in keyPool { view.shouldRasterize = true } } self.keyboardHeight = self.heightForOrientation(toInterfaceOrientation, withTopBanner: true) } override func didRotateFromInterfaceOrientation(fromInterfaceOrientation: UIInterfaceOrientation) { // optimization: ensures quick mode and shift transitions if let keyPool = self.layout?.keyPool { for view in keyPool { view.shouldRasterize = false } } } func heightForOrientation(orientation: UIInterfaceOrientation, withTopBanner: Bool) -> CGFloat { let isPad = UIDevice.currentDevice().userInterfaceIdiom == UIUserInterfaceIdiom.Pad //TODO: hardcoded stuff let actualScreenWidth = (UIScreen.mainScreen().nativeBounds.size.width / UIScreen.mainScreen().nativeScale) let canonicalPortraitHeight = (isPad ? CGFloat(264) : CGFloat(orientation.isPortrait && actualScreenWidth >= 400 ? 226 : 216)) let canonicalLandscapeHeight = (isPad ? CGFloat(352) : CGFloat(162)) let topBannerHeight = (withTopBanner ? metric("topBanner") : 0) return CGFloat(orientation.isPortrait ? canonicalPortraitHeight + topBannerHeight : canonicalLandscapeHeight + topBannerHeight) } /* BUG NOTE None of the UIContentContainer methods are called for this controller. */ //override func viewWillTransitionToSize(size: CGSize, withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator) { // super.viewWillTransitionToSize(size, withTransitionCoordinator: coordinator) //} func setupKeys() { if self.layout == nil { return } for page in keyboard.pages { for rowKeys in page.rows { // TODO: quick hack for key in rowKeys { if let keyView = self.layout?.viewForKey(key) { keyView.removeTarget(nil, action: nil, forControlEvents: UIControlEvents.AllEvents) switch key.type { case Key.KeyType.KeyboardChange: keyView.addTarget(self, action: "advanceTapped:", forControlEvents: .TouchUpInside) case Key.KeyType.Backspace: let cancelEvents: UIControlEvents = UIControlEvents.TouchUpInside|UIControlEvents.TouchUpInside|UIControlEvents.TouchDragExit|UIControlEvents.TouchUpOutside|UIControlEvents.TouchCancel|UIControlEvents.TouchDragOutside keyView.addTarget(self, action: "backspaceDown:", forControlEvents: .TouchDown) keyView.addTarget(self, action: "backspaceUp:", forControlEvents: cancelEvents) case Key.KeyType.ModeChange: keyView.addTarget(self, action: Selector("modeChangeTapped:"), forControlEvents: .TouchDown) //case Key.KeyType.Space : //case Key.KeyType.Return : // case Key.KeyType.CtrlZ : // keyView.addTarget(self, action: Selector("ctrlZTapped:"), forControlEvents: .TouchDown) //case Key.KeyType.AltCtrlZ : // keyView.addTarget(self, action: Selector("altCtrlZTapped:"), forControlEvents: .TouchDown) case Key.KeyType.DismissKeyboard : keyView.addTarget(self, action: Selector("dismissKeyboardTapped:"), forControlEvents: .TouchDown) //case Key.KeyType.Settings: // keyView.addTarget(self, action: Selector("toggleSettings"), forControlEvents: .TouchUpInside) default: break } if key.isCharacter && key.type != Key.KeyType.HiddenKey { if UIDevice.currentDevice().userInterfaceIdiom != UIUserInterfaceIdiom.Pad { keyView.addTarget(self, action: Selector("showPopup:"), forControlEvents: .TouchDown | .TouchDragInside | .TouchDragEnter) keyView.addTarget(keyView, action: Selector("hidePopup"), forControlEvents: .TouchDragExit | .TouchCancel) keyView.addTarget(self, action: Selector("hidePopupDelay:"), forControlEvents: .TouchUpInside | .TouchUpOutside | .TouchDragOutside) } } if key.type == Key.KeyType.Undo { keyView.addTarget(self, action: "undoTapped:", forControlEvents: .TouchUpInside) } if key.hasOutput && key.type != Key.KeyType.HiddenKey { keyView.addTarget(self, action: "keyPressedHelper:", forControlEvents: .TouchUpInside) } if /*key.type != Key.KeyType.Shift && */key.type != Key.KeyType.ModeChange { keyView.addTarget(self, action: Selector("highlightKey:"), forControlEvents: .TouchDown | .TouchDragInside | .TouchDragEnter) keyView.addTarget(self, action: Selector("unHighlightKey:"), forControlEvents: .TouchUpInside | .TouchUpOutside | .TouchDragOutside | .TouchDragExit | .TouchCancel) } if key.type != Key.KeyType.HiddenKey { keyView.addTarget(self, action: Selector("playKeySound"), forControlEvents: .TouchDown) } } } } } } ///////////////// // POPUP DELAY // ///////////////// var keyWithDelayedPopup: KeyboardKey? var popupDelayTimer: NSTimer? func showPopup(sender: KeyboardKey) { if sender == self.keyWithDelayedPopup { self.popupDelayTimer?.invalidate() } sender.showPopup() } func hidePopupDelay(sender: KeyboardKey) { self.popupDelayTimer?.invalidate() if sender != self.keyWithDelayedPopup { self.keyWithDelayedPopup?.hidePopup() self.keyWithDelayedPopup = sender } if sender.popup != nil { self.popupDelayTimer = NSTimer.scheduledTimerWithTimeInterval(0.05, target: self, selector: Selector("hidePopupCallback"), userInfo: nil, repeats: false) } } func hidePopupCallback() { self.keyWithDelayedPopup?.hidePopup() self.keyWithDelayedPopup = nil self.popupDelayTimer = nil } ///////////////////// // POPUP DELAY END // ///////////////////// override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated } // TODO: this is currently not working as intended; only called when selection changed -- iOS bug override func textDidChange(textInput: UITextInput) { self.contextChanged() } override func textWillChange(textInput: UITextInput) { self.contextChanged() } func contextChanged() { // self.setCapsIfNeeded() self.autoPeriodState = .NoSpace } //Orit: these constraints are causing an error - needs to be fixed func setHeight(height: CGFloat) { // if self.heightConstraint == nil { // self.heightConstraint = NSLayoutConstraint( // item:self.view, // attribute:NSLayoutAttribute.Height, // relatedBy:NSLayoutRelation.Equal, // toItem:nil, // attribute:NSLayoutAttribute.NotAnAttribute, // multiplier:0, // constant:height) // self.heightConstraint!.priority = 1000 // // self.view.addConstraint(self.heightConstraint!) // TODO: what if view already has constraint added? // } // else { self.heightConstraint?.constant = height // } } func updateAppearances(appearanceIsDark: Bool) { // self.layout?.solidColorMode = self.solidColorMode() //self.layout?.darkMode = appearanceIsDark self.layout?.updateKeyAppearance() // self.bannerView?.darkMode = appearanceIsDark self.settingsView?.darkMode = appearanceIsDark } func highlightKey(sender: KeyboardKey) { sender.highlighted = true } func unHighlightKey(sender: KeyboardKey) { sender.highlighted = false } func keyPressedHelper(sender: KeyboardKey) { if let model = self.layout?.keyForView(sender) { self.keyPressed(model) // auto exit from special char subkeyboard if /*model.type == Key.KeyType.Space ||*/ model.type == Key.KeyType.Return { self.currentMode = 0 } //else if model.uppercaseOutput/*lowercaseOutput*/ == "'" { // self.currentMode = 0 //} // else if model.type == Key.KeyType.Character { // self.currentMode = 0 // } // auto period on double space // TODO: timeout var lastCharCountInBeforeContext: Int = 0 var readyForDoubleSpacePeriod: Bool = true self.handleAutoPeriod(model) // Orit: TODO: reset context } // self.setCapsIfNeeded() } func handleAutoPeriod(key: Key) { // if !NSUserDefaults.standardUserDefaults().boolForKey(kPeriodShortcut) { // return // } if self.autoPeriodState == .FirstSpace { if key.type != Key.KeyType.Space { self.autoPeriodState = .NoSpace return } let charactersAreInCorrectState = { () -> Bool in let previousContext = (self.textDocumentProxy as? UITextDocumentProxy)?.documentContextBeforeInput if previousContext == nil || count(previousContext!) < 3 { return false } var index = previousContext!.endIndex index = index.predecessor() if previousContext![index] != " " { return false } index = index.predecessor() if previousContext![index] != " " { return false } index = index.predecessor() let char = previousContext![index] if self.characterIsWhitespace(char) || self.characterIsPunctuation(char) || char == "," { return false } return true }() if charactersAreInCorrectState { (self.textDocumentProxy as? UITextDocumentProxy)?.deleteBackward() (self.textDocumentProxy as? UITextDocumentProxy)?.deleteBackward() (self.textDocumentProxy as? UITextDocumentProxy)?.insertText(".") (self.textDocumentProxy as? UITextDocumentProxy)?.insertText(" ") } self.autoPeriodState = .NoSpace } else { if key.type == Key.KeyType.Space { self.autoPeriodState = .FirstSpace } } } func cancelBackspaceTimers() { self.backspaceDelayTimer?.invalidate() self.backspaceRepeatTimer?.invalidate() self.backspaceDelayTimer = nil self.backspaceRepeatTimer = nil } func backspaceDown(sender: KeyboardKey) { self.cancelBackspaceTimers() if let textDocumentProxy = self.textDocumentProxy as? UIKeyInput { textDocumentProxy.deleteBackward() } // self.setCapsIfNeeded() // trigger for subsequent deletes self.backspaceDelayTimer = NSTimer.scheduledTimerWithTimeInterval(backspaceDelay - backspaceRepeat, target: self, selector: Selector("backspaceDelayCallback"), userInfo: nil, repeats: false) } func backspaceUp(sender: KeyboardKey) { self.cancelBackspaceTimers() } func backspaceDelayCallback() { self.backspaceDelayTimer = nil self.backspaceRepeatTimer = NSTimer.scheduledTimerWithTimeInterval(backspaceRepeat, target: self, selector: Selector("backspaceRepeatCallback"), userInfo: nil, repeats: true) } func backspaceRepeatCallback() { self.playKeySound() if let textDocumentProxy = self.textDocumentProxy as? UIKeyInput { textDocumentProxy.deleteBackward() } //self.setCapsIfNeeded() } /* func ctrlZTapped (sender : KeyboardKey) { assert(true, "hi") } func altCtrlZTapped (sender : KeyboardKey) { assert(true,"hi") }*/ func dismissKeyboardTapped (sender : KeyboardKey) { self.dismissKeyboard() } func undoTapped (sender : KeyboardKey) { // self.undoManager?.undo() } /* func shiftDown(sender: KeyboardKey) { self.shiftStartingState = self.shiftState if let shiftStartingState = self.shiftStartingState { if shiftStartingState.uppercase() { // handled by shiftUp return } else { switch self.shiftState { case .Disabled: self.shiftState = .Enabled case .Enabled: self.shiftState = .Disabled case .Locked: self.shiftState = .Disabled } (sender.shape as? ShiftShape)?.withLock = false } } } func shiftUp(sender: KeyboardKey) { if self.shiftWasMultitapped { // do nothing } else { if let shiftStartingState = self.shiftStartingState { if !shiftStartingState.uppercase() { // handled by shiftDown } else { switch self.shiftState { case .Disabled: self.shiftState = .Enabled case .Enabled: self.shiftState = .Disabled case .Locked: self.shiftState = .Disabled } (sender.shape as? ShiftShape)?.withLock = false } } } self.shiftStartingState = nil self.shiftWasMultitapped = false } func shiftDoubleTapped(sender: KeyboardKey) { self.shiftWasMultitapped = true switch self.shiftState { case .Disabled: self.shiftState = .Locked case .Enabled: self.shiftState = .Locked case .Locked: self.shiftState = .Disabled } } */ /* func updateKeyCaps(uppercase: Bool) { let characterUppercase = (NSUserDefaults.standardUserDefaults().boolForKey(kSmallLowercase) ? uppercase : true) self.layout?.updateKeyCaps(false, uppercase: uppercase, characterUppercase: characterUppercase, shiftState: self.shiftState) }*/ func modeChangeTapped(sender: KeyboardKey) { if let toMode = self.layout?.viewToModel[sender]?.toMode { self.currentMode = toMode } } func setMode(mode: Int) { self.forwardingView.resetTrackedViews() //self.shiftStartingState = nil //self.shiftWasMultitapped = false //let uppercase = self.shiftState.uppercase() //let characterUppercase = (NSUserDefaults.standardUserDefaults().boolForKey(kSmallLowercase) ? uppercase : true) self.layout?.layoutKeys(mode)//, uppercase: uppercase, characterUppercase: characterUppercase, shiftState: self.shiftState) self.setupKeys() } func advanceTapped(sender: KeyboardKey) { self.forwardingView.resetTrackedViews() // self.shiftStartingState = nil // self.shiftWasMultitapped = false self.advanceToNextInputMode() } /*@IBAction func toggleSettings() { // lazy load settings if self.settingsView == nil { if var aSettings = self.createSettings() { aSettings.darkMode = self.darkMode() aSettings.hidden = true self.view.addSubview(aSettings) self.settingsView = aSettings aSettings.setTranslatesAutoresizingMaskIntoConstraints(false) let widthConstraint = NSLayoutConstraint(item: aSettings, attribute: NSLayoutAttribute.Width, relatedBy: NSLayoutRelation.Equal, toItem: self.view, attribute: NSLayoutAttribute.Width, multiplier: 1, constant: 0) let heightConstraint = NSLayoutConstraint(item: aSettings, attribute: NSLayoutAttribute.Height, relatedBy: NSLayoutRelation.Equal, toItem: self.view, attribute: NSLayoutAttribute.Height, multiplier: 1, constant: 0) let centerXConstraint = NSLayoutConstraint(item: aSettings, attribute: NSLayoutAttribute.CenterX, relatedBy: NSLayoutRelation.Equal, toItem: self.view, attribute: NSLayoutAttribute.CenterX, multiplier: 1, constant: 0) let centerYConstraint = NSLayoutConstraint(item: aSettings, attribute: NSLayoutAttribute.CenterY, relatedBy: NSLayoutRelation.Equal, toItem: self.view, attribute: NSLayoutAttribute.CenterY, multiplier: 1, constant: 0) self.view.addConstraint(widthConstraint) self.view.addConstraint(heightConstraint) self.view.addConstraint(centerXConstraint) self.view.addConstraint(centerYConstraint) } } if let settings = self.settingsView { let hidden = settings.hidden settings.hidden = !hidden self.forwardingView.hidden = hidden self.forwardingView.userInteractionEnabled = !hidden self.bannerView?.hidden = hidden } }*/ /*func setCapsIfNeeded() -> Bool { if self.shouldAutoCapitalize() { switch self.shiftState { case .Disabled: self.shiftState = .Enabled case .Enabled: self.shiftState = .Enabled case .Locked: self.shiftState = .Locked } return true } else { switch self.shiftState { case .Disabled: self.shiftState = .Disabled case .Enabled: self.shiftState = .Disabled case .Locked: self.shiftState = .Locked } return false } }*/ func characterIsPunctuation(character: Character) -> Bool { return (character == ".") || (character == "!") || (character == "?") } func characterIsNewline(character: Character) -> Bool { return (character == "\n") || (character == "\r") } func characterIsWhitespace(character: Character) -> Bool { // there are others, but who cares return (character == " ") || (character == "\n") || (character == "\r") || (character == "\t") } func stringIsWhitespace(string: String?) -> Bool { if string != nil { for char in string! { if !characterIsWhitespace(char) { return false } } } return true } /* func shouldAutoCapitalize() -> Bool { if !NSUserDefaults.standardUserDefaults().boolForKey(kAutoCapitalization) { return false } if let traits = self.textDocumentProxy as? UITextInputTraits { if let autocapitalization = traits.autocapitalizationType { var documentProxy = self.textDocumentProxy as? UITextDocumentProxy var beforeContext = documentProxy?.documentContextBeforeInput switch autocapitalization { case .None: return false case .Words: if let beforeContext = documentProxy?.documentContextBeforeInput { let previousCharacter = beforeContext[beforeContext.endIndex.predecessor()] return self.characterIsWhitespace(previousCharacter) } else { return true } case .Sentences: if let beforeContext = documentProxy?.documentContextBeforeInput { let offset = min(3, countElements(beforeContext)) var index = beforeContext.endIndex for (var i = 0; i < offset; i += 1) { index = index.predecessor() let char = beforeContext[index] if characterIsPunctuation(char) { if i == 0 { return false //not enough spaces after punctuation } else { return true //punctuation with at least one space after it } } else { if !characterIsWhitespace(char) { return false //hit a foreign character before getting to 3 spaces } else if characterIsNewline(char) { return true //hit start of line } } } return true //either got 3 spaces or hit start of line } else { return true } case .AllCharacters: return true } } else { return false } } else { return false } } */ // this only works if full access is enabled func playKeySound() { // if !NSUserDefaults.standardUserDefaults().boolForKey(kKeyboardClicks) { // return // } // dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), { AudioServicesPlaySystemSound(1104) }) } ////////////////////////////////////// // MOST COMMONLY EXTENDABLE METHODS // ////////////////////////////////////// class var layoutClass: KeyboardLayout.Type { get { return KeyboardLayout.self }} class var layoutConstants: LayoutConstants.Type { get { return LayoutConstants.self }} class var globalColors: GlobalColors.Type { get { return GlobalColors.self }} //fix this one - whn dismis keyboard is pressed func keyPressed(key: Key) { if let proxy = (self.textDocumentProxy as? UIKeyInput) { proxy.insertText(key.getKeyOutput())//outputForCase(/*shiftState.uppercase()*/)) } } // a settings view that replaces the keyboard when the settings button is pressed /*func createSettings() -> ExtraView? { // note that dark mode is not yet valid here, so we just put false for clarity var settingsView = DefaultSettings(globalColors: self.dynamicType.globalColors, darkMode: false, solidColorMode: self.solidColorMode()) //settingsView.backButton?.addTarget(self, action: Selector("toggleSettings"), forControlEvents: UIControlEvents.TouchUpInside) return settingsView }*/ }
apache-2.0
83133950a8b0a589b9e48e1465887fda
38.356704
274
0.569866
6.040589
false
false
false
false
joshpar/Lyrebird
LyrebirdSynth/Lyrebird/UGens/FilterUGens.swift
1
9805
// // FilterUGens.swift // Lyrebird // // Created by Joshua Parmenter on 6/2/16. // Copyright © 2016 Op133Studios. All rights reserved. // // out(i) = (a0 * in(i)) + (a1 * in(i-1)) + (b1 * out(i-1)) public final class FirstOrderSection : LyrebirdUGen { fileprivate var a0: LyrebirdValidUGenInput fileprivate var a1: LyrebirdValidUGenInput fileprivate var b1: LyrebirdValidUGenInput fileprivate var input: LyrebirdValidUGenInput fileprivate var lastA0: LyrebirdFloat = 0.0 fileprivate var lastA1: LyrebirdFloat = 0.0 fileprivate var lastB1: LyrebirdFloat = 0.0 fileprivate var input1: LyrebirdFloat = 0.0 public required init(rate: LyrebirdUGenRate, input: LyrebirdValidUGenInput, a0: LyrebirdValidUGenInput, a1: LyrebirdValidUGenInput, b1: LyrebirdValidUGenInput) { self.a0 = a0 self.a1 = a1 self.b1 = b1 self.input = input super.init(rate: rate) self.lastA0 = self.a0.floatValue(graph: graph) self.lastA1 = self.a1.floatValue(graph: graph) self.lastB1 = self.b1.floatValue(graph: graph) } override public final func next(numSamples: LyrebirdInt) -> Bool { let success: Bool = super.next(numSamples: numSamples) let inputSamples: [LyrebirdFloat] = input.sampleBlock(graph: graph, previousValue: 0.0) var input1: LyrebirdFloat = self.input1 var currentIn: LyrebirdFloat = 0.0 let newA0 = a0.floatValue(graph: graph) let newA1 = a1.floatValue(graph: graph) let newB1 = b1.floatValue(graph: graph) // try to avoid the interpolation if newA0 == lastA0 && newA1 == lastA1 && newB1 == lastB1 { for sampleIdx: LyrebirdInt in 0 ..< numSamples { currentIn = inputSamples[sampleIdx] + (lastB1 * input1) samples[sampleIdx] = (lastA0 * currentIn) + (lastA1 * input1) input1 = currentIn } } else { let a0Samps: [LyrebirdFloat] = a0.sampleBlock(graph: graph, previousValue: lastA0) let a1Samps: [LyrebirdFloat] = a1.sampleBlock(graph: graph, previousValue: lastA1) let b1Samps: [LyrebirdFloat] = b1.sampleBlock(graph: graph, previousValue: lastB1) for sampleIdx: LyrebirdInt in 0 ..< numSamples { currentIn = inputSamples[sampleIdx] + (b1Samps[sampleIdx] * input1) samples[sampleIdx] = (a0Samps[sampleIdx] * currentIn) + (a1Samps[sampleIdx] * input1) input1 = currentIn } lastA0 = a0Samps.last ?? 0.0 lastA1 = a1Samps.last ?? 0.0 lastB1 = b1Samps.last ?? 0.0 } self.input1 = input1 return success } } // out(i) = (a0 * in(i)) + (a1 * in(i-1)) + (a2 * in(i-2)) + (b1 * out(i-1)) + (b2 * out(i-2)) public final class SecondOrderSection : LyrebirdUGen { fileprivate var a0: LyrebirdValidUGenInput fileprivate var a1: LyrebirdValidUGenInput fileprivate var a2: LyrebirdValidUGenInput fileprivate var b1: LyrebirdValidUGenInput fileprivate var b2: LyrebirdValidUGenInput fileprivate var input: LyrebirdValidUGenInput fileprivate var lastA0: LyrebirdFloat = 0.0 fileprivate var lastA1: LyrebirdFloat = 0.0 fileprivate var lastA2: LyrebirdFloat = 0.0 fileprivate var lastB1: LyrebirdFloat = 0.0 fileprivate var lastB2: LyrebirdFloat = 0.0 fileprivate var input1: LyrebirdFloat = 0.0 fileprivate var input2: LyrebirdFloat = 0.0 public required init(rate: LyrebirdUGenRate, input: LyrebirdValidUGenInput, a0: LyrebirdValidUGenInput, a1: LyrebirdValidUGenInput, a2: LyrebirdValidUGenInput, b1: LyrebirdValidUGenInput, b2: LyrebirdValidUGenInput) { self.a0 = a0 self.a1 = a1 self.a2 = a2 self.b1 = b1 self.b2 = b2 self.input = input super.init(rate: rate) self.lastA0 = self.a0.floatValue(graph: graph) self.lastA1 = self.a1.floatValue(graph: graph) self.lastA2 = self.a2.floatValue(graph: graph) self.lastB1 = self.b1.floatValue(graph: graph) self.lastB2 = self.b2.floatValue(graph: graph) } override public final func next(numSamples: LyrebirdInt) -> Bool { let success: Bool = super.next(numSamples: numSamples) let inputSamples: [LyrebirdFloat] = input.sampleBlock(graph: graph, previousValue: 0.0) var input1: LyrebirdFloat = self.input1 var input2: LyrebirdFloat = self.input2 var currentIn: LyrebirdFloat = 0.0 let newA0 = a0.floatValue(graph: graph) let newA1 = a1.floatValue(graph: graph) let newA2 = a2.floatValue(graph: graph) let newB1 = b1.floatValue(graph: graph) let newB2 = b2.floatValue(graph: graph) // try to avoid the interpolation if (newA0 == lastA0) && (newA1 == lastA1) && (newA2 == lastA2) && (newB1 == lastB1) && (newB2 == lastB2) { for sampleIdx: LyrebirdInt in 0 ..< numSamples { currentIn = inputSamples[sampleIdx] + (newB1 * input1) + (newB2 * input2) samples[sampleIdx] = (newA0 * currentIn) + (newA1 * input1) + (newA2 * input2) input2 = input1 input1 = currentIn } } else { let a0Samps: [LyrebirdFloat] = a0.sampleBlock(graph: graph, previousValue: lastA0) let a1Samps: [LyrebirdFloat] = a1.sampleBlock(graph: graph, previousValue: lastA1) let a2Samps: [LyrebirdFloat] = a2.sampleBlock(graph: graph, previousValue: lastA2) let b1Samps: [LyrebirdFloat] = b1.sampleBlock(graph: graph, previousValue: lastB1) let b2Samps: [LyrebirdFloat] = b2.sampleBlock(graph: graph, previousValue: lastB2) for sampleIdx: LyrebirdInt in 0 ..< numSamples { currentIn = inputSamples[sampleIdx] + (b1Samps[sampleIdx] * input1) + (b2Samps[sampleIdx] * input2) samples[sampleIdx] = (a0Samps[sampleIdx] * currentIn) + (a1Samps[sampleIdx] * input1) + (a2Samps[sampleIdx] * input2) input2 = input1 input1 = currentIn } lastA0 = a0Samps.last ?? 0.0 lastA1 = a1Samps.last ?? 0.0 lastA2 = a2Samps.last ?? 0.0 lastB1 = b1Samps.last ?? 0.0 lastB2 = b2Samps.last ?? 0.0 } self.input1 = input1 self.input2 = input2 return success } } /** Bristow-Johnson SOS Cookbook */ open class FliterRBJ : LyrebirdUGen { internal var input: LyrebirdValidUGenInput internal var sos: SecondOrderSection? internal var a0: LyrebirdValidUGenInput = 0.0 internal var a1: LyrebirdValidUGenInput = 0.0 internal var a2: LyrebirdValidUGenInput = 0.0 internal var b1: LyrebirdValidUGenInput = 0.0 internal var b2: LyrebirdValidUGenInput = 0.0 public init(rate: LyrebirdUGenRate, input: LyrebirdValidUGenInput){ self.input = input super.init(rate: rate) calculateCoefs() self.sos = SecondOrderSection(rate: rate, input: self.input, a0: self.a0, a1: self.a1, a2: self.a2, b1: self.b1, b2: self.b2) } internal func calculateCoefs(){ } override public final func next(numSamples: LyrebirdInt) -> Bool { let success: Bool = super.next(numSamples: numSamples) calculateCoefs() if let sos = self.sos { self.samples = sos.samples } return success } } public final class FilterRBJBandPass : FliterRBJ { fileprivate var freq: LyrebirdValidUGenInput fileprivate var bandwidth: LyrebirdValidUGenInput fileprivate var lastFreq: LyrebirdFloat = 0.0 fileprivate var lastBandwidth: LyrebirdFloat = 0.0 public required init(rate: LyrebirdUGenRate, input: LyrebirdValidUGenInput, freq: LyrebirdValidUGenInput, bandwidth: LyrebirdValidUGenInput) { self.freq = freq self.bandwidth = bandwidth super.init(rate: rate, input: input) self.lastFreq = freq.floatValue(graph: graph) self.lastBandwidth = bandwidth.floatValue(graph: graph) } override internal final func calculateCoefs(){ super.calculateCoefs() let curFreq = freq.floatValue(graph: graph) let curBandwidth = bandwidth.floatValue(graph: graph) if curFreq > 0.0 { if (curFreq != lastFreq) || (curBandwidth != lastBandwidth) { let sampleRate = Lyrebird.engine.sampleRate let sampleDur = Lyrebird.engine.iSampleRate let w0 = M_TWOPI * freq.floatValue(graph: graph) * sampleDur let sin_w0 = sin(w0) let alpha = sin_w0 * sinh(((0.34657359027997 * bandwidth.floatValue(graph: graph) * w0)) / sin_w0); let b0rz = 1.0 / (1.0 + alpha) if let sos = sos { sos.a0 = alpha * b0rz; sos.b1 = cos(w0) * 2.0 * b0rz; sos.b2 = (1.0 - alpha) * (b0rz * -1.0); sos.a1 = 0.0 sos.a2 = a0 * -1.0 } lastFreq = curFreq lastBandwidth = curBandwidth } } else { lastFreq = curFreq a0 = 0.0 b1 = 0.0 b2 = 0.0 a1 = 0.0 a2 = 0.0 } } }
artistic-2.0
df654bfa56e91412bd339e326caadfb0
37.904762
221
0.588535
3.435179
false
false
false
false
ChrisAU/Locution
Papyrus/Protocols/Gesturable.swift
2
1145
// // Gesturable.swift // Papyrus // // Created by Chris Nevin on 24/9/16. // Copyright © 2016 CJNevin. All rights reserved. // import UIKit protocol Gesturable { @discardableResult func register(gestureType: UIGestureRecognizer.Type, selector: Selector) -> UIGestureRecognizer func unregister(gestureType: UIGestureRecognizer.Type) func hasGesture(ofType gestureType: UIGestureRecognizer.Type) -> Bool } extension Gesturable where Self: UIView { @discardableResult func register(gestureType: UIGestureRecognizer.Type, selector: Selector) -> UIGestureRecognizer { let gesture = gestureType.init(target: self, action: selector) gesture.delegate = self as? UIGestureRecognizerDelegate addGestureRecognizer(gesture) return gesture } func unregister(gestureType: UIGestureRecognizer.Type) { gestureRecognizers?.forEach { if type(of: $0) == gestureType { removeGestureRecognizer($0) } } } func hasGesture(ofType gestureType: UIGestureRecognizer.Type) -> Bool { return (gestureRecognizers?.filter { type(of: $0) == gestureType }.count ?? 0) > 0 } }
mit
337e743d0841fc343cff3a54397bffb3
34.75
120
0.714161
4.503937
false
false
false
false
zisko/swift
test/SILOptimizer/devirt_protocol_method_invocations.swift
1
6709
// RUN: %target-swift-frontend -O -emit-sil %s | %FileCheck %s protocol PPP { func f() } protocol QQQ : PPP { } protocol RRR : QQQ { } struct S : RRR {} extension QQQ { @_optimize(none) func f() {} } // Test that all witness_method instructions are devirtualized. // This test used to crash the compiler because it uses inherited conformances. // CHECK-LABEL: sil @$S34devirt_protocol_method_invocations24testInheritedConformanceyyF : $@convention(thin) () -> () // CHECK-NOT: witness_method // CHECK-NOT: class_method // CHECK: apply // CHECK: // end sil function '$S34devirt_protocol_method_invocations24testInheritedConformanceyyF' public func testInheritedConformance() { (S() as QQQ).f() } // Test that a witness_method instruction using an indirectly-inherited conformance // is devirtualized. // // This test used to crash the compiler because it uses inherited conformances. // CHECK-LABEL: sil @$S34devirt_protocol_method_invocations34testIndirectlyInheritedConformanceyyF : $@convention(thin) () -> () // CHECK-NOT: witness_method // CHECK: apply // CHECK: // end sil function '$S34devirt_protocol_method_invocations34testIndirectlyInheritedConformanceyyF' public func testIndirectlyInheritedConformance() { (S() as RRR).f() } public protocol Foo { func foo(_ x:Int) -> Int } public extension Foo { func boo(_ x:Int) -> Int32 { return 2222 + Int32(x) } func getSelf() -> Self { return self } } var gg = 1111 open class C : Foo { @inline(never) open func foo(_ x:Int) -> Int { gg += 1 return gg + x } } @_transparent func callfoo(_ f: Foo) -> Int { return f.foo(2) + f.foo(2) } @_transparent func callboo(_ f: Foo) -> Int32 { return f.boo(2) + f.boo(2) } @_transparent func callGetSelf(_ f: Foo) -> Foo { return f.getSelf() } // Check that methods returning Self are not devirtualized and do not crash the compiler. // CHECK-LABEL: sil [noinline] @$S34devirt_protocol_method_invocations05test_a1_b11_extension_C33_invocation_with_self_return_typeyAA3Foo_pAA1CCF // CHECK: init_existential_addr // CHECK: open_existential_addr // CHECK: return @inline(never) public func test_devirt_protocol_extension_method_invocation_with_self_return_type(_ c: C) -> Foo { return callGetSelf(c) } // CHECK: sil @$S34devirt_protocol_method_invocations12test24114020SiyF // CHECK: [[T0:%.*]] = integer_literal $Builtin.Int{{.*}}, 1 // CHECK: [[T1:%.*]] = struct $Int ([[T0]] : $Builtin.Int{{.*}}) // CHECK: return [[T1]] // CHECK: sil @$S34devirt_protocol_method_invocations14testExMetatypeSiyF // CHECK: [[T0:%.*]] = builtin "sizeof"<Int> // CHECK: [[T1:%.*]] = builtin {{.*}}([[T0]] // CHECK: [[T2:%.*]] = struct $Int ([[T1]] : {{.*}}) // CHECK: return [[T2]] : $Int // Check that calls to f.foo() get devirtualized and are not invoked // via the expensive witness_method instruction. // To achieve that the information about a concrete type C should // be propagated from init_existential_addr into witness_method and // apply instructions. // CHECK-LABEL: sil shared [noinline] @$S34devirt_protocol_method_invocations05test_a1_b1_C11_invocationySiAA1CCFTf4g_n // CHECK-NOT: witness_method // CHECK: checked_cast // CHECK-NOT: checked_cast // CHECK: bb1( // CHECK-NOT: checked_cast // CHECK: return // CHECK: bb2( // CHECK-NOT: checked_cast // CHECK: function_ref // CHECK: apply // CHECK: apply // CHECK: br bb1( // CHECK: bb3 // CHECK-NOT: checked_cast // CHECK: apply // CHECK: apply // CHECK: br bb1( @inline(never) public func test_devirt_protocol_method_invocation(_ c: C) -> Int { return callfoo(c) } // Check that calls of a method boo() from the protocol extension // get devirtualized and are not invoked via the expensive witness_method instruction // or by passing an existential as a parameter. // To achieve that the information about a concrete type C should // be propagated from init_existential_addr into apply instructions. // In fact, the call is expected to be inlined and then constant-folded // into a single integer constant. // CHECK-LABEL: sil shared [noinline] @$S34devirt_protocol_method_invocations05test_a1_b11_extension_C11_invocationys5Int32VAA1CCFTf4d_n // CHECK-NOT: checked_cast // CHECK-NOT: open_existential // CHECK-NOT: witness_method // CHECK-NOT: apply // CHECK: integer_literal // CHECK: return @inline(never) public func test_devirt_protocol_extension_method_invocation(_ c: C) -> Int32 { return callboo(c) } // Make sure that we are not crashing with an assertion due to specialization // of methods with the Self return type as an argument. // rdar://20868966 protocol Proto { func f() -> Self } class CC : Proto { func f() -> Self { return self } } func callDynamicSelfExistential(_ p: Proto) { p.f() } public func testSelfReturnType() { callDynamicSelfExistential(CC()) } // Make sure that we are not crashing with an assertion due to specialization // of methods with the Self return type. // rdar://20955745. protocol CP : class { func f() -> Self } func callDynamicSelfClassExistential(_ cp: CP) { cp.f() } class PP : CP { func f() -> Self { return self } } callDynamicSelfClassExistential(PP()) // Make sure we handle indirect conformances. // rdar://24114020 protocol Base { var x: Int { get } } protocol Derived : Base { } struct SimpleBase : Derived { var x: Int } public func test24114020() -> Int { let base: Derived = SimpleBase(x: 1) return base.x } protocol StaticP { static var size: Int { get } } struct HasStatic<T> : StaticP { static var size: Int { return MemoryLayout<T>.size } } public func testExMetatype() -> Int { let type: StaticP.Type = HasStatic<Int>.self return type.size } // rdar://32288618 public func testExMetatypeVar() -> Int { var type: StaticP.Type = HasStatic<Int>.self return type.size } // IRGen used to crash on the testPropagationOfConcreteTypeIntoExistential method. // rdar://26286278 protocol MathP { var sum: Int32 { get nonmutating set } func done() } extension MathP { @inline(never) func plus() -> Self { sum += 1 return self } @inline(never) func minus() { sum -= 1 if sum == 0 { done() } } } protocol MathA : MathP {} public final class V { var a: MathA init(a: MathA) { self.a = a } } // Check that all witness_method invocations are devirtualized. // CHECK-LABEL: sil shared [noinline] @$S34devirt_protocol_method_invocations44testPropagationOfConcreteTypeIntoExistential1v1xyAA1VC_s5Int32VtFTf4gd_n // CHECK-NOT: witness_method // CHECK-NOT: class_method // CHECK: return @inline(never) public func testPropagationOfConcreteTypeIntoExistential(v: V, x: Int32) { let y = v.a.plus() defer { y.minus() } }
apache-2.0
3bd010e2b99ba6e3de24cd9aa74d6934
24.509506
151
0.695037
3.48882
false
true
false
false
aroyarexs/PASTA
Example/Pods/Metron/Metron/Classes/Corner.swift
1
2223
import CoreGraphics /** * A `Corner` represents a place where two edges meet. */ public enum Corner { case minXminY case maxXminY case minXmaxY case maxXmaxY } public extension Corner { public init(x xEdge: CGRectEdge, y yEdge: CGRectEdge) { switch (xEdge, yEdge) { case (.minXEdge, .minYEdge): self = .minXminY case (.maxXEdge, .minYEdge): self = .maxXminY case (.minXEdge, .maxYEdge): self = .minXmaxY case (.maxXEdge, .maxYEdge): self = .maxXmaxY default: fatalError("Incorrect edge axis") } } /// - returns: The edge of this `Corner` for the provided axis. /// For example, the `minXminY` corner's `xAxis` edge is the `minXEdge`. public func edge(on axis: Axis) -> CGRectEdge { switch axis { case .xAxis: return xEdge case .yAxis: return yEdge } } /// - returns: The `xAxis` edge component of this corner /// (either `minXEdge` or `maxXEdge`). public var xEdge: CGRectEdge { switch self { case .minXminY, .minXmaxY: return .minXEdge case .maxXminY, .maxXmaxY: return .maxXEdge } } /// - returns: The `yAxis` edge component of this corner /// (either `minYEdge` or `maxYEdge`). public var yEdge: CGRectEdge { switch self { case .minXminY, .maxXminY: return .minYEdge case .minXmaxY, .maxXmaxY: return .maxYEdge } } /// - returns: The `Corner` that is opposite along the given axis. /// For example, the `minXminY` corner's opposite along /// the `xAxis` is `maxXminY`. public func opposite(on axis: Axis) -> Corner { switch axis { case .xAxis: return Corner(x: xEdge.opposite, y: yEdge) case .yAxis: return Corner(x: xEdge, y: yEdge.opposite) } } } // MARK: Opposable extension Corner : Opposable { public static var allOpposites: [(Corner, Corner)] { return [(.minXminY, .maxXmaxY), (.maxXminY, .minXmaxY)] } } // MARK: CornerType extension Corner : CornerType { public typealias EdgesType = CGRectEdge public var edges: (EdgesType, EdgesType) { return (xEdge, yEdge) } }
mit
6120f0bfabf1d9e51670a085761f25f6
27.139241
76
0.602789
3.976744
false
false
false
false
MakeAWishFoundation/SwiftyMocky
Tests/SwiftyMockyCLICoreTests/CommandLineInterfaceTests.swift
1
3171
import XCTest import class Foundation.Bundle import SwiftyMocky @testable import SwiftyMockyCLICore final class CommandLineInterfaceTests: XCTestCase { // MARK: - Properties static var allTests = [ ("test_command_generate", test_command_generate), ] var sut: Application! var factory: InstanceFactoryMock! // MARK: - Lifecycle override func setUp() { super.setUp() sut = Application() factory = InstanceFactoryMock() Instance.factory = factory } // MARK: - Setup func test_factory_setup() throws { XCTAssert(Instance.factory === factory) } // MARK: - Generate Command Tests func test_command_generate() throws { // Given let command = GenerationCommandMock() Given(factory, .resolveGenerationCommand(root: .any, willReturn: command)) // Then sut.generate(disableCache: false, verbose: true) // Verify Verify(factory, .once, .resolveGenerationCommand(root: .any)) Verify(command, .once, .generate(disableCache: false, verbose: true)) } func test_command_generate_handles_error() throws { // Given let command = GenerationCommandMock() Given(factory, .resolveGenerationCommand(root: .any, willReturn: command)) Given(command, .generate(disableCache: .any, verbose: .any, willThrow: TestError())) let errorHandled = expectation(description: "Should handle error") sut.handle = { XCTAssert($0 is TestError) errorHandled.fulfill() } // Then sut.generate(disableCache: false, verbose: false) // Verify Verify(command, .once, .generate(disableCache: .any, verbose: .any)) waitForExpectations(timeout: 0.2) } // MARK: - Helpers struct TestError: Error { } } private extension XCTestCase { enum ExecutionError: Error { case nonMatchingSystemRequirements case capturingOutputFailure } @discardableResult func executeCommand(_ arguments: [String]) throws -> String { guard #available(macOS 10.13, *) else { throw ExecutionError.nonMatchingSystemRequirements } let binary = Bundle.productsDirectory.appendingPathComponent("swiftymocky") let process = Process() process.executableURL = binary process.arguments = arguments let pipe = Pipe() process.standardOutput = pipe try process.run() process.waitUntilExit() let data = pipe.fileHandleForReading.readDataToEndOfFile() guard let output = String(data: data, encoding: .utf8) else { throw ExecutionError.capturingOutputFailure } return output } } private extension Bundle { static var productsDirectory: URL { #if os(macOS) for bundle in Bundle.allBundles where bundle.bundlePath.hasSuffix(".xctest") { return bundle.bundleURL.deletingLastPathComponent() } fatalError("couldn't find the products directory") #else return Bundle.main.bundleURL #endif } }
mit
b09b0dd067931647670a03db153ead36
26.336207
92
0.635446
4.811836
false
true
false
false
movabletype/mt-data-api-sdk-swift
Example/MTDataAPI/Classes/Controller/BlogTableViewController.swift
1
5005
// // BlogTableViewController.swift // MTDataAPI // // Created by CHEEBOW on 2015/04/14. // Copyright (c) 2015年 Six Apart, Ltd. All rights reserved. // import UIKit import SwiftyJSON import SVProgressHUD class BlogTableViewController: UITableViewController { var items = [JSON]() override func viewDidLoad() { super.viewDidLoad() // Uncomment the following line to preserve selection between presentations // self.clearsSelectionOnViewWillAppear = false // Uncomment the following line to display an Edit button in the navigation bar for this view controller. // self.navigationItem.rightBarButtonItem = self.editButtonItem() self.title = NSLocalizedString("Blog", comment: "Blog") SVProgressHUD.show() let api = DataAPI.sharedInstance let app = UIApplication.shared.delegate as! AppDelegate api.authentication(app.username, password: app.password, remember: true, success:{_ in api.listSites(nil, success: {(result: [JSON]?, total: Int?)-> Void in if let result = result { self.items = result self.tableView.reloadData() } SVProgressHUD.dismiss() }, failure: {(error: JSON?)-> Void in SVProgressHUD.showError(withStatus: error?["message"].stringValue ?? "") } ) }, failure: {(error: JSON?)-> Void in SVProgressHUD.showError(withStatus: error?["message"].stringValue ?? "") } ) } 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 Potentially incomplete method implementation. // Return the number of sections. return 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // #warning Incomplete method implementation. // Return the number of rows in the section. return self.items.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) // Configure the cell... let item = items[indexPath.row] cell.textLabel?.text = item["name"].stringValue return cell } /* // Override to support conditional editing of the table view. override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return NO if you do not want the specified item to be editable. return true } */ /* // Override to support editing the table view. override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { if editingStyle == .Delete { // Delete the row from the data source tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade) } else if editingStyle == .Insert { // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view } } */ /* // Override to support rearranging the table view. override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) { } */ /* // Override to support conditional rearranging of the table view. override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return NO if you do not want the item to be re-orderable. return true } */ /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using [segue destinationViewController]. // Pass the selected object to the new view controller. } */ override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let blog = items[indexPath.row] let id = blog["id"].stringValue let storyboard = UIStoryboard(name: "Entry", bundle: nil) let vc: EntryTableViewController = storyboard.instantiateInitialViewController() as! EntryTableViewController vc.blogID = id vc.title = blog["name"].stringValue self.navigationController?.pushViewController(vc, animated: true) } }
mit
90553385d6a1fbfcb3c98136260978a7
36.059259
157
0.63262
5.540421
false
false
false
false
qiuncheng/study-for-swift
learn-rx-swift/Chocotastic-starter/Chocotastic/BillingInfoViewController.swift
1
6102
/** * Copyright (c) 2016 Razeware LLC * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ import UIKit import RxSwift import RxCocoa class BillingInfoViewController: UIViewController { @IBOutlet private var creditCardNumberTextField: ValidatingTextField! @IBOutlet private var creditCardImageView: UIImageView! @IBOutlet private var expirationDateTextField: ValidatingTextField! @IBOutlet private var cvvTextField: ValidatingTextField! @IBOutlet private var purchaseButton: UIButton! private let throttleInterval = 0.1 private let cardType: Variable<CardType> = Variable(.Unknown) private let disposeBag = DisposeBag() //MARK: - View Lifecycle override func viewDidLoad() { super.viewDidLoad() title = "💳 Info" setupCardImageDisplay() setupTextChangeHandling() } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { let identifier = identifierForSegue(segue: segue) switch identifier { case .PurchaseSuccess: guard let destination = segue.destination as? ChocolateIsComingViewController else { assertionFailure("Couldn't get chocolate is coming VC!") return } destination.cardType = cardType.value } } //MARK: - RX Setup private func setupCardImageDisplay() { cardType.asObservable() .subscribe(onNext: { cardType in self.creditCardImageView.image = cardType.image }) .addDisposableTo(disposeBag) } private func setupTextChangeHandling() { let creditCardValid = creditCardNumberTextField .rx .text .throttle(throttleInterval, scheduler: MainScheduler.instance) .map { self.validate(cardText: $0) } creditCardValid.subscribe(onNext: { self.creditCardNumberTextField.valid = $0 }) .addDisposableTo(disposeBag) let expirationValid = expirationDateTextField .rx .text .throttle(throttleInterval, scheduler: MainScheduler.instance) .map { self.validate(cardText: $0) } expirationValid .subscribe(onNext: { self.expirationDateTextField.valid = $0 }) .addDisposableTo(disposeBag) let cvvValid = cvvTextField .rx .text .map({ self.validate(cardText: $0) }) cvvValid .subscribe(onNext: { self.cvvTextField.valid = $0 }) .addDisposableTo(disposeBag) let everythingValid = Observable.combineLatest(creditCardValid, expirationValid, cvvValid) { $0 && $1 && $2 } everythingValid .bindTo(purchaseButton.rx.enabled) .addDisposableTo(disposeBag) } //MARK: - Validation methods func validate(cardText: String) -> Bool { let noWhitespace = cardText.rw_removeSpaces() updateCardType(using: noWhitespace) formatCardNumber(using: noWhitespace) advanceIfNecessary(noSpacesCardNumber: noWhitespace) guard cardType.value != .Unknown else { //Definitely not valid if the type is unknown. return false } guard noWhitespace.rw_isLuhnValid() else { //Failed luhn validation return false } return noWhitespace.characters.count == self.cardType.value.expectedDigits } func validate(expirationDateText expiration: String) -> Bool { let strippedSlashExpiration = expiration.rw_removeSlash() formatExpirationDate(using: strippedSlashExpiration) advanceIfNecessary(expirationNoSpacesOrSlash: strippedSlashExpiration) return strippedSlashExpiration.rw_isValidExpirationDate() } func validate(cvvText cvv: String) -> Bool { guard cvv.rw_allCharactersAreNumbers() else { //Someone snuck a letter in here. return false } dismissIfNecessary(cvv: cvv) return cvv.characters.count == self.cardType.value.cvvDigits } //MARK: Single-serve helper functions private func updateCardType(using noSpacesNumber: String) { cardType.value = CardType.fromString(string: noSpacesNumber) } private func formatCardNumber(using noSpacesCardNumber: String) { creditCardNumberTextField.text = self.cardType.value.format(noSpaces: noSpacesCardNumber) } func advanceIfNecessary(noSpacesCardNumber: String) { if noSpacesCardNumber.characters.count == self.cardType.value.expectedDigits { self.expirationDateTextField.becomeFirstResponder() } } func formatExpirationDate(using expirationNoSpacesOrSlash: String) { expirationDateTextField.text = expirationNoSpacesOrSlash.rw_addSlash() } func advanceIfNecessary(expirationNoSpacesOrSlash: String) { if expirationNoSpacesOrSlash.characters.count == 6 { //mmyyyy self.cvvTextField.becomeFirstResponder() } } func dismissIfNecessary(cvv: String) { if cvv.characters.count == self.cardType.value.cvvDigits { let _ = self.cvvTextField.resignFirstResponder() } } } // MARK: - SegueHandler extension BillingInfoViewController: SegueHandler { enum SegueIdentifier: String { case PurchaseSuccess } }
mit
eb2e6ad98d0c19fbbe187b5d13663bdc
28.75122
96
0.711592
4.669985
false
false
false
false
LeeShiYoung/LSYWeibo
LSYWeiBo/Message/MessageTableViewController.swift
1
3136
// // MessageTableViewController.swift // LSYWeiBo // // Created by 李世洋 on 16/5/1. // Copyright © 2016年 李世洋. All rights reserved. // import UIKit class MessageTableViewController: BaseTableViewController { override func viewDidLoad() { super.viewDidLoad() if !login { visitorView?.setupVisitorInfo(false, iconStr: "visitordiscover_image_message", text: "登录后,别人评论你的微博,发给你的消息,都会在这里收到通知") } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Table view data source override func numberOfSectionsInTableView(tableView: UITableView) -> Int { // #warning Incomplete implementation, return the number of sections return 0 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // #warning Incomplete implementation, return the number of rows return 0 } /* override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("reuseIdentifier", forIndexPath: indexPath) // Configure the cell... return cell } */ /* // Override to support conditional editing of the table view. override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return false if you do not want the specified item to be editable. return true } */ /* // Override to support editing the table view. override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { if editingStyle == .Delete { // Delete the row from the data source tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade) } else if editingStyle == .Insert { // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view } } */ /* // Override to support rearranging the table view. override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) { } */ /* // Override to support conditional rearranging of the table view. override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return false if you do not want the item to be re-orderable. return true } */ /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
artistic-2.0
3e918558c0857e407ec80470207b05df
31.935484
157
0.679399
5.430851
false
false
false
false
liuchungui/UICollectionViewAnimationDemo
BGSimpleImageSelectCollectionViewDemo2/BGSimpleImageSelectCollectionView/BGFoundationKit/Extension/UIView+BGExtension.swift
2
2023
// // UIView+BGExtension.swift // BGFoundationKitDemo // // Created by user on 15/10/15. // Copyright © 2015年 BG. All rights reserved. // import UIKit extension UIView { /** 重用的标示,默认以类名为标示 */ class func reuseIdentify() -> String { return String(self) } /** 加载xib文件 */ static func loadFromXib() -> AnyObject { let array = NSBundle.mainBundle().loadNibNamed(String(self), owner: self, options: nil) return array.first! } var left: CGFloat { get { return self.frame.origin.x } set (newValue){ self.frame.origin.x = newValue } } var right: CGFloat { get { return self.frame.origin.x + self.frame.size.width } set (newValue){ self.frame.origin.x = newValue - self.frame.size.width } } var top: CGFloat { get { return self.frame.origin.y } set (newValue){ self.frame.origin.y = newValue } } var bottom: CGFloat { get { return self.frame.origin.y + self.frame.size.height } set (newValue){ self.frame.origin.y = newValue - self.frame.size.height } } var width: CGFloat { get { return self.frame.size.width } set (newValue) { self.frame.size.width = newValue } } var height: CGFloat { get { return self.frame.size.height } set (newValue) { self.frame.size.height = newValue } } var centerX: CGFloat { get { return self.center.x } set (newValue) { self.center.x = newValue } } var centerY: CGFloat { get { return self.center.y } set (newValue) { self.center.y = newValue } } }
mit
c3c6b7d38f9938d2aa0a72b375ef557f
19.884211
95
0.486391
4.168067
false
false
false
false
kickstarter/ios-oss
Library/ViewModels/DiscoveryFiltersViewModelTests.swift
1
18679
@testable import KsApi @testable import Library import Prelude import ReactiveExtensions_TestHelpers import ReactiveSwift import XCTest // A whole bunch of data to play around with in tests. private let selectableRowTemplate = SelectableRow( isSelected: false, params: .defaults ) private let expandableRowTemplate = ExpandableRow( isExpanded: false, params: .defaults, selectableRows: [] ) private let allProjectsRow = selectableRowTemplate |> SelectableRow.lens.params.includePOTD .~ true private let staffPicksRow = selectableRowTemplate |> SelectableRow.lens.params.staffPicks .~ true private let starredRow = selectableRowTemplate |> SelectableRow.lens.params.starred .~ true private let socialRow = selectableRowTemplate |> SelectableRow.lens.params.social .~ true private let recommendedRow = selectableRowTemplate |> SelectableRow.lens.params.recommended .~ true |> SelectableRow.lens.params.backed .~ false private let artSelectableRow = selectableRowTemplate |> SelectableRow.lens.params.category .~ .art private let documentarySelectableRow = selectableRowTemplate |> SelectableRow.lens.params.category .~ .documentary private let artExpandableRow = expandableRowTemplate |> ExpandableRow.lens.params.category .~ .art |> ExpandableRow.lens.selectableRows .~ [ artSelectableRow, selectableRowTemplate |> SelectableRow.lens.params.category .~ .illustration ] private let filmExpandableRow = expandableRowTemplate |> ExpandableRow.lens.params.category .~ .filmAndVideo |> ExpandableRow.lens.selectableRows .~ [ selectableRowTemplate |> SelectableRow.lens.params.category .~ .filmAndVideo, selectableRowTemplate |> SelectableRow.lens.params.category .~ .documentary ] private let categories = [ Category.art, Category.filmAndVideo ] internal final class DiscoveryFiltersViewModelTests: TestCase { private let vm: DiscoveryFiltersViewModelType = DiscoveryFiltersViewModel() private var defaultRootCategoriesTemplate: RootCategoriesEnvelope { RootCategoriesEnvelope.template |> RootCategoriesEnvelope.lens.categories .~ [ .art, .filmAndVideo, .illustration, .documentary ] } private let animateInView = TestObserver<(), Never>() private let loadCategoryRows = TestObserver<[ExpandableRow], Never>() private let loadCategoryRowsInitialId = TestObserver<Int?, Never>() private let loadCategoryRowsSelectedId = TestObserver<Int?, Never>() private let loadingIndicatorisVisible = TestObserver<Bool, Never>() private let loadTopRows = TestObserver<[SelectableRow], Never>() private let loadTopRowsInitialId = TestObserver<Int?, Never>() private let notifyDelegateOfSelectedRow = TestObserver<SelectableRow, Never>() private let loadFavoriteRows = TestObserver<[SelectableRow], Never>() private let loadFavoriteRowsId = TestObserver<Int?, Never>() private let categoriesResponse = RootCategoriesEnvelope.template |> RootCategoriesEnvelope.lens.categories .~ categories override func setUp() { super.setUp() self.vm.outputs.animateInView.observe(self.animateInView.observer) self.vm.outputs.loadingIndicatorIsVisible.observe(self.loadingIndicatorisVisible.observer) self.vm.outputs.loadCategoryRows.map(first).observe(self.loadCategoryRows.observer) self.vm.outputs.loadCategoryRows.map(second).observe(self.loadCategoryRowsInitialId.observer) self.vm.outputs.loadCategoryRows.map { $0.2 }.observe(self.loadCategoryRowsSelectedId.observer) self.vm.outputs.loadTopRows.map(first).observe(self.loadTopRows.observer) self.vm.outputs.loadTopRows.map(second).observe(self.loadTopRowsInitialId.observer) self.vm.outputs.notifyDelegateOfSelectedRow.observe(self.notifyDelegateOfSelectedRow.observer) self.vm.outputs.loadFavoriteRows.map(first).observe(self.loadFavoriteRows.observer) self.vm.outputs.loadFavoriteRows.map(second).observe(self.loadFavoriteRowsId.observer) } func testAnimateIn() { self.vm.inputs.configureWith(selectedRow: allProjectsRow) self.vm.inputs.viewDidLoad() self.scheduler.advance(by: AppEnvironment.current.apiDelayInterval) self.animateInView.assertValueCount(0) self.vm.inputs.viewDidAppear() self.animateInView.assertValueCount(1) } func testKSRAnalyticsEventsTrack() { self.vm.inputs.configureWith(selectedRow: allProjectsRow) self.vm.inputs.viewDidLoad() self.vm.inputs.viewDidAppear() self.scheduler.advance(by: AppEnvironment.current.apiDelayInterval) XCTAssertEqual( [], self.segmentTrackingClient.events ) self.vm.inputs.tapped(expandableRow: filmExpandableRow) XCTAssertEqual( [], self.segmentTrackingClient.events ) self.vm.inputs.tapped(selectableRow: documentarySelectableRow) XCTAssertEqual(["CTA Clicked"], self.segmentTrackingClient.events) XCTAssertEqual( [Category.documentary.intID], self.segmentTrackingClient.properties(forKey: "discover_subcategory_id", as: Int.self) ) XCTAssertEqual("discover", segmentTrackingClient.properties.last?["context_page"] as? String) XCTAssertEqual("subcategory_name", segmentTrackingClient.properties.last?["context_type"] as? String) XCTAssertEqual("discover_overlay", segmentTrackingClient.properties.last?["context_location"] as? String) XCTAssertEqual("category_home", segmentTrackingClient.properties.last?["discover_ref_tag"] as? String) XCTAssertEqual( "Documentary", segmentTrackingClient.properties.last?["discover_subcategory_name"] as? String ) XCTAssertEqual( "Film & Video", segmentTrackingClient.properties.last?["discover_category_name"] as? String ) XCTAssertEqual(11, segmentTrackingClient.properties.last?["discover_category_id"] as? Int) XCTAssertEqual(30, segmentTrackingClient.properties.last?["discover_subcategory_id"] as? Int) self.vm.inputs.tapped(selectableRow: socialRow) XCTAssertEqual(["CTA Clicked", "CTA Clicked"], self.segmentTrackingClient.events) XCTAssertEqual("discover", segmentTrackingClient.properties.last?["context_page"] as? String) XCTAssertEqual("social", segmentTrackingClient.properties.last?["context_type"] as? String) XCTAssertEqual("discover_overlay", segmentTrackingClient.properties.last?["context_location"] as? String) XCTAssertEqual("social_home", segmentTrackingClient.properties.last?["discover_ref_tag"] as? String) self.vm.inputs.tapped(selectableRow: staffPicksRow) XCTAssertEqual( ["CTA Clicked", "CTA Clicked", "CTA Clicked"], self.segmentTrackingClient.events ) XCTAssertEqual("discover", self.segmentTrackingClient.properties.last?["context_page"] as? String) XCTAssertEqual("pwl", self.segmentTrackingClient.properties.last?["context_type"] as? String) XCTAssertEqual( "discover_overlay", self.segmentTrackingClient.properties.last?["context_location"] as? String ) XCTAssertEqual( "recommended_home", self.segmentTrackingClient.properties.last?["discover_ref_tag"] as? String ) self.vm.inputs.tapped(selectableRow: starredRow) XCTAssertEqual( ["CTA Clicked", "CTA Clicked", "CTA Clicked", "CTA Clicked"], self.segmentTrackingClient.events ) XCTAssertEqual("discover", self.segmentTrackingClient.properties.last?["context_page"] as? String) XCTAssertEqual("watched", self.segmentTrackingClient.properties.last?["context_type"] as? String) XCTAssertEqual( "discover_overlay", self.segmentTrackingClient.properties.last?["context_location"] as? String ) XCTAssertEqual("starred_home", self.segmentTrackingClient.properties.last?["discover_ref_tag"] as? String) self.vm.inputs.tapped(selectableRow: recommendedRow) XCTAssertEqual( ["CTA Clicked", "CTA Clicked", "CTA Clicked", "CTA Clicked", "CTA Clicked"], self.segmentTrackingClient.events ) XCTAssertEqual("discover", self.segmentTrackingClient.properties.last?["context_page"] as? String) XCTAssertEqual("recommended", self.segmentTrackingClient.properties.last?["context_type"] as? String) XCTAssertEqual( "discover_overlay", self.segmentTrackingClient.properties.last?["context_location"] as? String ) XCTAssertEqual("recs_home", self.segmentTrackingClient.properties.last?["discover_ref_tag"] as? String) } func testTopFilters_Logged_Out() { self.vm.inputs.configureWith(selectedRow: allProjectsRow) self.loadTopRows.assertValueCount(0) self.vm.inputs.viewDidLoad() self.vm.inputs.viewDidAppear() self.scheduler.advance(by: AppEnvironment.current.apiDelayInterval) self.loadTopRows.assertValues( [ [ allProjectsRow |> SelectableRow.lens.isSelected .~ true, staffPicksRow ] ], "The top filter rows load immediately with the first one selected." ) self.loadTopRowsInitialId.assertValues([nil]) } func testTopFilters_Logged_In() { AppEnvironment.login(AccessTokenEnvelope(accessToken: "deadbeef", user: .template)) self.vm.inputs.configureWith(selectedRow: allProjectsRow) self.vm.inputs.viewDidLoad() self.vm.inputs.viewDidAppear() self.scheduler.advance(by: AppEnvironment.current.apiDelayInterval) self.loadTopRows.assertValues( [ [ allProjectsRow |> SelectableRow.lens.isSelected .~ true, staffPicksRow, starredRow, recommendedRow, socialRow ] ], "The top filter rows load immediately with the first one selected." ) self.loadTopRowsInitialId.assertValues([nil]) } func testTopFilters_Logged_In_Social() { AppEnvironment.login( AccessTokenEnvelope(accessToken: "deadbeef", user: .template |> \.social .~ true) ) self.vm.inputs.configureWith(selectedRow: allProjectsRow) self.vm.inputs.viewDidLoad() self.vm.inputs.viewDidAppear() self.scheduler.advance(by: AppEnvironment.current.apiDelayInterval) self.loadTopRows.assertValues( [ [ allProjectsRow |> SelectableRow.lens.isSelected .~ true, staffPicksRow, starredRow, recommendedRow, socialRow ] ], "The top filter rows load immediately with the first one selected." ) self.loadTopRowsInitialId.assertValues([nil]) } func testTopFilters_Logged_In_OptedOutOfRecommendations() { AppEnvironment.login( AccessTokenEnvelope( accessToken: "deadbeef", user: .template |> \.optedOutOfRecommendations .~ true ) ) self.vm.inputs.configureWith(selectedRow: allProjectsRow) self.vm.inputs.viewDidLoad() self.vm.inputs.viewDidAppear() self.scheduler.advance(by: AppEnvironment.current.apiDelayInterval) self.loadTopRows.assertValues( [ [ allProjectsRow |> SelectableRow.lens.isSelected .~ true, staffPicksRow, starredRow, socialRow ] ], "The top filter rows load immediately with the first one selected." ) self.loadTopRowsInitialId.assertValues([nil]) } func testTopFilters_Category_Selected() { self.vm.inputs.configureWith(selectedRow: artSelectableRow) self.vm.inputs.viewDidLoad() self.vm.inputs.viewDidAppear() self.scheduler.advance(by: AppEnvironment.current.apiDelayInterval) self.loadTopRows.assertValues( [ [ allProjectsRow, staffPicksRow ] ] ) self.loadTopRowsInitialId.assertValues([1]) } func testExpandingCategoryFilters() { withEnvironment(apiService: MockService(fetchGraphCategoriesResult: .success(self .defaultRootCategoriesTemplate))) { self.vm.inputs.configureWith(selectedRow: allProjectsRow) self.loadCategoryRows.assertValueCount(0) self.loadingIndicatorisVisible.assertValueCount(0) self.vm.inputs.viewDidLoad() self.vm.inputs.viewDidAppear() self.loadingIndicatorisVisible.assertValues([true]) self.scheduler.advance(by: AppEnvironment.current.apiDelayInterval) self.loadingIndicatorisVisible.assertValues([true, false]) self.loadCategoryRows.assertValues( [[artExpandableRow, filmExpandableRow]], "The root categories emit." ) self.loadCategoryRowsInitialId.assertValues([nil]) self.loadCategoryRowsSelectedId.assertValues([nil]) // Expand art self.vm.inputs.tapped(expandableRow: artExpandableRow) self.loadCategoryRows.assertValues( [ [artExpandableRow, filmExpandableRow], [artExpandableRow |> ExpandableRow.lens.isExpanded .~ true, filmExpandableRow] ], "The art category expands." ) self.loadCategoryRowsInitialId.assertValues([nil, nil]) self.loadCategoryRowsSelectedId.assertValues([nil, 1]) // Expand film self.vm.inputs.tapped(expandableRow: filmExpandableRow) self.loadCategoryRows.assertValues( [ [artExpandableRow, filmExpandableRow], [artExpandableRow |> ExpandableRow.lens.isExpanded .~ true, filmExpandableRow], [artExpandableRow, filmExpandableRow |> ExpandableRow.lens.isExpanded .~ true] ], "The art category collapses and the film category expands." ) self.loadCategoryRowsInitialId.assertValues([nil, nil, nil]) self.loadCategoryRowsSelectedId.assertValues([nil, 1, 11]) // Collapse the expanded film row self.vm.inputs.tapped(expandableRow: filmExpandableRow |> ExpandableRow.lens.isExpanded .~ true) self.loadCategoryRows.assertValues( [ [artExpandableRow, filmExpandableRow], [artExpandableRow |> ExpandableRow.lens.isExpanded .~ true, filmExpandableRow], [artExpandableRow, filmExpandableRow |> ExpandableRow.lens.isExpanded .~ true], [artExpandableRow, filmExpandableRow] ], "The film category collapses." ) self.loadCategoryRowsInitialId.assertValues([nil, nil, nil, nil]) self.loadCategoryRowsSelectedId.assertValues([nil, 1, 11, 11]) } } func testConfigureWithSelectedRow() { let artSelectedExpandedRow = expandableRowTemplate |> ExpandableRow.lens.params.category .~ .art |> ExpandableRow.lens.isExpanded .~ true |> ExpandableRow.lens.selectableRows .~ [ artSelectableRow |> SelectableRow.lens.isSelected .~ true, selectableRowTemplate |> SelectableRow.lens.params.category .~ .illustration ] withEnvironment(apiService: MockService(fetchGraphCategoriesResult: .success(self .defaultRootCategoriesTemplate))) { self.vm.inputs.configureWith(selectedRow: artSelectableRow) self.loadCategoryRows.assertValueCount(0) self.vm.inputs.viewDidLoad() self.vm.inputs.viewDidAppear() self.loadingIndicatorisVisible.assertValues([true]) self.scheduler.advance(by: AppEnvironment.current.apiDelayInterval) self.loadingIndicatorisVisible.assertValues([true, false]) self.loadCategoryRows.assertValues( [ [artSelectedExpandedRow, filmExpandableRow] ], "The art category expands." ) self.loadCategoryRowsInitialId.assertValues([1]) self.loadCategoryRowsSelectedId.assertValues([1]) } } func testTappingSelectableRow() { self.vm.inputs.configureWith(selectedRow: allProjectsRow) self.vm.inputs.viewDidLoad() self.vm.inputs.viewDidAppear() self.scheduler.advance(by: AppEnvironment.current.apiDelayInterval) self.vm.inputs.tapped(selectableRow: allProjectsRow) self.notifyDelegateOfSelectedRow.assertValues( [allProjectsRow], "The tapped row emits." ) XCTAssertEqual(["CTA Clicked"], self.segmentTrackingClient.events) XCTAssertEqual("discover", self.segmentTrackingClient.properties.last?["context_page"] as? String) XCTAssertEqual("all", self.segmentTrackingClient.properties.last?["context_type"] as? String) XCTAssertEqual( "discover_overlay", self.segmentTrackingClient.properties.last?["context_location"] as? String ) XCTAssertEqual(true, self.segmentTrackingClient.properties.last?["discover_everything"] as? Bool) XCTAssertEqual( "discovery_home", self.segmentTrackingClient.properties.last?["discover_ref_tag"] as? String ) } func testFavoriteRows_Without_Favorites() { self.vm.inputs.configureWith(selectedRow: allProjectsRow) self.vm.inputs.viewDidLoad() self.vm.inputs.viewDidAppear() self.scheduler.advance(by: AppEnvironment.current.apiDelayInterval) self.loadFavoriteRows.assertValueCount(0, "Favorite rows does not emit without favorites set.") } func testFavoriteRows_With_Favorites() { withEnvironment(apiService: MockService(fetchGraphCategoriesResult: .success(self.categoriesResponse))) { self.ubiquitousStore.favoriteCategoryIds = [1, 30] self.vm.inputs.configureWith(selectedRow: allProjectsRow) self.loadFavoriteRows.assertValueCount(0) self.vm.inputs.viewDidLoad() self.vm.inputs.viewDidAppear() self.scheduler.advance(by: AppEnvironment.current.apiDelayInterval) self.loadFavoriteRows.assertValues([[artSelectableRow, documentarySelectableRow]]) self.loadFavoriteRowsId.assertValues([nil]) } } func testFavoriteRows_With_Favorites_Selected() { withEnvironment(apiService: MockService(fetchGraphCategoriesResult: .success(self .defaultRootCategoriesTemplate))) { self.ubiquitousStore.favoriteCategoryIds = [1, 30] self.vm.inputs.configureWith(selectedRow: artSelectableRow) self.loadFavoriteRows.assertValueCount(0) self.vm.inputs.viewDidLoad() self.vm.inputs.viewDidAppear() self.scheduler.advance(by: AppEnvironment.current.apiDelayInterval) self.loadFavoriteRows.assertValues([ [ artSelectableRow |> SelectableRow.lens.isSelected .~ true, documentarySelectableRow ] ]) self.loadFavoriteRowsId.assertValues([1]) } } func testCategoriesFromCache() { self.cache[KSCache.ksr_discoveryFiltersCategories] = categories self.vm.inputs.configureWith(selectedRow: allProjectsRow) self.vm.inputs.viewDidLoad() self.vm.inputs.viewDidAppear() self.loadingIndicatorisVisible.assertValueCount(0) self.loadCategoryRows.assertValues( [[artExpandableRow, filmExpandableRow]], "Server did not advance, categories loaded from cache." ) } }
apache-2.0
cca35e43a0718c3c905fdd31401811cd
34.921154
110
0.72354
4.430503
false
true
false
false
andr3a88/TryNetworkLayer
TryNetworkLayer/Network/Operations/Operation.swift
1
2881
// // Operation.swift // TryNetworkLayer // // Created by Andrea on 30/12/2019. // Copyright © 2019 Andrea Stevanato All rights reserved. // import Foundation enum OperationErrors: Error { case badMapping } protocol Operation { associatedtype D = Dispatcher // Default value associatedtype R /// Request to execute var request: Request { get } /// Execute request in passed dispatcher /// /// - Parameter dispatcher: dispatcher func execute(in dispatcher: D, completion: @escaping (Result<R, Error>) -> Void) } extension Operation { /// Execute a request that has response of generic type `T` /// /// - Parameters: /// - dispatcher: The dispatcher /// - completion: The completion handler func executeBaseResponse<T: Codable>(dispatcher: Dispatcher, completion: @escaping (Result<T, Error>) -> Void) { do { try dispatcher.execute(request: self.request, completion: { (response: Response) in if let json = response.json { let decoder = JSONDecoder() do { let response = try decoder.decode(T.self, from: json) completion(.success(response)) } catch let error { completion(.failure(error)) } } else if let error = response.error { completion(.failure(error)) } }) } catch let error { completion(.failure(error)) } } /// Execute a request that has response of type `BaseDataArrayResponse<T>` /// /// - Parameters: /// - dispatcher: The dispatcher /// - completion: The completion handler func executeBaseArrayResponse<T: Codable>(dispatcher: Dispatcher, completion: @escaping (Result<[T], Error>) -> Void) { do { try dispatcher.execute(request: self.request, completion: { (response: Response) in if let json = response.json { let decoder = JSONDecoder() do { let response = try decoder.decode([T].self, from: json) completion(.success(response)) } catch let error { completion(.failure(error)) } } else if let error = response.error { completion(.failure(error)) } }) } catch let error { completion(.failure(error)) } } } private extension JSONDecoder { func decode<T>(_ type: T.Type, from json: Response.JSON) throws -> T where T: Decodable { let data = try JSONSerialization.data(withJSONObject: json, options: .prettyPrinted) return try self.decode(type, from: data) } }
mit
63ed7af01bfe6be091279226f8304e87
31
123
0.548264
4.931507
false
false
false
false
movabletype/smartphone-app
MT_iOS/MT_iOS/Classes/Model/EntryTextAreaItem.swift
1
1594
// // EntryTextAreaItem.swift // MT_iOS // // Created by CHEEBOW on 2015/06/02. // Copyright (c) 2015年 Six Apart, Ltd. All rights reserved. // import UIKit import MMMarkdown class EntryTextAreaItem: BaseEntryItem { var text = "" var assets = [Asset]() override init() { super.init() type = "textarea" } override func encodeWithCoder(aCoder: NSCoder) { super.encodeWithCoder(aCoder) aCoder.encodeObject(self.text, forKey: "text") aCoder.encodeObject(self.assets, forKey: "assets") } required init(coder aDecoder: NSCoder) { super.init(coder: aDecoder)! self.text = aDecoder.decodeObjectForKey("text") as! String if let object = aDecoder.decodeObjectForKey("assets") as? [Asset] { self.assets = object } } override func value()-> String { var value = "" let sourceText = text if isPreview { do { let markdown = try MMMarkdown.HTMLStringWithMarkdown(sourceText, extensions: MMMarkdownExtensions.GitHubFlavored) value = markdown } catch _ { value = sourceText } } else { value = sourceText } return value } override func dispValue()-> String { return text } func placeholder()-> String { return String(format: NSLocalizedString("Input %@...", comment: "Input %@..."), arguments: [self.label]) } override func clear() { text = "" } }
mit
fcf84a30482cfcf3fa7f65799ab9f2b0
23.875
129
0.56093
4.614493
false
false
false
false
suzp1984/IOS-ApiDemo
ApiDemo-Swift/ApiDemo-Swift/AudioSamplesViewController.swift
1
2628
// // AudioSamplesViewController.swift // ApiDemo-Swift // // Created by Jacob su on 7/30/16. // Copyright © 2016 [email protected]. All rights reserved. // import UIKit class AudioSamplesViewController: UIViewController, UINavigationControllerDelegate, UITableViewDelegate, UITableViewDataSource { let cellIdentifier = "Audios" let demos: [String] = ["audio"] override func viewDidLoad() { super.viewDidLoad() self.title = "Audios" let table = UITableView(frame: self.view.bounds) table.delegate = self table.dataSource = self table.backgroundColor = UIColor.cyan table.register(UITableViewCell.self, forCellReuseIdentifier: cellIdentifier) self.view.addSubview(table) self.navigationItem.leftItemsSupplementBackButton = true } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func numberOfSections(in tableView: UITableView) -> Int { return 1 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return demos.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { var cell : UITableViewCell! = tableView.dequeueReusableCell(withIdentifier: cellIdentifier, for: indexPath) if cell == nil { cell = UITableViewCell(style:.default, reuseIdentifier:cellIdentifier) cell.textLabel!.textColor = UIColor.white let v2 = UIView() // no need to set frame v2.backgroundColor = UIColor.blue.withAlphaComponent(0.2) cell.selectedBackgroundView = v2 // next line didn't work until iOS 7! cell.backgroundColor = UIColor.red } let v2 = UIView() // no need to set frame v2.backgroundColor = UIColor.blue.withAlphaComponent(0.2) cell.selectedBackgroundView = v2 cell.textLabel!.textColor = UIColor.white cell.backgroundColor = UIColor.red cell.textLabel!.text = demos[(indexPath as NSIndexPath).row] return cell } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { switch demos[(indexPath as NSIndexPath).row] { case demos[0]: self.navigationController?.pushViewController(AudioPlayViewController(), animated: true) default: break } } }
apache-2.0
e8137c22fde7803b3e8fa9585be200e8
32.679487
115
0.636467
5.317814
false
false
false
false
erndev/BicycleSpeed
BicycleSpeed/MainViewController.swift
1
5744
// // MainViewController.swift // BicycleSpeed // // Copyright (c) 2015, Ernesto García // Licensed under the MIT license: http://opensource.org/licenses/MIT // import UIKit import CoreBluetooth class MainViewController: UIViewController { struct Constants { static let ScanSegue = "ScanSegue" static let SensorUserDefaultsKey = "lastsensorused" } var bluetoothManager:BluetoothManager! var sensor:CadenceSensor? weak var scanViewController:ScanViewController? var infoViewController:InfoTableViewController? var accumulatedDistance:Double? lazy var distanceFormatter:NSLengthFormatter = { let formatter = NSLengthFormatter() formatter.numberFormatter.maximumFractionDigits = 1 return formatter }() //@IBOutlet var labelBTStatus:UILabel! @IBOutlet var scanItem:UIBarButtonItem! @IBOutlet weak var idLabel: UILabel! override func viewDidLoad() { bluetoothManager = BluetoothManager() bluetoothManager.bluetoothDelegate = self scanItem.enabled = false } deinit { disconnectSensor() } @IBAction func unwindSegue( segue:UIStoryboardSegue ) { bluetoothManager.stopScan() guard let sensor = (segue as? ScanUnwindSegue)?.sensor else { return } print("Need to connect to sensor \(sensor.peripheral.identifier)") connectToSensor(sensor) } func disconnectSensor( ) { if sensor != nil { bluetoothManager.disconnectSensor(sensor!) sensor = nil } accumulatedDistance = nil } func connectToSensor(sensor:CadenceSensor) { self.sensor = sensor bluetoothManager.connectToSensor(sensor) // Save the sensor ID NSUserDefaults.standardUserDefaults().setObject(sensor.peripheral.identifier.UUIDString, forKey: Constants.SensorUserDefaultsKey) NSUserDefaults.standardUserDefaults().synchronize() } // TODO: REconnect. Try this every X seconds func checkPreviousSensor() { guard let sensorID = NSUserDefaults.standardUserDefaults().objectForKey(Constants.SensorUserDefaultsKey) as? String else { return } guard let sensor = bluetoothManager.retrieveSensorWithIdentifier(sensorID) else { return } self.sensor = sensor connectToSensor(sensor) } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if let infoVC = segue.destinationViewController as? InfoTableViewController { infoViewController = infoVC } if segue.identifier == Constants.ScanSegue { // Scan segue bluetoothManager.startScan() scanViewController = (segue.destinationViewController as? UINavigationController)?.viewControllers.first as? ScanViewController } } } extension MainViewController : CadenceSensorDelegate { func errorDiscoveringSensorInformation(error: NSError) { print("An error ocurred disconvering the sensor services/characteristics: \(error)") } func sensorReady() { print("Sensor ready to go...") accumulatedDistance = 0.0 } func updateSensorInfo() { let name = sensor?.peripheral.name ?? "" let uuid = sensor?.peripheral.identifier.UUIDString ?? "" NSOperationQueue.mainQueue().addOperationWithBlock { () -> Void in self.infoViewController?.showDeviceName(name , uuid:uuid ) } } func sensorUpdatedValues( speedInMetersPerSecond speed:Double?, cadenceInRpm cadence:Double?, distanceInMeters distance:Double? ) { accumulatedDistance? += distance ?? 0 let distanceText = (accumulatedDistance != nil && accumulatedDistance! >= 1.0) ? distanceFormatter.stringFromMeters(accumulatedDistance!) : "N/A" let speedText = (speed != nil) ? distanceFormatter.stringFromValue(speed!*3.6, unit: .Kilometer) + NSLocalizedString("/h", comment:"(km) Per hour") : "N/A" let cadenceText = (cadence != nil) ? String(format: "%.2f %@", cadence!, NSLocalizedString("RPM", comment:"Revs per minute") ) : "N/A" NSOperationQueue.mainQueue().addOperationWithBlock { () -> Void in self.infoViewController?.showMeasurementWithSpeed(speedText , cadence: cadenceText, distance: distanceText ) } } } extension MainViewController : BluetoothManagerDelegate { func stateChanged(state: CBCentralManagerState) { print("State Changed: \(state)") var enabled = false var title = "" switch state { case .PoweredOn: title = "Bluetooth ON" enabled = true // When the bluetooth changes to ON, try to reconnect to the previous sensor checkPreviousSensor() case .Resetting: title = "Reseeting" case .PoweredOff: title = "Bluetooth Off" case .Unauthorized: title = "Bluetooth not authorized" case .Unknown: title = "Unknown" case .Unsupported: title = "Bluetooth not supported" } infoViewController?.showBluetoothStatusText( title ) scanItem.enabled = enabled } func sensorConnection( sensor:CadenceSensor, error:NSError?) { print("") guard error == nil else { self.sensor = nil print("Error connecting to sensor: \(sensor.peripheral.identifier)") updateSensorInfo() accumulatedDistance = nil return } self.sensor = sensor self.sensor?.sensorDelegate = self print("Sensor connected. \(sensor.peripheral.name). [\(sensor.peripheral.identifier)]") updateSensorInfo() sensor.start() } func sensorDisconnected( sensor:CadenceSensor, error:NSError?) { print("Sensor disconnected") self.sensor = nil } func sensorDiscovered( sensor:CadenceSensor ) { scanViewController?.addSensor(sensor) } }
bsd-2-clause
b92ce21edc0a873dec865614a3d05e2b
27.29064
159
0.689709
4.797828
false
false
false
false
wikimedia/wikipedia-ios
Wikipedia/Code/WMFReferencePageViewController.swift
1
7360
import WMF extension UIViewController { @objc class func wmf_viewControllerFromReferencePanelsStoryboard() -> Self { return self.wmf_viewControllerFromStoryboardNamed("WMFReferencePanels") } } protocol WMFReferencePageViewAppearanceDelegate : NSObjectProtocol { func referencePageViewControllerWillAppear(_ referencePageViewController: WMFReferencePageViewController) func referencePageViewControllerWillDisappear(_ referencePageViewController: WMFReferencePageViewController) } extension WMFReferencePageViewAppearanceDelegate where Self: ArticleScrolling { func referencePageViewControllerWillAppear(_ referencePageViewController: WMFReferencePageViewController) { guard let firstRefVC = referencePageViewController.pageViewController.viewControllers?.first as? WMFReferencePanelViewController, let refId = firstRefVC.reference?.refId else { return } webView.wmf_unHighlightAllLinkIDs() webView.wmf_highlightLinkID(refId) } func referencePageViewControllerWillDisappear(_ referencePageViewController: WMFReferencePageViewController) { webView.wmf_unHighlightAllLinkIDs() } } extension UIPageViewControllerDelegate where Self: ArticleScrolling & ViewController { /// This function needs to be called by `pageViewController(_ pageViewController: UIPageViewController, didFinishAnimating finished: Bool, previousViewControllers: [UIViewController], transitionCompleted completed: Bool)`. Due to objc issues, the delegate's cannot have a default extension with this actual method that is called. func didFinishAnimating(_ pageViewController: UIPageViewController) { guard let firstRefVC = pageViewController.viewControllers?.first as? WMFReferencePanelViewController, let ref = firstRefVC.reference else { return } (presentedViewController as? WMFReferencePageViewController)?.currentReference = ref webView.wmf_unHighlightAllLinkIDs() webView.wmf_highlightLinkID(ref.refId) } } class WMFReferencePageViewController: ReferenceViewController, UIPageViewControllerDataSource { @objc var lastClickedReferencesIndex:Int = 0 @objc var lastClickedReferencesGroup = [WMFLegacyReference]() weak internal var appearanceDelegate: WMFReferencePageViewAppearanceDelegate? @objc public var pageViewController = UIPageViewController(transitionStyle: .scroll, navigationOrientation: .horizontal, options: nil) @IBOutlet fileprivate var containerView: UIView! var articleURL: URL? override func apply(theme: Theme) { super.apply(theme: theme) guard viewIfLoaded != nil else { return } backgroundView.apply(theme: theme) } fileprivate lazy var pageControllers: [UIViewController] = { var controllers:[UIViewController] = [] for reference in self.lastClickedReferencesGroup { let panel = WMFReferencePanelViewController.wmf_viewControllerFromReferencePanelsStoryboard() panel.articleURL = articleURL panel.apply(theme: theme) panel.reference = reference controllers.append(panel) } return controllers }() @objc lazy var backgroundView: WMFReferencePageBackgroundView = { return WMFReferencePageBackgroundView() }() override func viewDidLoad() { super.viewDidLoad() updateReference(with: lastClickedReferencesIndex) addChild(pageViewController) pageViewController.view.frame = containerView.bounds pageViewController.view.autoresizingMask = [.flexibleWidth, .flexibleHeight] containerView.addSubview(pageViewController.view) pageViewController.didMove(toParent: self) pageViewController.dataSource = self let direction:UIPageViewController.NavigationDirection = UIApplication.shared.wmf_isRTL ? .forward : .reverse let initiallyVisibleController = pageControllers[lastClickedReferencesIndex] pageViewController.setViewControllers([initiallyVisibleController], direction: direction, animated: true, completion: nil) addBackgroundView() if let scrollView = view.wmf_firstSubviewOfType(UIScrollView.self) { scrollView.clipsToBounds = false } apply(theme: theme) accessibilityElements = [backToReferenceButton as Any, navigationItem.title as Any, closeButton as Any, pageControllers as Any] } fileprivate func addBackgroundView() { view.wmf_addSubviewWithConstraintsToEdges(backgroundView) view.sendSubviewToBack(backgroundView) } @objc internal func firstPanelView() -> UIView? { guard let viewControllers = pageViewController.viewControllers, let firstVC = viewControllers.first as? WMFReferencePanelViewController else { return nil } return firstVC.containerView } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) appearanceDelegate?.referencePageViewControllerWillAppear(self) } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) appearanceDelegate?.referencePageViewControllerWillDisappear(self) } func presentationCount(for pageViewController: UIPageViewController) -> Int { return pageControllers.count } func presentationIndex(for pageViewController: UIPageViewController) -> Int { guard let viewControllers = pageViewController.viewControllers, let currentVC = viewControllers.first, let presentationIndex = pageControllers.firstIndex(of: currentVC) else { return 0 } return presentationIndex } func pageViewController(_ pageViewController: UIPageViewController, viewControllerAfter viewController: UIViewController) -> UIViewController? { guard let index = pageControllers.firstIndex(of: viewController) else { return nil } return index >= pageControllers.count - 1 ? nil : pageControllers[index + 1] } func pageViewController(_ pageViewController: UIPageViewController, viewControllerBefore viewController: UIViewController) -> UIViewController? { guard let index = pageControllers.firstIndex(of: viewController) else { return nil } return index == 0 ? nil : pageControllers[index - 1] } override func willTransition(to newCollection: UITraitCollection, with coordinator: UIViewControllerTransitionCoordinator) { super.willTransition(to: newCollection, with: coordinator) self.presentingViewController?.dismiss(animated: false, completion: nil) } func updateReference(with index: Int) { guard index < lastClickedReferencesGroup.count else { return } currentReference = lastClickedReferencesGroup[index] } var currentReference: WMFLegacyReference? = nil { didSet { referenceId = currentReference?.anchor.removingPercentEncoding referenceLinkText = currentReference?.text } } }
mit
a47da16fa0ae5ab05e37eff1b24b8a4e
40.348315
333
0.711549
6.169321
false
false
false
false
OpsLabJPL/MarsImagesIOS
Pods/SwiftMessages/SwiftMessages/SwiftMessages.swift
3
31445
// // SwiftMessages.swift // SwiftMessages // // Created by Timothy Moose on 8/1/16. // Copyright © 2016 SwiftKick Mobile LLC. All rights reserved. // import UIKit private let globalInstance = SwiftMessages() /** The `SwiftMessages` class provides the interface for showing and hiding messages. It behaves like a queue, only showing one message at a time. Message views that adopt the `Identifiable` protocol (as `MessageView` does) will have duplicates removed. */ open class SwiftMessages { /** Specifies whether the message view is displayed at the top or bottom of the selected presentation container. */ public enum PresentationStyle { /** Message view slides down from the top. */ case top /** Message view slides up from the bottom. */ case bottom /** Message view fades into the center. */ case center /** User-defined animation */ case custom(animator: Animator) } /** Specifies how the container for presenting the message view is selected. */ public enum PresentationContext { /** Displays the message view under navigation bars and tab bars if an appropriate one is found. Otherwise, it is displayed in a new window at level `UIWindow.Level.normal`. Use this option to automatically display under bars, where applicable. Because this option involves a top-down search, an approrpiate context might not be found when the view controller heirarchy incorporates custom containers. If this is the case, the .ViewController option can provide a more targeted context. */ case automatic /** Displays the message in a new window at the specified window level. SwiftMessages automatically increases the top margins of any message view that adopts the `MarginInsetting` protocol (as `MessageView` does) to account for the status bar. As of iOS 13, windows can no longer cover the status bar. The only alternative is to set `Config.prefersStatusBarHidden = true` to hide it. */ case window(windowLevel: UIWindow.Level) /** Displays the message view under navigation bars and tab bars if an appropriate one is found using the given view controller as a starting point and searching up the parent view controller chain. Otherwise, it is displayed in the given view controller's view. This option can be used for targeted placement in a view controller heirarchy. */ case viewController(_: UIViewController) /** Displays the message view in the given container view. */ case view(_: UIView) } /** Specifies the duration of the message view's time on screen before it is automatically hidden. */ public enum Duration { /** Hide the message view after the default duration. */ case automatic /** Disables automatic hiding of the message view. */ case forever /** Hide the message view after the speficied number of seconds. - Parameter seconds: The number of seconds. */ case seconds(seconds: TimeInterval) /** The `indefinite` option is similar to `forever` in the sense that the message view will not be automatically hidden. However, it provides two options that can be useful in some scenarios: - `delay`: wait the specified time interval before displaying the message. If you hide the message during the delay interval by calling either `hideAll()` or `hide(id:)`, the message will not be displayed. This is not the case for `hide()` because it only acts on a visible message. Messages shown during another message's delay window are displayed first. - `minimum`: if the message is displayed, ensure that it is displayed for a minimum time interval. If you explicitly hide the during this interval, the message will be hidden at the end of the interval. This option is useful for displaying a message when a process is taking too long but you don't want to display the message if the process completes in a reasonable amount of time. The value `indefinite(delay: 0, minimum: 0)` is equivalent to `forever`. For example, if a URL load is expected to complete in 2 seconds, you may use the value `indefinite(delay: 2, minimum 1)` to ensure that the message will not be displayed in most cases, but will be displayed for at least 1 second if the operation takes longer than 2 seconds. By specifying a minimum duration, you can avoid hiding the message too fast if the operation finishes right after the delay interval. */ case indefinite(delay: TimeInterval, minimum: TimeInterval) } /** Specifies options for dimming the background behind the message view similar to a popover view controller. */ public enum DimMode { /** Don't dim the background behind the message view. */ case none /** Dim the background behind the message view a gray color. - `interactive`: Specifies whether or not tapping the dimmed area dismisses the message view. */ case gray(interactive: Bool) /** Dim the background behind the message view using the given color. SwiftMessages does not apply alpha transparency to the color, so any alpha must be baked into the `UIColor` instance. - `color`: The color of the dim view. - `interactive`: Specifies whether or not tapping the dimmed area dismisses the message view. */ case color(color: UIColor, interactive: Bool) /** Dim the background behind the message view using a blur effect with the given style - `style`: The blur effect style to use - `alpha`: The alpha level of the blur - `interactive`: Specifies whether or not tapping the dimmed area dismisses the message view. */ case blur(style: UIBlurEffect.Style, alpha: CGFloat, interactive: Bool) public var interactive: Bool { switch self { case .gray(let interactive): return interactive case .color(_, let interactive): return interactive case .blur (_, _, let interactive): return interactive case .none: return false } } public var modal: Bool { switch self { case .gray, .color, .blur: return true case .none: return false } } } /** Specifies events in the message lifecycle. */ public enum Event { case willShow case didShow case willHide case didHide } /** A closure that takes an `Event` as an argument. */ public typealias EventListener = (Event) -> Void /** The `Config` struct specifies options for displaying a single message view. It is provided as an optional argument to one of the `MessageView.show()` methods. */ public struct Config { public init() {} /** Specifies whether the message view is displayed at the top or bottom of the selected presentation container. The default is `.Top`. */ public var presentationStyle = PresentationStyle.top /** Specifies how the container for presenting the message view is selected. The default is `.Automatic`. */ public var presentationContext = PresentationContext.automatic /** Specifies the duration of the message view's time on screen before it is automatically hidden. The default is `.Automatic`. */ public var duration = Duration.automatic /** Specifies options for dimming the background behind the message view similar to a popover view controller. The default is `.None`. */ public var dimMode = DimMode.none /** Specifies whether or not the interactive pan-to-hide gesture is enabled on the message view. For views that implement the `BackgroundViewable` protocol (as `MessageView` does), the pan gesture recognizer is installed in the `backgroundView`, which allows for card-style views with transparent margins that shouldn't be interactive. Otherwise, it is installed in the message view itself. The default is `true`. */ public var interactiveHide = true /** Specifies the preferred status bar style when the view is being displayed in a window. This can be useful when the view is being displayed behind the status bar and the message view has a background color that needs a different status bar style than the current one. The default is `nil`. */ public var preferredStatusBarStyle: UIStatusBarStyle? /** Specifies the preferred status bar visibility when the view is being displayed in a window. As of iOS 13, windows can no longer cover the status bar. The only alternative is to hide the status bar by setting this options to `true`. Default is `nil`. */ public var prefersStatusBarHidden: Bool? /** If a view controller is created to host the message view, should the view controller auto rotate? The default is 'true', meaning it should auto rotate. */ public var shouldAutorotate = true /** Specified whether or not duplicate `Identifiable` messages are ignored. The default is `true`. */ public var ignoreDuplicates = true /** Specifies an optional array of event listeners. */ public var eventListeners: [EventListener] = [] /** Specifies that in cases where the message is displayed in its own window, such as with `.window` presentation context, the window should become the key window. This option should only be used if the message view needs to receive non-touch events, such as keyboard input. From Apple's documentation https://developer.apple.com/reference/uikit/uiwindow: > Whereas touch events are delivered to the window where they occurred, > events that do not have a relevant coordinate value are delivered to > the key window. Only one window at a time can be the key window, and > you can use a window’s keyWindow property to determine its status. > Most of the time, your app’s main window is the key window, but UIKit > may designate a different window as needed. */ public var becomeKeyWindow: Bool? /** The `dimMode` background will use this accessibility label, e.g. "dismiss" when the `interactive` option is used. */ public var dimModeAccessibilityLabel: String = "dismiss" /** If specified, SwiftMessages calls this closure when an instance of `WindowViewController` is needed. Use this if you need to supply a custom subclass of `WindowViewController`. */ public var windowViewController: ((_ windowLevel: UIWindow.Level?, _ config: SwiftMessages.Config) -> WindowViewController)? /** Supply an instance of `KeyboardTrackingView` to have the message view avoid the keyboard. */ public var keyboardTrackingView: KeyboardTrackingView? } /** Not much to say here. */ public init() {} /** Adds the given configuration and view to the message queue to be displayed. - Parameter config: The configuration options. - Parameter view: The view to be displayed. */ open func show(config: Config, view: UIView) { let presenter = Presenter(config: config, view: view, delegate: self) messageQueue.sync { enqueue(presenter: presenter) } } /** Adds the given view to the message queue to be displayed with default configuration options. - Parameter config: The configuration options. - Parameter view: The view to be displayed. */ public func show(view: UIView) { show(config: defaultConfig, view: view) } /// A block that returns an arbitrary view. public typealias ViewProvider = () -> UIView /** Adds the given configuration and view provider to the message queue to be displayed. The `viewProvider` block is guaranteed to be called on the main queue where it is safe to interact with `UIKit` components. This variant of `show()` is recommended when the message might be added from a background queue. - Parameter config: The configuration options. - Parameter viewProvider: A block that returns the view to be displayed. */ open func show(config: Config, viewProvider: @escaping ViewProvider) { DispatchQueue.main.async { [weak self] in guard let strongSelf = self else { return } let view = viewProvider() strongSelf.show(config: config, view: view) } } /** Adds the given view provider to the message queue to be displayed with default configuration options. The `viewProvider` block is guaranteed to be called on the main queue where it is safe to interact with `UIKit` components. This variant of `show()` is recommended when the message might be added from a background queue. - Parameter viewProvider: A block that returns the view to be displayed. */ public func show(viewProvider: @escaping ViewProvider) { show(config: defaultConfig, viewProvider: viewProvider) } /** Hide the current message being displayed by animating it away. */ open func hide(animated: Bool = true) { messageQueue.sync { hideCurrent(animated: animated) } } /** Hide the current message, if there is one, by animating it away and clear the message queue. */ open func hideAll() { messageQueue.sync { queue.removeAll() delays.ids.removeAll() counts.removeAll() hideCurrent() } } /** Hide a message with the given `id`. If the specified message is currently being displayed, it will be animated away. Works with message views, such as `MessageView`, that adopt the `Identifiable` protocol. - Parameter id: The identifier of the message to remove. */ open func hide(id: String) { messageQueue.sync { if id == _current?.id { hideCurrent() } queue = queue.filter { $0.id != id } delays.ids.remove(id) counts[id] = nil } } /** Hide the message when the number of calls to show() and hideCounted(id:) for a given message ID are equal. This can be useful for messages that may be shown from multiple code paths to ensure that all paths are ready to hide. */ open func hideCounted(id: String) { messageQueue.sync { if let count = counts[id] { if count < 2 { counts[id] = nil } else { counts[id] = count - 1 return } } if id == _current?.id { hideCurrent() } queue = queue.filter { $0.id != id } delays.ids.remove(id) } } /** Get the count of a message with the given ID (see `hideCounted(id:)`) */ public func count(id: String) -> Int { return counts[id] ?? 0 } /** Explicitly set the count of a message with the given ID (see `hideCounted(id:)`). Not sure if there's a use case for this, but why not?! */ public func set(count: Int, for id: String) { guard counts[id] != nil else { return } return counts[id] = count } /** Specifies the default configuration to use when calling the variants of `show()` that don't take a `config` argument or as a base for custom configs. */ public var defaultConfig = Config() /** Specifies the amount of time to pause between removing a message and showing the next. Default is 0.5 seconds. */ open var pauseBetweenMessages: TimeInterval = 0.5 /// Type for keeping track of delayed presentations fileprivate class Delays { fileprivate var ids = Set<String>() fileprivate func add(presenter: Presenter) { ids.insert(presenter.id) } @discardableResult fileprivate func remove(presenter: Presenter) -> Bool { guard ids.contains(presenter.id) else { return false } ids.remove(presenter.id) return true } } func show(presenter: Presenter) { messageQueue.sync { enqueue(presenter: presenter) } } fileprivate let messageQueue = DispatchQueue(label: "it.swiftkick.SwiftMessages", attributes: []) fileprivate var queue: [Presenter] = [] fileprivate var delays = Delays() fileprivate var counts: [String : Int] = [:] fileprivate var _current: Presenter? = nil { didSet { if oldValue != nil { let delayTime = DispatchTime.now() + pauseBetweenMessages messageQueue.asyncAfter(deadline: delayTime) { [weak self] in self?.dequeueNext() } } } } fileprivate func enqueue(presenter: Presenter) { if presenter.config.ignoreDuplicates { counts[presenter.id] = (counts[presenter.id] ?? 0) + 1 if _current?.id == presenter.id && _current?.isHiding == false { return } if queue.filter({ $0.id == presenter.id }).count > 0 { return } } func doEnqueue() { queue.append(presenter) dequeueNext() } if let delay = presenter.delayShow { delays.add(presenter: presenter) messageQueue.asyncAfter(deadline: .now() + delay) { [weak self] in // Don't enqueue if the view has been hidden during the delay window. guard let strongSelf = self, strongSelf.delays.remove(presenter: presenter) else { return } doEnqueue() } } else { doEnqueue() } } fileprivate func dequeueNext() { guard self._current == nil, queue.count > 0 else { return } let current = queue.removeFirst() self._current = current // Set `autohideToken` before the animation starts in case // the dismiss gesture begins before we've queued the autohide // block on animation completion. self.autohideToken = current current.showDate = CACurrentMediaTime() DispatchQueue.main.async { [weak self] in guard let strongSelf = self else { return } do { try current.show { completed in guard let strongSelf = self else { return } guard completed else { strongSelf.messageQueue.sync { strongSelf.internalHide(id: current.id) } return } if current === strongSelf.autohideToken { strongSelf.queueAutoHide() } } } catch { strongSelf.messageQueue.sync { strongSelf._current = nil } } } } fileprivate func internalHide(id: String) { if id == _current?.id { hideCurrent() } queue = queue.filter { $0.id != id } delays.ids.remove(id) } fileprivate func hideCurrent(animated: Bool = true) { guard let current = _current, !current.isHiding else { return } let action = { [weak self] in current.hide(animated: animated) { (completed) in guard completed, let strongSelf = self else { return } strongSelf.messageQueue.sync { guard strongSelf._current === current else { return } strongSelf.counts[current.id] = nil strongSelf._current = nil } } } let delay = current.delayHide ?? 0 DispatchQueue.main.asyncAfter(deadline: .now() + delay) { action() } } fileprivate weak var autohideToken: AnyObject? fileprivate func queueAutoHide() { guard let current = _current else { return } autohideToken = current if let pauseDuration = current.pauseDuration { let delayTime = DispatchTime.now() + pauseDuration messageQueue.asyncAfter(deadline: delayTime, execute: { // Make sure we've still got a green light to auto-hide. if self.autohideToken !== current { return } self.internalHide(id: current.id) }) } } deinit { // Prevent orphaned messages hideCurrent() } } /* MARK: - Accessing messages */ extension SwiftMessages { /** Returns the message view of type `T` if it is currently being shown or hidden. - Returns: The view of type `T` if it is currently being shown or hidden. */ public func current<T: UIView>() -> T? { var view: T? messageQueue.sync { view = _current?.view as? T } return view } /** Returns a message view with the given `id` if it is currently being shown or hidden. - Parameter id: The id of a message that adopts `Identifiable`. - Returns: The view with matching id if currently being shown or hidden. */ public func current<T: UIView>(id: String) -> T? { var view: T? messageQueue.sync { if let current = _current, current.id == id { view = current.view as? T } } return view } /** Returns a message view with the given `id` if it is currently in the queue to be shown. - Parameter id: The id of a message that adopts `Identifiable`. - Returns: The view with matching id if currently queued to be shown. */ public func queued<T: UIView>(id: String) -> T? { var view: T? messageQueue.sync { if let queued = queue.first(where: { $0.id == id }) { view = queued.view as? T } } return view } /** Returns a message view with the given `id` if it is currently being shown, hidden or in the queue to be shown. - Parameter id: The id of a message that adopts `Identifiable`. - Returns: The view with matching id if currently queued to be shown. */ public func currentOrQueued<T: UIView>(id: String) -> T? { return current(id: id) ?? queued(id: id) } } /* MARK: - PresenterDelegate */ extension SwiftMessages: PresenterDelegate { func hide(presenter: Presenter) { messageQueue.sync { self.internalHide(id: presenter.id) } } public func hide(animator: Animator) { messageQueue.sync { guard let presenter = self.presenter(forAnimator: animator) else { return } self.internalHide(id: presenter.id) } } public func panStarted(animator: Animator) { autohideToken = nil } public func panEnded(animator: Animator) { queueAutoHide() } private func presenter(forAnimator animator: Animator) -> Presenter? { if let current = _current, animator === current.animator { return current } let queued = queue.filter { $0.animator === animator } return queued.first } } /** MARK: - Creating views from nibs This extension provides several convenience functions for instantiating views from nib files. SwiftMessages provides several default nib files in the Resources folder that can be drag-and-dropped into a project as a starting point and modified. */ extension SwiftMessages { /** Loads a nib file with the same name as the generic view type `T` and returns the first view found in the nib file with matching type `T`. For example, if the generic type is `MyView`, a nib file named `MyView.nib` is loaded and the first top-level view of type `MyView` is returned. The main bundle is searched first followed by the SwiftMessages bundle. - Parameter filesOwner: An optional files owner. - Throws: `Error.CannotLoadViewFromNib` if a view matching the generic type `T` is not found in the nib. - Returns: An instance of generic view type `T`. */ public class func viewFromNib<T: UIView>(_ filesOwner: AnyObject = NSNull.init()) throws -> T { let name = T.description().components(separatedBy: ".").last assert(name != nil) let view: T = try internalViewFromNib(named: name!, bundle: nil, filesOwner: filesOwner) return view } /** Loads a nib file with specified name and returns the first view found in the nib file with matching type `T`. The main bundle is searched first followed by the SwiftMessages bundle. - Parameter name: The name of the nib file (excluding the .xib extension). - Parameter filesOwner: An optional files owner. - Throws: `Error.CannotLoadViewFromNib` if a view matching the generic type `T` is not found in the nib. - Returns: An instance of generic view type `T`. */ public class func viewFromNib<T: UIView>(named name: String, filesOwner: AnyObject = NSNull.init()) throws -> T { let view: T = try internalViewFromNib(named: name, bundle: nil, filesOwner: filesOwner) return view } /** Loads a nib file with specified name in the specified bundle and returns the first view found in the nib file with matching type `T`. - Parameter name: The name of the nib file (excluding the .xib extension). - Parameter bundle: The name of the bundle containing the nib file. - Parameter filesOwner: An optional files owner. - Throws: `Error.CannotLoadViewFromNib` if a view matching the generic type `T` is not found in the nib. - Returns: An instance of generic view type `T`. */ public class func viewFromNib<T: UIView>(named name: String, bundle: Bundle, filesOwner: AnyObject = NSNull.init()) throws -> T { let view: T = try internalViewFromNib(named: name, bundle: bundle, filesOwner: filesOwner) return view } fileprivate class func internalViewFromNib<T: UIView>(named name: String, bundle: Bundle? = nil, filesOwner: AnyObject = NSNull.init()) throws -> T { let resolvedBundle: Bundle if let bundle = bundle { resolvedBundle = bundle } else { if Bundle.main.path(forResource: name, ofType: "nib") != nil { resolvedBundle = Bundle.main } else { resolvedBundle = Bundle.sm_frameworkBundle() } } let arrayOfViews = resolvedBundle.loadNibNamed(name, owner: filesOwner, options: nil) ?? [] #if swift(>=4.1) guard let view = arrayOfViews.compactMap( { $0 as? T} ).first else { throw SwiftMessagesError.cannotLoadViewFromNib(nibName: name) } #else guard let view = arrayOfViews.flatMap( { $0 as? T} ).first else { throw SwiftMessagesError.cannotLoadViewFromNib(nibName: name) } #endif return view } } /* MARK: - Static APIs This extension provides a shared instance of `SwiftMessages` and a static API wrapper around this instance for simplified syntax. For example, `SwiftMessages.show()` is equivalent to `SwiftMessages.sharedInstance.show()`. */ extension SwiftMessages { /** A default shared instance of `SwiftMessages`. The `SwiftMessages` class provides a set of static APIs that wrap calls to this instance. For example, `SwiftMessages.show()` is equivalent to `SwiftMessages.sharedInstance.show()`. */ public static var sharedInstance: SwiftMessages { return globalInstance } public static func show(viewProvider: @escaping ViewProvider) { globalInstance.show(viewProvider: viewProvider) } public static func show(config: Config, viewProvider: @escaping ViewProvider) { globalInstance.show(config: config, viewProvider: viewProvider) } public static func show(view: UIView) { globalInstance.show(view: view) } public static func show(config: Config, view: UIView) { globalInstance.show(config: config, view: view) } public static func hide(animated: Bool = true) { globalInstance.hide(animated: animated) } public static func hideAll() { globalInstance.hideAll() } public static func hide(id: String) { globalInstance.hide(id: id) } public static func hideCounted(id: String) { globalInstance.hideCounted(id: id) } public static var defaultConfig: Config { get { return globalInstance.defaultConfig } set { globalInstance.defaultConfig = newValue } } public static var pauseBetweenMessages: TimeInterval { get { return globalInstance.pauseBetweenMessages } set { globalInstance.pauseBetweenMessages = newValue } } public static func current<T: UIView>(id: String) -> T? { return globalInstance.current(id: id) } public static func queued<T: UIView>(id: String) -> T? { return globalInstance.queued(id: id) } public static func currentOrQueued<T: UIView>(id: String) -> T? { return globalInstance.currentOrQueued(id: id) } public static func count(id: String) -> Int { return globalInstance.count(id: id) } public static func set(count: Int, for id: String) { globalInstance.set(count: count, for: id) } }
apache-2.0
f8d105d7122cf79a1987779f8aa83e41
33.894562
153
0.603022
4.99444
false
false
false
false
headione/criticalmaps-ios
CriticalMapsKit/Sources/SettingsFeature/RideEventSettingsCore.swift
1
1062
import ComposableArchitecture import Helpers import SharedModels // MARK: Actions public enum RideEventSettingsActions: Equatable { case setRideEventsEnabled(Bool) case setRideEventTypeEnabled(RideEventSettings.RideEventTypeSetting) case setRideEventRadius(EventDistance) } // MARK: Environment public struct RideEventSettingsEnvironment { public init() {} } public typealias EventReducer = Reducer<RideEventSettings, RideEventSettingsActions, RideEventSettingsEnvironment> /// Reducer handling next ride event settings actions public let rideeventSettingsReducer = EventReducer { state, action, _ in switch action { case let .setRideEventsEnabled(value): state.isEnabled = value return .none case let .setRideEventTypeEnabled(type): guard let index = state.typeSettings.firstIndex(where: { $0.type == type.type }) else { return .none } state.typeSettings[index].isEnabled = type.isEnabled return .none case let .setRideEventRadius(distance): state.eventDistance = distance return .none } }
mit
134f83f28cc52449d4757717c269a536
26.947368
114
0.763653
4.678414
false
false
false
false
JGiola/swift-package-manager
Sources/Basic/misc.swift
1
5229
/* 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 http://swift.org/LICENSE.txt for license information See http://swift.org/CONTRIBUTORS.txt for Swift project authors */ import SPMLibc import POSIX import Foundation /// Replace the current process image with a new process image. /// /// - Parameters: /// - path: Absolute path to the executable. /// - args: The executable arguments. public func exec(path: String, args: [String]) throws { let cArgs = CStringArray(args) guard execv(path, cArgs.cArray) != -1 else { throw POSIX.SystemError.exec(errno, path: path, args: args) } } // MARK: Utility function for searching for executables /// Create a list of AbsolutePath search paths from a string, such as the PATH environment variable. /// /// - Parameters: /// - pathString: The path string to parse. /// - currentWorkingDirectory: The current working directory, the relative paths will be converted to absolute paths /// based on this path. /// - Returns: List of search paths. public func getEnvSearchPaths( pathString: String?, currentWorkingDirectory: AbsolutePath? ) -> [AbsolutePath] { // Compute search paths from PATH variable. return (pathString ?? "").split(separator: ":").map(String.init).compactMap({ pathString in // If this is an absolute path, we're done. if pathString.first == "/" { return AbsolutePath(pathString) } // Otherwise convert it into absolute path relative to the working directory. guard let cwd = currentWorkingDirectory else { return nil } return AbsolutePath(pathString, relativeTo: cwd) }) } /// Lookup an executable path from an environment variable value, current working /// directory or search paths. Only return a value that is both found and executable. /// /// This method searches in the following order: /// * If env value is a valid absolute path, return it. /// * If env value is relative path, first try to locate it in current working directory. /// * Otherwise, in provided search paths. /// /// - Parameters: /// - filename: The name of the file to find. /// - currentWorkingDirectory: The current working directory to look in. /// - searchPaths: The additional search paths to look in if not found in cwd. /// - Returns: Valid path to executable if present, otherwise nil. public func lookupExecutablePath( filename value: String?, currentWorkingDirectory: AbsolutePath? = localFileSystem.currentWorkingDirectory, searchPaths: [AbsolutePath] = [] ) -> AbsolutePath? { // We should have a value to continue. guard let value = value, !value.isEmpty else { return nil } let path: AbsolutePath if let cwd = currentWorkingDirectory { // We have a value, but it could be an absolute or a relative path. path = AbsolutePath(value, relativeTo: cwd) } else if let absPath = try? AbsolutePath(validating: value) { // Current directory not being available is not a problem // for the absolute-specified paths. path = absPath } else { return nil } if localFileSystem.isExecutableFile(path) { return path } // Ensure the value is not a path. guard !value.contains("/") else { return nil } // Try to locate in search paths. for path in searchPaths { let exec = path.appending(component: value) if localFileSystem.isExecutableFile(exec) { return exec } } return nil } /// A wrapper for Range to make it Codable. /// /// Technically, we can use conditional conformance and make /// stdlib's Range Codable but since extensions leak out, it /// is not a good idea to extend types that you don't own. /// /// Range conformance will be added soon to stdlib so we can remove /// this type in the future. public struct CodableRange<Bound> where Bound: Comparable & Codable { /// The underlying range. public let range: Range<Bound> /// Create a CodableRange instance. public init(_ range: Range<Bound>) { self.range = range } } extension CodableRange: Codable { private enum CodingKeys: String, CodingKey { case lowerBound, upperBound } public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) try container.encode(range.lowerBound, forKey: .lowerBound) try container.encode(range.upperBound, forKey: .upperBound) } public init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) let lowerBound = try container.decode(Bound.self, forKey: .lowerBound) let upperBound = try container.decode(Bound.self, forKey: .upperBound) self.init(Range(uncheckedBounds: (lowerBound, upperBound))) } } extension AbsolutePath { /// File URL created from the normalized string representation of the path. public var asURL: Foundation.URL { return URL(fileURLWithPath: asString) } }
apache-2.0
b64bc717e12fbced53c16aee95dd8e4b
33.86
118
0.683305
4.539063
false
false
false
false
yageek/TPGSwift
Sources/APIURLSerialization.swift
1
3248
// // APIURLSerialization.swift // TPGSwift // // Created by Yannick Heinrich on 11.05.16. // Copyright © 2016 yageek's company. All rights reserved. // import Foundation // MARK: - URL serialization. extension API { fileprivate static let StopCodeParameter = "stopCode" fileprivate static let StopNameParameter = "stopName" fileprivate static let LineParameter = "line" fileprivate static let LinesCodeParameter = "linesCode" fileprivate static let LongitudeParameter = "longitude" fileprivate static let LatitudeParameter = "latitude" fileprivate static let DepartureCodeParameter = "departureCode" fileprivate static let DestinationsCodeParameter = "destinationsCode" /// The `NSURL` requests corresponding to the current enum value. public var URL: Foundation.URL { guard let Key = API.Key else { fatalError("API KEY has to been set.") } let result:(path: String, parameters: [String: Any?]?) = { switch self { case .getStops(let stopCode, let stopName, let line, let longitude, let latitude): return ("GetStops", [API.StopCodeParameter: stopCode, API.StopNameParameter: stopName, API.LineParameter: line, API.LongitudeParameter: longitude, API.LatitudeParameter: latitude]) case .getPhysicalStops(let stopCode, let stopName): return ("GetPhysicalStops", [API.StopCodeParameter: stopCode, API.StopNameParameter: stopName]) case .getNextDepartures(let stopCode, let departureCode, let linesCode, let destinationsCode): return ("GetNextDepartures", [API.StopCodeParameter: stopCode, API.DepartureCodeParameter: departureCode, API.LinesCodeParameter: linesCode, API.DestinationsCodeParameter: destinationsCode]) case .getAllNextDepartures(let stopCode, let linesCode, let destinationsCode): return ("GetNextDepartures", [API.StopCodeParameter: stopCode, API.LinesCodeParameter: linesCode, API.DestinationsCodeParameter: destinationsCode]) case .getThermometer(let departureCode): return ("GetThermometer", [API.DepartureCodeParameter: departureCode]) case .getThermometerPhysicalStops(let departureCode): return ("GetThermometerPhysicalStops", [API.DepartureCodeParameter: departureCode]) case .getLinesColors: return ("GetLinesColors", nil) case .getDisruptions: return ("GetDisruptions", nil) } }() var parameters = ["key": Key as AnyObject] as [String: Any] if let additionalParameters = result.parameters { for (key, value) in additionalParameters { parameters[key] = value } } let pathURL = API.HostURL.appendingPathComponent(result.path).appendingPathExtension("json") var components = URLComponents(url: pathURL, resolvingAgainstBaseURL: true) components?.queryItems = parameters.sorted(by: { $0.key > $1.key }).map { value in return URLQueryItem(name: value.key, value: "\(value.value)") } guard let url = components?.url else { fatalError("Wrong API specification")} return url } }
mit
b2feace4ff41570a451fa528e8bc0e74
47.462687
206
0.680628
4.692197
false
false
false
false
philipgreat/b2b-swift-app
B2BSimpleApp/B2BSimpleApp/FooterRemoteManagerImpl.swift
1
2229
//Domain B2B/Footer/ import SwiftyJSON import Alamofire import ObjectMapper class FooterRemoteManagerImpl:RemoteManagerImpl,CustomStringConvertible{ override init(){ //lazy load for all the properties //This is good for UI applications as it might saves RAM which is very expensive in mobile devices } override var remoteURLPrefix:String{ //Every manager need to config their own URL return "https://philipgreat.github.io/naf/footerManager/" } func loadFooterDetail(footerId:String, footerSuccessAction: (Footer)->String, footerErrorAction: (String)->String){ let methodName = "loadFooterDetail" let parameters = [footerId] let url = compositeCallURL(methodName, parameters: parameters) Alamofire.request(.GET, url).validate().responseJSON { response in switch response.result { case .Success: if let value = response.result.value { let json = JSON(value) if let footer = self.extractFooterFromJSON(json){ footerSuccessAction(footer) } } case .Failure(let error): print(error) footerErrorAction("\(error)") } } } func extractFooterFromJSON(json:JSON) -> Footer?{ let jsonTool = SwiftyJSONTool() let footer = jsonTool.extractFooter(json) return footer } //Confirming to the protocol CustomStringConvertible of Foundation var description: String{ //Need to find out a way to improve this method performance as this method might called to //debug or log, using + is faster than \(var). let result = "FooterRemoteManagerImpl, V1" return result } static var CLASS_VERSION = 1 //This value is for serializer like message pack to identify the versions match between //local and remote object. } //Reference http://grokswift.com/simple-rest-with-swift/ //Reference https://github.com/SwiftyJSON/SwiftyJSON //Reference https://github.com/Alamofire/Alamofire //Reference https://github.com/Hearst-DD/ObjectMapper //let remote = RemoteManagerImpl() //let result = remote.compositeCallURL(methodName: "getDetail",parameters:["O0000001"]) //print(result)
mit
11a13a355e22356355add8bb486cda0c
25.182927
100
0.685958
3.823328
false
false
false
false
baottran/nSURE
nSURE/DashMiniCardCell.swift
1
1085
// // DashMiniCardCell.swift // nSURE // // Created by Bao Tran on 7/29/15. // Copyright (c) 2015 Sprout Designs. All rights reserved. // import UIKit class DashMiniCardCell: UICollectionViewCell { @IBOutlet weak var vehicleImage: UIImageView! @IBOutlet weak var customerNameLabel: UILabel! @IBOutlet weak var vehicleLine1: UILabel! @IBOutlet weak var vehicleLine2: UILabel! @IBOutlet weak var timerLabel: UILabel! @IBOutlet weak var currentStatusLabel: UILabel! @IBOutlet weak var currentActivityLabel: UILabel! override func drawRect(rect: CGRect) { let effect = UIBlurEffect(style: UIBlurEffectStyle.Light) let topEffectView = UIVisualEffectView(effect: effect) let bottomEffectView = UIVisualEffectView(effect: effect) topEffectView.frame = CGRectMake(0, 0, 300, 50) bottomEffectView.frame = CGRectMake(0, 150, 300, 100) vehicleImage.addSubview(topEffectView) vehicleImage.addSubview(bottomEffectView) } }
mit
06e74efa2611a509cc800bf621ef13c3
27.552632
66
0.669124
4.520833
false
false
false
false
mmick66/KDRearrangeableCollectionViewFlowLayout
KDRearrangeableCollectionViewFlowLayout/KDRearrangeableCollectionViewCell.swift
1
1036
// // KDRearrangeableCollectionViewCell.swift // KDRearrangeableCollectionViewFlowLayout // // Created by Michael Michailidis on 16/03/2015. // Copyright (c) 2015 Karmadust. All rights reserved. // import UIKit class KDRearrangeableCollectionViewCell: UICollectionViewCell { @IBOutlet weak var titleLabel: UILabel! var baseBackgroundColor : UIColor? override init(frame: CGRect) { super.init(frame: frame) } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override func awakeFromNib() { super.awakeFromNib() } var dragging : Bool = false { didSet { if dragging == true { self.baseBackgroundColor = self.backgroundColor self.backgroundColor = UIColor.red } else { self.backgroundColor = self.baseBackgroundColor } } } }
mit
7216d9432ff2604dd0059f912745a798
20.583333
63
0.557915
5.481481
false
false
false
false
LYM-mg/MGDYZB
MGDYZB简单封装版/MGDYZB/Class/Home/Controller/SearchResultViewController.swift
1
10667
// // SearchResultViewController.swift // MGDYZB // // Created by i-Techsys.com on 17/4/10. // Copyright © 2017年 ming. All rights reserved. // import UIKit import SafariServices class SearchResultViewController: UIViewController { // MARK: - 懒加载属性 fileprivate lazy var searchVM: SearchViewModel = SearchViewModel() fileprivate lazy var collectionView : UICollectionView = {[unowned self] in // 1.创建布局 let layout = UICollectionViewFlowLayout() layout.itemSize = CGSize(width: kNormalItemW, height: kNormalItemH) layout.minimumLineSpacing = 0 layout.minimumInteritemSpacing = kItemMargin/2 layout.sectionInset = UIEdgeInsets(top: 5, left: kItemMargin/2, bottom: 0, right: kItemMargin/2) // 2.创建UICollectionView let collectionView = UICollectionView(frame: self.view.bounds, collectionViewLayout: layout) collectionView.backgroundColor = UIColor.white collectionView.autoresizingMask = [.flexibleHeight, .flexibleWidth] collectionView.register(UINib(nibName: "CollectionNormalCell", bundle: nil), forCellWithReuseIdentifier: kNormalCellID) collectionView.dataSource = self collectionView.delegate = self return collectionView }() fileprivate lazy var searchBar: UISearchBar = { let searchBar = UISearchBar() searchBar.frame = CGRect(x: 10, y: 22, width: MGScreenW * 0.9, height: 30) searchBar.placeholder = "请输入🔍关键字" searchBar.showsCancelButton = true //显示“取消”按钮 searchBar.barTintColor = UIColor.white searchBar.keyboardType = UIKeyboardType.default searchBar.delegate = self return searchBar }() override func viewDidLoad() { super.viewDidLoad() setUpMainView() } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) searchBar.removeFromSuperview() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } } // MARK: - 设置UI extension SearchResultViewController { func setUpMainView() { view.addSubview(collectionView) UIView.animate(withDuration: 0.8) { self.searchBar.frame = CGRect(x: 10, y: 22, width: MGScreenW, height: 40) self.navigationController?.view.addSubview(self.searchBar) } for view in searchBar.subviews { for subView in view.subviews { if NSStringFromClass(subView.classForCoder) == "UINavigationButton" { let btn = subView as? UIButton btn?.setTitleColor(UIColor.blue, for: .normal) // btn?.backgroundColor = UIColor.orange btn?.setTitle("取消" , for: .normal) } if NSStringFromClass(subView.classForCoder) == "UISearchBarTextField" { let textField = subView as? UITextField textField?.tintColor = UIColor.gray } } } if #available(iOS 9, *) { if traitCollection.forceTouchCapability == .available { registerForPreviewing(with: self, sourceView: self.view) } } self.navigationController!.navigationBar.setBackgroundImage(#imageLiteral(resourceName: "navigationBarBackgroundImage"), for: .default) setUpRefresh() } } // MARK: - loadData extension SearchResultViewController { fileprivate func loadData() { // 1.请求数据 searchVM.searchDataWithKeyword { [weak self] in // 1.1.刷新表格 self!.collectionView.header.endRefreshing() self!.collectionView.footer.endRefreshing() self?.collectionView.reloadData() } } fileprivate func setUpRefresh() { // MARK: - 下拉 self.collectionView.header = MJRefreshGifHeader(refreshingBlock: { [weak self]() -> Void in self!.searchVM.anchorGroups.removeAll() self!.searchVM.offset = 0 self!.loadData() }) // MARK: - 上拉 self.collectionView.footer = MJRefreshAutoGifFooter(refreshingBlock: {[weak self] () -> Void in self!.searchVM.offset += 20 self!.loadData() }) self.collectionView.header.isAutoChangeAlpha = true self.collectionView.footer.noticeNoMoreData() } } // MARK: - UICollectionViewDataSource extension SearchResultViewController: UICollectionViewDataSource { func numberOfSections(in collectionView: UICollectionView) -> Int { return searchVM.anchorGroups.count } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return searchVM.anchorGroups[section].anchors.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { // 1.获取cell let cell = collectionView.dequeueReusableCell(withReuseIdentifier: kNormalCellID, for: indexPath) as! CollectionNormalCell if searchVM.anchorGroups.count > 0 { cell.anchor = searchVM.anchorGroups[indexPath.section].anchors[indexPath.item] } return cell } } // MARK: - UICollectionViewDelegate extension SearchResultViewController: UICollectionViewDelegate { @objc(collectionView:viewForSupplementaryElementOfKind:atIndexPath:) func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView { // 1.取出HeaderView let headerView = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: kHeaderViewID, for: indexPath) as! CollectionHeaderView // 2.给HeaderView设置数据 headerView.group = searchVM.anchorGroups[indexPath.section] return headerView } func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { // 1.取出对应的主播信息 let anchor = searchVM.anchorGroups[indexPath.section].anchors[indexPath.item] // 2.判断是秀场房间&普通房间 anchor.isVertical == 0 ? pushNormalRoomVc(anchor: anchor) : presentShowRoomVc(anchor: anchor) } fileprivate func presentShowRoomVc(anchor: AnchorModel) { if #available(iOS 9.0, *) { // 1.创建SFSafariViewController let safariVC = SFSafariViewController(url: URL(string: anchor.jumpUrl)!, entersReaderIfAvailable: true) // 2.以Modal方式弹出 present(safariVC, animated: true, completion: nil) } else { let webVC = WKWebViewController(navigationTitle: anchor.room_name, urlStr: anchor.jumpUrl) present(webVC, animated: true, completion: nil) } } fileprivate func pushNormalRoomVc(anchor: AnchorModel) { // 1.创建WebViewController let webVC = WKWebViewController(navigationTitle: anchor.room_name, urlStr: anchor.jumpUrl) webVC.navigationController?.setNavigationBarHidden(true, animated: true) // 2.以Push方式弹出 navigationController?.pushViewController(webVC, animated: true) } } // MARK: - UIViewControllerPreviewingDelegate extension SearchResultViewController: UIViewControllerPreviewingDelegate { func previewingContext(_ previewingContext: UIViewControllerPreviewing, viewControllerForLocation location: CGPoint) -> UIViewController? { guard let indexPath = collectionView.indexPathForItem(at: location) else { return nil } guard let cell = collectionView.cellForItem(at: indexPath) else { return nil } if #available(iOS 9.0, *) { previewingContext.sourceRect = cell.frame } var vc = UIViewController() let anchor = searchVM.anchorGroups[indexPath.section].anchors[indexPath.item] if anchor.isVertical == 0 { if #available(iOS 9, *) { vc = SFSafariViewController(url: URL(string: anchor.jumpUrl)!, entersReaderIfAvailable: true) } else { vc = WKWebViewController(navigationTitle: anchor.room_name, urlStr: anchor.jumpUrl) } }else { vc = WKWebViewController(navigationTitle: anchor.room_name, urlStr: anchor.jumpUrl) } return vc } func previewingContext(_ previewingContext: UIViewControllerPreviewing, commit viewControllerToCommit: UIViewController) { show(viewControllerToCommit, sender: nil) } } extension SearchResultViewController: UISearchResultsUpdating{ func updateSearchResults(for searchController: UISearchController) { // self.showHudInViewWithMode(view: self.view, hint: "正在搜索", mode: .indeterminate, imageName: nil) if var textToSearch = searchController.searchBar.text { //去除搜索字符串左右和中间的空格 textToSearch = textToSearch.trimmingCharacters(in: CharacterSet.whitespaces) searchVM.keyword = textToSearch loadData() collectionView.reloadData() } } } // MARK: - UISearchBarDelegate extension SearchResultViewController: UISearchBarDelegate { func searchBarTextDidBeginEditing(_ searchBar: UISearchBar) { searchBar.setShowsCancelButton(true, animated: true) let btn: UIButton = searchBar.value(forKeyPath: "_cancelButton") as! UIButton // 修改searchBar右侧按钮的文字 btn.setTitle("取消", for: .normal) } func searchBarCancelButtonClicked(_ searchBar: UISearchBar) { searchBar.resignFirstResponder() let _ = self.navigationController?.popViewController(animated: true) } func searchBarSearchButtonClicked(_ searchBar: UISearchBar) { searchBar.showsCancelButton = true //去除搜索字符串左右和中间的空格 let textToSearch = searchBar.text!.trimmingCharacters(in: CharacterSet.whitespaces) searchVM.keyword = textToSearch loadData() collectionView.reloadData() searchBar.resignFirstResponder() } func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) { if searchText.count == 0 { } } func scrollViewDidScroll(_ scrollView: UIScrollView) { searchBar.resignFirstResponder() } }
mit
a5a7ece3b989ae01d521b9fd0297e77b
38.706107
231
0.661636
5.504233
false
false
false
false
sachin004/firefox-ios
Client/Application/AppDelegate.swift
1
19202
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import Shared import Storage import AVFoundation import XCGLogger import Breakpad import MessageUI private let log = Logger.browserLogger class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? var browserViewController: BrowserViewController! var rootViewController: UINavigationController! weak var profile: BrowserProfile? var tabManager: TabManager! @available(iOS 9, *) lazy var quickActions: QuickActions = { let actions = QuickActions() return actions }() weak var application: UIApplication? var launchOptions: [NSObject: AnyObject]? let appVersion = NSBundle.mainBundle().objectForInfoDictionaryKey("CFBundleShortVersionString") as! String func application(application: UIApplication, willFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Hold references to willFinishLaunching parameters for delayed app launch self.application = application self.launchOptions = launchOptions log.debug("Configuring window…") self.window = UIWindow(frame: UIScreen.mainScreen().bounds) self.window!.backgroundColor = UIConstants.AppBackgroundColor // Short circuit the app if we want to email logs from the debug menu if DebugSettingsBundleOptions.emailLogsOnLaunch { self.window?.rootViewController = UIViewController() presentEmailComposerWithLogs() return true } else { return startApplication(application, withLaunchOptions: launchOptions) } } private func startApplication(application: UIApplication, withLaunchOptions launchOptions: [NSObject: AnyObject]?) -> Bool { log.debug("Setting UA…") // Set the Firefox UA for browsing. setUserAgent() log.debug("Starting keyboard helper…") // Start the keyboard helper to monitor and cache keyboard state. KeyboardHelper.defaultHelper.startObserving() log.debug("Creating Sync log file…") // Create a new sync log file on cold app launch. Note that this doesn't roll old logs. Logger.syncLogger.newLogWithDate(NSDate()) log.debug("Creating corrupt DB logger…") Logger.corruptLogger.newLogWithDate(NSDate()) log.debug("Getting profile…") let profile = getProfile(application) if !DebugSettingsBundleOptions.disableLocalWebServer { log.debug("Starting web server…") // Set up a web server that serves us static content. Do this early so that it is ready when the UI is presented. setUpWebServer(profile) } log.debug("Setting AVAudioSession category…") do { // for aural progress bar: play even with silent switch on, and do not stop audio from other apps (like music) try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback, withOptions: AVAudioSessionCategoryOptions.MixWithOthers) } catch _ { log.error("Failed to assign AVAudioSession category to allow playing with silent switch on for aural progress bar") } let defaultRequest = NSURLRequest(URL: UIConstants.DefaultHomePage) let imageStore = DiskImageStore(files: profile.files, namespace: "TabManagerScreenshots", quality: UIConstants.ScreenshotQuality) log.debug("Configuring tabManager…") self.tabManager = TabManager(defaultNewTabRequest: defaultRequest, prefs: profile.prefs, imageStore: imageStore) self.tabManager.stateDelegate = self // Add restoration class, the factory that will return the ViewController we // will restore with. log.debug("Initing BVC…") browserViewController = BrowserViewController(profile: self.profile!, tabManager: self.tabManager) browserViewController.restorationIdentifier = NSStringFromClass(BrowserViewController.self) browserViewController.restorationClass = AppDelegate.self browserViewController.automaticallyAdjustsScrollViewInsets = false rootViewController = UINavigationController(rootViewController: browserViewController) rootViewController.automaticallyAdjustsScrollViewInsets = false rootViewController.delegate = self rootViewController.navigationBarHidden = true self.window!.rootViewController = rootViewController log.debug("Configuring Breakpad…") activeCrashReporter = BreakpadCrashReporter(breakpadInstance: BreakpadController.sharedInstance()) configureActiveCrashReporter(profile.prefs.boolForKey("crashreports.send.always")) log.debug("Adding observers…") NSNotificationCenter.defaultCenter().addObserverForName(FSReadingListAddReadingListItemNotification, object: nil, queue: nil) { (notification) -> Void in if let userInfo = notification.userInfo, url = userInfo["URL"] as? NSURL { let title = (userInfo["Title"] as? String) ?? "" profile.readingList?.createRecordWithURL(url.absoluteString, title: title, addedBy: UIDevice.currentDevice().name) } } // check to see if we started 'cos someone tapped on a notification. if let localNotification = launchOptions?[UIApplicationLaunchOptionsLocalNotificationKey] as? UILocalNotification { viewURLInNewTab(localNotification) } log.debug("Done with setting up the application.") return true } /** * We maintain a weak reference to the profile so that we can pause timed * syncs when we're backgrounded. * * The long-lasting ref to the profile lives in BrowserViewController, * which we set in application:willFinishLaunchingWithOptions:. * * If that ever disappears, we won't be able to grab the profile to stop * syncing... but in that case the profile's deinit will take care of things. */ func getProfile(application: UIApplication) -> Profile { if let profile = self.profile { return profile } let p = BrowserProfile(localName: "profile", app: application) self.profile = p return p } func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject : AnyObject]?) -> Bool { // Override point for customization after application launch. var shouldPerformAdditionalDelegateHandling = true log.debug("Did finish launching.") dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0)) { AdjustIntegration.sharedInstance.triggerApplicationDidFinishLaunchingWithOptions(launchOptions) } log.debug("Making window key and visible…") self.window!.makeKeyAndVisible() // Now roll logs. log.debug("Triggering log roll.") dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), Logger.syncLogger.deleteOldLogsDownToSizeLimit ) if #available(iOS 9, *) { // If a shortcut was launched, display its information and take the appropriate action if let shortcutItem = launchOptions?[UIApplicationLaunchOptionsShortcutItemKey] as? UIApplicationShortcutItem { quickActions.launchedShortcutItem = shortcutItem // This will block "performActionForShortcutItem:completionHandler" from being called. shouldPerformAdditionalDelegateHandling = false } } log.debug("Done with applicationDidFinishLaunching.") return shouldPerformAdditionalDelegateHandling } func application(application: UIApplication, openURL url: NSURL, sourceApplication: String?, annotation: AnyObject) -> Bool { if let components = NSURLComponents(URL: url, resolvingAgainstBaseURL: false) { if components.scheme != "firefox" && components.scheme != "firefox-x-callback" { return false } var url: String? for item in (components.queryItems ?? []) as [NSURLQueryItem] { switch item.name { case "url": url = item.value default: () } } if let url = url, newURL = NSURL(string: url.unescape()) { self.browserViewController.openURLInNewTab(newURL) return true } } return false } // We sync in the foreground only, to avoid the possibility of runaway resource usage. // Eventually we'll sync in response to notifications. func applicationDidBecomeActive(application: UIApplication) { guard !DebugSettingsBundleOptions.emailLogsOnLaunch else { return } self.profile?.syncManager.applicationDidBecomeActive() // We could load these here, but then we have to futz with the tab counter // and making NSURLRequests. self.browserViewController.loadQueuedTabs() // handle quick actions is available if #available(iOS 9, *) { if let shortcut = quickActions.launchedShortcutItem { // dispatch asynchronously so that BVC is all set up for handling new tabs // when we try and open them self.quickActions.handleShortCutItem(shortcut, completionBlock: self.handleShortCutItemType) quickActions.launchedShortcutItem = nil } } } func applicationDidEnterBackground(application: UIApplication) { self.profile?.syncManager.applicationDidEnterBackground() var taskId: UIBackgroundTaskIdentifier = 0 taskId = application.beginBackgroundTaskWithExpirationHandler { _ in log.warning("Running out of background time, but we have a profile shutdown pending.") application.endBackgroundTask(taskId) } dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0)) { self.profile?.shutdown() application.endBackgroundTask(taskId) } } private func setUpWebServer(profile: Profile) { let server = WebServer.sharedInstance ReaderModeHandlers.register(server, profile: profile) ErrorPageHelper.register(server) AboutHomeHandler.register(server) AboutLicenseHandler.register(server) SessionRestoreHandler.register(server) // Bug 1223009 was an issue whereby CGDWebserver crashed when moving to a background task // catching and handling the error seemed to fix things, but we're not sure why. // Either way, not implicitly unwrapping a try is not a great way of doing things // so this is better anyway. do { try server.start() } catch let err as NSError { log.error("Unable to start WebServer \(err)") } } private func setUserAgent() { let firefoxUA = UserAgent.defaultUserAgent() // Set the UA for WKWebView (via defaults), the favicon fetcher, and the image loader. // This only needs to be done once per runtime. Note that we use defaults here that are // readable from extensions, so they can just use the cached identifier. let defaults = NSUserDefaults(suiteName: AppInfo.sharedContainerIdentifier())! defaults.registerDefaults(["UserAgent": firefoxUA]) FaviconFetcher.userAgent = firefoxUA SDWebImageDownloader.sharedDownloader().setValue(firefoxUA, forHTTPHeaderField: "User-Agent") // Record the user agent for use by search suggestion clients. SearchViewController.userAgent = firefoxUA } func application(application: UIApplication, handleActionWithIdentifier identifier: String?, forLocalNotification notification: UILocalNotification, completionHandler: () -> Void) { if let actionId = identifier { if let action = SentTabAction(rawValue: actionId) { viewURLInNewTab(notification) switch(action) { case .Bookmark: addBookmark(notification) break case .ReadingList: addToReadingList(notification) break default: break } } else { print("ERROR: Unknown notification action received") } } else { print("ERROR: Unknown notification received") } } func application(application: UIApplication, didReceiveLocalNotification notification: UILocalNotification) { viewURLInNewTab(notification) } private func presentEmailComposerWithLogs() { if let buildNumber = NSBundle.mainBundle().objectForInfoDictionaryKey(String(kCFBundleVersionKey)) as? NSString { let mailComposeViewController = MFMailComposeViewController() mailComposeViewController.mailComposeDelegate = self mailComposeViewController.setSubject("Email logs for iOS client version v\(appVersion) (\(buildNumber))") do { let logNamesAndData = try Logger.diskLogFilenamesAndData() logNamesAndData.forEach { nameAndData in if let data = nameAndData.1 { mailComposeViewController.addAttachmentData(data, mimeType: "text/plain", fileName: nameAndData.0) } } } catch _ { print("Failed to retrieve logs from device") } self.window?.rootViewController?.presentViewController(mailComposeViewController, animated: true, completion: nil) } } private func viewURLInNewTab(notification: UILocalNotification) { if let alertURL = notification.userInfo?[TabSendURLKey] as? String { if let urlToOpen = NSURL(string: alertURL) { browserViewController.openURLInNewTab(urlToOpen) } } } private func addBookmark(notification: UILocalNotification) { if let alertURL = notification.userInfo?[TabSendURLKey] as? String, let title = notification.userInfo?[TabSendTitleKey] as? String { browserViewController.addBookmark(alertURL, title: title) } } private func addToReadingList(notification: UILocalNotification) { if let alertURL = notification.userInfo?[TabSendURLKey] as? String, let title = notification.userInfo?[TabSendTitleKey] as? String { if let urlToOpen = NSURL(string: alertURL) { NSNotificationCenter.defaultCenter().postNotificationName(FSReadingListAddReadingListItemNotification, object: self, userInfo: ["URL": urlToOpen, "Title": title]) } } } @available(iOS 9.0, *) func application(application: UIApplication, performActionForShortcutItem shortcutItem: UIApplicationShortcutItem, completionHandler: Bool -> Void) { let handledShortCutItem = quickActions.handleShortCutItem(shortcutItem, completionBlock: handleShortCutItemType) completionHandler(handledShortCutItem) } @available(iOS 9, *) func handleShortCutItemType(type: ShortcutType, userData: [String : NSSecureCoding]?) { switch(type) { case .NewTab: browserViewController.applyNormalModeTheme(force: true) browserViewController.openBlankNewTabAndFocus() case .NewPrivateTab: browserViewController.applyPrivateModeTheme(force: true) browserViewController.openBlankNewTabAndFocus(isPrivate: true) } } } // MARK: - Root View Controller Animations extension AppDelegate: UINavigationControllerDelegate { func navigationController(navigationController: UINavigationController, animationControllerForOperation operation: UINavigationControllerOperation, fromViewController fromVC: UIViewController, toViewController toVC: UIViewController) -> UIViewControllerAnimatedTransitioning? { if operation == UINavigationControllerOperation.Push { return BrowserToTrayAnimator() } else if operation == UINavigationControllerOperation.Pop { return TrayToBrowserAnimator() } else { return nil } } } extension AppDelegate: TabManagerStateDelegate { func tabManagerWillStoreTabs(tabs: [Browser]) { // It is possible that not all tabs have loaded yet, so we filter out tabs with a nil URL. let storedTabs: [RemoteTab] = tabs.flatMap( Browser.toTab ) // Don't insert into the DB immediately. We tend to contend with more important // work like querying for top sites. let queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0) dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(ProfileRemoteTabsSyncDelay * Double(NSEC_PER_MSEC))), queue) { self.profile?.storeTabs(storedTabs) } } } extension AppDelegate: MFMailComposeViewControllerDelegate { func mailComposeController(controller: MFMailComposeViewController, didFinishWithResult result: MFMailComposeResult, error: NSError?) { // Dismiss the view controller and start the app up controller.dismissViewControllerAnimated(true, completion: nil) startApplication(application!, withLaunchOptions: self.launchOptions) } } var activeCrashReporter: CrashReporter? func configureActiveCrashReporter(optedIn: Bool?) { if let reporter = activeCrashReporter { configureCrashReporter(reporter, optedIn: optedIn) } } public func configureCrashReporter(reporter: CrashReporter, optedIn: Bool?) { let configureReporter: () -> () = { let addUploadParameterForKey: String -> Void = { key in if let value = NSBundle.mainBundle().objectForInfoDictionaryKey(key) as? String { reporter.addUploadParameter(value, forKey: key) } } addUploadParameterForKey("AppID") addUploadParameterForKey("BuildID") addUploadParameterForKey("ReleaseChannel") addUploadParameterForKey("Vendor") } if let optedIn = optedIn { // User has explicitly opted-in for sending crash reports. If this is not true, then the user has // explicitly opted-out of crash reporting so don't bother starting breakpad or stop if it was running if optedIn { reporter.start(true) configureReporter() reporter.setUploadingEnabled(true) } else { reporter.stop() } } // We haven't asked the user for their crash reporting preference yet. Log crashes anyways but don't send them. else { reporter.start(true) configureReporter() } }
mpl-2.0
a803d93ddabdd8b78719e1b0b1a7f4d7
42.482993
185
0.672977
5.725888
false
false
false
false
eTilbudsavis/native-ios-eta-sdk
Sources/CoreAPI/CGSize_Fitting.swift
1
3441
// // ┌────┬─┐ ┌─────┐ // │ ──┤ └─┬───┬───┤ ┌──┼─┬─┬───┐ // ├── │ ╷ │ · │ · │ ╵ │ ╵ │ ╷ │ // └────┴─┴─┴───┤ ┌─┴─────┴───┴─┴─┘ // └─┘ // // Copyright (c) 2018 ShopGun. All rights reserved. import UIKit extension CGSize { /// The w/h aspect ratio of the size, or 1.0 if any of the dimensions are <= 0 var aspectRatio: CGFloat { return width > 0 && height > 0 ? width / height : 1.0 } /// Returns a size that is smaller than the current size, and but matches the specified w/h aspect ratio func scaledDownToAspectRatio(_ ratio: CGFloat) -> CGSize { var fittingSize = CGSize(width: self.height * ratio, height: self.width / ratio) if fittingSize.width <= self.width { fittingSize.height = self.height } else { fittingSize.width = self.width } return fittingSize } func closestFitting<T>(sizes: [(CGSize, T)], alwaysLargerIfPossible alwaysLarger: Bool) -> (size: CGSize, val: T)? { var closestOversized: (size: CGSize, diff: CGFloat, val: T)? = nil var closestUndersized: (size: CGSize, diff: CGFloat, val: T)? = nil for (inputSize, val) in sizes { // get the size the input would be that exactly fits into the target size. let fittingSize = self.scaledDownToAspectRatio(inputSize.aspectRatio) // how much difference between the actual input size, and how big it will be when fit to the target size // negative means input is smaller than the target size let fittingDiff = CGSize(width: inputSize.width - fittingSize.width, height: inputSize.height - fittingSize.height) // the largest (or smallest, if undersized) dimension of the fit size let maxDiff = max(abs(fittingDiff.width), abs(fittingDiff.height)) if fittingDiff.width < 0 || fittingDiff.height < 0 { // the input is smaller than the fittingSize // the maxDiff is smaller than the last found undersized, so save it as the new closest if maxDiff < closestUndersized?.diff ?? CGFloat.infinity { closestUndersized = (size: inputSize, diff: maxDiff, val: val) } } else { // the image is larger (or equal to) than the fittingSize // the maxDiff is smaller than the last found one oversized, so save it as the new closest if maxDiff < closestOversized?.diff ?? CGFloat.infinity { closestOversized = (size: inputSize, diff: maxDiff, val: val) } } } // there is an oversized image, and the difference to the target size is less than the undersized image, so use it if let oversized = closestOversized, (alwaysLarger || oversized.diff < closestUndersized?.diff ?? CGFloat.infinity) { return (oversized.size, oversized.val) } else if let undersized = closestUndersized { return (undersized.size, undersized.val) } else { return nil } } }
mit
8a1e39431146c8a9d75d9a659eba00fe
44.901408
125
0.561215
4.532684
false
false
false
false
lakesoft/LKUserDefaultOption
Pod/Classes/LKUserDefaultOptionSingleSelectionGeneric.swift
1
1422
// // LKUserDefaultOptionSingleSelectionGeneric.swift // Pods // // Created by Hiroshi Hashiguchi on 2015/10/11. // // public class LKUserDefaultOptionSingleSelectionGeneric:LKUserDefaultOption, LKUserDefaultOptionSingleSelection { // MARK: - Local public var items:[LKUserDefaultOptionModelItem] = [] // MARK: - LKUserDefaultOptionModel override public func valueLabel() -> String { return label(selectedIndexPath) } override public func save() { let item = items[selectedIndexPath.row] saveUserDefaults(item.itemId) } override public func restore() { if let id = restoreUserDefaults() as? String { for (index, item) in items.enumerate() { if id == item.itemId { selectedIndexPath = NSIndexPath(forRow: index, inSection: 0) break } } } } // MARK: - LKUserDefaultOptionSelection public func label(indexPath:NSIndexPath) -> String { let item = items[indexPath.row] return item.itemLabel } public func numberOfRows(section:Int) -> Int { return items.count } // MARK: - LKUserDefaultOptionSingleSelection public var selectedIndexPath: NSIndexPath = NSIndexPath(forRow: 0, inSection: 0) public func closeWhenSelected() -> Bool { return false } }
mit
a41dba016c630957e85b40b944c8f1cd
26.882353
112
0.618143
5.096774
false
false
false
false
ezefranca/sptrans-olho-vivo-iOS
SPTransOlhoVivo.swift
1
2618
// // SPTransOlhoVivo.swift // InstaAPI // // Created by Ezequiel on 1/28/16. import Foundation import Alamofire class SPTransOlhoVivo { let BASE_URL_SPTRANS = "http://api.olhovivo.sptrans.com.br/v0" let TOKEN = "cfd03d518181527ab8211864f0a436a705118b731569502a6420b7c0228daa4d" func autenticar(){ Alamofire.request(.POST, BASE_URL_SPTRANS + "/Login/Autenticar?token=" + TOKEN) .response { response in print(response) // original URL request } } func buscarDetalheLinha(termosBusca: String, completionHandler: (AnyObject?, NSError?) -> ()) { genericGET("/Linha/Buscar?termosBusca=" + termosBusca, completionHandler: completionHandler) } func carregarDetalhesLinha(codigoLinha: String, completionHandler: (AnyObject?, NSError?) -> ()) { genericGET("/Linha/CarregarDetalhes?codigoLinha=" + codigoLinha, completionHandler: completionHandler) } func buscarParada(termosBusca: String, completionHandler: (AnyObject?, NSError?) -> ()) { genericGET("/Parada/Buscar?termosBusca=" + termosBusca, completionHandler: completionHandler) } func buscarParadaPorLinha(codigoLinha: String, completionHandler: (AnyObject?, NSError?) -> ()) { genericGET("/Parada/BuscarParadasPorLinha?codigoLinha=" + codigoLinha, completionHandler: completionHandler) } func pegarPosicaoOnibus(codigoLinha: String, completionHandler: (AnyObject?, NSError?) -> ()) { genericGET("/Posicao?codigoLinha=" + codigoLinha, completionHandler: completionHandler) } func pegarTempoDeChegadaDeUmOnibusNaParada(codigoLinha: String, codigoParada: String, completionHandler: (AnyObject?, NSError?) -> ()) { genericGET("/Previsao?codigoParada=" + codigoParada + "&codigoLinha=" + codigoLinha, completionHandler: completionHandler) } func pegarTemposDeChegadaParada(codigoParada: String, completionHandler: (AnyObject?, NSError?) -> ()) { genericGET("/Previsao/Parada?codigoParada=" + codigoParada, completionHandler: completionHandler) } func genericGET(url: String, completionHandler: (AnyObject?, NSError?) -> ()) { Alamofire.request(.GET, BASE_URL_SPTRANS + url) .responseJSON { response in switch response.result { case .Success(let value): print(value) completionHandler(value as? AnyObject, nil) case .Failure(let error): completionHandler(nil, error) } } } }
mit
d54397df3bd6f6b247c958ca98b967ba
39.921875
140
0.658136
3.948718
false
false
false
false
AlexMcArdle/LooseFoot
LooseFoot/Systems/RedditLoader.swift
1
9471
/** * Copyright (c) 2016 Razeware LLC * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ import Foundation import reddift import Toaster import RealmSwift import SwiftyJSON protocol RedditLoaderDelegate: class { func redditLoaderDidUpdateLinks(redditLoader: RedditLoader) func redditLoaderDidUpdateComments(redditLoader: RedditLoader, comments: [AMComment]) func redditLoaderDidSelectLink(redditLoader: RedditLoader) func redditLoaderDidReturnToPosts(redditLoader: RedditLoader) func redditLoaderDidVote(redditLoader: RedditLoader, link: AMLink) func redditLoaderDidUpdateSubreddits(redditLoader: RedditLoader) } private func doOnMainThread(execute work: @escaping @convention(block) () -> Swift.Void) { DispatchQueue.main.async { work() } } //private func lewisMessage(text: String, interval: TimeInterval = 0) -> Post { // let user = User(id: 2, name: "cpt.lewis") // return Post(date: Date(timeIntervalSinceNow: interval), text: text, user: user) //} class RedditLoader { static let sharedReddit = RedditLoader() weak var delegate: RedditLoaderDelegate? var searchDelegate: RedditLoaderDelegate? var realm: Realm? var redditSession: Session = Session() var names: [String] = [] var r_links: [Link] = [] var linksLast: [AMLink] = [] var links: [AMLink] = { var arr = [AMLink]() return arr }() { didSet { doOnMainThread { self.delegate?.redditLoaderDidUpdateLinks(redditLoader: self) } } } var r_comments: [Comment] = [] var commentsLast: [AMComment] = [] var comments: [AMComment] = { var arr = [AMComment]() return arr }() { didSet { doOnMainThread { self.delegate?.redditLoaderDidUpdateComments(redditLoader: self, comments: self.comments) } } } var r_subreddits: [Subreddit] = [] var subreddits: [AMSubreddit] = { var arr = [AMSubreddit]() return arr }() { didSet { doOnMainThread { self.searchDelegate?.redditLoaderDidUpdateSubreddits(redditLoader: self) } } } init() { self.realm = try! Realm() } func connect() { names.removeAll(keepingCapacity: false) names += OAuth2TokenRepository.savedNames if let name = names.first { do { let token = try OAuth2TokenRepository.token(of: name) self.redditSession = Session(token: token) print("Logged in: \(name)") } catch { print("token error") } } } func subredditToAMSubreddit() { var newSubreddits: [AMSubreddit] = [] for subreddit in self.r_subreddits { newSubreddits.append(AMSubreddit(sub: subreddit)) } self.subreddits = newSubreddits self.r_subreddits = [] } func linkToPost() { var newLinks: [AMLink] = [] let indexCountOfLinks = (self.r_links.count - 1) for i in 0...indexCountOfLinks { newLinks.append(AMLink(link: self.r_links[i])) } let linksBak = self.links self.linksLast = linksBak self.links = newLinks self.r_links = [] } func commentToAMComment() { var newComments: [AMComment] = [] for comment in self.r_comments { newComments.append(AMComment(comment: comment)) } let commentsBak = self.comments self.commentsLast = commentsBak self.comments = newComments self.r_comments = [] } // func returnFromComments() { // // // save current state and restore previous Posts // doOnMainThread { // let lastPosts = self.postsLast // let currentComments = self.comments // self.commentsLast = currentComments // self.posts = lastPosts // self.comments = [] // self.delegate?.redditLoaderDidReturnToPosts(redditLoader: self) // } // } // func expandPost(at: Int) { //// doOnMainThread { //// let post = self.posts[at+1] //// debugPrint(post) //// post.isExpanded = !post.isExpanded //// debugPrint(post) //// } // } func login() { try! OAuth2Authorizer.sharedInstance.challengeWithAllScopes() } func vote(link: AMLink, direction: VoteDirection) { //print("vote: \(direction.rawValue) + \(post.postPosition)") connect() let newDir = (link.l.likes == direction) ? .none : direction do { try redditSession.setVote(newDir, name: link.l.name, completion: { (result) in switch result { case .failure(let error): debugPrint("error: \(error)") Toast(text: "Vote: error").show() case .success(let listing): doOnMainThread { debugPrint(listing) let linkIndex: Int = self.links.index(of: link)! print("voted: \(linkIndex)") //self.links[linkIndex].l.likes = newDir self.links[linkIndex].l.likes = newDir self.delegate?.redditLoaderDidVote(redditLoader: self, link: self.links[linkIndex]) } } }) } catch { print("upvote error") } } func getUser(user: String) { } func getUserSubreddits(user: String, paginator: Paginator? = nil) { let _paginator = paginator ?? Paginator() debugPrint(paginator) do { try redditSession.getUserRelatedSubreddit(.subscriber, paginator: _paginator, completion: { (result) in switch result { case .failure(let error): debugPrint(error) case .success(let listing): //debugPrint(listing) self.r_subreddits.append(contentsOf: listing.children.flatMap{$0 as? Subreddit}) if(listing.paginator.isVacant) { print("isVacant") self.subredditToAMSubreddit() } else { print("!isVacant") self.getUserSubreddits(user: "", paginator: listing.paginator) } } }) } catch { print("getUserSubreddits error") } } func getComments(link: AMLink) { // let paginator = Paginator() // let commentId = link.id // let sortType = LinkSortType.top do { try redditSession.getArticles(link.l, sort: .top, completion: { (result) in switch result { case .failure(let error): print(error) case .success(let listing): var newArray: [Comment] = [] newArray.append(contentsOf: listing.0.children.flatMap{$0 as? Comment}) self.r_comments.append(contentsOf: listing.1.children.flatMap{$0 as? Comment}) self.commentToAMComment() } }) } catch { print("getComments error") } } func getSubreddit(_ sub: String?) { let paginator = Paginator() //let subreddit: Subreddit? = (sub=="Frontpage") ? nil : Subreddit(subreddit: sub!) let subreddit: Subreddit? if let temp = sub { subreddit = Subreddit(subreddit: temp) } else { subreddit = nil } let sortType = LinkSortType.hot do { try redditSession.getList(paginator, subreddit:subreddit, sort:sortType, timeFilterWithin:.day, completion: { (result) in switch result { case .failure(let error): Toast(text: "GetSub: \(error)").show() case .success(let listing): self.r_links.append(contentsOf: listing.children.flatMap{$0 as? Link}) self.linkToPost() } }) } catch { print("getSubreddit error") } } }
gpl-3.0
b774078e69eaeb9fc297740738c38255
33.692308
133
0.564671
4.595342
false
false
false
false
AnderGoig/SwiftInstagram
Sources/Endpoints/Media.swift
1
3464
// // Media.swift // SwiftInstagram // // Created by Ander Goig on 29/10/17. // Copyright © 2017 Ander Goig. All rights reserved. // import CoreLocation extension Instagram { // MARK: Media Endpoints /// Get information about a media object. /// /// - parameter id: The ID of the media object to reference. /// - parameter success: The callback called after a correct retrieval. /// - parameter failure: The callback called after an incorrect retrieval. /// /// - important: It requires *public_content* scope. public func media(withId id: String, success: SuccessHandler<InstagramMedia>?, failure: FailureHandler?) { request("/media/\(id)", success: success, failure: failure) } /// Get information about a media object. /// /// - parameter shortcode: The shortcode of the media object to reference. /// - parameter success: The callback called after a correct retrieval. /// - parameter failure: The callback called after an incorrect retrieval. /// /// - important: It requires *public_content* scope. /// /// - note: A media object's shortcode can be found in its shortlink URL. /// An example shortlink is http://instagram.com/p/tsxp1hhQTG/. Its corresponding shortcode is tsxp1hhQTG. public func media(withShortcode shortcode: String, success: SuccessHandler<InstagramMedia>?, failure: FailureHandler?) { request("/media/shortcode/\(shortcode)", success: success, failure: failure) } /// Search for recent media in a given area. /// /// - parameter latitude: Latitude of the center search coordinate. If used, `longitude` is required. /// - parameter longitude: Longitude of the center search coordinate. If used, `latitude` is required. /// - parameter distance: Default is 1km (1000m), max distance is 5km. /// - parameter success: The callback called after a correct retrieval. /// - parameter failure: The callback called after an incorrect retrieval. /// /// - important: It requires *public_content* scope. public func searchMedia(latitude: Double? = nil, longitude: Double? = nil, distance: Int? = nil, success: SuccessHandler<[InstagramMedia]>?, failure: FailureHandler?) { var parameters = Parameters() parameters["lat"] ??= latitude parameters["lng"] ??= longitude parameters["distance"] ??= distance request("/media/search", parameters: parameters, success: success, failure: failure) } /// Search for recent media in a given area. /// /// - parameter coordinates: Latitude and longitude of the center search coordinates. /// - parameter distance: Default is 1km (1000m), max distance is 5km. /// - parameter success: The callback called after a correct retrieval. /// - parameter failure: The callback called after an incorrect retrieval. /// /// - important: It requires *public_content* scope. public func searchMedia(coordinates: CLLocationCoordinate2D? = nil, distance: Int? = nil, success: SuccessHandler<[InstagramMedia]>?, failure: FailureHandler?) { searchMedia(latitude: coordinates?.latitude, longitude: coordinates?.longitude, distance: distance, success: success, failure: failure) } }
mit
8566ca40072991dd5c97d986642f251f
43.974026
143
0.645394
4.829847
false
false
false
false
Awalz/ark-ios-monitor
ArkMonitor/ArkPalette.swift
1
1787
// Copyright (c) 2016 Ark // // 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 public struct ArkPalette { static public let backgroundColor = UIColor(r: 0, g: 0, b: 0) static public let secondaryBackgroundColor = UIColor(r: 19, g: 19, b: 19) static public let tertiaryBackgroundColor = UIColor(r: 42, g: 42, b: 42) static public let textColor = UIColor(r: 119, g: 119, b: 125) static public let highlightedTextColor = UIColor(r: 249, g: 247, b: 247) static public let accentColor = UIColor(r: 0, g: 191, b: 192) } extension UIColor { convenience init(r: Int, g: Int, b: Int) { self.init(red: CGFloat(r) / 255.0, green: CGFloat(g) / 255.0, blue: CGFloat(b) / 255.0, alpha: 1.0) } }
mit
c7904b5c2bd171dd61fee598aa93d7dc
54.84375
137
0.712927
4.079909
false
false
false
false
ZhangMingNan/MNMeiTuan
15-MeiTuan/15-MeiTuan/View/MerchantSegmented.swift
1
3559
// // MerchantSegmented.swift // 15-MeiTuan // // Created by 张明楠 on 15/8/16. // Copyright (c) 2015年 张明楠. All rights reserved. // import UIKit enum SelectType:Int{ case left = 0 case right = 1 } protocol MerchantSegmentedDelegate{ func switchButton(type:SelectType) } class MerchantSegmented: UIView { var butW:CGFloat? var leftButton:UIButton? var rightButton:UIButton? var delegate:MerchantSegmentedDelegate? //0 选中左侧按钮, 1 选中右侧按钮 var currentSelected:SelectType = SelectType.left{ didSet{ if currentSelected == .right { self.leftButton?.selected = false self.rightButton?.selected = true self.leftButton?.setTitleColor(mainColor, forState: UIControlState.Normal) self.rightButton?.setTitleColor(UIColor.whiteColor(), forState: UIControlState.Normal) }else if currentSelected == .left { self.leftButton?.selected = true self.rightButton?.selected = false self.leftButton?.setTitleColor(UIColor.whiteColor(), forState: UIControlState.Normal) self.rightButton?.setTitleColor(mainColor, forState: UIControlState.Normal) } } } var butTitles:(left:String,right:String)?{ didSet{ self.leftButton?.setTitle(butTitles!.left, forState: UIControlState.Normal) self.rightButton?.setTitle(butTitles!.right, forState: UIControlState.Normal) } } override init(frame: CGRect) { super.init(frame: frame) self.butW = self.width() * 0.5 self.leftButton = UIButton(frame: CGRectMake(0, 0,self.butW!, frame.height)) self.rightButton = UIButton(frame: CGRectMake(self.butW!,0, self.butW!, frame.height)) self.leftButton?.titleLabel?.font = UIFont.systemFontOfSize(13) self.rightButton?.titleLabel?.font = UIFont.systemFontOfSize(13) self.leftButton?.userInteractionEnabled = false self.rightButton?.userInteractionEnabled = false self.leftButton!.setBackgroundImage(UIImage.resizableImageWithName("btn_segmentedcontrol_left_normal"), forState: UIControlState.Normal) self.leftButton!.setBackgroundImage(UIImage.resizableImageWithName("btn_segmentedcontrol_left_selected"), forState: UIControlState.Selected) self.rightButton!.setBackgroundImage(UIImage.resizableImageWithName("btn_segmentedcontrol_right_normal"), forState: UIControlState.Normal) self.rightButton!.setBackgroundImage(UIImage.resizableImageWithName("btn_segmentedcontrol_right_selected"), forState: UIControlState.Selected) self.addSubview(self.leftButton!) self.addSubview(self.rightButton!) self.leftButton?.selected = true self.rightButton?.setTitleColor(mainColor, forState: UIControlState.Normal) self.addGestureRecognizer(UITapGestureRecognizer(target: self, action: "tapBut:")) } func tapBut(tap:UITapGestureRecognizer){ var location = tap.locationInView(self) if CGRectContainsPoint(leftButton!.frame, location){ self.currentSelected = .left }else if CGRectContainsPoint(rightButton!.frame, location) { self.currentSelected = .right } //调用代理方法 self.delegate?.switchButton(self.currentSelected) } required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func layoutSubviews() { super.layoutSubviews() } }
apache-2.0
2a01ee7e4f188c7bf79709b2d0093128
38.875
150
0.689655
4.697456
false
false
false
false
colemancda/Pedido
CorePedidoServer/CorePedidoServer/User+Function.swift
1
1697
// // User+Function.swift // CorePedidoServer // // Created by Alsey Coleman Miller on 12/6/14. // Copyright (c) 2014 ColemanCDA. All rights reserved. // import Foundation import CoreData import NetworkObjects import CorePedido func UserEntityFunctions() -> [String] { return [UserFunction.ChangePassword.rawValue] } func UserPerformFunction(function: UserFunction, managedObject: User, context: NSManagedObjectContext, user: User?, recievedJsonObject: [String : AnyObject]?) -> (ServerFunctionCode, [String : AnyObject]?) { switch function { case .ChangePassword: if recievedJsonObject == nil { return (ServerFunctionCode.RecievedInvalidJSONObject, nil) } // get values from JSON let oldPassword = recievedJsonObject!["oldPassword"] as? String let newPassword = recievedJsonObject!["newPassword"] as? String if oldPassword == nil || newPassword == nil { return (ServerFunctionCode.RecievedInvalidJSONObject, nil) } var validOldPassword = false context.performBlockAndWait({ () -> Void in validOldPassword = (oldPassword == managedObject.password) }) if !validOldPassword { return (ServerFunctionCode.CannotPerformFunction, nil) } // change password... context.performBlockAndWait({ () -> Void in managedObject.password = newPassword! }) // return success return (ServerFunctionCode.PerformedSuccesfully, nil) } }
mit
d7392d178a5bd460715f64d63753ce1b
26.836066
207
0.602239
5.336478
false
false
false
false
saitjr/HappyLayerFriends
TheLyrics/TheLyrics/ViewController.swift
1
1289
// // ViewController.swift // TheLyrics // // Created by saitjr on 8/8/16. // Copyright © 2016 saitjr. All rights reserved. // import UIKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. setupUI() } } extension ViewController { private func setupUI() { view.backgroundColor = .brownColor() let orangeView = UIView() orangeView.frame = CGRect(x: 0, y: 0, width: 100, height: 60) orangeView.center = CGPoint(x: orangeView.center.x, y: view.center.y) orangeView.backgroundColor = .orangeColor() view.addSubview(orangeView) let imageView = UIImageView(image: UIImage(named: "Text.png")) imageView.bounds = CGRect(x: 0, y: 0, width: view.bounds.size.width, height: 80) imageView.center = view.center imageView.contentMode = .ScaleAspectFit view.addSubview(imageView) UIView.animateWithDuration(3, delay: 0, options: [.Repeat, .Autoreverse], animations: { orangeView.frame.origin.x = self.view.bounds.size.width - orangeView.bounds.size.width }, completion: nil) } }
mit
a283f5887a3bd514ab06fc179d5ced05
30.439024
102
0.629658
4.222951
false
false
false
false
RMizin/PigeonMessenger-project
FalconMessenger/ChatsControllers/ChatLogHistoryFetcher.swift
1
4888
// // ChatLogHistoryFetcher.swift // FalconMessenger // // Created by Roman Mizin on 8/28/18. // Copyright © 2018 Roman Mizin. All rights reserved. // import UIKit import Firebase protocol ChatLogHistoryDelegate: class { func chatLogHistory(isEmpty: Bool) func chatLogHistory(updated messages: [Message]) } class ChatLogHistoryFetcher: NSObject { weak var delegate: ChatLogHistoryDelegate? fileprivate var loadingGroup = DispatchGroup() fileprivate let messagesFetcher = MessagesFetcher() fileprivate var messages = [Message]() fileprivate var conversation: Conversation? fileprivate var isGroupChat: Bool! fileprivate var messagesToLoad: Int! public func loadPreviousMessages(_ messages: [Message], _ conversation: Conversation, _ messagesToLoad: Int, _ isGroupChat: Bool) { self.messages = messages self.conversation = conversation self.messagesToLoad = messagesToLoad self.isGroupChat = isGroupChat loadChatHistory() } fileprivate func loadChatHistory() { guard let currentUserID = Auth.auth().currentUser?.uid, let conversationID = conversation?.chatID else { return } if messages.count <= 0 { delegate?.chatLogHistory(isEmpty: true) } getFirstID(currentUserID, conversationID) } fileprivate func getFirstID(_ currentUserID: String, _ conversationID: String) { let firstIDReference = Database.database().reference().child("user-messages") .child(currentUserID).child(conversationID).child(userMessagesFirebaseFolder) let numberOfMessagesToLoad = messagesToLoad + messages.count let firstIDQuery = firstIDReference.queryLimited(toLast: UInt(numberOfMessagesToLoad)) firstIDQuery.observeSingleEvent(of: .childAdded, with: { (snapshot) in let firstID = snapshot.key self.getLastID(firstID, currentUserID, conversationID) }) } fileprivate func getLastID(_ firstID: String, _ currentUserID: String, _ conversationID: String) { let nextMessageIndex = messages.count + 1 let lastIDReference = Database.database().reference().child("user-messages") .child(currentUserID).child(conversationID).child(userMessagesFirebaseFolder) let lastIDQuery = lastIDReference.queryLimited(toLast: UInt(nextMessageIndex)) lastIDQuery.observeSingleEvent(of: .childAdded, with: { (snapshot) in let lastID = snapshot.key if (firstID == lastID) && self.messages.contains(where: { (message) -> Bool in return message.messageUID == lastID }) { self.delegate?.chatLogHistory(isEmpty: false) return } self.getRange(firstID, lastID, currentUserID, conversationID) }) } fileprivate func getRange(_ firstID: String, _ lastID: String, _ currentUserID: String, _ conversationID: String) { let rangeReference = Database.database().reference().child("user-messages") .child(currentUserID).child(conversationID).child(userMessagesFirebaseFolder) let rangeQuery = rangeReference.queryOrderedByKey().queryStarting(atValue: firstID).queryEnding(atValue: lastID) rangeQuery.observeSingleEvent(of: .value, with: { (snapshot) in for _ in 0 ..< snapshot.childrenCount { self.loadingGroup.enter() } self.notifyWhenGroupFinished(query: rangeQuery) self.getMessages(from: rangeQuery) }) } fileprivate var userMessageHande: DatabaseHandle! var previousMessages = [Message]() fileprivate func getMessages(from query: DatabaseQuery) { previousMessages = [Message]() self.userMessageHande = query.observe(.childAdded, with: { (snapshot) in let messageUID = snapshot.key self.getMetadata(fromMessageWith: messageUID) }) } fileprivate func getMetadata(fromMessageWith messageUID: String) { let reference = Database.database().reference().child("messages").child(messageUID) reference.observeSingleEvent(of: .value, with: { (snapshot) in guard var dictionary = snapshot.value as? [String: AnyObject] else { return } dictionary.updateValue(messageUID as AnyObject, forKey: "messageUID") dictionary = self.messagesFetcher.preloadCellData(to: dictionary, isGroupChat: self.isGroupChat) let message = Message(dictionary: dictionary) message.conversation = self.conversation prefetchThumbnail(from: message.thumbnailImageUrl) self.messagesFetcher.loadUserNameForOneMessage(message: message, completion: { (_, newMessage) in self.previousMessages.append(newMessage) self.loadingGroup.leave() }) }) } fileprivate func notifyWhenGroupFinished(query: DatabaseQuery) { loadingGroup.notify(queue: DispatchQueue.main, execute: { let updatedMessages = self.previousMessages query.removeObserver(withHandle: self.userMessageHande) self.delegate?.chatLogHistory(updated: updatedMessages) }) } }
gpl-3.0
054b6e11c14df5ccc7ec3360b156d43e
38.41129
117
0.72478
4.418626
false
false
false
false
flathead/Flame
Flame/BSPDataParser.swift
1
2133
// // BSPDataParser.swift // Flame // // Created by Kenny Deriemaeker on 17/05/16. // Copyright © 2016 Kenny Deriemaeker. All rights reserved. // import Foundation /** Convenience wrapper around NSData for easy sequential access to binary data inside BSP files (or any binary file). */ class BSPDataParser { var readOffset: Int private var data: NSData! init(_ data: NSData) { self.data = data readOffset = 0 } func readByte() -> Int { let range = NSRange(location: readOffset, length: sizeof(UInt8)) var buffer = [UInt8](count: 1, repeatedValue: 0) data.getBytes(&buffer, range: range) readOffset += sizeof(UInt8) return Int(buffer[0]) } func readShort() -> Int { let range = NSRange(location: readOffset, length: sizeof(UInt16)) var buffer = [UInt16](count: 1, repeatedValue: 0) data.getBytes(&buffer, range: range) readOffset += sizeof(UInt16) return Int(buffer[0].littleEndian) } func readLong() -> Int { let range = NSRange(location: readOffset, length: sizeof(UInt32)) var buffer = [UInt32](count: 1, repeatedValue: 0) data.getBytes(&buffer, range: range) readOffset += sizeof(UInt32) return Int(buffer[0].littleEndian) } func readFloat() -> Float { let range = NSRange(location: readOffset, length: sizeof(Float32)) var buffer = [Float32](count: 1, repeatedValue: 0) data.getBytes(&buffer, range: range) readOffset += sizeof(Float32) return Float(buffer[0]) } func readString(length: Int) -> String { var buffer = [Int8](count: length, repeatedValue: 0) data.getBytes(&buffer, range: NSRange(location: readOffset, length: length)) var result = "" for c in buffer { if c == 0 { break } result.append(Character(UnicodeScalar(Int(c)))) } readOffset += length return result } }
mit
d9c883591c22c3fae75bc9d7909c18ff
25.65
84
0.574109
4.281124
false
false
false
false
ArnavChawla/InteliChat
Carthage/Checkouts/swift-sdk/Source/DiscoveryV1/Models/NluEnrichmentEntities.swift
1
3765
/** * Copyright IBM Corporation 2018 * * 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 /** An object speficying the Entities enrichment and related parameters. */ public struct NluEnrichmentEntities: Codable { /// When `true`, sentiment analysis of entities will be performed on the specified field. public var sentiment: Bool? /// When `true`, emotion detection of entities will be performed on the specified field. public var emotion: Bool? /// The maximum number of entities to extract for each instance of the specified field. public var limit: Int? /// When `true`, the number of mentions of each identified entity is recorded. The default is `false`. public var mentions: Bool? /// When `true`, the types of mentions for each idetifieid entity is recorded. The default is `false`. public var mentionTypes: Bool? /// When `true`, a list of sentence locations for each instance of each identified entity is recorded. The default is `false`. public var sentenceLocation: Bool? /// The enrichement model to use with entity extraction. May be a custom model provided by Watson Knowledge Studio, the public model for use with Knowledge Graph `en-news`, or the default public model `alchemy`. public var model: String? // Map each property name to the key that shall be used for encoding/decoding. private enum CodingKeys: String, CodingKey { case sentiment = "sentiment" case emotion = "emotion" case limit = "limit" case mentions = "mentions" case mentionTypes = "mention_types" case sentenceLocation = "sentence_location" case model = "model" } /** Initialize a `NluEnrichmentEntities` with member variables. - parameter sentiment: When `true`, sentiment analysis of entities will be performed on the specified field. - parameter emotion: When `true`, emotion detection of entities will be performed on the specified field. - parameter limit: The maximum number of entities to extract for each instance of the specified field. - parameter mentions: When `true`, the number of mentions of each identified entity is recorded. The default is `false`. - parameter mentionTypes: When `true`, the types of mentions for each idetifieid entity is recorded. The default is `false`. - parameter sentenceLocation: When `true`, a list of sentence locations for each instance of each identified entity is recorded. The default is `false`. - parameter model: The enrichement model to use with entity extraction. May be a custom model provided by Watson Knowledge Studio, the public model for use with Knowledge Graph `en-news`, or the default public model `alchemy`. - returns: An initialized `NluEnrichmentEntities`. */ public init(sentiment: Bool? = nil, emotion: Bool? = nil, limit: Int? = nil, mentions: Bool? = nil, mentionTypes: Bool? = nil, sentenceLocation: Bool? = nil, model: String? = nil) { self.sentiment = sentiment self.emotion = emotion self.limit = limit self.mentions = mentions self.mentionTypes = mentionTypes self.sentenceLocation = sentenceLocation self.model = model } }
mit
7cb31aed4e58f6767c02c2d914ebf09f
47.896104
231
0.715007
4.563636
false
false
false
false
chanhx/Octogit
iGithub/Extensions/Event+DataProcess.swift
2
6806
// // Event+DataProcess.swift // iGithub // // Created by Chan Hocheung on 7/24/16. // Copyright © 2016 Hocheung. All rights reserved. // import Foundation extension Event { var title: String { switch self.type! { case .commitCommentEvent: let e = self as! CommitCommentEvent let commitID = e.comment!.commitID! let shortSHA = commitID.substring(to: 7) return "\(e.actor!) commented on \(shortSHA) at \(e.repository!)" case .createEvent: let e = self as! CreateEvent switch e.refType! { case .repository: return "\(e.actor!) created \(e.refType!) \(e.repository!)" default: return "\(e.actor!) created \(e.refType!) \(e.ref!) at \(e.repository!)" } case .deleteEvent: let e = self as! DeleteEvent return "\(e.actor!) deleted \(e.refType!) \(e.ref!) at \(e.repository!)" case .forkEvent: let e = self as! ForkEvent return "\(e.actor!) forked \(e.forkee!) from \(e.repository!)" case .gollumEvent: let e = self as! GollumEvent return "\(e.actor!) \(e.action!) \(e.pageName!) in the \(e.repository!) wiki" case .issueCommentEvent: let e = self as! IssueCommentEvent let object = e.issue!.isPullRequest ? "pull request" : "issue" return "\(e.actor!) \(e.action!) comment on \(object) \(e.repository!)#\(e.issue!.number!)" case .issuesEvent: let e = self as! IssueEvent return "\(e.actor!) \(e.action!) issue \(e.repository!)#\(e.issue!.number!)" case .memberEvent: let e = self as! MemberEvent return "\(e.actor!) added \(e.member!) to \(e.repository!)" case .publicEvent: return "\(self.actor!) made \(self.repository!) public" case .pullRequestEvent: let e = self as! PullRequestEvent var action: String if e.action! == .closed && e.pullRequest!.isMerged! { action = "merged" } else { action = e.action!.rawValue } return "\(e.actor!) \(action) pull request \(e.repository!)#\(e.pullRequest!.number!)" case .pullRequestReviewCommentEvent: let e = self as! PullRequestReviewCommentEvent return "\(e.actor!) \(e.action!) comment on pull request \(e.repository!)#\(e.pullRequest!.number!)" case .pushEvent: let e = self as! PushEvent let ref = e.ref!.removePrefix("refs/heads/") return "\(e.actor!) pushed to \(ref) at \(e.repository!)" case .releaseEvent: let e = self as! ReleaseEvent return "\(e.actor!) released \(e.releaseTagName!) at \(e.repository!)" case .watchEvent: return "\(self.actor!) starred \(self.repository!)" default: return "" } } var content: String? { switch self.type! { case .commitCommentEvent: let e = self as! CommitCommentEvent return e.comment!.body! case .createEvent: let e = self as! CreateEvent switch e.refType! { case .repository: return e.repoDescription default: return nil } case .forkEvent: let e = self as! ForkEvent return e.forkeeDescription case .gollumEvent: let e = self as! GollumEvent return e.summary case .issueCommentEvent: let e = self as! IssueCommentEvent return e.comment! case .issuesEvent: let e = self as! IssueEvent return e.issue!.title case .publicEvent: let e = self as! PublicEvent return e.repositoryDescription case .pullRequestEvent: let e = self as! PullRequestEvent return e.pullRequest?.title case .pullRequestReviewCommentEvent: let e = self as! PullRequestReviewCommentEvent return e.comment! case .pushEvent: let e = self as! PushEvent var messages: [String] = [] for commit in e.commits! { let sha = commit.sha! let shortSHA = sha.substring(to: 7) let message = "\(shortSHA) \(commit.message!.components(separatedBy: "\n")[0])" messages.append(message) } return messages.joined(separator: "\n") default: return nil } } var icon: (text: String, color: UIColor) { var icon: Octicon? var color = UIColor.darkGray switch type! { case .commitCommentEvent, .pullRequestReviewCommentEvent, .issueCommentEvent: icon = Octicon.comment case .createEvent: let e = self as! CreateEvent switch e.refType! { case .branch: icon = Octicon.gitBranch case .repository: icon = Octicon.repo case .tag: icon = Octicon.tag } case .deleteEvent: icon = Octicon.diffRemoved case .forkEvent: icon = Octicon.repoForked case .gollumEvent: icon = Octicon.book case .issuesEvent: let e = self as! IssueEvent switch e.action! { case .closed: icon = Octicon.issueClosed color = UIColor(netHex: 0xBD2C00) default: icon = Octicon.issueOpened color = UIColor(netHex: 0x6CB644) } case .memberEvent: icon = Octicon.organization case .publicEvent: icon = Octicon.repo case .pullRequestEvent: let e = self as! PullRequestEvent if e.action! == .closed && e.pullRequest!.isMerged! { icon = Octicon.gitMerge color = UIColor(netHex: 0x6E5494) } else if e.action! == .closed { icon = Octicon.gitPullrequest color = UIColor(netHex: 0xBD2C00) } else { icon = Octicon.gitPullrequest color = UIColor(netHex: 0x6BB644) } case .pushEvent: icon = Octicon.gitCommit case .releaseEvent: icon = Octicon.tag case .watchEvent: icon = Octicon.star color = UIColor(netHex: 0xFFBF03) default: break } return (icon?.rawValue ?? "", color) } }
gpl-3.0
a20bc63db868862bf62144f4d8ab7e8d
34.815789
112
0.518001
4.560992
false
false
false
false
m-schmidt/Refracto
Refracto/LinkCell.swift
1
644
// LinkCell.swift - Cell for Links and Actions import UIKit class LinkCell: SettingsBaseTableViewCell { static let identifier = "LinkCell" func configure(title: String, enabled: Bool, isLink: Bool) { if let textLabel = textLabel { textLabel.text = title textLabel.textColor = enabled ? Colors.accent : Colors.settingsCellDiabledForeground } var traits: UIAccessibilityTraits = [] traits = traits.union(enabled ? [] : [.notEnabled]) traits = traits.union(isLink ? [.link] : [.button]) accessibilityTraits = traits isAccessibilityElement = true } }
bsd-3-clause
823103dd8501fa8cd8f451cfbd1e6651
31.2
96
0.647516
4.80597
false
false
false
false
srn214/Floral
Floral/Pods/Tiercel/Tiercel/Extensions/OperationQueue+DispatchQueue.swift
1
1785
// // OperationQueue+DispatchQueue.swift // Tiercel // // Created by Daniels on 2019/4/30. // Copyright © 2019 Daniels. All rights reserved. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import Foundation extension OperationQueue { convenience init(qualityOfService: QualityOfService = .default, maxConcurrentOperationCount: Int = OperationQueue.defaultMaxConcurrentOperationCount, underlyingQueue: DispatchQueue? = nil, name: String? = nil) { self.init() self.qualityOfService = qualityOfService self.maxConcurrentOperationCount = maxConcurrentOperationCount self.underlyingQueue = underlyingQueue self.name = name } }
mit
21955b366c969cab70a65450be8005b8
43.6
106
0.723094
4.770053
false
false
false
false
tkremenek/swift
test/Generics/unify_nested_types_3.swift
1
1121
// RUN: %target-typecheck-verify-swift -requirement-machine=verify -debug-requirement-machine 2>&1 | %FileCheck %s protocol P1 { associatedtype T : P1 } protocol P2 { associatedtype T } struct X<A : P1> : P2 { typealias T = X<A.T> } protocol P2a { associatedtype T : P2 } protocol P3a { associatedtype T where T == X<U> associatedtype U : P1 } struct G<T : P2a & P3a> {} // X.T has a DependentMemberType in it; make sure that we build the // correct substitution schema. // CHECK-LABEL: Requirement machine for <τ_0_0 where τ_0_0 : P2a, τ_0_0 : P3a> // CHECK-LABEL: Rewrite system: { // CHECK: - τ_0_0.[P2a&P3a:T].[concrete: X<τ_0_0> with <τ_0_0.[P3a:U]>] => τ_0_0.[P2a&P3a:T] // CHECK: - τ_0_0.[P2a&P3a:T].[P2:T].[concrete: X<τ_0_0> with <τ_0_0.[P3a:U].[P1:T]>] => τ_0_0.[P2a&P3a:T].[P2:T] // CHECK: } // CHECK-LABEL: Equivalence class map: { // CHECK: τ_0_0.[P2a&P3a:T] => { conforms_to: [P2] concrete_type: [concrete: X<τ_0_0> with <τ_0_0.[P3a:U]>] } // CHECK: τ_0_0.[P2a&P3a:T].[P2:T] => { concrete_type: [concrete: X<τ_0_0> with <τ_0_0.[P3a:U].[P1:T]>] } // CHECK: } // CHECK: }
apache-2.0
fd94c8764428fa3a1843464adec0f82b
28.052632
114
0.611413
2.208
false
false
false
false
aducret/vj-ios-tp2
Shooter/Shooter/Utils/Grid.swift
1
3365
// // Grid.swift // Shooter // // Created by Argentino Ducret on 6/23/17. // Copyright © 2017 ITBA. All rights reserved. // import Foundation import UIKit import SpriteKit public class Grid { private let scene: SKScene private let width: CGFloat private let height: CGFloat private let nodeRadius: CGFloat public let grid: [[Node]] private let collisionBitMask: UInt32 private let nodeDiameter: CGFloat private let gridSizeX: UInt private let gridSizeY: UInt public init(scene: SKScene, width: CGFloat, height: CGFloat, nodeRadius: CGFloat, collisionBitMask: UInt32) { self.scene = scene self.width = width self.height = height self.nodeRadius = nodeRadius self.collisionBitMask = collisionBitMask nodeDiameter = nodeRadius * 2.0 gridSizeX = UInt(round(width / nodeDiameter)) gridSizeY = UInt(round(height / nodeDiameter)) grid = createGrid(gridSizeX: gridSizeX, gridSizeY: gridSizeY, nodeDiameter: nodeDiameter, collisionBitMask: collisionBitMask, scene: scene) } public func nodeFromWorldPoint(point: CGPoint) -> Node { let flattened = grid.flatMap { $0 } let node: Node? = flattened.first { point.x >= ($0.worldPosition.x - nodeRadius) && point.x <= ($0.worldPosition.x + nodeRadius) && point.y >= ($0.worldPosition.y - nodeRadius) && point.y <= ($0.worldPosition.y + nodeRadius) } return node! } public func getNeighbourds(node: Node) -> [Node] { var neighbourds: [Node] = [] for x in -1...1 { for y in -1...1 { if x == 0 && y == 0 { continue } let checkX = node.gridX + x let checkY = node.gridY + y if checkX >= 0 && checkX < Int(gridSizeX) && checkY >= 0 && checkY < Int(gridSizeY) { neighbourds.append(grid[checkX][checkY]) } } } return neighbourds } } private func createGrid(gridSizeX: UInt, gridSizeY: UInt, nodeDiameter: CGFloat, collisionBitMask: UInt32, scene: SKScene) -> [[Node]]{ let xTop = Int(gridSizeX) let yTop = Int(gridSizeY) let nodeRadius = nodeDiameter / 2.0 let repetedValue = Node(worldPosition: CGPoint(x: 0, y: 0), gridX: 0, gridY: 0) var grid = [[Node]](repeating: [Node](repeating: repetedValue, count: xTop), count: yTop) let worldBottomLeft = scene.children.filter { $0.name ?? "" == "WorldBottomLeft" }[0].position for x in 0..<xTop { for y in 0..<yTop { let worldPoint = worldBottomLeft + CGPoint(x: 1, y: 0) * (CGFloat(x) * nodeDiameter + nodeRadius) + CGPoint(x: 0, y: 1) * (CGFloat(y) * nodeDiameter + nodeRadius) let walkable = scene.nodes(at: worldPoint).reduce(true) { result, node in if let physicsBody = node.physicsBody { return physicsBody.categoryBitMask & collisionBitMask == 0 && result } else { return result } } grid[x][y] = Node(worldPosition: worldPoint, walkable: walkable, gridX: x, gridY: y) } } return grid; }
mit
5c1cf729ec804445b850414adb653987
33.680412
174
0.571046
4.057901
false
false
false
false
TheBrewery/Hikes
Pods/SKPhotoBrowser/SKPhotoBrowser/SKLocalPhoto.swift
1
1976
// // SKLocalPhoto.swift // SKPhotoBrowser // // Created by Antoine Barrault on 13/04/2016. // Copyright © 2016 suzuki_keishi. All rights reserved. // import UIKit // MARK: - SKLocalPhoto public class SKLocalPhoto: NSObject, SKPhotoProtocol { public var underlyingImage: UIImage! public var photoURL: String! public var shouldCachePhotoURLImage: Bool = false public var caption: String! public var index: Int = 0 override init() { super.init() } convenience init(url: String) { self.init() photoURL = url } convenience init(url: String, holder: UIImage?) { self.init() photoURL = url underlyingImage = holder } public func checkCache() {} public func loadUnderlyingImageAndNotify() { if underlyingImage != nil && photoURL == nil { loadUnderlyingImageComplete() } if photoURL != nil { // Fetch Image if NSFileManager.defaultManager().fileExistsAtPath(photoURL) { if let data = NSFileManager.defaultManager().contentsAtPath(photoURL) { self.loadUnderlyingImageComplete() if let image = UIImage(data: data) { self.underlyingImage = image self.loadUnderlyingImageComplete() } } } } } public func loadUnderlyingImageComplete() { NSNotificationCenter.defaultCenter().postNotificationName(SKPHOTO_LOADING_DID_END_NOTIFICATION, object: self) } // MARK: - class func public class func photoWithImageURL(url: String) -> SKLocalPhoto { return SKLocalPhoto(url: url) } public class func photoWithImageURL(url: String, holder: UIImage?) -> SKLocalPhoto { return SKLocalPhoto(url: url, holder: holder) } }
mit
0fa8add5fb70fe5c40111771032badbf
26.816901
117
0.578228
5.294906
false
false
false
false
appunite/BRNImagePickerSheet
BRNImagePickerSheet/BRNImagePickerSheet/BRNImagePickerCollectionView.swift
1
1761
// // BRNImagePickerCollectionView.swift // BRNImagePickerSheet // // Created by Laurin Brandner on 07/09/14. // Copyright (c) 2014 Laurin Brandner. All rights reserved. // import UIKit @objc public class BRNImagePickerCollectionView: UICollectionView { var bouncing: Bool { get { let contentOffset = self.contentOffset let contentSize = self.contentSize let contentInset = self.contentInset return contentOffset.x < -contentInset.left || contentOffset.x + self.frame.width > contentSize.width + contentInset.right } } // MARK: Initialization override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) { super.init(frame: frame, collectionViewLayout: layout) self.panGestureRecognizer.addTarget(self, action: "handlePanGesture:") } required public init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: - Panning func handlePanGesture(gestureRecognizer: UIPanGestureRecognizer) { if gestureRecognizer.state == .Ended { let translation = gestureRecognizer.translationInView(self) if translation == CGPointZero { if !self.bouncing { let possibleIndexPath = self.indexPathForItemAtPoint(gestureRecognizer.locationInView(self)) if let indexPath = possibleIndexPath { self.selectItemAtIndexPath(indexPath, animated: false, scrollPosition: .None) self.delegate?.collectionView?(self, didSelectItemAtIndexPath: indexPath) } } } } } }
mit
2ba9feb8014e69a1c0c4ed1c9c3495e9
32.865385
134
0.62862
5.537736
false
false
false
false
programersun/HiChongSwift
HiChongSwift/SquareMapViewController.swift
1
2970
// // SquareMapViewController.swift // HiChongSwift // // Created by eagle on 15/1/6. // Copyright (c) 2015年 多思科技. All rights reserved. // import UIKit import MapKit class SquareMapViewController: UIViewController { var businessData: SquareMerchantInfoMsg? @IBOutlet private weak var icyMapView: MKMapView! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. if let data = businessData { let latitude = data.businessLatitude.bridgeToObjectiveC().doubleValue let longitude = data.businessLongitude.bridgeToObjectiveC().doubleValue let location = CLLocation(latitude: latitude, longitude: longitude) icyMapView.setRegion(MKCoordinateRegionMake(location.coordinate, MKCoordinateSpanMake(0.018, 0.018)), animated: false) let business = SquareMapBusiness(location: location, businessName: data.businessName, businessMapNote: data.businessMapNote) icyMapView.addAnnotation(business) } else { alert("无法加载商家信息,请后退重试") } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ } extension SquareMapViewController: MKMapViewDelegate { func mapView(mapView: MKMapView!, viewForAnnotation annotation: MKAnnotation!) -> MKAnnotationView! { if let business = annotation as? SquareMapBusiness { var view = mapView.dequeueReusableAnnotationViewWithIdentifier("pin") as! MKPinAnnotationView! if view == nil { view = MKPinAnnotationView(annotation: annotation, reuseIdentifier: "pin") view.canShowCallout = true } else { view.annotation = annotation } return view } else { return nil } } } class SquareMapBusiness: NSObject { init(location: CLLocation, businessName: String, businessMapNote: String) { self.location = location self.businessName = businessName self.businessMapNote = businessMapNote } let location: CLLocation let businessName: String let businessMapNote: String } extension SquareMapBusiness: MKAnnotation { var coordinate: CLLocationCoordinate2D { return location.coordinate } var title: String { return businessName } var subtitle: String { return businessMapNote } }
apache-2.0
7b3bdb9741cbc4d2634dd3ba203cbe05
30.869565
136
0.662347
5.161972
false
false
false
false
prebid/prebid-mobile-ios
PrebidMobileTests/RenderingTests/Tests/UtilitiesExtensionsTests/TestPBMFunctions.swift
1
12151
/*   Copyright 2018-2021 Prebid.org, 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 XCTest @testable import PrebidMobile class TestPBMFunctions: XCTestCase { // Source: https://github.com/semver/semver/issues/232 let versionValidatorRegExpr = "^(0|[1-9]\\d*)\\.(0|[1-9]\\d*)\\.(0|[1-9]\\d*)(-(0|[1-9]\\d*|\\d*[a-zA-Z-][0-9a-zA-Z-]*)(\\.(0|[1-9]\\d*|\\d*[a-zA-Z-][0-9a-zA-Z-]*))*)?(\\+[0-9a-zA-Z-]+(\\.[0-9a-zA-Z-]+)*)?$" func testAttemptToOpenURL() { let url = URL(string:"foo://bar")! let mockUIApplication = MockUIApplication() let expectation = self.expectation(description: "expected MockUIApplication.openURL to fire") mockUIApplication.openURLClosure = { _ in expectation.fulfill() return true } PBMFunctions.attempt(toOpen:url, pbmUIApplication:mockUIApplication) self.waitForExpectations(timeout: 1.0, handler:nil) } func testClampInt() { var expected:Int var actual:Int //Simple expected = 5 actual = PBMFunctions.clampInt(5, lowerBound:1, upperBound:10) XCTAssert(expected == actual) //Lower than lowBound expected = 1 actual = PBMFunctions.clampInt(0, lowerBound:1, upperBound:10) XCTAssert(expected == actual) //Higher than upperBound expected = 10 actual = PBMFunctions.clampInt(1000, lowerBound:1, upperBound:10) XCTAssert(expected == actual) //Equal to upperBound expected = 10 actual = PBMFunctions.clampInt(10, lowerBound:1, upperBound:10) XCTAssert(expected == actual) //Equal to lowerBound expected = 1 actual = PBMFunctions.clampInt(1, lowerBound:1, upperBound:10) XCTAssert(expected == actual) ////////////////// //Negative Numbers ////////////////// //Simple expected = -5 actual = PBMFunctions.clampInt(-5, lowerBound:-10, upperBound:-1) XCTAssert(expected == actual) //Lower than lowBound expected = -10 actual = PBMFunctions.clampInt(-1000, lowerBound:-10, upperBound:-1) XCTAssert(expected == actual) //Higher than upperBound expected = -1 actual = PBMFunctions.clampInt(1000, lowerBound:-10, upperBound:-1) XCTAssert(expected == actual) //Equal to lowerBound expected = -10 actual = PBMFunctions.clampInt(-10, lowerBound:-10, upperBound:-1) XCTAssert(expected == actual) //Equal to upperBound expected = -1 actual = PBMFunctions.clampInt(-1, lowerBound:-10, upperBound:-1) XCTAssert(expected == actual) } func testClampDouble() { var expected:Double var actual:Double //Simple expected = 5.1 actual = PBMFunctions.clamp(5.1, lowerBound:1.1, upperBound:10.1) XCTAssert(expected == actual) //Lower than lowBound expected = 1.1 actual = PBMFunctions.clamp(0.1, lowerBound:1.1, upperBound:10.1) XCTAssert(expected == actual) //Higher than upperBound expected = 10.1 actual = PBMFunctions.clamp(1000.1, lowerBound:1.1, upperBound:10.1) XCTAssert(expected == actual) //Equal to upperBound expected = 10.1 actual = PBMFunctions.clamp(10.1, lowerBound:1.1, upperBound:10.1) XCTAssert(expected == actual) //Equal to lowerBound expected = 1.1 actual = PBMFunctions.clamp(1.1, lowerBound:1.1, upperBound:10.1) XCTAssert(expected == actual) ////////////////// //Negative Numbers ////////////////// //Simple expected = -5.1 actual = PBMFunctions.clamp(-5.1, lowerBound:-10.1, upperBound:-1.1) XCTAssert(expected == actual) //Lower than lowBound expected = -10.1 actual = PBMFunctions.clamp(-1000.1, lowerBound:-10.1, upperBound:-1.1) XCTAssert(expected == actual) //Higher than upperBound expected = -1.1 actual = PBMFunctions.clamp(1000.1, lowerBound:-10.1, upperBound:-1.1) XCTAssert(expected == actual) //Equal to lowerBound expected = -10.1 actual = PBMFunctions.clamp(-10.1, lowerBound:-10.1, upperBound:-1.1) XCTAssert(expected == actual) //Equal to upperBound expected = -1.1 actual = PBMFunctions.clamp(-1.1, lowerBound:-10.1, upperBound:-1.1) XCTAssert(expected == actual) } func testDictionaryFromDataWithEmptyData() { do { try _ = PBMFunctions.dictionaryFromData(Data()) } catch { return } XCTFail("Expected an error ") } func testDictionaryFromDataWithLocalData() { let files = ["ACJBanner.json", "ACJSingleAdWithoutSDKParams.json"] for file in files { guard let data = UtilitiesForTesting.loadFileAsDataFromBundle(file) else { XCTFail("could not load \(file)") continue } guard let jsonDict = try? PBMFunctions.dictionaryFromData(data) else { XCTFail() return } XCTAssert(jsonDict.keys.count > 0) } } func testDictionaryFromJSONString() { let jsonString = UtilitiesForTesting.loadFileAsStringFromBundle("ACJBanner.json")! guard let dict = try? PBMFunctions.dictionaryFromJSONString(jsonString) else { XCTFail() return } guard let ads = dict["ads"] as? JsonDictionary else { XCTFail() return } guard let adunits = ads["adunits"] as? [JsonDictionary] else { XCTFail() return } guard let firstAdUnit = adunits.first else { XCTFail() return } guard let auid = firstAdUnit["auid"] as? String else { XCTFail() return } XCTAssert(auid == "1610810552") } // iOS info func testBundleForSDK() { let sdkBundle = PBMFunctions.bundleForSDK() let path = sdkBundle.bundlePath do { let fileArray = try FileManager.default.contentsOfDirectory(atPath: path) for file in fileArray { Log.info("file = \(file)") } //We expect that if this is the SDK Bundle, it will contain a few files XCTAssert(fileArray.contains("mraid.js")) } catch { XCTFail("error = \(error)") } } func testInfoPlistValue() { //Basic tests var result = PBMFunctions.infoPlistValue("CFBundleExecutable") XCTAssert(result?.PBMdoesMatch("PrebidMobile") == true, "Got \(String(describing: result))") result = PBMFunctions.infoPlistValue("CFBundleIdentifier") XCTAssert(result?.PBMdoesMatch("org.prebid.mobile") == true, "Got \(String(describing: result))") //Version number should start and end with an unbroken string of numbers or periods. result = PBMFunctions.infoPlistValue("CFBundleShortVersionString") XCTAssert(result?.PBMdoesMatch(versionValidatorRegExpr) == true, "Got \(String(describing: result))") //Expected failures result = PBMFunctions.infoPlistValue("DERP") XCTAssert(result?.PBMdoesMatch("^[0-9\\.]+$") == nil, "Got \(String(describing: result))") result = PBMFunctions.infoPlistValue("aklhakfhadlskfhlkahf") XCTAssert(result == nil, "Got \(String(describing: result))") } func testsdkVersion() { let version = PBMFunctions.sdkVersion() XCTAssert(version.count > 0) XCTAssert(version.PBMdoesMatch(versionValidatorRegExpr) == true, "Got \(String(describing: version))") } func testStatusBarHeight() { let mockApplication = MockUIApplication() //Test with default (visible status bar in portrait) var expected:CGFloat = 2.0 var actual = PBMFunctions.statusBarHeight(application:mockApplication) XCTAssert(expected == actual, "Expected \(expected), got \(actual)") //Test with visible status bar in landscape mockApplication.statusBarOrientation = .landscapeLeft expected = 1.0 actual = PBMFunctions.statusBarHeight(application:mockApplication) XCTAssert(expected == actual, "Expected \(expected), got \(actual)") //Test with hidden status bar mockApplication.isStatusBarHidden = true expected = 0.0 actual = PBMFunctions.statusBarHeight(application:mockApplication) XCTAssert(expected == actual, "Expected \(expected), got \(actual)") } // MARK: JSON func testDictionaryFromDataWithInvalidData() { let data = UtilitiesForTesting.loadFileAsDataFromBundle("mraid.js")! var dict: JsonDictionary? do { dict = try PBMFunctions.dictionaryFromData(data) XCTFail("Test method should throw exception") } catch { XCTAssert(error.localizedDescription.contains("Could not convert json data to jsonObject:")) } XCTAssertNil(dict) } func testDictionaryFromDataWithInvalidJSON() { let data = "[\"A\", \"B\", \"C\"]".data(using: .utf8)! var dict: JsonDictionary? do { dict = try PBMFunctions.dictionaryFromData(data) XCTFail("Test method should throw exception") } catch { XCTAssert(error.localizedDescription.contains("Could not cast jsonObject to JsonDictionary:")) } XCTAssertNil(dict) } func testDictionaryFromData() { let data = "{\"key\" : \"value\"}".data(using: .utf8)! let dict = try! PBMFunctions.dictionaryFromData(data) XCTAssertEqual(dict["key"] as! String, "value") } func testToStringJsonDictionaryWithInvalidJSON() { let jsonDict: JsonDictionary = ["test" : UIImage()] var jsonString: String? do { jsonString = try PBMFunctions.toStringJsonDictionary(jsonDict) XCTFail("Test method should throw exception") } catch { XCTAssert(error.localizedDescription.contains("Not valid JSON object:")) } XCTAssertNil(jsonString) } func testExtractVideoAdParamsFromTheURLString() { let urlCorrectString = "http://mobile-d.openx.net/v/1.0/av?auid=540851203" let resultDict = PBMFunctions.extractVideoAdParams(fromTheURLString: urlCorrectString, forKeys: ["auid"]) XCTAssertEqual(resultDict["domain"], "mobile-d.openx.net") XCTAssertEqual(resultDict["auid"], "540851203") let urlIncorrectString = "http./mobile-d.openx.net.auid.540851203" let resultDict2 = PBMFunctions.extractVideoAdParams(fromTheURLString: urlIncorrectString, forKeys: ["auid"]) XCTAssertNil(resultDict2["domain"]) XCTAssertNil(resultDict2["auid"]) } }
apache-2.0
267dd1795ced9de6698236ab3d8cc907
32.169399
211
0.584102
4.703603
false
true
false
false
tedinpcshool/classmaster
classmaster_good/classmaster/HostViewController.swift
2
3045
// // HostViewController.swift // // Copyright 2017 Handsome LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // import UIKit import InteractiveSideMenu class HostViewController: MenuContainerViewController { override var preferredStatusBarStyle: UIStatusBarStyle { return .lightContent } override func viewDidLoad() { super.viewDidLoad() menuViewController = self.storyboard!.instantiateViewController(withIdentifier: "NavigationMenu") as! MenuViewController contentViewControllers = contentControllers() selectContentViewController(contentViewControllers.first!) } override func menuTransitionOptionsBuilder() -> TransitionOptionsBuilder? { return TransitionOptionsBuilder() { builder in builder.duration = 0.5 builder.contentScale = 1 } } @IBAction func pushBtnToMenu(_ sender: UIBarButtonItem) { showMenu() } private func contentControllers() -> [MenuItemContentViewController] { var contentList = [MenuItemContentViewController]() let introClass = UIStoryboard(name: "Intro", bundle: nil) let nIntroVC = introClass.instantiateViewController(withIdentifier: "goToIntroVC") as! MenuItemContentViewController contentList.append(nIntroVC) let priceClass = UIStoryboard(name: "Price", bundle: nil) let nPriceVC = priceClass.instantiateViewController(withIdentifier: "goToPriceVC") as! MenuItemContentViewController contentList.append(nPriceVC) let storybordClass = UIStoryboard(name: "Class", bundle: nil) let nClassVC = storybordClass.instantiateViewController(withIdentifier: "classVC") as! MenuItemContentViewController contentList.append(nClassVC) let memberClass = UIStoryboard(name: "MemArea", bundle: nil) // let nMemberVC = memberClass.instantiateViewController(withIdentifier: "MemberVC") as! MenuItemContentViewController let nWeinVC = memberClass.instantiateViewController(withIdentifier: "goToWeinVC2") as! MenuItemContentViewController contentList.append(nWeinVC) // contentList.append(self.storyboard?.instantiateViewController(withIdentifier: "First") as! MenuItemContentViewController) // contentList.append(self.storyboard?.instantiateViewController(withIdentifier: "goIntroVC") as! MenuItemContentViewController) return contentList } }
mit
e28b6ded39c4196485acae31a14cdf08
39.065789
135
0.712644
5.214041
false
false
false
false
KrauseFx/fastlane
fastlane/swift/SocketClient.swift
1
12048
// SocketClient.swift // Copyright (c) 2022 FastlaneTools // // ** NOTE ** // This file is provided by fastlane and WILL be overwritten in future updates // If you want to add extra functionality to this project, create a new file in a // new group so that it won't be marked for upgrade // import Dispatch import Foundation public enum SocketClientResponse: Error { case alreadyClosedSockets case malformedRequest case malformedResponse case serverError case clientInitiatedCancelAcknowledged case commandTimeout(seconds: Int) case connectionFailure case success(returnedObject: String?, closureArgumentValue: String?) } class SocketClient: NSObject { enum SocketStatus { case ready case closed } static let connectTimeoutSeconds = 2 static let defaultCommandTimeoutSeconds = 10800 // 3 hours static let doneToken = "done" // TODO: remove these static let cancelToken = "cancelFastlaneRun" fileprivate var inputStream: InputStream! fileprivate var outputStream: OutputStream! fileprivate var cleaningUpAfterDone = false fileprivate let dispatchGroup = DispatchGroup() fileprivate let readSemaphore = DispatchSemaphore(value: 1) fileprivate let writeSemaphore = DispatchSemaphore(value: 1) fileprivate let commandTimeoutSeconds: Int private let writeQueue: DispatchQueue private let readQueue: DispatchQueue private let streamQueue: DispatchQueue private let host: String private let port: UInt32 let maxReadLength = 65536 // max for ipc on 10.12 is kern.ipc.maxsockbuf: 8388608 ($sysctl kern.ipc.maxsockbuf) private(set) weak var socketDelegate: SocketClientDelegateProtocol? public private(set) var socketStatus: SocketStatus // localhost only, this prevents other computers from connecting init(host: String = "localhost", port: UInt32 = 2000, commandTimeoutSeconds: Int = defaultCommandTimeoutSeconds, socketDelegate: SocketClientDelegateProtocol) { self.host = host self.port = port self.commandTimeoutSeconds = commandTimeoutSeconds readQueue = DispatchQueue(label: "readQueue", qos: .background, attributes: .concurrent) writeQueue = DispatchQueue(label: "writeQueue", qos: .background, attributes: .concurrent) streamQueue = DispatchQueue.global(qos: .background) socketStatus = .closed self.socketDelegate = socketDelegate super.init() } func connectAndOpenStreams() { var readStream: Unmanaged<CFReadStream>? var writeStream: Unmanaged<CFWriteStream>? streamQueue.sync { CFStreamCreatePairWithSocketToHost(kCFAllocatorDefault, self.host as CFString, self.port, &readStream, &writeStream) self.inputStream = readStream!.takeRetainedValue() self.outputStream = writeStream!.takeRetainedValue() self.inputStream.delegate = self self.outputStream.delegate = self self.inputStream.schedule(in: .main, forMode: .defaultRunLoopMode) self.outputStream.schedule(in: .main, forMode: .defaultRunLoopMode) } dispatchGroup.enter() readQueue.sync { self.inputStream.open() } dispatchGroup.enter() writeQueue.sync { self.outputStream.open() } let secondsToWait = DispatchTimeInterval.seconds(SocketClient.connectTimeoutSeconds) let connectTimeout = DispatchTime.now() + secondsToWait let timeoutResult = dispatchGroup.wait(timeout: connectTimeout) let failureMessage = "Couldn't connect to ruby process within: \(SocketClient.connectTimeoutSeconds) seconds" let success = testDispatchTimeoutResult(timeoutResult, failureMessage: failureMessage, timeToWait: secondsToWait) guard success else { socketDelegate?.commandExecuted(serverResponse: .connectionFailure) { _ in } return } socketStatus = .ready socketDelegate?.connectionsOpened() } public func send(rubyCommand: RubyCommandable) { verbose(message: "sending: \(rubyCommand.json)") send(string: rubyCommand.json) writeSemaphore.signal() } public func sendComplete() { closeSession(sendAbort: true) } private func testDispatchTimeoutResult(_ timeoutResult: DispatchTimeoutResult, failureMessage: String, timeToWait: DispatchTimeInterval) -> Bool { switch timeoutResult { case .success: return true case .timedOut: log(message: "Timeout: \(failureMessage)") if case let .seconds(seconds) = timeToWait { socketDelegate?.commandExecuted(serverResponse: .commandTimeout(seconds: seconds)) { _ in } } return false } } private func stopInputSession() { inputStream.close() } private func stopOutputSession() { outputStream.close() } private func sendThroughQueue(string: String) { let data = string.data(using: .utf8)! data.withUnsafeBytes { (buffer: UnsafeRawBufferPointer) in if let buffer = buffer.baseAddress { self.outputStream.write(buffer.assumingMemoryBound(to: UInt8.self), maxLength: data.count) } } } private func privateSend(string: String) { writeQueue.sync { writeSemaphore.wait() self.sendThroughQueue(string: string) writeSemaphore.signal() let timeoutSeconds = self.cleaningUpAfterDone ? 1 : self.commandTimeoutSeconds let timeToWait = DispatchTimeInterval.seconds(timeoutSeconds) let commandTimeout = DispatchTime.now() + timeToWait let timeoutResult = writeSemaphore.wait(timeout: commandTimeout) _ = self.testDispatchTimeoutResult(timeoutResult, failureMessage: "Ruby process didn't return after: \(SocketClient.connectTimeoutSeconds) seconds", timeToWait: timeToWait) } } private func send(string: String) { guard !cleaningUpAfterDone else { // This will happen after we abort if there are commands waiting to be executed // Need to check state of SocketClient in command runner to make sure we can accept `send` socketDelegate?.commandExecuted(serverResponse: .alreadyClosedSockets) { _ in } return } if string == SocketClient.doneToken { cleaningUpAfterDone = true } privateSend(string: string) } func closeSession(sendAbort: Bool = true) { socketStatus = .closed stopInputSession() if sendAbort { send(rubyCommand: ControlCommand(commandType: .done)) } stopOutputSession() socketDelegate?.connectionsClosed() } public func enter() { dispatchGroup.enter() } public func leave() { readSemaphore.signal() writeSemaphore.signal() } } extension SocketClient: StreamDelegate { func stream(_ aStream: Stream, handle eventCode: Stream.Event) { guard !cleaningUpAfterDone else { // Still getting response from server eventhough we are done. // No big deal, we're closing the streams anyway. // That being said, we need to balance out the dispatchGroups dispatchGroup.leave() return } if aStream === inputStream { switch eventCode { case Stream.Event.openCompleted: dispatchGroup.leave() case Stream.Event.errorOccurred: verbose(message: "input stream error occurred") closeSession(sendAbort: true) case Stream.Event.hasBytesAvailable: read() case Stream.Event.endEncountered: // nothing special here break case Stream.Event.hasSpaceAvailable: // we don't care about this break default: verbose(message: "input stream caused unrecognized event: \(eventCode)") } } else if aStream === outputStream { switch eventCode { case Stream.Event.openCompleted: dispatchGroup.leave() case Stream.Event.errorOccurred: // probably safe to close all the things because Ruby already disconnected verbose(message: "output stream recevied error") case Stream.Event.endEncountered: // nothing special here break case Stream.Event.hasSpaceAvailable: // we don't care about this break default: verbose(message: "output stream caused unrecognized event: \(eventCode)") } } } func read() { readQueue.sync { self.readSemaphore.wait() var buffer = [UInt8](repeating: 0, count: maxReadLength) var output = "" while self.inputStream!.hasBytesAvailable { let bytesRead: Int = inputStream!.read(&buffer, maxLength: buffer.count) if bytesRead >= 0 { guard let read = String(bytes: buffer[..<bytesRead], encoding: .utf8) else { fatalError("Unable to decode bytes from buffer \(buffer[..<bytesRead])") } output.append(contentsOf: read) } else { verbose(message: "Stream read() error") } } self.processResponse(string: output) readSemaphore.signal() } } func handleFailure(message: [String]) { log(message: "Encountered a problem: \(message.joined(separator: "\n"))") let shutdownCommand = ControlCommand(commandType: .cancel(cancelReason: .serverError)) send(rubyCommand: shutdownCommand) } func processResponse(string: String) { guard !string.isEmpty else { socketDelegate?.commandExecuted(serverResponse: .malformedResponse) { self.handleFailure(message: ["empty response from ruby process"]) $0.writeSemaphore.signal() } return } let responseString = string.trimmingCharacters(in: .whitespacesAndNewlines) let socketResponse = SocketResponse(payload: responseString) verbose(message: "response is: \(responseString)") switch socketResponse.responseType { case .clientInitiatedCancel: socketDelegate?.commandExecuted(serverResponse: .clientInitiatedCancelAcknowledged) { $0.writeSemaphore.signal() self.closeSession(sendAbort: false) } case let .failure(failureInformation, failureClass, failureMessage): LaneFile.fastfileInstance?.onError(currentLane: ArgumentProcessor(args: CommandLine.arguments).currentLane, errorInfo: failureInformation.joined(), errorClass: failureClass, errorMessage: failureMessage) socketDelegate?.commandExecuted(serverResponse: .serverError) { $0.writeSemaphore.signal() self.handleFailure(message: failureInformation) } case let .parseFailure(failureInformation): socketDelegate?.commandExecuted(serverResponse: .malformedResponse) { $0.writeSemaphore.signal() self.handleFailure(message: failureInformation) } case let .readyForNext(returnedObject, closureArgumentValue): socketDelegate?.commandExecuted(serverResponse: .success(returnedObject: returnedObject, closureArgumentValue: closureArgumentValue)) { $0.writeSemaphore.signal() } } } } // Please don't remove the lines below // They are used to detect outdated files // FastlaneRunnerAPIVersion [0.9.2]
mit
d66706662c5861375d876d1694b85885
35.289157
215
0.639525
5.206569
false
false
false
false
premprakash0961988/numbergame
SwiftApp/SwiftApp/ViewController.swift
1
8574
// // ViewController.swift // SwiftApp // // Created by Prem Chaurasiya on 29/09/14. // Copyright (c) 2014 PP. All rights reserved. // import UIKit class ViewController: UIViewController { var allBoxes : [RoundedLable] = [] var selectedBoxes = [RoundedLable]() var dataSet : [UInt32] = [] var baseView : TouchableView? var operationsCollectionView : UICollectionView? var currentEquationBoard : UILabel? var scoreCard : UILabel? let shapeLayer = CAShapeLayer() let numberOfRows = 4 var selectedOperation : Operation! var boxWindow : UIWindow! override func viewDidLoad() { super.viewDidLoad() self.navigationController?.setNavigationBarHidden(true, animated: false) self.view.backgroundColor = UIColor.darkGray createScoreCard() createEquationBoard() addOperationsView() creatDataSetForRows(numberOfRows) createView(numberOfRows) selectedOperation = availableOperations().first self.view.isMultipleTouchEnabled = true } func createView (_ numberOfBoxes : NSInteger) { let viewDimension : Int = Int(self.view.frame.width - 22.0) let width : NSInteger = viewDimension / numberOfBoxes let height : NSInteger = width let frame = CGRect(x: 10, y: self.view.frame.height - CGFloat(viewDimension) - 10 , width: CGFloat(viewDimension), height: CGFloat(viewDimension)) boxWindow = UIWindow() boxWindow.frame = frame boxWindow.makeKeyAndVisible() self.baseView = TouchableView(frame: boxWindow.bounds) baseView?.delegate = self baseView?.subView.touchDelegate = self self.baseView?.backgroundColor = self.view.backgroundColor ?? UIColor.clear boxWindow.addSubview(baseView!) var x : Int = 5, y : Int = 5 let totalBoxes = numberOfBoxes * numberOfBoxes - 1 for i in 0...totalBoxes { let newLable : RoundedLable = RoundedLable(frame: CGRect(x: CGFloat(x), y: CGFloat(y), width: CGFloat(width) - 10, height: CGFloat(height) - 10)) newLable.text = NSString(format: "%d", self.dataSet[i]) as String newLable.textColor = UIColor.white newLable.color = baseView?.backgroundColor ?? UIColor.clear newLable.textAlignment = NSTextAlignment.center //newLable.font = UIFont(name: "Baskerville-SemiBold", size: ) x += width ; if(CGFloat(x) >= baseView!.frame.width) { x = 5 y += height } let toRect = newLable.frame var fromRect = toRect fromRect.origin.y = (((arc4random()%2) == 1) ? -CGFloat((arc4random()%100)) - 600 : CGFloat((arc4random()%1000)) + 600) fromRect.origin.x = (((arc4random()%2) == 1) ? -CGFloat((arc4random()%100)) - 400 : CGFloat((arc4random()%1000)) + 400) newLable.frame = fromRect let animationDuration : TimeInterval = 0.3 let delayInAnimation : TimeInterval = Double(i)*animationDuration let factor : Double = Double((arc4random()%5)) + 3 UIView.animate(withDuration: animationDuration, delay:delayInAnimation/factor, usingSpringWithDamping: 0.9, initialSpringVelocity:5, options: UIViewAnimationOptions.allowUserInteraction, animations: { () -> Void in newLable.frame = toRect }, completion: nil) baseView?.subView.addSubview(newLable) allBoxes.append(newLable) } } func creatDataSetForRows(_ numberOfBoxes : NSInteger) { let totalBoxes = numberOfBoxes * numberOfBoxes for _ in 0...totalBoxes*2 { let newInt : UInt32 = (arc4random()%20) + 1 self.dataSet.append(newInt) } } func currentStateForGame() -> RoundedLable.RoundedLabelState { var total = 0 var roundedLabelState = RoundedLable.RoundedLabelState.stateInCorrect; for (index, _) in selectedBoxes.enumerated() { let label : RoundedLable = selectedBoxes[index] let text = label.text! let number = Int(text) ?? 0 if(index == selectedBoxes.count - 1 && number == total) { roundedLabelState = RoundedLable.RoundedLabelState.stateCorrect; } else { total = label.operation.result(firstInput: total, secondInput: number) } } return roundedLabelState; } func currentEquationResult() -> Int { var total = 0 for (index, _) in selectedBoxes.enumerated() { let label : RoundedLable = selectedBoxes[index] let text = label.text! let number = Int(text) ?? 0 total = label.operation.result(firstInput: total, secondInput: number) } return total } func resetViews() { let previousScore = Int(self.scoreCard?.text ?? "0") var scoreEarned : Int = previousScore! let numberOfBoxes = selectedBoxes.count for (index, _) in selectedBoxes.enumerated() { let label : RoundedLable = selectedBoxes[index] let state = self.currentStateForGame() if(state == RoundedLable.RoundedLabelState.stateCorrect) { let value = Int(label.text ?? "0") scoreEarned += value! * numberOfBoxes //Int(pow(Double(10), Double(numberOfBoxes))) let delayTime = DispatchTime.now() + Double(Int64(0.5 * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC) DispatchQueue.main.asyncAfter(deadline: delayTime) { self.drawUserInteractions() } let delayTime1 = DispatchTime.now() + Double(Int64(2.0 * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC) DispatchQueue.global(qos: .background).asyncAfter(deadline: delayTime1) { IntelligentGuy.calculateAllPossibleOptions(self.currentData()) } UIView.animate (withDuration: 0.5, delay:0.5, usingSpringWithDamping:0.5, initialSpringVelocity: 10, options: UIViewAnimationOptions.allowUserInteraction, animations: { () -> Void in label.transform = CGAffineTransform(scaleX: 0.001, y: 0.001) }, completion: { finished in UIView.animate (withDuration: 0.5, delay:0.5, usingSpringWithDamping:0.5, initialSpringVelocity: 10, options: UIViewAnimationOptions.allowUserInteraction, animations: { () -> Void in label.transform = CGAffineTransform.identity label.text = NSString(format: "%d", self.objectForNextIndex()) as String label.setRoundedLabelState(RoundedLable.RoundedLabelState.stateUnTouched) }, completion: { finished in }) }) } else { label.setRoundedLabelState(RoundedLable.RoundedLabelState.stateUnTouched) self.drawUserInteractions() } } if(scoreEarned != previousScore) { self.setUserScore(scoreEarned) } selectedBoxes.removeAll() self.drawUserInteractions() } func setUserScore(_ score : Int) { let scoreCard : UILabel = self.scoreCard! UIView.animate (withDuration: 0.5, delay:0.5, usingSpringWithDamping:0.5, initialSpringVelocity: 10, options: UIViewAnimationOptions.allowUserInteraction, animations: { () -> Void in scoreCard.text = NSString(format: "%d", score) as String }, completion: { finished in }) } func objectForNextIndex() -> Int { return Int(arc4random())%30 } func showUserStatus() { } func currentData() -> [Int] { var data = [Int]() for box in allBoxes { let text = box.text! let number = Int(text) ?? 0 data.append(number) } return data } @IBAction func touchUpInside() { print("touchUpInside") } }
mit
dc7a8c1ca24619324e8661587fad1a4b
36.278261
226
0.572312
4.868825
false
false
false
false
jeffreybergier/SwiftLint
Source/SwiftLintFramework/Rules/RedundantStringEnumValueRule.swift
3
4659
// // RedundantStringEnumValueRule.swift // SwiftLint // // Created by Marcelo Fabri on 08/12/16. // Copyright © 2016 Realm. All rights reserved. // import Foundation import SourceKittenFramework private func children(of dict: [String: SourceKitRepresentable], matching kind: SwiftDeclarationKind) -> [[String: SourceKitRepresentable]] { return dict.substructure.flatMap { subDict in if let kindString = subDict.kind, SwiftDeclarationKind(rawValue: kindString) == kind { return subDict } return nil } } public struct RedundantStringEnumValueRule: ASTRule, ConfigurationProviderRule { public var configuration = SeverityConfiguration(.warning) public init() {} public static let description = RuleDescription( identifier: "redundant_string_enum_value", name: "Redundant String Enum Value", description: "String enum values can be omitted when they are equal to the enumcase name.", nonTriggeringExamples: [ "enum Numbers: String {\n case one\n case two\n}\n", "enum Numbers: Int {\n case one = 1\n case two = 2\n}\n", "enum Numbers: String {\n case one = \"ONE\"\n case two = \"TWO\"\n}\n", "enum Numbers: String {\n case one = \"ONE\"\n case two = \"two\"\n}\n", "enum Numbers: String {\n case one, two\n}\n" ], triggeringExamples: [ "enum Numbers: String {\n case one = ↓\"one\"\n case two = ↓\"two\"\n}\n", "enum Numbers: String {\n case one = ↓\"one\", two = ↓\"two\"\n}\n", "enum Numbers: String {\n case one, two = ↓\"two\"\n}\n" ] ) public func validate(file: File, kind: SwiftDeclarationKind, dictionary: [String: SourceKitRepresentable]) -> [StyleViolation] { guard kind == .enum else { return [] } // Check if it's a String enum guard dictionary.inheritedTypes.contains("String") else { return [] } let violations = violatingOffsetsForEnum(dictionary: dictionary, file: file) return violations.map { StyleViolation(ruleDescription: type(of: self).description, severity: configuration.severity, location: Location(file: file, byteOffset: $0)) } } private func violatingOffsetsForEnum(dictionary: [String: SourceKitRepresentable], file: File) -> [Int] { var caseCount = 0 var violations = [Int]() for enumCase in children(of: dictionary, matching: .enumcase) { caseCount += enumElementsCount(dictionary: enumCase) violations += violatingOffsetsForEnumCase(dictionary: enumCase, file: file) } guard violations.count == caseCount else { return [] } return violations } private func enumElementsCount(dictionary: [String: SourceKitRepresentable]) -> Int { return children(of: dictionary, matching: .enumelement).filter({ element in return !filterEnumInits(dictionary: element).isEmpty }).count } private func violatingOffsetsForEnumCase(dictionary: [String: SourceKitRepresentable], file: File) -> [Int] { return children(of: dictionary, matching: .enumelement).flatMap { element -> [Int] in guard let name = element.name else { return [] } return violatingOffsetsForEnumElement(dictionary: element, name: name, file: file) } } private func violatingOffsetsForEnumElement(dictionary: [String: SourceKitRepresentable], name: String, file: File) -> [Int] { let enumInits = filterEnumInits(dictionary: dictionary) return enumInits.flatMap { dictionary -> Int? in guard let offset = dictionary.offset, let length = dictionary.length else { return nil } // the string would be quoted if offset and length were used directly let enumCaseName = file.contents.bridge() .substringWithByteRange(start: offset + 1, length: length - 2) ?? "" guard enumCaseName == name else { return nil } return offset } } private func filterEnumInits(dictionary: [String: SourceKitRepresentable]) -> [[String: SourceKitRepresentable]] { return dictionary.elements.filter { $0.kind == "source.lang.swift.structure.elem.init_expr" } } }
mit
cd148e098d14505984784d9c466dbb8a
37.098361
118
0.596816
4.841667
false
false
false
false
jpsim/SourceKitten
Source/SourceKittenFramework/SwiftDeclarationAttributeKind.swift
1
9762
/// Swift declaration attribute kinds. /// Found in `strings SourceKitService | grep source.decl.attribute.`. public enum SwiftDeclarationAttributeKind: String, CaseIterable { case ibaction = "source.decl.attribute.ibaction" case iboutlet = "source.decl.attribute.iboutlet" case ibdesignable = "source.decl.attribute.ibdesignable" case ibinspectable = "source.decl.attribute.ibinspectable" case gkinspectable = "source.decl.attribute.gkinspectable" case objc = "source.decl.attribute.objc" case objcName = "source.decl.attribute.objc.name" case silgenName = "source.decl.attribute._silgen_name" case available = "source.decl.attribute.available" case `final` = "source.decl.attribute.final" case `required` = "source.decl.attribute.required" case `optional` = "source.decl.attribute.optional" case noreturn = "source.decl.attribute.noreturn" case epxorted = "source.decl.attribute._exported" case nsCopying = "source.decl.attribute.NSCopying" case nsManaged = "source.decl.attribute.NSManaged" case `lazy` = "source.decl.attribute.lazy" case lldbDebuggerFunction = "source.decl.attribute.LLDBDebuggerFunction" case uiApplicationMain = "source.decl.attribute.UIApplicationMain" case unsafeNoObjcTaggedPointer = "source.decl.attribute.unsafe_no_objc_tagged_pointer" case inline = "source.decl.attribute.inline" case semantics = "source.decl.attribute._semantics" case dynamic = "source.decl.attribute.dynamic" case infix = "source.decl.attribute.infix" case prefix = "source.decl.attribute.prefix" case postfix = "source.decl.attribute.postfix" case transparent = "source.decl.attribute._transparent" case requiresStoredProperyInits = "source.decl.attribute.requires_stored_property_inits" case nonobjc = "source.decl.attribute.nonobjc" case fixedLayout = "source.decl.attribute._fixed_layout" case inlineable = "source.decl.attribute._inlineable" case specialize = "source.decl.attribute._specialize" case objcMembers = "source.decl.attribute.objcMembers" case mutating = "source.decl.attribute.mutating" case nonmutating = "source.decl.attribute.nonmutating" case convenience = "source.decl.attribute.convenience" case `override` = "source.decl.attribute.override" case silStored = "source.decl.attribute.sil_stored" case `weak` = "source.decl.attribute.weak" case effects = "source.decl.attribute.effects" case objcBriged = "source.decl.attribute.__objc_bridged" case nsApplicationMain = "source.decl.attribute.NSApplicationMain" case objcNonLazyRealization = "source.decl.attribute.objc_non_lazy_realization" case synthesizedProtocol = "source.decl.attribute.__synthesized_protocol" case testable = "source.decl.attribute.testable" case alignment = "source.decl.attribute._alignment" case `rethrows` = "source.decl.attribute.rethrows" case swiftNativeObjcRuntimeBase = "source.decl.attribute._swift_native_objc_runtime_base" case indirect = "source.decl.attribute.indirect" case warnUnqualifiedAccess = "source.decl.attribute.warn_unqualified_access" case cdecl = "source.decl.attribute._cdecl" case versioned = "source.decl.attribute._versioned" case discardableResult = "source.decl.attribute.discardableResult" case implements = "source.decl.attribute._implements" case objcRuntimeName = "source.decl.attribute._objcRuntimeName" case staticInitializeObjCMetadata = "source.decl.attribute._staticInitializeObjCMetadata" case restatedObjCConformance = "source.decl.attribute._restatedObjCConformance" // only available in Swift >= 4.1 case `private` = "source.decl.attribute.private" case `fileprivate` = "source.decl.attribute.fileprivate" case `internal` = "source.decl.attribute.internal" case `public` = "source.decl.attribute.public" case `open` = "source.decl.attribute.open" case setterPrivate = "source.decl.attribute.setter_access.private" case setterFilePrivate = "source.decl.attribute.setter_access.fileprivate" case setterInternal = "source.decl.attribute.setter_access.internal" case setterPublic = "source.decl.attribute.setter_access.public" case setterOpen = "source.decl.attribute.setter_access.open" case optimize = "source.decl.attribute._optimize" case consuming = "source.decl.attribute.__consuming" case implicitlyUnwrappedOptional = "source.decl.attribute._implicitly_unwrapped_optional" // only available in Swift >= 4.1.50 case underscoredObjcNonLazyRealization = "source.decl.attribute._objc_non_lazy_realization" case clangImporterSynthesizedType = "source.decl.attribute._clangImporterSynthesizedType" case forbidSerializingReference = "source.decl.attribute._forbidSerializingReference" case usableFromInline = "source.decl.attribute.usableFromInline" case weakLinked = "source.decl.attribute._weakLinked" case inlinable = "source.decl.attribute.inlinable" case dynamicMemberLookup = "source.decl.attribute.dynamicMemberLookup" case _frozen = "source.decl.attribute._frozen" // only available in Swift < 4.1 case autoclosure = "source.decl.attribute.autoclosure" case noescape = "source.decl.attribute.noescape" // only available in Swift >= 5.0 case __raw_doc_comment = "source.decl.attribute.__raw_doc_comment" case __setter_access = "source.decl.attribute.__setter_access" case _borrowed = "source.decl.attribute._borrowed" case _dynamicReplacement = "source.decl.attribute._dynamicReplacement" case _effects = "source.decl.attribute._effects" case _hasInitialValue = "source.decl.attribute._hasInitialValue" case _hasStorage = "source.decl.attribute._hasStorage" case _nonoverride = "source.decl.attribute._nonoverride" case _private = "source.decl.attribute._private" case _show_in_interface = "source.decl.attribute._show_in_interface" case dynamicCallable = "source.decl.attribute.dynamicCallable" // only available in Swift >= 5.1 case frozen = "source.decl.attribute.frozen" case _projectedValueProperty = "source.decl.attribute._projectedValueProperty" case _alwaysEmitIntoClient = "source.decl.attribute._alwaysEmitIntoClient" case _implementationOnly = "source.decl.attribute._implementationOnly" case ibsegueaction = "source.decl.attribute.ibsegueaction" case _custom = "source.decl.attribute._custom" case _disfavoredOverload = "source.decl.attribute._disfavoredOverload" case propertyWrapper = "source.decl.attribute.propertyWrapper" case IBSegueAction = "source.decl.attribute.IBSegueAction" case _functionBuilder = "source.decl.attribute._functionBuilder" // Only available in Swift >= 5.2 case differentiable = "source.decl.attribute.differentiable" case _nonEphemeral = "source.decl.attribute._nonEphemeral" case _originallyDefinedIn = "source.decl.attribute._originallyDefinedIn" case _inheritsConvenienceInitializers = "source.decl.attribute._inheritsConvenienceInitializers" case _hasMissingDesignatedInitializers = "source.decl.attribute._hasMissingDesignatedInitializers" // Only available in Swift >= 5.3 case _spi = "source.decl.attribute._spi" case _typeEraser = "source.decl.attribute._typeEraser" case derivative = "source.decl.attribute.derivative" case main = "source.decl.attribute.main" case noDerivative = "source.decl.attribute.noDerivative" case transpose = "source.decl.attribute.transpose" // Only available in Swift >= 5.4 case _specializeExtension = "source.decl.attribute._specializeExtension" case actor = "source.decl.attribute.actor" case actorIndependent = "source.decl.attribute.actorIndependent" case async = "source.decl.attribute.async" case asyncHandler = "source.decl.attribute.asyncHandler" case globalActor = "source.decl.attribute.globalActor" case resultBuilder = "source.decl.attribute.resultBuilder" // Only available in Swift >= 5.5 case spawn = "source.decl.attribute.spawn" case _unsafeMainActor = "source.decl.attribute._unsafeMainActor" case _unsafeSendable = "source.decl.attribute._unsafeSendable" case isolated = "source.decl.attribute.isolated" case _inheritActorContext = "source.decl.attribute._inheritActorContext" case nonisolated = "source.decl.attribute.nonisolated" case _implicitSelfCapture = "source.decl.attribute._implicitSelfCapture" case completionHandlerAsync = "source.decl.attribute.completionHandlerAsync" case _marker = "source.decl.attribute._marker" case reasync = "source.decl.attribute.reasync" case Sendable = "source.decl.attribute.Sendable" // Only available in Swift >= 5.6 case distributed = "source.decl.attribute.distributed" case _unavailableFromAsync = "source.decl.attribute._unavailableFromAsync" case preconcurrency = "source.decl.attribute.preconcurrency" case _assemblyVision = "source.decl.attribute._assemblyVision" case _const = "source.decl.attribute._const" case _typeSequence = "source.decl.attribute._typeSequence" case _nonSendable = "source.decl.attribute._nonSendable" case _noAllocation = "source.decl.attribute._noAllocation" case _noImplicitCopy = "source.decl.attribute._noImplicitCopy" case _noLocks = "source.decl.attribute._noLocks" // Only available in Swift >= 5.7 case _local = "source.decl.attribute._local" case _backDeploy = "source.decl.attribute._backDeploy" case exclusivity = "source.decl.attribute.exclusivity" case _unsafeInheritExecutor = "source.decl.attribute._unsafeInheritExecutor" case _compilerInitialized = "source.decl.attribute._compilerInitialized" }
mit
59746568cc48227c7dbf6f9ad1e08372
55.755814
102
0.750051
4.146984
false
false
false
false
makingsensetraining/mobile-pocs
IOS/SwiftSeedProject/SwiftSeedProject/Infrastructure/PersistenceData.swift
1
3106
// // PersistenceData.swift // SwiftSeedProject // // Created by Lucas Pelizza on 4/10/17. // Copyright © 2017 Making Sense. All rights reserved. // import Foundation import CoreData class PersistenceData: Persistence { static let NotificationTag = "%@EntityHasChanged" let coreDataManager: CoreDataStack init(coreDataManager: CoreDataStack) { self.coreDataManager = coreDataManager } public func getAll<T: PersistenceObject>(entityName: String) -> [T] { let objectContext = coreDataManager.mainManagedObjectContext let fetch = NSFetchRequest<NSFetchRequestResult>(entityName: entityName) do { let fetchedObjects = try objectContext.fetch(fetch) as! [T] return fetchedObjects } catch let error as NSError { fatalError("Failed to fetch \(entityName): \(error)") } return [] } public func getCustomBy<T: PersistenceObject>(attributeName: String, attributeValue: String) -> T? { let objectContext = coreDataManager.mainManagedObjectContext let fetch: NSFetchRequest<NSFetchRequestResult> = T.fetchRequest() fetch.predicate = NSPredicate(format: "(%@ = %@)", attributeName, attributeValue) fetch.fetchLimit = 1 do { let fetchedObjects = try objectContext.fetch(fetch) return fetchedObjects.count > 0 ? fetchedObjects.item(at: 0) as? T : nil } catch let error as NSError { fatalError("Failed to fetch \(T.EntityName): \(error)") } } public func getBy<T: PersistenceObject>(entityIdentifier: String) -> T? { return getCustomBy(attributeName: "identifier", attributeValue: entityIdentifier) } public func add<T: PersistenceObject>(attributes: [String : AnyObject]? = nil, entityName: String) -> T { let objectContext = coreDataManager.mainManagedObjectContext let entity = NSEntityDescription.entity(forEntityName: entityName, in: objectContext)! let entityModel = NSManagedObject(entity: entity, insertInto: objectContext) if let attributes = attributes { for (key, value) in attributes { entityModel.setValue(value, forKey: key) } } do { try objectContext.save() return entityModel as! T } catch let error as NSError { fatalError("Failed to save one new \(entityName): \(error)") } } public func addAll<T: PersistenceObject>(entity: [T], entityName: String) { preconditionFailure("This method must be completed") } public func save() { coreDataManager.saveChanges() } public func getNotificationTagfor(entity: String) -> String { return String(format: PersistenceData.NotificationTag, entity) } private func entityHasChanged(entity: String) { let nc = NotificationCenter.default nc.post(name:NSNotification.Name(rawValue: getNotificationTagfor(entity: entity)), object: nil) } }
mit
19fd8c5e5052fd5e80559bf8b9d67d74
35.104651
109
0.6438
5.040584
false
false
false
false
huang-kun/YJKit
Example/Tests/YJKVOTest_Swift.swift
1
2213
// // YJKVOTest_Swift.swift // YJKit // // Created by huang-kun on 16/7/21. // Copyright © 2016年 huang-kun. All rights reserved. // import XCTest class YJKVOTest_Swift: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testExample() { // This is an example of a functional test case. // Use XCTAssert and related functions to verify your tests produce the correct results. } func testPerformanceExample() { // This is an example of a performance test case. self.measureBlock { // Put the code you want to measure the time of here. } } func testObserve() { let foo = Foo() let bar = Bar() foo.observe(PACK(bar, "name")) { (_, _, newValue) in print("\(newValue)") } bar.name = "Bar" bar.name = "Barrrrrrr" } func testBind() { let foo = Foo() let bar = Bar() PACK(foo, "name").boundTo(PACK(bar, "name")) bar.name = "Bar" XCTAssert(foo.name == "Bar") bar.name = "Barrrrrrr" XCTAssert(foo.name == "Barrrrrrr") } func testPipe() { let foo = Foo() let bar = Bar() PACK(foo, "name").boundTo(PACK(bar, "name")) .filter { (newValue) -> Bool in if let name = newValue as? String { return name.characters.count > 3 } return false } .convert { (newValue) -> AnyObject in let name = newValue as! String return name.uppercaseString } .applied { print("value updated.") } bar.name = "Bar" XCTAssert(foo.name == nil) bar.name = "Barrrr" XCTAssert(foo.name == "BARRRR") } }
mit
fcd7c8306fb073b589da8dcf0b48fae7
24.697674
111
0.508597
4.341847
false
true
false
false
Francescu/WatchTV
TV/TVProgram.swift
1
3677
// // TVProgram.swift // TV // // Created by Francescu on 01/05/2015. // Copyright (c) 2015 Francescu. All rights reserved. // import Foundation import Timepiece extension NSDate { func isAfter(dateToCompare : NSDate) -> Bool { //Declare Variables var isGreater = false //Compare Values if self.compare(dateToCompare) == NSComparisonResult.OrderedDescending { isGreater = true } //Return Result return isGreater } func isBefore(dateToCompare : NSDate) -> Bool { //Declare Variables var isLess = false //Compare Values if self.compare(dateToCompare) == NSComparisonResult.OrderedAscending { isLess = true } //Return Result return isLess } func isSame(dateToCompare : NSDate) -> Bool { //Declare Variables var isEqualTo = false //Compare Values if self.compare(dateToCompare) == NSComparisonResult.OrderedSame { isEqualTo = true } //Return Result return isEqualTo } } enum DataState { case Data(FormatedContentType, String) case NotYet static func dateString() -> String { return NSDate().stringFromFormat("YYYY-MM-DD") } func data() -> FormatedContentType? { switch self { case let .Data(data, dateString) where dateString == DataState.dateString(): return data default: return nil } } } enum TVChannel:String { case TF1 = "tf1", France2 = "france2", France3 = "france3", CanalPlus = "canalp", France5 = "france5", M6 = "m6", Arte = "arte", Direct8 = "d8", W9 = "w9" case TMC = "tmc", NT1 = "nt1", NRJ12 = "nrj12" func imageName() -> String { return self.rawValue } } @objc(TVProgram) class TVProgram:NSObject, NSCoding { let channel:String let beginAt:NSDate let endAt:NSDate? let name:String let content:String? @objc init (channel:String, beginAt:NSDate, endAt:NSDate?, name:String, content:String? = nil) { self.channel = channel self.beginAt = beginAt self.endAt = endAt self.name = name self.content = content } required init(coder aDecoder: NSCoder) { self.channel = aDecoder.decodeObjectForKey("channel") as! String self.beginAt = aDecoder.decodeObjectForKey("beginAt") as! NSDate self.endAt = aDecoder.decodeObjectForKey("endAt") as? NSDate self.name = aDecoder.decodeObjectForKey("name") as! String self.content = aDecoder.decodeObjectForKey("content") as? String super.init() } func encodeWithCoder(aCoder: NSCoder) { aCoder.encodeObject(self.channel, forKey: "channel") aCoder.encodeObject(self.beginAt, forKey: "beginAt") aCoder.encodeObject(self.endAt, forKey: "endAt") aCoder.encodeObject(self.name, forKey: "name") aCoder.encodeObject(self.content, forKey: "content") } // // func programWithEndDate(endAt:NSDate) -> TVProgram { // return TVProgram(channel: channel, beginAt: beginAt, endAt: endAt, name: name, content: content) // } } func programNow(programs:[TVProgram]) -> TVProgram { let now = NSDate() return programs.reduce(programs[0]) { buffer, element in if element.beginAt.isAfter(now) { return buffer } if element.beginAt.isAfter(buffer.beginAt) { return element } return buffer } }
mit
a1f9b1ab933f39a8ffa2af1b33e27d94
25.453237
158
0.591515
4.245958
false
false
false
false
the-blue-alliance/the-blue-alliance-ios
the-blue-alliance-ios/Protocols/Stateful.swift
1
1447
import Foundation import UIKit protocol Stateful: AnyObject { var noDataViewController: NoDataViewController { get set } /** The string to dispaly in the no data view. */ var noDataText: String? { get } /** Add the no data view to the view hierarchy. This method should not be called directly - you probably want showNoDataView. */ func addNoDataView(_ noDataView: UIView) /** Remove the no data view from the view hierarchy. This method should not be called directly - you probably want removeNoDataView. */ func removeNoDataView(_ noDataView: UIView) } extension Stateful { /** Remove the no data view from the view hierarchy. */ func removeNoDataView() { removeNoDataView(noDataViewController.view) } } extension Stateful where Self: Refreshable { /** Show the no data view in the view hierarchy. */ func showNoDataView() { if isRefreshing { return } noDataViewController.textLabel?.text = noDataText let noDataView = noDataViewController.view as UIView // If the no data view is already in our view hierarchy, don't animate in if noDataView.superview != nil { return } noDataView.alpha = 0 addNoDataView(noDataView) UIView.animate(withDuration: 0.25, animations: { noDataView.alpha = 1.0 }) } }
mit
e825cac442a6b95234af267c6f790b74
22.721311
133
0.636489
4.791391
false
false
false
false
mlgoogle/viossvc
viossvc/Scenes/Home/ActivityVC.swift
1
1434
// // AttentionUsController.swift // wp // // Created by macbook air on 16/12/23. // Copyright © 2016年 com.yundian. All rights reserved. // import UIKit class ActivityVC: UIViewController,UIWebViewDelegate { let webView = UIWebView() var urlString: String? var isRefresh: (()->())? override func viewDidLoad() { super.viewDidLoad() view.addSubview(webView) webView.frame = view.frame webView.delegate = self webView.backgroundColor = UIColor.whiteColor() view.backgroundColor = UIColor.whiteColor() let url = NSURL(string: "http://www.yundiantrip.com/") let request = NSURLRequest(URL: url!) webView.loadRequest(request) let leftBtn = UIButton(frame: CGRect(x: 0, y: 0, width: 12, height: 20)) leftBtn.setImage(UIImage.init(named: "return"), forState: UIControlState.Normal) leftBtn.addTarget(self, action: #selector(didBack), forControlEvents: UIControlEvents.TouchUpInside) navigationItem.leftBarButtonItem = UIBarButtonItem(customView: leftBtn) } //自定义导航栏返回按钮 func didBack() { isRefresh!() navigationController?.popViewControllerAnimated(true) } func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool { return true } }
apache-2.0
635d0bd3d7cb19e38ab56a32c98eeeaa
31.068182
137
0.661233
4.750842
false
false
false
false
narner/AudioKit
Playgrounds/AudioKitPlaygrounds/Playgrounds/Synthesis.playground/Pages/Sawtooth Wave Oscillator Operation.xcplaygroundpage/Contents.swift
1
653
//: ## Sawtooth Wave Oscillator Operation //: Maybe the most annoying sound ever. Sorry. import AudioKitPlaygrounds import AudioKit //: Set up the operations that will be used to make a generator node let generator = AKOperationGenerator { _ in let freq = AKOperation.jitter(amplitude: 200, minimumFrequency: 1, maximumFrequency: 10) + 200 let amp = AKOperation.randomVertexPulse(minimum: 0, maximum: 0.3, updateFrequency: 1) return AKOperation.sawtoothWave(frequency: freq, amplitude: amp) } AudioKit.output = generator AudioKit.start() generator.start() import PlaygroundSupport PlaygroundPage.current.needsIndefiniteExecution = true
mit
fd91b37d665ad1fe350cabadc7caab5b
31.65
98
0.776417
4.472603
false
false
false
false
ru-kio/Hydra
FXHydra/FXRecommendationsController.swift
3
7588
// // FXRecommendationsController.swift // FXHydra // // Created by kioshimafx on 5/9/16. // Copyright © 2016 FXSolutions. All rights reserved. // import UIKit class FXRecommendationsController: UITableViewController { var recommendAudios = [FXAudioItemModel]() var target_string:String! override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) { super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) } init(style: UITableViewStyle,target:String) { super.init(style: style) self.target_string = target } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() // Uncomment the following line to preserve selection between presentations // self.clearsSelectionOnViewWillAppear = false // Uncomment the following line to display an Edit button in the navigation bar for this view controller. // self.navigationItem.rightBarButtonItem = self.editButtonItem() self.title = "Recommendations" self.tableViewStyle() self.tableView.registerClass(FXDefaultMusicCell.self, forCellReuseIdentifier: "FXDefaultMusicCell") self.loadContent() } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) self.navigationController?.navigationBar.translucent = false } override func viewWillDisappear(animated: Bool) { super.viewWillDisappear(animated) self.navigationController?.navigationBar.translucent = true } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func tableViewStyle() { self.tableView.tableFooterView = UIView() self.tableView.separatorInset = UIEdgeInsetsMake(0, 50, 0, 0) self.tableView.indicatorStyle = UIScrollViewIndicatorStyle.White self.definesPresentationContext = true self.extendedLayoutIncludesOpaqueBars = true self.tableView.backgroundColor = UIColor ( red: 0.2228, green: 0.2228, blue: 0.2228, alpha: 1.0 ) self.tableView.separatorColor = UIColor ( red: 0.2055, green: 0.2015, blue: 0.2096, alpha: 1.0 ) self.view.backgroundColor = UIColor ( red: 0.1221, green: 0.1215, blue: 0.1227, alpha: 1.0 ) } func animateTable() { self.tableView.reloadData() //// let cells = tableView.visibleCells let tableHeight: CGFloat = tableView.bounds.size.height for i in cells { let cell: UITableViewCell = i as UITableViewCell cell.transform = CGAffineTransformMakeTranslation(0, tableHeight) } var index = 0 for a in cells { let cell: UITableViewCell = a as UITableViewCell UIView.animateWithDuration(0.5, delay: 0.05 * Double(index), usingSpringWithDamping: 0.8, initialSpringVelocity: 0, options: [], animations: { cell.transform = CGAffineTransformMakeTranslation(0, 0); }, completion: nil) index += 1 } } // MARK: - Table view data source override func numberOfSectionsInTableView(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 self.recommendAudios.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let auidoModel = self.recommendAudios[indexPath.row] let cell = tableView.dequeueReusableCellWithIdentifier("FXDefaultMusicCell", forIndexPath: indexPath) as! FXDefaultMusicCell cell.bindedAudioModel = auidoModel return cell } override func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) { let musicModel = self.recommendAudios[indexPath.row] self.drawMusicCell(cell as! FXDefaultMusicCell, audioModel: musicModel) } override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { return 60 } override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { tableView.deselectRowAtIndexPath(indexPath, animated: true) FXPlayerService.sharedManager().currentAudiosArray = self.recommendAudios FXPlayerService.sharedManager().currentAudioIndexInArray = indexPath.row FXPlayerService.sharedManager().startPlayAtIndex() self.tableView.updateWithBlock { (tableView) -> Void in tableView.reloadRow(UInt(indexPath.row), inSection: UInt(indexPath.section), withRowAnimation: UITableViewRowAnimation.None) } /// self.navigationController?.popViewControllerAnimated(true) } // MARK: - Drawing cells func drawMusicCell(cell:FXDefaultMusicCell,audioModel:FXAudioItemModel) { cell.audioAristLabel.text = audioModel.artist cell.audioTitleLabel.text = audioModel.title cell.audioTimeLabel.text = audioModel.getDurationString() if FXDataService.sharedManager().checkAudioIdInDownloads(audioModel.audioID) == false { cell.downloadButton.setImage(UIImage(named: "download_button"), forState: UIControlState.Normal) cell.downloadButton.tintColor = UIColor ( red: 0.0, green: 0.8408, blue: 1.0, alpha: 1.0) cell.downloadButton.addTarget(self, action: #selector(FXAllAudiosController.startDownload(_:)), forControlEvents: UIControlEvents.TouchUpInside) } else { cell.downloadButton.hidden = true } /// if audioModel.bitrate > 0 { cell.audioBitrate.text = "\(audioModel.bitrate)" cell.bitRateBackgroundImage.image = bitrateImageBlue } else { cell.bitRateBackgroundImage.image = bitrateImageDark cell.audioBitrate.text = "●●●" audioModel.getBitrate { (bitrate) -> () in cell.audioBitrate.text = "\(bitrate)" cell.bitRateBackgroundImage.image = bitrateImageBlue } } /// } func startDownload(sender:AnyObject?) { log.debug("::: sender \(sender) :::") let superView = sender?.superview!!.superview as! FXDefaultMusicCell let audioModel = superView.bindedAudioModel FXDownloadsPoolService.sharedManager().downloadAudioOnLocalStorage(audioModel) } func loadContent() { FXApiManager.sharedManager().vk_audioGetRecommendations(self.target_string, offset: 0, count: 50) { (audios) in self.recommendAudios = audios self.animateTable() } } }
mit
9314b5bb266086fd24b668929594df67
31.818182
156
0.631183
5.327477
false
false
false
false
nghialv/Sapporo
Example/Example/Source/Simple/SimpleCell.swift
1
950
// // SimpleCell.swift // Example // // Created by Le VanNghia on 6/29/15. // Copyright (c) 2015 Le Van Nghia. All rights reserved. // import UIKit import Sapporo final class SimpleCellModel: SACellModel { let title: String var des: String init(title: String, des: String, selectionHandler: ((SACell) -> Void)?) { self.title = title self.des = des super.init(cellType: SimpleCell.self, size: .init(width: 110, height: 110), selectionHandler: selectionHandler) } } final class SimpleCell: SACell, SACellType { typealias CellModel = SimpleCellModel @IBOutlet weak var titleLabel: UILabel! @IBOutlet weak var desLabel: UILabel! override func configure() { super.configure() guard let cellmodel = cellmodel else { return } titleLabel.text = cellmodel.title desLabel.text = cellmodel.des } }
mit
f255b8116ce7ca0e80f4ee68a86a3fc0
22.75
119
0.622105
4.185022
false
false
false
false
KitoHo/reicast-emulator
shell/apple/emulator-osx/emulator-osx/EmuGLView.swift
4
2124
// // EmuGLView.swift // emulator-osx // // Created by admin on 8/5/15. // Copyright (c) 2015 reicast. All rights reserved. // import Cocoa class EmuGLView: NSOpenGLView { override var acceptsFirstResponder: Bool { return true; } override func drawRect(dirtyRect: NSRect) { super.drawRect(dirtyRect) // Drawing code here. // screen_width = view.drawableWidth; // screen_height = view.drawableHeight; //glClearColor(0.65f, 0.65f, 0.65f, 1.0f); //glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); openGLContext!.makeCurrentContext() while !emu_single_frame(Int32(dirtyRect.width), Int32(dirtyRect.height)) { } openGLContext!.flushBuffer() } override func awakeFromNib() { var renderTimer = NSTimer.scheduledTimerWithTimeInterval(0.001, target: self, selector: Selector("timerTick"), userInfo: nil, repeats: true) NSRunLoop.currentRunLoop().addTimer(renderTimer, forMode: NSDefaultRunLoopMode); NSRunLoop.currentRunLoop().addTimer(renderTimer, forMode: NSEventTrackingRunLoopMode); let attrs:[NSOpenGLPixelFormatAttribute] = [ UInt32(NSOpenGLPFADoubleBuffer), UInt32(NSOpenGLPFADepthSize), UInt32(24), // Must specify the 3.2 Core Profile to use OpenGL 3.2 UInt32(NSOpenGLPFAOpenGLProfile), UInt32(NSOpenGLProfileVersion3_2Core), UInt32(0) ] let pf = NSOpenGLPixelFormat(attributes:attrs) let context = NSOpenGLContext(format: pf!, shareContext: nil); self.pixelFormat = pf; self.openGLContext = context; openGLContext!.makeCurrentContext() emu_gles_init(); } func timerTick() { self.needsDisplay = true; } override func keyDown(e: NSEvent) { emu_key_input(e.characters!, 1); } override func keyUp(e: NSEvent) { emu_key_input(e.characters!, 0); } }
gpl-2.0
6fc1a9f4b9253c34b04f71bceeff9b48
27.702703
148
0.596045
4.325866
false
false
false
false
moonrailgun/OpenCode
OpenCode/Classes/RepositoryDetail/Controller/RepoBranchController.swift
1
2494
// // RepoBranchController.swift // OpenCode // // Created by 陈亮 on 16/5/27. // Copyright © 2016年 moonrailgun. All rights reserved. // import UIKit import SwiftyJSON class RepoBranchController: UIViewController, UITableViewDataSource, UITableViewDelegate { let BRANCH_CELL_ID = "branch" var tableView:UITableView? var rawData:AnyObject? var data:JSON? override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. initView() initData() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func initView(){ tableView = UITableView(frame: self.view.bounds, style: .Plain) tableView?.dataSource = self tableView?.delegate = self self.view.addSubview(tableView!) } func initData(){ if let raw = rawData{ self.data = JSON(raw) tableView?.reloadData() } } func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if let d = data{ return d.count }else{ return 0 } } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { var cell = tableView.dequeueReusableCellWithIdentifier(BRANCH_CELL_ID) if(cell == nil){ cell = UITableViewCell(style: .Default, reuseIdentifier: BRANCH_CELL_ID) cell?.accessoryType = .DisclosureIndicator } if let d = self.data{ let branch = d[indexPath.row] cell?.textLabel?.text = branch["name"].string } return cell! } func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { print(indexPath) print("未完成") } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
gpl-2.0
b1f55b3b76ac540ab73a10d2cc134729
26.263736
109
0.611447
5.104938
false
false
false
false
nessBautista/iOSBackup
iOSNotebook/Pods/Outlaw/Sources/Outlaw/Extractable+ValueWithContext.swift
1
5873
// // Extractable+ValueWithContext.swift // Outlaw // // Created by Brian Mullen on 11/15/16. // Copyright © 2016 Molbie LLC. All rights reserved. // import Foundation // MARK: - // MARK: ValueWithContext public extension Extractable { public func value<V: ValueWithContext>(for key: Key, using context: V.Context) throws -> V { let any = try self.any(for: key) do { guard let result = try V.value(from: any, using: context) as? V else { throw OutlawError.typeMismatchWithKey(key: key.outlawKey, expected: V.self, actual: any) } return result } catch let OutlawError.typeMismatch(expected: expected, actual: actual) { throw OutlawError.typeMismatchWithKey(key: key.outlawKey, expected: expected, actual: actual) } } public func value<V: ValueWithContext>(for key: Key, using context: V.Context) -> V? { return try? self.value(for: key, using: context) } public func value<V: ValueWithContext>(for key: Key, using context: V.Context, or value: V) -> V { guard let result: V = self.value(for: key, using: context) else { return value } return result } } // MARK: - // MARK: ValueWithContext Array public extension Extractable { public func value<V: ValueWithContext>(for key: Key, using context: V.Context) throws -> [V] { let any = try self.any(for: key) do { return try Array<V>.mappedValue(from: any, using: context) } catch let OutlawError.typeMismatch(expected: expected, actual: actual) { throw OutlawError.typeMismatchWithKey(key: key.outlawKey, expected: expected, actual: actual) } } public func value<V: ValueWithContext>(for key: Key, using context: V.Context) -> [V]? { return try? self.value(for: key, using: context) } public func value<V: ValueWithContext>(for key: Key, using context: V.Context, or value: [V]) -> [V] { guard let result: [V] = self.value(for: key, using: context) else { return value } return result } } // MARK: - // MARK: Optional ValueWithContext Array public extension Extractable { public func value<V: ValueWithContext>(for key: Key, using context: V.Context) throws -> [V?] { let any = try self.any(for: key) do { return try Array<V?>.mappedValue(from: any, using: context) } catch let OutlawError.typeMismatch(expected: expected, actual: actual) { throw OutlawError.typeMismatchWithKey(key: key.outlawKey, expected: expected, actual: actual) } } public func value<V: ValueWithContext>(for key: Key, using context: V.Context) -> [V?]? { return try? self.value(for: key, using: context) } public func value<V: ValueWithContext>(for key: Key, using context: V.Context, or value: [V?]) -> [V?] { guard let result: [V?] = self.value(for: key, using: context) else { return value } return result } } // MARK: - // MARK: ValueWithContext Dictionary public extension Extractable { public func value<K, V: ValueWithContext>(for key: Key, using context: V.Context) throws -> [K: V] { let any = try self.any(for: key) do { return try Dictionary<K, V>.mappedValue(from: any, using: context) } catch let OutlawError.typeMismatch(expected: expected, actual: actual) { throw OutlawError.typeMismatchWithKey(key: key.outlawKey, expected: expected, actual: actual) } } public func value<K, V: ValueWithContext>(for key: Key, using context: V.Context) -> [K: V]? { return try? self.value(for: key, using: context) } public func value<K, V: ValueWithContext>(for key: Key, using context: V.Context, or value: [K: V]) -> [K: V] { guard let result: [K: V] = self.value(for: key, using: context) else { return value } return result } } // MARK: - // MARK: Optional ValueWithContext Dictionary public extension Extractable { public func value<K, V: ValueWithContext>(for key: Key, using context: V.Context) throws -> [K: V?] { let any = try self.any(for: key) do { return try Dictionary<K, V?>.mappedValue(from: any, using: context) } catch let OutlawError.typeMismatch(expected: expected, actual: actual) { throw OutlawError.typeMismatchWithKey(key: key.outlawKey, expected: expected, actual: actual) } } public func value<K, V: ValueWithContext>(for key: Key, using context: V.Context) -> [K: V?]? { return try? self.value(for: key, using: context) } public func value<K, V: ValueWithContext>(for key: Key, using context: V.Context, or value: [K: V?]) -> [K: V?] { guard let result: [K: V?] = self.value(for: key, using: context) else { return value } return result } } // MARK: - // MARK: ValueWithContext Set public extension Extractable { public func value<V: ValueWithContext>(for key: Key, using context: V.Context) throws -> Set<V> { let any = try self.any(for: key) do { return try Set<V>.mappedValue(from: any, using: context) } catch let OutlawError.typeMismatch(expected: expected, actual: actual) { throw OutlawError.typeMismatchWithKey(key: key.outlawKey, expected: expected, actual: actual) } } public func value<V: ValueWithContext>(for key: Key, using context: V.Context) -> Set<V>? { return try? self.value(for: key, using: context) } public func value<V: ValueWithContext>(for key: Key, using context: V.Context, or value: Set<V>) -> Set<V> { guard let result: Set<V> = self.value(for: key, using: context) else { return value } return result } }
cc0-1.0
a9f2e11d6ac49900c75a7756aa772ae6
36.401274
117
0.624149
3.805574
false
false
false
false
Dev1an/eID-Reader
eidReader/BEIDCard.swift
1
14288
// // BEIDCard.swift // cardreader // // Created by Damiaan on 28-12-16. // Copyright © 2016 Damiaan. All rights reserved. // import Foundation import CryptoTokenKit import MapKit let idFile: [UInt8] = [0xDF, 0x01, 0x40, 0x38] let photoFile: [UInt8] = [0xDF, 0x01, 0x40, 0x35] let addressFile: [UInt8] = [0xDF, 0x01, 0x40, 0x33] let basicInfoFile: [UInt8] = [0xDF, 0x01, 0x40, 0x31] let geocoder = CLGeocoder() class Address: NSObject, MKAnnotation, NSCoding { let street: String let city: String let postalCode: String var coordinate = CLLocationCoordinate2D(latitude: 0, longitude: 0) var title: String? var subtitle: String? { return "\(street)\n\(postalCode) \(city)" } enum ArchiveKey: String { case street, city, postalColde, title, latitude, longitude } func encode(with aCoder: NSCoder) { aCoder.encode(street, forKey: ArchiveKey.street.rawValue) aCoder.encode(city, forKey: ArchiveKey.city.rawValue) aCoder.encode(postalCode, forKey: ArchiveKey.postalColde.rawValue) aCoder.encode(title, forKey: ArchiveKey.title.rawValue) aCoder.encode(coordinate.latitude, forKey: ArchiveKey.latitude.rawValue) aCoder.encode(coordinate.longitude, forKey: ArchiveKey.longitude.rawValue) } required init?(coder aDecoder: NSCoder) { street = aDecoder.decodeObject(forKey: ArchiveKey.street.rawValue) as! String postalCode = aDecoder.decodeObject(forKey: ArchiveKey.postalColde.rawValue) as! String city = aDecoder.decodeObject(forKey: ArchiveKey.city.rawValue) as! String title = aDecoder.decodeObject(forKey: ArchiveKey.title.rawValue) as? String let latitude = aDecoder.decodeDouble(forKey: ArchiveKey.latitude.rawValue) let longitude = aDecoder.decodeDouble(forKey: ArchiveKey.longitude.rawValue) coordinate = CLLocationCoordinate2D(latitude: latitude, longitude: longitude) } init (address: (street: String, postalCode: String, city: String), title: String? = nil, geocodeCompletionHandler: @escaping CLGeocodeCompletionHandler) { (street, postalCode, city) = address self.title = title geocoder.geocodeAddressString("\(street), \(postalCode) \(city)", completionHandler: geocodeCompletionHandler) } override var debugDescription: String { return "\(street)\n\(postalCode) \(city)" } } class BasicInfo: NSObject, NSCoding { enum Index: UInt8 { case fileStructureVersion = 0, cardNumber, chipNumber, validityStart, validityEnd, releasePlace, nationalIdNumber, lastName, firstName, otherName, nationality, birthPlace, birthDate, sex, nobleCondition, documentType, specialStatus, pictureHash, duplicate, specialOrganisation, memberOfFamily, protection } enum Sex: UInt8, CustomStringConvertible { case female, male var description: String { switch self { case .female: return NSLocalizedString("female", comment: "Sex") case .male: return NSLocalizedString("male", comment: "Sex") } } } enum ArchiveKey: String { case cardNumber, releasePlace, firstName, lastName, otherName, nationality, birthPlace, validityStart, validityEnd, birthday, birthNumber } static let validityDateFormatter = DateFormatter(format: "dd.MM.yyyy") static let nationalIDNumberFormatter = DateFormatter(format: "YYMMdd") static let nationalIDNumberDottedFormatter = DateFormatter(format: "YY.MM.dd") let cardNumber, releasePlace, firstName, lastName, otherName, nationality, birthPlace: String let validityStart, validityEnd, birthday: Date let birthNumber: UInt16 init(from file: Data) { let ranges = loadDictionary(from: file.dropLast(2)) func field(_ index: Index) -> Data.SubSequence { return file[ranges[index.rawValue]!] } func string(with index: Index) -> String { return String(bytes: field(index), encoding: .utf8)! } func range(of index: Index) -> CountableRange<Int> { return ranges[index.rawValue]! } cardNumber = string(with: .cardNumber) validityStart = BasicInfo.validityDateFormatter.date(from: string(with: .validityStart))! validityEnd = BasicInfo.validityDateFormatter.date(from: string(with: .validityEnd))! birthPlace = string(with: .birthPlace) birthday = BasicInfo.nationalIDNumberFormatter.date(from: String(bytes: file[range(of: .nationalIdNumber).dropLast(5)], encoding: .utf8)!)! let birthNumberDigits = file[range(of: .nationalIdNumber).suffix(5).dropLast(2)].map {UInt16($0 & 0b1111)} birthNumber = 100 * birthNumberDigits[0] + 10*birthNumberDigits[1] + birthNumberDigits[2] lastName = string(with: .lastName) firstName = string(with: .firstName) otherName = string(with: .otherName) nationality = string(with: .nationality) releasePlace = string(with: .releasePlace) } required init?(coder aDecoder: NSCoder) { func string(with key: ArchiveKey) -> String { return aDecoder.decodeObject(forKey: key.rawValue) as! String } cardNumber = string(with: .cardNumber) releasePlace = string(with: .releasePlace) firstName = string(with: .firstName) lastName = string(with: .lastName) otherName = string(with: .otherName) nationality = string(with: .nationality) birthPlace = string(with: .birthPlace) validityStart = aDecoder.decodeObject(forKey: ArchiveKey.validityStart.rawValue) as! Date validityEnd = aDecoder.decodeObject(forKey: ArchiveKey.validityEnd.rawValue) as! Date birthday = aDecoder.decodeObject(forKey: ArchiveKey.birthday.rawValue) as! Date birthNumber = aDecoder.decodeObject(forKey: ArchiveKey.birthNumber.rawValue) as! UInt16 } func encode(with aCoder: NSCoder) { func encode(_ object: Any?, for key: ArchiveKey) { aCoder.encode(object, forKey: key.rawValue) } encode(cardNumber, for: .cardNumber) encode(releasePlace, for: .releasePlace) encode(firstName, for: .firstName) encode(lastName, for: .lastName) encode(otherName, for: .otherName) encode(nationality, for: .nationality) encode(birthPlace, for: .birthPlace) encode(validityStart, for: .validityStart) encode(validityEnd, for: .validityEnd) encode(birthday, for: .birthday) encode(birthNumber, for: .birthNumber) } var sex: Sex { return Sex(rawValue: UInt8(UInt16(birthNumber) % UInt16(2)))! } override var debugDescription: String { return "ID card of \(firstName) \(otherName) \(lastName)" } var nationalIDNumber : String { let checksum = 97 - (1000 * Int(BasicInfo.nationalIDNumberFormatter.string(from: birthday))! + Int(birthNumber)) % 97 let paddedBirthNumber = String(format: "%03d", birthNumber) let paddedChecksum = String(format: "%02d", checksum) return BasicInfo.nationalIDNumberDottedFormatter.string(from: birthday) + "-\(paddedBirthNumber).\(paddedChecksum)" } } extension TKSmartCard { enum CardError: Error { case NoPreciseDiagnostic, EepromCorrupted, WrongParameterP1P2, CommandNotAvailableWithinCurrentLifeCycle var localizedDescription: String { return "\(self)" } } enum SelectFileError: Error { case SelectedFileNotActivated, FileNotFound, LcInconsistentWithP1P2, AttemptToSelectForbiddenLogicalChannel, ClaNotSupported } enum ReadBinaryError: Error { case SecurityStatusNotSatisfied, IncorrectLength(expected: UInt8) } enum ReadResponse { case data(Data) case error(Error) } struct UnknownError: Error {} /// Select a file on the card by path as described in ISO 7816-4 /// /// - Parameter dedicatedFile: Absolute path to dedicated file without the MF Identifier func select(dedicatedFile file: [UInt8], handler reply: @escaping (Error?)->Void) { let packet = Data( [ 0x00, 0xA4, 0x08, 0x0C, UInt8(file.count) ] + file ) self.transmit(packet) { (selectFileReply, error) in if let error = error { reply(error) } else if let selectFileReply = selectFileReply { switch (selectFileReply[0], selectFileReply[1]) { case (0x62, 0x83): reply(SelectFileError.SelectedFileNotActivated) case (0x64, 0): reply(CardError.NoPreciseDiagnostic) case (0x65, 0x81): reply(CardError.EepromCorrupted) case (0x6A, 0x82): reply(SelectFileError.FileNotFound) case (0x6A, 0x86): reply(CardError.WrongParameterP1P2) case (0x6A, 0x87): reply(SelectFileError.LcInconsistentWithP1P2) case (0x69, 0x99), (0x69, 0x85): reply(SelectFileError.AttemptToSelectForbiddenLogicalChannel) case (0x6D, 0): reply(CardError.CommandNotAvailableWithinCurrentLifeCycle) case (0x6E, 0): reply(SelectFileError.ClaNotSupported) case (0x90, 0): reply(nil) default: reply(UnknownError()) } } else { fatalError("transmit must either have a response or an error") } } } /// Read bytes from current file /// as described in section "7.2.3 READ BINARY command" of ISO 7816-4 /// /// - Parameters: /// - length: number of bytes to read (Le) /// - offset: number of bytes to skip (15-bit unsigned integer, ranging from 0 to 32 767) /// - handler: function to execute after completion func readBytes(length: UInt8, offset: UInt16 = 0, handler: @escaping (_ response: ReadResponse) -> Void) { let packet = Data([ 0x00, // Commmand header: CLA (Class byte) 0xB0, // INS (Instruction byte: READ BINARY) UInt8(offset >> 8), // P1 (Parameter byte: offset's high byte) UInt8(offset & 0xff), // P2 (Parameter byte: offset's low byte) length // Length of the file ]) transmit(packet) { (binaryReply, error) in if let error = error { handler(.error(error)) } else if let binaryReply = binaryReply { let statusBytes = (binaryReply[binaryReply.endIndex-2], binaryReply.last!) switch statusBytes { case (0x64, 0): handler(.error(CardError.NoPreciseDiagnostic) ) case (0x65, 0x81): handler(.error(CardError.EepromCorrupted) ) case (0x6B, 0): handler(.error(CardError.WrongParameterP1P2) ) case (0x6D, 0): handler(.error(CardError.CommandNotAvailableWithinCurrentLifeCycle) ) case (0x69, 0x82): handler(.error(ReadBinaryError.SecurityStatusNotSatisfied) ) case (0x6C, _): handler(.error(ReadBinaryError.IncorrectLength(expected: binaryReply.last!)) ) case (0x90, 0): handler(.data( Data(binaryReply.dropLast(2)) )) default: handler( .error( UnknownError() ) ) } } } } func readBytesUntilError(data: Data = Data([]), updateProgress: ((_ progress: UInt8)->Void)? = nil, handler reply: @escaping (_ response: ReadResponse)->Void) { let offset = UInt16(data.count) updateProgress?(UInt8(offset/256)) readBytes(length: 0, offset: offset) { switch $0 { case .error(let error): switch error { case ReadBinaryError.IncorrectLength(let expectedLength): self.readBytes(length: expectedLength, offset: offset) { response in updateProgress?(UInt8(offset/256)) switch response { case .error(let error): reply(.error(error)) case .data(let newData): var concat = Data() concat.reserveCapacity(data.count+newData.count) concat.append(data) concat.append(newData) reply(.data(concat)) } } case CardError.WrongParameterP1P2: if data.count > 0 { reply(.data(data)) } else { reply(.error(error)) } default: reply(.error(error)) } case .data(let newData): var concat = Data() concat.reserveCapacity(data.count+newData.count) concat.append(data) concat.append(newData) if newData.count < 256 { reply(.data(concat)) } else { self.readBytesUntilError(data: concat, updateProgress: updateProgress, handler: reply) } } } } /// Select dedicated file and read all its bytes. This is a helper function that combines the SELECT & READ BINARY commands from ISO 7816-4 (sections 7.1.1 & 7.2.3) /// /// - Parameters: /// - file: Absolute path to dedicated file without the MF Identifier /// - updateProgress: function that gets called while reading the large files and informs the progress of the read command /// - reply: function that gets called when the file is read func read(file: [UInt8], updateProgress: ((UInt8)->Void)? = nil, reply: @escaping (_ response: ReadResponse)->Void) { select(dedicatedFile: file) { if let error = $0 { reply(.error(error) ) } else { self.readBytesUntilError(updateProgress: updateProgress, handler: reply) } } } func syncRead(file: [UInt8], updateProgress: ((UInt8)->Void)? = nil) throws -> Data { let semaphore = DispatchSemaphore(value: 0) var response: ReadResponse? self.read(file: file, updateProgress: updateProgress) { response = $0 semaphore.signal() } semaphore.wait() switch response! { case .data(let data): return data case .error(let error): throw error } } func getAddress(geocodeCompletionHandler: @escaping CLGeocodeCompletionHandler = {(_,_) in}) throws -> Address { let data = try syncRead(file: addressFile) let street = 2 ..< Int(data[1]) + 2 let postalCode = street.upperBound + 2 ..< street.upperBound + Int(data[street.upperBound+1]) + 2 let city = postalCode.upperBound + 2 ..< postalCode.upperBound + Int(data[postalCode.upperBound+1]) + 2 return Address( address: ( String(bytes: data[street], encoding: .utf8)!, String(bytes: data[postalCode], encoding: .utf8)!, String(bytes: data[city], encoding: .utf8)! ), title: NSLocalizedString("Domicile", comment: "Domicile"), geocodeCompletionHandler: geocodeCompletionHandler ) } func getBasicInfo() throws -> BasicInfo { return BasicInfo(from: try syncRead(file: basicInfoFile)) } func getProfileImage(updateProgress: ((UInt8)->Void)? = nil) throws -> Data { return try syncRead(file: photoFile, updateProgress: updateProgress) } } func loadDictionary(from data: Data) -> [UInt8: CountableRange<Int>] { var dictionary = [UInt8: CountableRange<Int>]() var cursor = 2 while cursor<data.endIndex && data[cursor-2] != 0 { let length = Int( data[cursor-1] ) dictionary[data[cursor-2]] = cursor ..< cursor+length cursor += length + 2 } return dictionary } extension DateFormatter { convenience init(format: String) { self.init() self.dateFormat = format } convenience init(style: DateFormatter.Style) { self.init() self.dateStyle = style } }
mit
cb050ef42022930299e3b6696133335a
33.097852
306
0.706376
3.445141
false
false
false
false
kumabook/StickyNotesiOS
StickyNotes/SiteCollectionViewCell.swift
1
969
// // SiteCollectionViewCell.swift // StickyNotes // // Created by Hiroki Kumamoto on 2017/04/28. // Copyright © 2017 kumabook. All rights reserved. // import Foundation import UIKit class SiteCollectionViewCell: UICollectionViewCell { var titleLabel: UILabel! var imageView: UIImageView! override init(frame: CGRect) { super.init(frame: frame) let length = frame.size.width - 48 imageView = UIImageView(frame: CGRect(x: 24, y: 12, width: length, height: length)) imageView.contentMode = .scaleAspectFit titleLabel = UILabel(frame: CGRect(x: 0, y: imageView.frame.size.height + 12 , width: frame.size.width, height: frame.size.height / 3)) titleLabel.textAlignment = NSTextAlignment.center contentView.addSubview(imageView) contentView.addSubview(titleLabel) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
mit
3b26d009d5d8947b5905e5b18e0b3eba
31.266667
144
0.683884
4.227074
false
false
false
false
strangeliu/firefox-ios
Storage/Bookmarks.swift
3
11546
/* 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 UIKit import Shared // A small structure to encapsulate all the possible data that we can get // from an application sharing a web page or a URL. public struct ShareItem { public let url: String public let title: String? public let favicon: Favicon? public init(url: String, title: String?, favicon: Favicon?) { self.url = url self.title = title self.favicon = favicon } } public protocol ShareToDestination { func shareItem(item: ShareItem) } public protocol SearchableBookmarks { func bookmarksByURL(url: NSURL) -> Deferred<Maybe<Cursor<BookmarkItem>>> } public struct BookmarkRoots { // These match Places on desktop. public static let RootGUID = "root________" public static let MobileFolderGUID = "mobile______" public static let MenuFolderGUID = "menu________" public static let ToolbarFolderGUID = "toolbar_____" public static let UnfiledFolderGUID = "unfiled_____" /* public static let TagsFolderGUID = "tags________" public static let PinnedFolderGUID = "pinned______" public static let FakeDesktopFolderGUID = "desktop_____" */ static let RootID = 0 static let MobileID = 1 static let MenuID = 2 static let ToolbarID = 3 static let UnfiledID = 4 } /** * This matches Places's nsINavBookmarksService, just for sanity. * These are only used at the DB layer. */ public enum BookmarkNodeType: Int { case Bookmark = 1 case Folder = 2 case Separator = 3 case DynamicContainer = 4 } /** * The immutable base interface for bookmarks and folders. */ public class BookmarkNode { public var id: Int? = nil public var guid: String public var title: String public var favicon: Favicon? = nil init(guid: String, title: String) { self.guid = guid self.title = title } } /** * An immutable item representing a bookmark. * * To modify this, issue changes against the backing store and get an updated model. */ public class BookmarkItem: BookmarkNode { public let url: String! public init(guid: String, title: String, url: String) { self.url = url super.init(guid: guid, title: title) } } /** * A folder is an immutable abstraction over a named * thing that can return its child nodes by index. */ public class BookmarkFolder: BookmarkNode { public var count: Int { return 0 } public subscript(index: Int) -> BookmarkNode? { return nil } public func itemIsEditableAtIndex(index: Int) -> Bool { return false } } /** * A model is a snapshot of the bookmarks store, suitable for backing a table view. * * Navigation through the folder hierarchy produces a sequence of models. * * Changes to the backing store implicitly invalidates a subset of models. * * 'Refresh' means requesting a new model from the store. */ public class BookmarksModel { let modelFactory: BookmarksModelFactory public let current: BookmarkFolder public init(modelFactory: BookmarksModelFactory, root: BookmarkFolder) { self.modelFactory = modelFactory self.current = root } /** * Produce a new model rooted at the appropriate folder. Fails if the folder doesn't exist. */ public func selectFolder(folder: BookmarkFolder, success: BookmarksModel -> (), failure: Any -> ()) { modelFactory.modelForFolder(folder, success: success, failure: failure) } /** * Produce a new model rooted at the appropriate folder. Fails if the folder doesn't exist. */ public func selectFolder(guid: String, success: BookmarksModel -> (), failure: Any -> ()) { modelFactory.modelForFolder(guid, success: success, failure: failure) } /** * Produce a new model rooted at the base of the hierarchy. Should never fail. */ public func selectRoot(success: BookmarksModel -> (), failure: Any -> ()) { modelFactory.modelForRoot(success, failure: failure) } /** * Produce a new model rooted at the same place as this model. Can fail if * the folder has been deleted from the backing store. */ public func reloadData(success: BookmarksModel -> (), failure: Any -> ()) { modelFactory.modelForFolder(current, success: success, failure: failure) } } public protocol BookmarksModelFactory { func modelForFolder(folder: BookmarkFolder, success: BookmarksModel -> (), failure: Any -> ()) func modelForFolder(guid: String, success: BookmarksModel -> (), failure: Any -> ()) func modelForRoot(success: BookmarksModel -> (), failure: Any -> ()) // Whenever async construction is necessary, we fall into a pattern of needing // a placeholder that behaves correctly for the period between kickoff and set. var nullModel: BookmarksModel { get } func isBookmarked(url: String, success: Bool -> (), failure: Any -> ()) func remove(bookmark: BookmarkNode) -> Success func removeByURL(url: String) -> Success func clearBookmarks() -> Success } /* * A folder that contains an array of children. */ public class MemoryBookmarkFolder: BookmarkFolder, SequenceType { let children: [BookmarkNode] public init(guid: String, title: String, children: [BookmarkNode]) { self.children = children super.init(guid: guid, title: title) } public struct BookmarkNodeGenerator: GeneratorType { public typealias Element = BookmarkNode let children: [BookmarkNode] var index: Int = 0 init(children: [BookmarkNode]) { self.children = children } public mutating func next() -> BookmarkNode? { return index < children.count ? children[index++] : nil } } override public var favicon: Favicon? { get { if let path = NSBundle.mainBundle().pathForResource("bookmark_folder_closed", ofType: "png") { let url = NSURL(fileURLWithPath: path) return Favicon(url: url.absoluteString, date: NSDate(), type: IconType.Local) } return nil } set { } } override public var count: Int { return children.count } override public subscript(index: Int) -> BookmarkNode { get { return children[index] } } override public func itemIsEditableAtIndex(index: Int) -> Bool { return true } public func generate() -> BookmarkNodeGenerator { return BookmarkNodeGenerator(children: self.children) } /** * Return a new immutable folder that's just like this one, * but also contains the new items. */ func append(items: [BookmarkNode]) -> MemoryBookmarkFolder { if (items.isEmpty) { return self } return MemoryBookmarkFolder(guid: self.guid, title: self.title, children: self.children + items) } } public class MemoryBookmarksSink: ShareToDestination { var queue: [BookmarkNode] = [] public init() { } public func shareItem(item: ShareItem) { let title = item.title == nil ? "Untitled" : item.title! func exists(e: BookmarkNode) -> Bool { if let bookmark = e as? BookmarkItem { return bookmark.url == item.url; } return false; } // Don't create duplicates. if (!queue.contains(exists)) { queue.append(BookmarkItem(guid: Bytes.generateGUID(), title: title, url: item.url)) } } } private extension SuggestedSite { func asBookmark() -> BookmarkNode { let b = BookmarkItem(guid: self.guid ?? Bytes.generateGUID(), title: self.title, url: self.url) b.favicon = self.icon return b } } public class BookmarkFolderWithDefaults: BookmarkFolder { private let folder: BookmarkFolder private let sites: SuggestedSitesCursor init(folder: BookmarkFolder, sites: SuggestedSitesCursor) { self.folder = folder self.sites = sites super.init(guid: folder.guid, title: folder.title) } override public var count: Int { return self.folder.count + self.sites.count } override public subscript(index: Int) -> BookmarkNode? { if index < self.folder.count { return self.folder[index] } if let site = self.sites[index - self.folder.count] { return site.asBookmark() } return nil } override public func itemIsEditableAtIndex(index: Int) -> Bool { return index < self.folder.count } } /** * A trivial offline model factory that represents a simple hierarchy. */ public class MockMemoryBookmarksStore: BookmarksModelFactory, ShareToDestination { let mobile: MemoryBookmarkFolder let root: MemoryBookmarkFolder var unsorted: MemoryBookmarkFolder let sink: MemoryBookmarksSink public init() { let res = [BookmarkItem]() mobile = MemoryBookmarkFolder(guid: BookmarkRoots.MobileFolderGUID, title: "Mobile Bookmarks", children: res) unsorted = MemoryBookmarkFolder(guid: BookmarkRoots.UnfiledFolderGUID, title: "Unsorted Bookmarks", children: []) sink = MemoryBookmarksSink() root = MemoryBookmarkFolder(guid: BookmarkRoots.RootGUID, title: "Root", children: [mobile, unsorted]) } public func modelForFolder(folder: BookmarkFolder, success: (BookmarksModel) -> (), failure: (Any) -> ()) { self.modelForFolder(folder.guid, success: success, failure: failure) } public func modelForFolder(guid: String, success: (BookmarksModel) -> (), failure: (Any) -> ()) { var m: BookmarkFolder switch (guid) { case BookmarkRoots.MobileFolderGUID: // Transparently merges in any queued items. m = self.mobile.append(self.sink.queue) break; case BookmarkRoots.RootGUID: m = self.root break; case BookmarkRoots.UnfiledFolderGUID: m = self.unsorted break; default: failure("No such folder.") return } success(BookmarksModel(modelFactory: self, root: m)) } public func modelForRoot(success: (BookmarksModel) -> (), failure: (Any) -> ()) { success(BookmarksModel(modelFactory: self, root: self.root)) } /** * This class could return the full data immediately. We don't, because real DB-backed code won't. */ public var nullModel: BookmarksModel { let f = MemoryBookmarkFolder(guid: BookmarkRoots.RootGUID, title: "Root", children: []) return BookmarksModel(modelFactory: self, root: f) } public func shareItem(item: ShareItem) { self.sink.shareItem(item) } public func isBookmarked(url: String, success: (Bool) -> (), failure: (Any) -> ()) { failure("Not implemented") } public func remove(bookmark: BookmarkNode) -> Success { return deferMaybe(DatabaseError(description: "Not implemented")) } public func removeByURL(url: String) -> Success { return deferMaybe(DatabaseError(description: "Not implemented")) } public func clearBookmarks() -> Success { return succeed() } }
mpl-2.0
0d0b5aa980d5d1cc6c02519e2b0f086b
29.957105
121
0.642474
4.554635
false
false
false
false
maheshasabe/SwiftUtility
SwiftUtility/Classes/Validators/Validator.swift
1
1080
// // Validator.swift // Pods // // Created by Mahesh Asabe on 03/08/17. // // import Foundation public class Validator: NSObject { class public func validateEmail(_ emailId: String) -> Bool { let emailRegex = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,6}" return NSPredicate(format: "SELF MATCHES %@", emailRegex).evaluate(with: emailId) } class public func validatePhoneNumber(_ phoneNumber:String) -> Bool { let characterSet = CharacterSet(charactersIn: "+0123456789").inverted var filtered:NSString! let inputString:[String] = phoneNumber.components(separatedBy: characterSet) let stringArray:NSArray = NSArray.init(array: inputString) filtered = stringArray.componentsJoined(by: "") as NSString! return phoneNumber == filtered as String } class public func validateURL(_ url: String) -> Bool { let emailRegex = "(https?:\\/\\/)?[a-zA-Z0-9.]+\\.(?:[a-zA-Z]{2,3})" return NSPredicate(format: "SELF MATCHES %@", emailRegex).evaluate(with: url) } }
mit
ab1de86b07b5b081170e9836e022250a
33.83871
89
0.62963
4.029851
false
false
false
false
AlesTsurko/DNMKit
DNM_iOS/DNM_iOS/ButtonSwitchPanel.swift
1
3495
// // ButtonSwitchPanel.swift // denm_view // // Created by James Bean on 9/25/15. // Copyright © 2015 James Bean. All rights reserved. // import UIKit public class ButtonSwitchPanel: UIView { internal let pad: CGFloat = 0 public var buttonSwitches: [ButtonSwitch] = [] public var left: CGFloat = 0 public var top: CGFloat = 0 public var target: AnyObject? // this should be extended in subclass! public var title: String = "" public var titleLabel: TextLayerConstrainedByHeight? public var statesByText: [String : Bool] = [:] public var rememberedStatesByText: [String : Bool] = [:] public var buttonSwitchByID: [String : ButtonSwitch] = [:] public init(left: CGFloat, top: CGFloat, target: AnyObject? = nil, titles: [String] = []) { self.left = left self.top = top self.target = target super.init(frame: CGRectMake(left, top, 0, 40 + 10)) addButtonSwitchesWithTitles(titles) } public override init(frame: CGRect) { super.init(frame: frame) } public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } public func stateHasChangedFromSender(sender: ButtonSwitch) { statesByText[sender.id] = sender.isOn } public func addButtonSwitch(buttonSwitch: ButtonSwitch) { buttonSwitches.append(buttonSwitch) buttonSwitchByID[buttonSwitch.text] = buttonSwitch } public func addButtonSwitchesWithTitles(titles: [String]) { for title in titles { addButtonSwitchWithTitle(title) } } public func insertButtonSwitchWithTitle(title: String, atIndex index: Int) { let buttonSwitch = ButtonSwitch(width: 100, height: 25, text: title, id: title) insertButtonSwitch(buttonSwitch, atIndex: index) } public func insertButtonSwitch(buttonSwitch: ButtonSwitch, atIndex index: Int) { buttonSwitches.insert(buttonSwitch, atIndex: index) buttonSwitchByID[buttonSwitch.id] = buttonSwitch } public func addButtonSwitchWithTitle(title: String) { let buttonSwitch = ButtonSwitch(width: 100, height: 25, text: title, id: title) addButtonSwitch(buttonSwitch) //buttonSwitchByID[buttonSwitch.text] = buttonSwitch } public func layout() { for (b, buttonSwitch) in buttonSwitches.enumerate() { buttonSwitch.layer.position.y = 0.5 * buttonSwitch.frame.height if b == 0 { buttonSwitch.layer.position.x = 0.5 * buttonSwitch.frame.width } else { let buttonSwitch_left = pad + buttonSwitches[b-1].frame.maxX buttonSwitch.layer.position.x = buttonSwitch_left + 0.5 * buttonSwitch.frame.width } addSubview(buttonSwitch) } } public func build() { layout() setFrame() setInitialStatesByTextByID() } internal func setInitialStatesByTextByID() { for buttonSwitch in buttonSwitches { statesByText[buttonSwitch.id] = buttonSwitch.isOn } setRememberedStates() } internal func setRememberedStates() { for (id, state) in statesByText { rememberedStatesByText[id] = state } } internal func setFrame() { self.frame = CGRectMake( left, top, buttonSwitches.last!.frame.maxX, buttonSwitches.first!.frame.height ) } }
gpl-2.0
fcf6617e16ef5c8e183839fea533f3ea
31.654206
98
0.63423
4.422785
false
false
false
false
huonw/swift
test/SILGen/super.swift
1
10119
// RUN: %empty-directory(%t) // RUN: %target-swift-frontend -I %t -emit-module -emit-module-path=%t/resilient_struct.swiftmodule -module-name resilient_struct %S/../Inputs/resilient_struct.swift // RUN: %target-swift-frontend -I %t -emit-module -emit-module-path=%t/resilient_class.swiftmodule -module-name resilient_class %S/../Inputs/resilient_class.swift // RUN: %target-swift-emit-silgen -module-name super -parse-as-library -I %t %s | %FileCheck %s import resilient_class public class Parent { public final var finalProperty: String { return "Parent.finalProperty" } public var property: String { return "Parent.property" } public final class var finalClassProperty: String { return "Parent.finalProperty" } public class var classProperty: String { return "Parent.property" } public func methodOnlyInParent() {} public final func finalMethodOnlyInParent() {} public func method() {} public final class func finalClassMethodOnlyInParent() {} public class func classMethod() {} } public class Child : Parent { // CHECK-LABEL: sil @$S5super5ChildC8propertySSvg : $@convention(method) (@guaranteed Child) -> @owned String { // CHECK: bb0([[SELF:%.*]] : $Child): // CHECK: [[SELF_COPY:%.*]] = copy_value [[SELF]] // CHECK: [[CASTED_SELF_COPY:%[0-9]+]] = upcast [[SELF_COPY]] : $Child to $Parent // CHECK: [[SUPER_METHOD:%[0-9]+]] = function_ref @$S5super6ParentC8propertySSvg : $@convention(method) (@guaranteed Parent) -> @owned String // CHECK: [[RESULT:%.*]] = apply [[SUPER_METHOD]]([[CASTED_SELF_COPY]]) // CHECK: destroy_value [[CASTED_SELF_COPY]] // CHECK: return [[RESULT]] public override var property: String { return super.property } // CHECK-LABEL: sil @$S5super5ChildC13otherPropertySSvg : $@convention(method) (@guaranteed Child) -> @owned String { // CHECK: bb0([[SELF:%.*]] : $Child): // CHECK: [[COPIED_SELF:%.*]] = copy_value [[SELF]] // CHECK: [[CASTED_SELF_COPY:%[0-9]+]] = upcast [[COPIED_SELF]] : $Child to $Parent // CHECK: [[SUPER_METHOD:%[0-9]+]] = function_ref @$S5super6ParentC13finalPropertySSvg // CHECK: [[RESULT:%.*]] = apply [[SUPER_METHOD]]([[CASTED_SELF_COPY]]) // CHECK: destroy_value [[CASTED_SELF_COPY]] // CHECK: return [[RESULT]] public var otherProperty: String { return super.finalProperty } } public class Grandchild : Child { // CHECK-LABEL: sil @$S5super10GrandchildC06onlyInB0yyF public func onlyInGrandchild() { // CHECK: function_ref @$S5super6ParentC012methodOnlyInB0yyF : $@convention(method) (@guaranteed Parent) -> () super.methodOnlyInParent() // CHECK: function_ref @$S5super6ParentC017finalMethodOnlyInB0yyF super.finalMethodOnlyInParent() } // CHECK-LABEL: sil @$S5super10GrandchildC6methodyyF public override func method() { // CHECK: function_ref @$S5super6ParentC6methodyyF : $@convention(method) (@guaranteed Parent) -> () super.method() } } public class GreatGrandchild : Grandchild { // CHECK-LABEL: sil @$S5super15GreatGrandchildC6methodyyF public override func method() { // CHECK: function_ref @$S5super10GrandchildC6methodyyF : $@convention(method) (@guaranteed Grandchild) -> () super.method() } } public class ChildToResilientParent : ResilientOutsideParent { // CHECK-LABEL: sil @$S5super22ChildToResilientParentC6methodyyF : $@convention(method) (@guaranteed ChildToResilientParent) -> () public override func method() { // CHECK: bb0([[SELF:%.*]] : $ChildToResilientParent): // CHECK: [[COPY_SELF:%.*]] = copy_value [[SELF]] // CHECK: [[UPCAST_SELF:%.*]] = upcast [[COPY_SELF]] // CHECK: [[BORROW_UPCAST_SELF:%.*]] = begin_borrow [[UPCAST_SELF]] // CHECK: [[CAST_BORROW_BACK_TO_BASE:%.*]] = unchecked_ref_cast [[BORROW_UPCAST_SELF]] // CHECK: [[FUNC:%.*]] = super_method [[CAST_BORROW_BACK_TO_BASE]] : $ChildToResilientParent, #ResilientOutsideParent.method!1 : (ResilientOutsideParent) -> () -> (), $@convention(method) (@guaranteed ResilientOutsideParent) -> () // CHECK: end_borrow [[BORROW_UPCAST_SELF]] from [[UPCAST_SELF]] // CHECK: apply [[FUNC]]([[UPCAST_SELF]]) super.method() } // CHECK: } // end sil function '$S5super22ChildToResilientParentC6methodyyF' // CHECK-LABEL: sil @$S5super22ChildToResilientParentC11classMethodyyFZ : $@convention(method) (@thick ChildToResilientParent.Type) -> () public override class func classMethod() { // CHECK: bb0([[METASELF:%.*]] : $@thick ChildToResilientParent.Type): // CHECK: [[UPCAST_METASELF:%.*]] = upcast [[METASELF]] // CHECK: [[FUNC:%.*]] = super_method [[SELF]] : $@thick ChildToResilientParent.Type, #ResilientOutsideParent.classMethod!1 : (ResilientOutsideParent.Type) -> () -> (), $@convention(method) (@thick ResilientOutsideParent.Type) -> () // CHECK: apply [[FUNC]]([[UPCAST_METASELF]]) super.classMethod() } // CHECK: } // end sil function '$S5super22ChildToResilientParentC11classMethodyyFZ' // CHECK-LABEL: sil @$S5super22ChildToResilientParentC11returnsSelfACXDyFZ : $@convention(method) (@thick ChildToResilientParent.Type) -> @owned ChildToResilientParent public class func returnsSelf() -> Self { // CHECK: bb0([[METASELF:%.*]] : $@thick ChildToResilientParent.Type): // CHECK: [[CAST_METASELF:%.*]] = unchecked_trivial_bit_cast [[METASELF]] : $@thick ChildToResilientParent.Type to $@thick @dynamic_self ChildToResilientParent.Type // CHECK: [[UPCAST_CAST_METASELF:%.*]] = upcast [[CAST_METASELF]] : $@thick @dynamic_self ChildToResilientParent.Type to $@thick ResilientOutsideParent.Type // CHECK: [[FUNC:%.*]] = super_method [[METASELF]] : $@thick ChildToResilientParent.Type, #ResilientOutsideParent.classMethod!1 : (ResilientOutsideParent.Type) -> () -> () // CHECK: apply [[FUNC]]([[UPCAST_CAST_METASELF]]) // CHECK: unreachable super.classMethod() } // CHECK: } // end sil function '$S5super22ChildToResilientParentC11returnsSelfACXDyFZ' } public class ChildToFixedParent : OutsideParent { // CHECK-LABEL: sil @$S5super18ChildToFixedParentC6methodyyF : $@convention(method) (@guaranteed ChildToFixedParent) -> () public override func method() { // CHECK: bb0([[SELF:%.*]] : $ChildToFixedParent): // CHECK: [[COPY_SELF:%.*]] = copy_value [[SELF]] // CHECK: [[UPCAST_COPY_SELF:%.*]] = upcast [[COPY_SELF]] // CHECK: [[BORROWED_UPCAST_COPY_SELF:%.*]] = begin_borrow [[UPCAST_COPY_SELF]] // CHECK: [[DOWNCAST_BORROWED_UPCAST_COPY_SELF:%.*]] = unchecked_ref_cast [[BORROWED_UPCAST_COPY_SELF]] : $OutsideParent to $ChildToFixedParent // CHECK: [[FUNC:%.*]] = super_method [[DOWNCAST_BORROWED_UPCAST_COPY_SELF]] : $ChildToFixedParent, #OutsideParent.method!1 : (OutsideParent) -> () -> (), $@convention(method) (@guaranteed OutsideParent) -> () // CHECK: end_borrow [[BORROWED_UPCAST_COPY_SELF]] from [[UPCAST_COPY_SELF]] // CHECK: apply [[FUNC]]([[UPCAST_COPY_SELF]]) super.method() } // CHECK: } // end sil function '$S5super18ChildToFixedParentC6methodyyF' // CHECK-LABEL: sil @$S5super18ChildToFixedParentC11classMethodyyFZ : $@convention(method) (@thick ChildToFixedParent.Type) -> () public override class func classMethod() { // CHECK: bb0([[SELF:%.*]] : $@thick ChildToFixedParent.Type): // CHECK: [[UPCAST_SELF:%.*]] = upcast [[SELF]] // CHECK: [[FUNC:%.*]] = super_method [[SELF]] : $@thick ChildToFixedParent.Type, #OutsideParent.classMethod!1 : (OutsideParent.Type) -> () -> (), $@convention(method) (@thick OutsideParent.Type) -> () // CHECK: apply [[FUNC]]([[UPCAST_SELF]]) super.classMethod() } // CHECK: } // end sil function '$S5super18ChildToFixedParentC11classMethodyyFZ' // CHECK-LABEL: sil @$S5super18ChildToFixedParentC11returnsSelfACXDyFZ : $@convention(method) (@thick ChildToFixedParent.Type) -> @owned ChildToFixedParent public class func returnsSelf() -> Self { // CHECK: bb0([[SELF:%.*]] : $@thick ChildToFixedParent.Type): // CHECK: [[FIRST_CAST:%.*]] = unchecked_trivial_bit_cast [[SELF]] // CHECK: [[SECOND_CAST:%.*]] = upcast [[FIRST_CAST]] // CHECK: [[FUNC:%.*]] = super_method [[SELF]] : $@thick ChildToFixedParent.Type, #OutsideParent.classMethod!1 : (OutsideParent.Type) -> () -> () // CHECK: apply [[FUNC]]([[SECOND_CAST]]) // CHECK: unreachable super.classMethod() } // CHECK: } // end sil function '$S5super18ChildToFixedParentC11returnsSelfACXDyFZ' } public extension ResilientOutsideChild { public func callSuperMethod() { super.method() } public class func callSuperClassMethod() { super.classMethod() } } public class GenericBase<T> { public func method() {} } public class GenericDerived<T> : GenericBase<T> { public override func method() { // CHECK-LABEL: sil private @$S5super14GenericDerivedC6methodyyFyyXEfU_ : $@convention(thin) <T> (@guaranteed GenericDerived<T>) -> () // CHECK: upcast {{.*}} : $GenericDerived<T> to $GenericBase<T> // CHECK: return { super.method() }() // CHECK: } // end sil function '$S5super14GenericDerivedC6methodyyFyyXEfU_' // CHECK-LABEL: sil private @$S5super14GenericDerivedC6methodyyF13localFunctionL_yylF : $@convention(thin) <T> (@guaranteed GenericDerived<T>) -> () // CHECK: upcast {{.*}} : $GenericDerived<T> to $GenericBase<T> // CHECK: return // CHECK: } // end sil function '$S5super14GenericDerivedC6methodyyF13localFunctionL_yylF' func localFunction() { super.method() } localFunction() // CHECK-LABEL: sil private @$S5super14GenericDerivedC6methodyyF15genericFunctionL_yyqd__r__lF : $@convention(thin) <T><U> (@in_guaranteed U, @guaranteed GenericDerived<T>) -> () // CHECK: upcast {{.*}} : $GenericDerived<T> to $GenericBase<T> // CHECK: return func genericFunction<U>(_: U) { super.method() } // CHECK: } // end sil function '$S5super14GenericDerivedC6methodyyF15genericFunctionL_yyqd__r__lF' genericFunction(0) } }
apache-2.0
e81ca61c7276561caead17bd2caabe5a
49.094059
238
0.665777
3.771524
false
false
false
false
hachinobu/SwiftPasscodeLock
SwiftPasscodeLock/Views/PasscodePlaceholderView.swift
5
2810
// // PasscodePlaceholderView.swift // SwiftPasscodeLock // // Created by Yanko Dimitrov on 11/20/14. // Copyright (c) 2014 Yanko Dimitrov. All rights reserved. // import UIKit @IBDesignable public class PasscodePlaceholderView: UIView { public enum State { case Inactive case Active case Error } @IBInspectable public var inactiveColor: UIColor = UIColor.whiteColor() { didSet { setupView() } } @IBInspectable public var activeColor: UIColor = UIColor.whiteColor() { didSet { setupView() } } @IBInspectable public var errorColor: UIColor = UIColor.redColor() { didSet { setupView() } } @IBInspectable public var borderWidth: CGFloat = 1 { didSet { setupView() } } @IBInspectable public var borderColor: UIColor = UIColor.whiteColor() { didSet { setupView() } } @IBInspectable public var borderRadius: CGFloat = 8 { didSet { setupView() } } /////////////////////////////////////////////////////// // MARK: - Initializers /////////////////////////////////////////////////////// public override init(frame: CGRect) { super.init(frame: frame) setupView() } public required init(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } /////////////////////////////////////////////////////// // MARK: - Methods /////////////////////////////////////////////////////// private func setupView() { layer.cornerRadius = borderRadius layer.borderWidth = borderWidth layer.borderColor = borderColor.CGColor backgroundColor = inactiveColor } public func changeState(state: PasscodePlaceholderView.State) { switch state { case .Inactive: animate(backgroundColor: inactiveColor, borderColor: borderColor) case .Active: animate(backgroundColor: activeColor, borderColor: activeColor) case .Error: animate(backgroundColor: errorColor, borderColor: errorColor) } } private func animate(#backgroundColor: UIColor, borderColor: UIColor) { UIView.animateWithDuration( 0.5, delay: 0, usingSpringWithDamping: 1, initialSpringVelocity: 0, options: nil, animations: { self.backgroundColor = backgroundColor self.layer.borderColor = borderColor.CGColor }, completion: nil ) } }
mit
4c79ce03567f7c04622057a0429c1490
23.224138
93
0.502491
6.030043
false
false
false
false
jerrypupu111/LearnDrawingToolSet
SwiftGL-Demo/Source/iOS/NoteButton.swift
1
1235
// // NoteButton.swift // SwiftGL // // Created by jerry on 2016/2/15. // Copyright © 2016年 Jerry Chan. All rights reserved. // import UIKit import GLFramework class NoteButton:UIButton { var note:SANote! let btnWidth:CGFloat = 40 override init(frame: CGRect) { super.init(frame: frame) self.frame = CGRect(x: 0,y: -8,width: btnWidth,height: 40) setImage(UIImage(named: "chat-up"), for: UIControlState()) layer.cornerRadius = 0.25 * btnWidth backgroundColor = UIColor.white tintColor = themeDarkColor layer.borderColor = UIColor.lightGray.cgColor layer.borderWidth = 1 } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func setPosition(_ position:CGFloat) { let offset:CGFloat = 10 layer.transform = CATransform3DMakeTranslation(position - offset, 0, 0) } func selectStyle() { } func deSelectStyle() { UIView.animate(withDuration: 1, animations: { self.layer.borderWidth = 1 self.layer.borderColor = UIColor.lightGray.cgColor }) } }
mit
0257c69d8b6ad8ab5cbac45e34842c41
23.156863
80
0.599026
4.307692
false
false
false
false