repo_name
stringlengths
6
91
path
stringlengths
8
968
copies
stringclasses
202 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
PureSwift/Bluetooth
Sources/BluetoothHCI/HCILEReadPhy.swift
1
2581
// // HCILEReadPHY.swift // Bluetooth // // Created by Alsey Coleman Miller on 6/14/18. // Copyright © 2018 PureSwift. All rights reserved. // import Foundation // MARK: - Method public extension BluetoothHostControllerInterface { /// LE Read PHY Command /// /// This ommand is used to read the current transmitter PHY and receiver PHY /// on the connection identified by the Connection_Handle. func lowEnergyReadPhy(connectionHandle: UInt16, timeout: HCICommandTimeout = .default) async throws -> HCILEReadPHYReturn { let parameters = HCILEReadPHY(connectionHandle: connectionHandle) let value = try await deviceRequest(parameters, HCILEReadPHYReturn.self, timeout: timeout) return value } } // MARK: - Command /// LE Read PHY Command /// /// The command is used to read the current transmitter PHY and receiver PHY /// on the connection identified by the Connection_Handle. @frozen public struct HCILEReadPHY: HCICommandParameter { public static let command = HCILowEnergyCommand.readPhy //0x0030 /// Range 0x0000-0x0EFF (all other values reserved for future use) public let connectionHandle: UInt16 //Connection_Handle public init(connectionHandle: UInt16) { self.connectionHandle = connectionHandle } public var data: Data { let connectionHandleBytes = connectionHandle.littleEndian.bytes return Data([ connectionHandleBytes.0, connectionHandleBytes.1 ]) } } // MARK: - Return parameter /// LE Read PHY Command /// /// The command is used to read the current transmitter PHY and receiver PHY /// on the connection identified by the Connection_Handle. @frozen public struct HCILEReadPHYReturn: HCICommandReturnParameter { public static let command = HCILowEnergyCommand.readPhy //0x0030 public static let length: Int = 4 public let connectionHandle: UInt16 public let txPhy: LowEnergyTxPhy public let rxPhy: LowEnergyRxPhy public init?(data: Data) { guard data.count == type(of: self).length else { return nil } connectionHandle = UInt16(littleEndian: UInt16(bytes: (data[0], data[1]))) guard let txPhy = LowEnergyTxPhy(rawValue: data[2]) else { return nil } guard let rxPhy = LowEnergyRxPhy(rawValue: data[3]) else { return nil } self.txPhy = txPhy self.rxPhy = rxPhy } }
mit
005a08b4569e1fe17323abfcc2cfddf4
26.741935
127
0.653876
4.350759
false
false
false
false
jsslai/Action
Carthage/Checkouts/RxSwift/RxCocoa/iOS/UITabBar+Rx.swift
1
3386
// // UITabBar+Rx.swift // Rx // // Created by Jesse Farless on 5/13/16. // Copyright © 2016 Krunoslav Zaher. All rights reserved. // #if os(iOS) || os(tvOS) import Foundation import UIKit #if !RX_NO_MODULE import RxSwift #endif /** iOS only */ #if os(iOS) extension Reactive where Base: UITabBar { /** Reactive wrapper for `delegate` message `tabBar:willBeginCustomizingItems:`. */ public var willBeginCustomizing: ControlEvent<[UITabBarItem]> { let source = delegate.methodInvoked(#selector(UITabBarDelegate.tabBar(_:willBeginCustomizing:))) .map { a in return try castOrThrow([UITabBarItem].self, a[1]) } return ControlEvent(events: source) } /** Reactive wrapper for `delegate` message `tabBar:didBeginCustomizingItems:`. */ public var didBeginCustomizing: ControlEvent<[UITabBarItem]> { let source = delegate.methodInvoked(#selector(UITabBarDelegate.tabBar(_:didBeginCustomizing:))) .map { a in return try castOrThrow([UITabBarItem].self, a[1]) } return ControlEvent(events: source) } /** Reactive wrapper for `delegate` message `tabBar:willEndCustomizingItems:changed:`. */ public var willEndCustomizing: ControlEvent<([UITabBarItem], Bool)> { let source = delegate.methodInvoked(#selector(UITabBarDelegate.tabBar(_:willEndCustomizing:changed:))) .map { (a: [Any]) -> (([UITabBarItem], Bool)) in let items = try castOrThrow([UITabBarItem].self, a[1]) let changed = try castOrThrow(Bool.self, a[2]) return (items, changed) } return ControlEvent(events: source) } /** Reactive wrapper for `delegate` message `tabBar:didEndCustomizingItems:changed:`. */ public var didEndCustomizing: ControlEvent<([UITabBarItem], Bool)> { let source = delegate.methodInvoked(#selector(UITabBarDelegate.tabBar(_:didEndCustomizing:changed:))) .map { (a: [Any]) -> (([UITabBarItem], Bool)) in let items = try castOrThrow([UITabBarItem].self, a[1]) let changed = try castOrThrow(Bool.self, a[2]) return (items, changed) } return ControlEvent(events: source) } } #endif /** iOS and tvOS */ extension UITabBar { /** Factory method that enables subclasses to implement their own `delegate`. - returns: Instance of delegate proxy that wraps `delegate`. */ public func createRxDelegateProxy() -> RxTabBarDelegateProxy { return RxTabBarDelegateProxy(parentObject: self) } } extension Reactive where Base: UITabBar { /** Reactive wrapper for `delegate`. For more information take a look at `DelegateProxyType` protocol documentation. */ public var delegate: DelegateProxy { return RxTabBarDelegateProxy.proxyForObject(base) } /** Reactive wrapper for `delegate` message `tabBar:didSelectItem:`. */ public var didSelectItem: ControlEvent<UITabBarItem> { let source = delegate.methodInvoked(#selector(UITabBarDelegate.tabBar(_:didSelect:))) .map { a in return try castOrThrow(UITabBarItem.self, a[1]) } return ControlEvent(events: source) } } #endif
mit
8d4fbf32df604d4d3e9456f26faf4300
27.445378
110
0.63161
4.767606
false
false
false
false
ArtSabintsev/Swift-3-CocoaHeads-DC-Talk
Demo/APIDesignGuidelines.playground/Contents.swift
1
694
import Foundation /** Label closure parameters and tuple members */ // Not Prefered typealias aBadPersonTuple = (String, Int) let badTuple = aBadPersonTuple("Arthur", 30) badTuple.0 badTuple.1 // Prefered typealias aGoodPersonTuple = (name: String, age: Int) let goodTuple = aGoodPersonTuple(name: "Arthur", age: 30) goodTuple.name goodTuple.age /* --- */ // Not Prefered typealias aBadClosure = (String, Int) -> () func aBadFunc(completion handler: aBadClosure) {} //aBadFunc { (<#String#>, <#Int#>) in // <#code#> //} // Prefered typealias aGoodClosure = (name: String, age: Int) -> () func aGoodFunc(completion handler: aGoodClosure) {} aGoodFunc { (name, age) in }
mit
025ec5cc8d41ec878bc02062c5a1a830
15.926829
57
0.682997
3.126126
false
false
false
false
justinlevi/AudioRecorder
AudioRecorder/EditorController.swift
1
6072
// // EditorController.swift // AudioRecorder // // Created by Harshad Dange on 20/07/2014. // Copyright (c) 2014 Laughing Buddha Software. All rights reserved. // import Cocoa import AVFoundation import CoreMedia protocol EditorControllerDelegate { func editorControllerDidFinishExporting(editor: EditorController) } enum RecordingPreset: Int { case Low = 0 case Medium case High func settings() -> Dictionary<String, Int> { switch self { case .Low: return [AVLinearPCMBitDepthKey: 16, AVNumberOfChannelsKey : 1, AVSampleRateKey : 12_000, AVLinearPCMIsBigEndianKey : 0, AVLinearPCMIsFloatKey : 0] case .Medium: return [AVLinearPCMBitDepthKey: 16, AVNumberOfChannelsKey : 1, AVSampleRateKey : 24_000, AVLinearPCMIsBigEndianKey : 0, AVLinearPCMIsFloatKey : 0] case .High: return [AVLinearPCMBitDepthKey: 16, AVNumberOfChannelsKey : 1, AVSampleRateKey : 48_000, AVLinearPCMIsBigEndianKey : 0, AVLinearPCMIsFloatKey : 0] } } func exportSettings() -> Dictionary <String, Int> { var recordingSetting = self.settings() recordingSetting[AVFormatIDKey] = kAudioFormatLinearPCM recordingSetting[AVLinearPCMIsNonInterleaved] = 0 return recordingSetting } } class EditorController: NSWindowController, EditorViewDelegate { override func windowDidLoad() { super.windowDidLoad() refreshView() // Implement this method to handle any initialization after your window controller's window has been loaded from its nib file. editorView.delegate = self startField.stringValue = NSTimeInterval(0).hhmmss() endField.stringValue = duration.hhmmss() } @IBOutlet var editorView : EditorView @IBOutlet var startField : NSTextField @IBOutlet var endField : NSTextField @IBOutlet var qualitySelector : NSSegmentedControl var recordingURL: NSURL? var exportSession: AVAssetExportSession? var delegate: EditorControllerDelegate? var assetReadingQueue: dispatch_queue_t? var assetReader: AVAssetReader? var assetWriter: AVAssetWriter? var powerTrace: Float[]? { didSet { refreshView() } } var duration: NSTimeInterval = 0.0 { didSet { refreshView() } } @IBAction func clickSave(sender : NSButton) { if let assetURL = recordingURL { window.ignoresMouseEvents = true let selectedRange = editorView.selectedRange() let asset: AVAsset = AVAsset.assetWithURL(assetURL) as AVAsset let startTime = CMTimeMakeWithSeconds(selectedRange.start, 600) let duration = CMTimeMakeWithSeconds((selectedRange.end - selectedRange.start), 600) let timeRange = CMTimeRange(start: startTime, duration: duration) let exportPath = assetURL.path.stringByDeletingPathExtension + "-edited.wav" assetReader = AVAssetReader(asset: asset, error: nil) let assetTrack = asset.tracksWithMediaType(AVMediaTypeAudio).firstObject() as? AVAssetTrack let readerOutput = AVAssetReaderTrackOutput(track: assetTrack, outputSettings: nil) assetReader!.addOutput(readerOutput) assetReader!.timeRange = timeRange assetWriter = AVAssetWriter(URL: NSURL(fileURLWithPath: exportPath), fileType: AVFileTypeWAVE, error: nil) let selectedQuality = RecordingPreset.fromRaw(qualitySelector.selectedSegment) let writerInput = AVAssetWriterInput(mediaType: AVMediaTypeAudio, outputSettings: selectedQuality?.exportSettings()) writerInput.expectsMediaDataInRealTime = false assetWriter!.addInput(writerInput) assetWriter!.startWriting() assetWriter!.startSessionAtSourceTime(kCMTimeZero) assetReader!.startReading() assetReadingQueue = dispatch_queue_create("com.lbs.audiorecorder.assetreadingqueue", DISPATCH_QUEUE_SERIAL) writerInput.requestMediaDataWhenReadyOnQueue(assetReadingQueue){ while writerInput.readyForMoreMediaData { var nextBuffer: CMSampleBufferRef? = readerOutput.copyNextSampleBuffer() if (self.assetReader!.status == AVAssetReaderStatus.Reading) && (nextBuffer != nil) { writerInput.appendSampleBuffer(nextBuffer) } else { writerInput.markAsFinished() switch self.assetReader!.status { case .Failed: self.assetWriter!.cancelWriting() println("Failed :(") case .Completed: println("Done!") self.assetWriter!.endSessionAtSourceTime(duration) self.assetWriter!.finishWriting() dispatch_async(dispatch_get_main_queue()){ if let theDelegate = self.delegate { theDelegate.editorControllerDidFinishExporting(self) } } default: println("This should not happen :/") } break; } } } } } @IBAction func cliickReset(sender : NSButton) { editorView.reset() } func refreshView() -> () { if editorView != nil { editorView.duration = duration if let trace = powerTrace { editorView.audioLevels = trace } } } // MARK: EditorViewDelegate methods func timeRangeChanged(editor: EditorView, timeRange: (start: NSTimeInterval, end: NSTimeInterval)) { startField.stringValue = timeRange.start.hhmmss() endField.stringValue = timeRange.end.hhmmss() } }
mit
ca9d9820e7b894c439abf98b4393f71a
35.8
158
0.618083
5.525023
false
false
false
false
laszlokorte/reform-swift
ReformCore/ReformCore/MorphInstruction.swift
1
2210
// // MorphInstruction.swift // ReformCore // // Created by Laszlo Korte on 14.08.15. // Copyright © 2015 Laszlo Korte. All rights reserved. // public struct MorphInstruction : Instruction { public typealias DistanceType = RuntimeDistance & Labeled public var target : FormIdentifier? { return formId } public let formId : FormIdentifier public let anchorId : AnchorIdentifier public let distance : DistanceType public init(formId : FormIdentifier, anchorId: AnchorIdentifier, distance : DistanceType) { self.formId = formId self.anchorId = anchorId self.distance = distance } public func evaluate<T:Runtime>(_ runtime: T) { guard let form = runtime.get(formId) as? Morphable else { runtime.reportError(.unknownForm) return } guard let anchor = form.getAnchors()[anchorId] else { runtime.reportError(.unknownAnchor) return } guard let delta = distance.getDeltaFor(runtime) else { runtime.reportError(.invalidDistance) return } anchor.translate(runtime, delta: delta) } public func getDescription(_ stringifier: Stringifier) -> String { let formName = stringifier.labelFor(formId) ?? "???" let anchorName = stringifier.labelFor(formId, anchorId: anchorId) ?? "??" return "Move \(formName)'s \(anchorName) \(distance.getDescription(stringifier))" } public func analyze<T:Analyzer>(_ analyzer: T) { } public var isDegenerated : Bool { return distance.isDegenerated } } extension MorphInstruction : Mergeable { public func mergeWith(_ other: MorphInstruction, force: Bool) -> MorphInstruction? { guard formId == other.formId else { return nil } guard anchorId == other.anchorId else { return nil } guard let newDistance = merge(distance: distance, distance: other.distance, force: force) else { return nil } return MorphInstruction(formId: formId, anchorId: anchorId, distance: newDistance) } }
mit
95884ebb7a37ceb83591f832c77c2594
28.851351
104
0.620643
4.740343
false
false
false
false
ramonvasc/MXLCalendarManagerSwift
MXLCalendarManagerSwift/MXLCalendarEvent.swift
1
41507
// // MXLCalendarEvent.swift // Pods // // Created by Ramon Vasconcelos on 22/08/2017. // // // 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 EventKit let DAILY_FREQUENCY = "DAILY" let WEEKLY_FREQUENCY = "WEEKLY" let MONTHLY_FREQUENCY = "MONTHLY" let YEARLY_FREQUENCY = "YEARLY" public enum MXLCalendarEventRuleType { case MXLCalendarEventRuleTypeRepetition case MXLCalendarEventRuleTypeException } public class MXLCalendarEvent { public var dateFormatter: DateFormatter public var exRuleFrequency: String? public var exRuleCount: String? public var exRuleRuleWkSt: String? public var exRuleInterval: String? public var exRuleWeekStart: String? public var exRuleUntilDate: Date? public var exRuleBySecond: [String]? public var exRuleByMinute: [String]? public var exRuleByHour: [String]? public var exRuleByDay: [String]? public var exRuleByMonthDay: [String]? public var exRuleByYearDay: [String]? public var exRuleByWeekNo: [String]? public var exRuleByMonth: [String]? public var exRuleBySetPos: [String]? public var repeatRuleFrequency: String? public var repeatRuleCount: String? public var repeatRuleRuleWkSt: String? public var repeatRuleInterval: String? public var repeatRuleWeekStart: String? public var repeatRuleUntilDate: Date? public var repeatRuleBySecond: [String]? public var repeatRuleByMinute: [String]? public var repeatRuleByHour: [String]? public var repeatRuleByDay: [String]? public var repeatRuleByMonthDay: [String]? public var repeatRuleByYearDay: [String]? public var repeatRuleByWeekNo: [String]? public var repeatRuleByMonth: [String]? public var repeatRuleBySetPos: [String]? public var eventExceptionDates: [Date] = [Date]() public var calendar: Calendar? public var eventStartDate: Date? public var eventEndDate: Date? public var eventCreatedDate: Date? public var eventLastModifiedDate: Date? public var eventIsAllDay: Bool? public var eventUniqueID: String? public var eventRecurrenceID: String? public var eventSummary: String? public var eventDescription: String? public var eventLocation: String? public var eventStatus: String? public var attendees: [MXLCalendarAttendee]? public var rruleString: String? public init(withStartDate startString: String, endDate endString: String, createdAt createdString: String, lastModified lastModifiedString: String, uniqueID: String, recurrenceID: String, summary: String, description: String, location: String, status: String, recurrenceRules: String, exceptionDates: [String], exceptionRules: String, timeZoneIdentifier: String, attendees: [MXLCalendarAttendee]) { self.calendar = Calendar(identifier: .gregorian) self.dateFormatter = DateFormatter() self.dateFormatter.timeZone = TimeZone(identifier: timeZoneIdentifier.isEmpty ? "GMT" : timeZoneIdentifier) calendar?.timeZone = dateFormatter.timeZone self.dateFormatter.dateFormat = "yyyyMMdd HHmmss" self.eventStartDate = dateFromString(dateString: startString) self.eventEndDate = dateFromString(dateString: endString) self.eventCreatedDate = dateFromString(dateString: createdString) self.eventLastModifiedDate = dateFromString(dateString: lastModifiedString) self.eventExceptionDates = exceptionDates .compactMap({ (exceptionDateString) -> Date? in return self.dateFromString(dateString: exceptionDateString) }) self.rruleString = recurrenceRules parseRules(rule: recurrenceRules, forType: .MXLCalendarEventRuleTypeRepetition) parseRules(rule: exceptionRules, forType: .MXLCalendarEventRuleTypeException) self.eventUniqueID = uniqueID self.eventRecurrenceID = recurrenceID self.eventSummary = summary.replacingOccurrences(of: "\\", with: "") self.eventDescription = description.replacingOccurrences(of: "\\", with: "") self.eventLocation = location.replacingOccurrences(of: "\\", with: "") self.eventStatus = status self.attendees = attendees } public func dateFromString(dateString: String) -> Date? { var date: Date? let dateString = dateString.replacingOccurrences(of: "T", with: " ") let containsZone = dateString.range(of: "z", options: .caseInsensitive) != nil if containsZone { dateFormatter.dateFormat = "yyyyMMdd HHmmssz" } date = dateFormatter.date(from: dateString) if date == nil { if containsZone { dateFormatter.dateFormat = "yyyyMMddz" } else { dateFormatter.dateFormat = "yyyyMMdd" } date = dateFormatter.date(from: dateString) if date != nil { eventIsAllDay = true } } dateFormatter.dateFormat = "yyyyMMdd HHmmss" return date } public func parseRules(rule: String, forType type: MXLCalendarEventRuleType) { var ruleScanner = Scanner() let rulesArray = rule.components(separatedBy: ";") // Split up rules string into array var frequencyPointer: NSString? var frequency = String() var countPointer: NSString? var count = String() var untilPointer: NSString? var untilString = String() var intervalPointer: NSString? var interval = String() var byDayPointer: NSString? var byDay = String() var byMonthDayPointer: NSString? var byMonthDay = String() var byYearDayPointer: NSString? var byYearDay = String() var byWeekNoPointer: NSString? var byWeekNo = String() var byMonthPointer: NSString? var byMonth = String() var weekStartPointer: NSString? var weekStart = String() // Loop through each rule for rule in rulesArray { ruleScanner = Scanner(string: rule) // If the rule is for the FREQuency if rule.range(of: "FREQ") != nil { ruleScanner.scanUpTo("=", into: nil) ruleScanner.scanUpTo(";", into: &frequencyPointer) frequency = String(frequencyPointer ?? "") frequency = frequency.replacingOccurrences(of: "=", with: "") if type == .MXLCalendarEventRuleTypeRepetition { repeatRuleFrequency = frequency } else { exRuleFrequency = frequency } } // If the rule is COUNT if rule.range(of: "COUNT") != nil { ruleScanner.scanUpTo("=", into: nil) ruleScanner.scanUpTo(";", into: &countPointer) count = String(countPointer ?? "") count = count.replacingOccurrences(of: "=", with: "") if type == . MXLCalendarEventRuleTypeRepetition { repeatRuleCount = count } else { exRuleCount = count } } // If the rule is for the UNTIL date if rule.range(of: "UNTIL") != nil { ruleScanner.scanUpTo("=", into: nil) ruleScanner.scanUpTo(";", into: &untilPointer) untilString = String(untilPointer ?? "") untilString = untilString.replacingOccurrences(of: "=", with: "") if type == .MXLCalendarEventRuleTypeRepetition { repeatRuleUntilDate = dateFromString(dateString: untilString) } else { exRuleUntilDate = dateFromString(dateString: untilString) } } // If the rule is INTERVAL if rule.range(of: "INTERVAL") != nil { ruleScanner.scanUpTo("=", into: nil) ruleScanner.scanUpTo(";", into: &intervalPointer) interval = String(intervalPointer ?? "") interval = interval.replacingOccurrences(of: "=", with: "") if type == . MXLCalendarEventRuleTypeRepetition { repeatRuleInterval = interval } else { exRuleInterval = interval } } // If the rule is BYDAY if rule.range(of: "BYDAY") != nil { ruleScanner.scanUpTo("=", into: nil) ruleScanner.scanUpTo(";", into: &byDayPointer) byDay = String(byDayPointer ?? "") byDay = byDay.replacingOccurrences(of: "=", with: "") if type == . MXLCalendarEventRuleTypeRepetition { repeatRuleByDay = byDay.components(separatedBy: ",") } else { exRuleByDay = byDay.components(separatedBy: ",") } } // If the rule is BYMONTHDAY if rule.range(of: "BYMONTHDAY") != nil { ruleScanner.scanUpTo("=", into: nil) ruleScanner.scanUpTo(";", into: &byMonthDayPointer) byMonthDay = String(byMonthDayPointer ?? "") byMonthDay = byMonthDay.replacingOccurrences(of: "=", with: "") if type == . MXLCalendarEventRuleTypeRepetition { repeatRuleByMonthDay = byMonthDay.components(separatedBy: ",") } else { exRuleByMonthDay = byMonthDay.components(separatedBy: ",") } } // If the rule is BYYEARDAY if rule.range(of: "BYYEARDAY") != nil { ruleScanner.scanUpTo("=", into: nil) ruleScanner.scanUpTo(";", into: &byYearDayPointer) byYearDay = String(byYearDayPointer ?? "") byYearDay = byYearDay.replacingOccurrences(of: "=", with: "") if type == . MXLCalendarEventRuleTypeRepetition { repeatRuleByYearDay = byYearDay.components(separatedBy: ",") } else { exRuleByYearDay = byYearDay.components(separatedBy: ",") } } // If the rule is BYWEEKNO if rule.range(of: "BYWEEKNO") != nil { ruleScanner.scanUpTo("=", into: nil) ruleScanner.scanUpTo(";", into: &byWeekNoPointer) byWeekNo = String(byWeekNoPointer ?? "") byWeekNo = byWeekNo.replacingOccurrences(of: "=", with: "") if type == . MXLCalendarEventRuleTypeRepetition { repeatRuleByWeekNo = byWeekNo.components(separatedBy: ",") } else { exRuleByWeekNo = byWeekNo.components(separatedBy: ",") } } // If the rule is BYMONTH if rule.range(of: "BYMONTH=") != nil { ruleScanner.scanUpTo("=", into: nil) ruleScanner.scanUpTo(";", into: &byMonthPointer) byMonth = String(byMonthPointer ?? "") byMonth = byMonth.replacingOccurrences(of: "=", with: "") if type == . MXLCalendarEventRuleTypeRepetition { repeatRuleByMonth = byMonth.components(separatedBy: ",") } else { exRuleByMonth = byMonth.components(separatedBy: ",") } } // If the rule is WKST if rule.range(of: "WKST") != nil { ruleScanner.scanUpTo("=", into: nil) ruleScanner.scanUpTo(";", into: &weekStartPointer) weekStart = String(weekStartPointer ?? "") weekStart = weekStart.replacingOccurrences(of: "=", with: "") if type == . MXLCalendarEventRuleTypeRepetition { repeatRuleWeekStart = weekStart } else { exRuleWeekStart = weekStart } } } } public func check(day: Int, month: Int, year: Int) -> Bool { guard var components = calendar?.dateComponents([.day, .month, .year], from: Date()) else { return false } components.day = day components.month = month components.year = year return checkDate(date: calendar?.date(from: components)) } public func checkDate(date: Date?) -> Bool { guard let date = date, let eventStartDate = eventStartDate, let eventEndDate = eventEndDate else { return false } // If the event starts in the future if eventStartDate.compare(date) == .orderedDescending { return false } // If the event does not repeat, the 'date' must be the event's start date for event to occur on this date if repeatRuleFrequency == nil { // Load date into DateComponent from the Calendar instance let difference = calendar?.dateComponents([.day, .month, .year, .hour, .minute, .second], from: eventStartDate, to: date) // Check if the event's start date is equal to the provided date if difference?.day == 0, difference?.month == 0, difference?.year == 0, difference?.hour == 0, difference?.minute == 0, difference?.second == 0 { return exceptionOn(date: date) ? false : true // Check if there's an exception rule covering this date. Return accordingly } else { return false // Event won't occur on this date } } guard let calendar = calendar else { return false } // If the date is in the event's exception dates, event won't occur if eventExceptionDates.contains(where: { calendar.isDate(date, inSameDayAs: $0) }) { return false } // Extract the components from the provided date let components = calendar.dateComponents([.day, .weekOfYear, .month, .year, .weekday], from: date) guard let day = components.day, let month = components.month, let weekday = components.weekday, let weekOfYear = components.weekOfYear, let dayOfYear = calendar.ordinality(of: .day, in: .year, for: date) else { return false } let dayString = dayOfWeekFromInteger(day: weekday) let weekNumberString = String(format: "%li", weekOfYear) let monthString = String(format: "%li", month) // If the event is set to repeat on a certain day of the week, it MUST be the current date's weekday for it to occur if let repeatRuleByDay = repeatRuleByDay, !repeatRuleByDay.contains(dayString) { // These checks are to catch if the event is set to repeat on a particular weekday of the month (e.g., every third Sunday) if !repeatRuleByDay.contains(String(format: "1%@", dayString)), !repeatRuleByDay.contains(String(format: "2%@", dayString)), !repeatRuleByDay.contains(String(format: "3%@", dayString)) { return false } } // Same as above (and bellow) if let repeatRuleByMonthDay = repeatRuleByMonthDay, !repeatRuleByMonthDay.contains(String(format: "%li", day)) { return false } if let repeatRuleByYearDay = repeatRuleByYearDay, !repeatRuleByYearDay.contains(String(format: "%li", dayOfYear)) { return false } if let repeatRuleByWeekNo = repeatRuleByWeekNo, !repeatRuleByWeekNo.contains(weekNumberString) { return false } if let repeatRuleByMonth = repeatRuleByMonth, !repeatRuleByMonth.contains(monthString) { return false } // If there's no repetition interval provided, it means the interval = 1. // We explicitly set it to "1" for use in calculations below repeatRuleInterval = repeatRuleInterval ?? "1" guard let repeatRuleInterval = repeatRuleInterval, let repeatRuleIntervalInt = Int(repeatRuleInterval) else { return false } // If it's set to repeat every week... if repeatRuleFrequency == WEEKLY_FREQUENCY { // Is there a limit on the number of repetitions // (e.g., event repeats for the 3 occurrences after it first occurred) if let repeatRuleCount = repeatRuleCount, let repeatRuleCountInt = Int(repeatRuleCount) { // Get the number of weeks from the first occurrence until the last one, then multiply by 7 days a week let daysUntilLastOccurrence = (repeatRuleCountInt - 1) * repeatRuleIntervalInt * 7 var comp = DateComponents() comp.day = daysUntilLastOccurrence // Create a date by adding the number of days until the final occurrence onto the first occurrence guard let maximumDate = calendar.date(byAdding: comp, to: eventEndDate) else { return false } // If the final possible occurrence is in the future... if maximumDate.compare(date) == .orderedDescending || maximumDate.compare(date) == .orderedSame { // Get the number of weeks between the final date and current date if let difference = calendar.dateComponents([.day], from: maximumDate, to: date).day { if difference % repeatRuleIntervalInt != 0 { return false } else { return true } } } else { return false } } else if let repeatRuleUntilDate = repeatRuleUntilDate { if repeatRuleUntilDate.compare(date) == .orderedDescending || repeatRuleUntilDate.compare(date) == .orderedSame, let difference = calendar.dateComponents([.day], from: repeatRuleUntilDate, to: date).day { if difference % repeatRuleIntervalInt != 0 { return false } else { return true } } else { return false } } else if let difference = calendar.dateComponents([.day], from: eventStartDate, to: date).day { if difference % repeatRuleIntervalInt != 0 { return false } else { return true } } } else if repeatRuleFrequency == DAILY_FREQUENCY { if let repeatRuleCount = repeatRuleCount, let repeatRuleCountInt = Int(repeatRuleCount) { // Get the number of days from the first occurrence until the last one let daysUntilLastOccurrence = (repeatRuleCountInt - 1) * repeatRuleIntervalInt var comp = DateComponents() comp.day = daysUntilLastOccurrence // Create a date by adding the number of days until the final occurrence onto the first occurrence guard let maximumDate = calendar.date(byAdding: comp, to: eventEndDate) else { return false } // If the final possible occurrence is in the future... if maximumDate.compare(date) == .orderedDescending || maximumDate.compare(date) == .orderedSame { // Get the number of weeks between the final date and current date if let difference = calendar.dateComponents([.day], from: maximumDate, to: date).day { if difference % repeatRuleIntervalInt != 0 { return false } else { return true } } } else { return false } } else if let repeatRuleUntilDate = repeatRuleUntilDate { if repeatRuleUntilDate.compare(date) == .orderedDescending || repeatRuleUntilDate.compare(date) == .orderedSame, let difference = calendar.dateComponents([.day], from: repeatRuleUntilDate, to: date).day { if difference % repeatRuleIntervalInt != 0 { return false } else { return true } } else { return false } } else if let difference = calendar.dateComponents([.day], from: eventStartDate, to: date).day { if difference % repeatRuleIntervalInt != 0 { return false } else { return true } } } else if repeatRuleFrequency == MONTHLY_FREQUENCY { if let repeatRuleCount = repeatRuleCount, let repeatRuleCountInt = Int(repeatRuleCount) { let monthsUntilLastOccurrence = (repeatRuleCountInt - 1) * repeatRuleIntervalInt var comp = DateComponents() comp.month = monthsUntilLastOccurrence let maximumDate = calendar.date(byAdding: comp, to: eventEndDate) if maximumDate?.compare(date) == .orderedDescending || maximumDate?.compare(date) == .orderedSame, let calendarDate = calendar.date(from: comp), let difference = calendar.dateComponents([.month], from: calendarDate, to: date).month { if difference % repeatRuleIntervalInt != 0 { return false } else { return true } } else { return false } } else if let repeatRuleUntilDate = repeatRuleUntilDate { if repeatRuleUntilDate.compare(date) == .orderedDescending || repeatRuleUntilDate.compare(date) == .orderedSame, let difference = calendar.dateComponents([.month], from: repeatRuleUntilDate, to: date).month { if difference % repeatRuleIntervalInt != 0 { return false } else { return true } } else { return false } } else { if let difference = calendar.dateComponents([.day], from: eventStartDate, to: date).month, difference % repeatRuleIntervalInt != 0 { return false } else { return true } } } else if repeatRuleFrequency == YEARLY_FREQUENCY { if let repeatRuleCount = repeatRuleCount, let repeatRuleCountInt = Int(repeatRuleCount) { let yearsUntilLastOccurrence = (repeatRuleCountInt - 1) * repeatRuleIntervalInt var comp = DateComponents() comp.year = yearsUntilLastOccurrence let maximumDate = calendar.date(byAdding: comp, to: eventEndDate) if maximumDate?.compare(date) == .orderedDescending || maximumDate?.compare(date) == .orderedSame, let calendarDate = calendar.date(from: comp), let difference = calendar.dateComponents([.year], from:calendarDate, to: date).year { if difference % repeatRuleIntervalInt != 0 { return false } else { return true } } } else if let repeatRuleUntilDate = repeatRuleUntilDate { if repeatRuleUntilDate.compare(date) == .orderedDescending || repeatRuleUntilDate.compare(date) == .orderedSame, let difference = calendar.dateComponents([.year], from: repeatRuleUntilDate, to: date).year { if difference % repeatRuleIntervalInt != 0 { return false } else { return true } } else { return false } } else { if let difference = calendar.dateComponents([.year], from: eventStartDate, to: date).year { if difference % repeatRuleIntervalInt != 0 { return false } else { return true } } } } else { return false } return false } // This algorith functions the same as check(day, month, year) except rather than checking repeatRule parameters, it checks exRule public func exceptionOn(date: Date) -> Bool { // If the event does not repeat, the 'date' must be the event's start date for event to occur on this date if exRuleFrequency == nil { return false } // If the date is in the event's exception dates, event won't occur if eventExceptionDates.contains(date) { return false } guard let calendar = calendar else { return false } let components = calendar.dateComponents([.day, .weekOfYear, .month, .year, .weekday], from: date) guard let day = components.day, let month = components.month, let weekday = components.weekday, let weekOfYear = components.weekOfYear, let dayOfYear = calendar.ordinality(of: .day, in: .year, for: date), let eventCreatedDate = eventCreatedDate else { return false } let dayString = dayOfWeekFromInteger(day: weekday) let weekNumberString = String(format: "%li", weekOfYear) let monthString = String(format: "%li", month) // If the event is set to repeat on a certain day of the week, it MUST be the current date's weekday for it to occur if let exRuleByDay = exRuleByDay, !exRuleByDay.contains(dayString) { // These checks are to catch if the event is set to repeat on a particular weekday of the month (e.g., every third Sunday) if !exRuleByDay.contains(String(format: "1%@", dayString)), !exRuleByDay.contains(String(format: "2%@", dayString)), !exRuleByDay.contains(String(format: "3%@", dayString)) { return false } } // Same as above (and bellow) if let exRuleByMonthDay = exRuleByMonthDay, !exRuleByMonthDay.contains(String(format: "%li", day)) { return false } if let exRuleByYearDay = exRuleByYearDay, !exRuleByYearDay.contains(String(format: "%li", dayOfYear)) { return false } if let exRuleByWeekNo = exRuleByWeekNo, !exRuleByWeekNo.contains(weekNumberString) { return false } if let exRuleByMonth = exRuleByMonth, !exRuleByMonth.contains(monthString) { return false } exRuleInterval = exRuleInterval ?? "1" guard let exRuleInterval = exRuleInterval, let exRuleIntervalInt = Int(exRuleInterval), let eventEndDate = eventEndDate else { return false } // If it's set to repeat every week... if exRuleFrequency == WEEKLY_FREQUENCY { // Is there a limit on the number of repetitions // (e.g., event repeats for the 3 occurrences after it first occurred) if let exRuleCount = exRuleCount, let exRuleCountInt = Int(exRuleCount) { // Get the final possible time the event will be repeated var comp = DateComponents() comp.day = exRuleCountInt * exRuleIntervalInt // Create a date by adding the final week it'll occur onto the first occurrence guard let maximumDate = calendar.date(byAdding: comp, to: eventEndDate) else { return false } // If the final possible occurrence is in the future... if maximumDate.compare(date) == .orderedDescending || maximumDate.compare(date) == .orderedSame { // Get the number of weeks between the final date and current date if let difference = calendar.dateComponents([.day], from: maximumDate, to: date).day { if difference % exRuleIntervalInt != 0 { return false } else { return true } } } else { return false } } else if let exRuleUntilDate = exRuleUntilDate { if exRuleUntilDate.compare(date) == .orderedDescending || exRuleUntilDate.compare(date) == .orderedSame, let difference = calendar.dateComponents([.day], from: exRuleUntilDate, to: date).day { if difference % exRuleIntervalInt != 0 { return false } else { return true } } else { return false } } else if let difference = calendar.dateComponents([.day], from: eventCreatedDate, to: date).day { if difference % exRuleIntervalInt != 0 { return false } else { return true } } } else if exRuleFrequency == MONTHLY_FREQUENCY { if let exRuleCount = exRuleCount, let exRuleCountInt = Int(exRuleCount) { let finalMonth = exRuleCountInt * exRuleIntervalInt var comp = DateComponents() comp.month = finalMonth let maximumDate = calendar.date(byAdding: comp, to: eventEndDate) if maximumDate?.compare(date) == .orderedDescending || maximumDate?.compare(date) == .orderedSame, let calendarDate = calendar.date(from: comp), let difference = calendar.dateComponents([.month], from: calendarDate, to: date).month { if difference % exRuleIntervalInt != 0 { return false } else { return true } } else { return false } } else if let exRuleUntilDate = exRuleUntilDate { if exRuleUntilDate.compare(date) == .orderedDescending || exRuleUntilDate.compare(date) == .orderedSame, let difference = calendar.dateComponents([.month], from: exRuleUntilDate, to: date).month { if difference % exRuleIntervalInt != 0 { return false } else { return true } } else { return false } } else { if let difference = calendar.dateComponents([.day], from: eventCreatedDate, to: date).month, difference % exRuleIntervalInt != 0 { return false } else { return true } } } else if exRuleFrequency == YEARLY_FREQUENCY { if let exRuleCount = exRuleCount, let exRuleCountInt = Int(exRuleCount) { let finalYear = exRuleCountInt * exRuleIntervalInt var comp = DateComponents() comp.year = finalYear let maximumDate = calendar.date(byAdding: comp, to: eventEndDate) if maximumDate?.compare(date) == .orderedDescending || maximumDate?.compare(date) == .orderedSame, let calendarDate = calendar.date(from: comp), let difference = calendar.dateComponents([.year], from:calendarDate, to: date).year { if difference % exRuleIntervalInt != 0 { return false } else { return true } } } else if let exRuleUntilDate = exRuleUntilDate, let difference = calendar.dateComponents([.year], from: exRuleUntilDate, to: date).year { if difference % exRuleIntervalInt != 0 { return false } else { return true } } else { if let difference = calendar.dateComponents([.year], from: eventCreatedDate, to: date).year { if difference % exRuleIntervalInt != 0 { return false } else { return true } } } } else { return false } return false } public func convertToEKEventOn(date: Date, store eventStore: EKEventStore) -> EKEvent? { guard let eventStartDate = eventStartDate, let eventEndDate = eventEndDate, let eventSummary = eventSummary, let eventIsAllDay = eventIsAllDay else { return nil } var components = Calendar.current.dateComponents([.hour, .minute, .day, .month, .year], from: eventStartDate) var endComponents = Calendar.current.dateComponents([.hour, .minute, .day, .month, .year], from: eventEndDate) let selectedDayComponents = Calendar.current.dateComponents([.day, .month, .year], from: date) components.day = selectedDayComponents.day components.month = selectedDayComponents.month components.year = selectedDayComponents.year endComponents.day = selectedDayComponents.day endComponents.month = selectedDayComponents.month endComponents.year = selectedDayComponents.year let event = EKEvent(eventStore: eventStore) event.title = eventSummary event.notes = eventDescription event.location = eventLocation event.isAllDay = eventIsAllDay event.startDate = Calendar.current.date(from: components) ?? Date() event.endDate = Calendar.current.date(from: endComponents) ?? Date() return event } public func checkTime(targetTime: Date) -> Bool { guard let firstStartTime = eventStartDate, let firstEndTime = eventEndDate else { return false } if repeatRuleFrequency == nil { return dateWithinRange(date: targetTime, start: firstStartTime, end: firstEndTime) } else { guard let calendar = calendar else { return false } // check if there's an occurrence that starts on the same day as targetTime if checkDate(date: targetTime) { // now check if targetTime is actually inside that occurrence // number of years, months, days, between firstStart's date and targetTimes's date let daysSinceFirstStart = calendar.dateComponents([.year, .month, .day], from: firstStartTime, to: targetTime) // add to firstStart and firstEnd the computed number of years, months, days, to get start and end times of the target occurrence if let targetStartTime = calendar.date(byAdding: daysSinceFirstStart, to: firstStartTime), let targetEndTime = calendar.date(byAdding: daysSinceFirstStart, to: firstEndTime), dateWithinRange(date: targetTime, start: targetStartTime, end: targetEndTime) { return true } } else { // check if there's an occurrence that starts the day before targetTime. let startOfTargetDay = calendar.startOfDay(for: targetTime) let nightBeforeTargetTime = startOfTargetDay.addingTimeInterval(-1) if checkDate(date: nightBeforeTargetTime) { // now check if targetTime is actually inside that occurrence, this time by using number of years, months, days, since firstEnd's date let daysSinceFirstEnd = calendar.dateComponents([.year, .month, .day], from: firstEndTime, to: targetTime) if let targetStartTime = calendar.date(byAdding: daysSinceFirstEnd, to: firstStartTime), let targetEndTime = calendar.date(byAdding: daysSinceFirstEnd, to: firstEndTime), dateWithinRange(date: targetTime, start: targetStartTime, end: targetEndTime), dateWithinRange(date: nightBeforeTargetTime, start: targetStartTime, end: targetEndTime) { return true } } } // KNOWN LIMITATION: this only works for events that span across at most 2 days return false } } private func dateWithinRange(date: Date, start: Date, end: Date) -> Bool { guard start < end else { return false } let range = start ... end return range.contains(date) } private func dayOfWeekFromInteger(day: Int) -> String { switch day { case 1: return "SU" case 2: return "MO" case 3: return "TU" case 4: return "WE" case 5: return "TH" case 6: return "FR" case 7: return "SA" default: return "" } } } func ==<T: Equatable>(lhs: [T]?, rhs: [T]?) -> Bool { switch (lhs, rhs) { case (.some(let lhs), .some(let rhs)): return lhs == rhs case (.none, .none): return true default: return false } } extension MXLCalendarEvent: Equatable { public static func == (lhs: MXLCalendarEvent, rhs: MXLCalendarEvent) -> Bool { let exRuleCheck = lhs.exRuleCount == rhs.exRuleCount && lhs.exRuleRuleWkSt == rhs.exRuleRuleWkSt && lhs.exRuleInterval == rhs.exRuleInterval && lhs.exRuleWeekStart == rhs.exRuleWeekStart && lhs.exRuleUntilDate == rhs.exRuleUntilDate && lhs.exRuleBySecond == rhs.exRuleBySecond && lhs.exRuleByMinute == rhs.exRuleByMinute && lhs.exRuleByHour == rhs.exRuleByHour && lhs.exRuleByDay == rhs.exRuleByDay && lhs.exRuleByMonthDay == rhs.exRuleByMonthDay && lhs.exRuleByYearDay == rhs.exRuleByYearDay && lhs.exRuleByWeekNo == rhs.exRuleByWeekNo && lhs.exRuleByMonth == rhs.exRuleByMonth && lhs.exRuleBySetPos == rhs.exRuleBySetPos let repeatRuleCheck = lhs.repeatRuleFrequency == rhs.repeatRuleFrequency && lhs.repeatRuleCount == rhs.repeatRuleCount && lhs.repeatRuleRuleWkSt == rhs.repeatRuleRuleWkSt && lhs.repeatRuleInterval == rhs.repeatRuleInterval && lhs.repeatRuleWeekStart == rhs.repeatRuleWeekStart && lhs.repeatRuleUntilDate == rhs.repeatRuleUntilDate && lhs.repeatRuleBySecond == rhs.repeatRuleBySecond && lhs.repeatRuleByMinute == rhs.repeatRuleByMinute && lhs.repeatRuleByHour == rhs.repeatRuleByHour && lhs.repeatRuleByDay == rhs.repeatRuleByDay && lhs.repeatRuleByMonthDay == rhs.repeatRuleByMonthDay && lhs.repeatRuleByYearDay == rhs.repeatRuleByYearDay && lhs.repeatRuleByWeekNo == rhs.repeatRuleByWeekNo && lhs.repeatRuleByMonth == rhs.repeatRuleByMonth && lhs.repeatRuleBySetPos == rhs.repeatRuleBySetPos let eventCheck = lhs.dateFormatter == rhs.dateFormatter && lhs.calendar == rhs.calendar && lhs.eventStartDate == rhs.eventStartDate && lhs.eventEndDate == rhs.eventEndDate && lhs.eventCreatedDate == rhs.eventCreatedDate && lhs.eventLastModifiedDate == rhs.eventLastModifiedDate && lhs.eventIsAllDay == rhs.eventIsAllDay && lhs.eventUniqueID == rhs.eventUniqueID && lhs.eventRecurrenceID == rhs.eventRecurrenceID && lhs.eventSummary == rhs.eventSummary && lhs.eventDescription == rhs.eventDescription && lhs.eventLocation == rhs.eventStatus && lhs.attendees == rhs.attendees && lhs.rruleString == rhs.rruleString return exRuleCheck && repeatRuleCheck && eventCheck } }
mit
926b087a847806c5c7d853912f88e7fe
43.297759
259
0.575469
4.993624
false
false
false
false
midoks/Swift-Learning
GitHubStar/GitHubStar/GitHubStar/Controllers/common/commits/GsCommitsHomeViewController.swift
1
8343
// // GsCommitsHomeViewController.swift // GitHubStar // // Created by midoks on 16/4/25. // Copyright © 2016年 midoks. All rights reserved. // import UIKit import SwiftyJSON class GsCommitsHomeViewController: GsHomeViewController { var _resultData:JSON? var _file = Array<Array<JSON>>() var _fixedUrl = "" override func viewDidLoad() { super.viewDidLoad() initView() } func initView(){ if _resultData != nil { self.setAvatar(url: _resultData!["author"]["avatar_url"].stringValue) let msg = _resultData!["commit"]["message"].stringValue let msgArr = msg.components(separatedBy: "\n") self.setName(name: msgArr[0]) self.setDesc(desc: _resultData!["commit"]["committer"]["date"].stringValue) var v = Array<GsIconView>() let additions = GsIconView() additions.key.text = _resultData!["stats"]["additions"].stringValue additions.desc.text = "Additions" v.append(additions) let deletions = GsIconView() deletions.key.text = _resultData!["stats"]["deletions"].stringValue deletions.desc.text = "Deletions" v.append(deletions) let parents = GsIconView() parents.key.text = String(_resultData!["parents"].count) parents.desc.text = "Parents" v.append(parents) self.setIconView(icon: v) } } func setUrlData(data:JSON) { self.setAvatar(url: data["author"]["avatar_url"].stringValue) _fixedUrl = data["url"].stringValue } override func refreshUrl(){ super.refreshUrl() if _fixedUrl != "" { self.startRefresh() GitHubApi.instance.webGet(absoluteUrl: _fixedUrl) { (data, response, error) -> Void in self.endRefresh() if data != nil { self._resultData = self.gitJsonParse(data: data!) self.reloadTable() } } } } func filterFileData(){ let file = _resultData!["files"] var tmpFile = Array<String>() var k = Array<Array<JSON>>() var kk = Array<JSON>() for i in file { var iValue = i.1 var tmpValue = iValue["filename"].stringValue.components(separatedBy: "/") _ = tmpValue.popLast() let fileName = "/" + tmpValue.joined(separator: "/").uppercased() if tmpFile.contains(fileName) { kk.append(iValue) } else { if tmpFile.count > 0 { k.append(kk) } kk = Array<JSON>() iValue["dir"] = JSON(fileName) kk.append(iValue) tmpFile.append(fileName) } } _file = k } func reloadTable(){ filterFileData() //print(_resultData) //print(_file) initView() _tableView?.reloadData() } } extension GsCommitsHomeViewController { func viewWillTransitionToSize(size: CGSize, withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator) { super.viewWillTransition(to: size, with: coordinator) self.reloadTable() //_tableView?.reloadSectionIndexTitles() } } //Mark: - UITableViewDataSource && UITableViewDelegate - extension GsCommitsHomeViewController{ func numberOfSectionsInTableView(tableView: UITableView) -> Int { if _resultData != nil { //print("_file:",_file.count) var r = 3 if _file.count > 0 { r += _file.count } return r } return 0 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { //print("section:",section) if _resultData != nil { if section == 0 { return 0 } else if section == 1 { return 1 } else if (section>1 && section<_file.count+2) { return _file[section - 2].count } return 1 } return 0 } func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { if _resultData != nil { if indexPath.section == 1 { if indexPath.row == 0 { let v = _resultData!["commit"]["message"].stringValue if v != "" { let h = v.textSize(font: UIFont.systemFont(ofSize: 14), width: self.view.frame.width - 20) return h + 20 } } } else if indexPath.section == 2 { } } return 44 } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { if _resultData != nil { if indexPath.section == 1 { let cell = UITableViewCell(style: .default, reuseIdentifier: nil) cell.textLabel?.text = _resultData!["commit"]["message"].stringValue cell.textLabel?.numberOfLines = 0 cell.selectionStyle = UITableViewCellSelectionStyle.none cell.textLabel?.font = UIFont.systemFont(ofSize: 14) return cell } else if (indexPath.section>1 && indexPath.section<_file.count+2) { let data = _file[indexPath.section - 2] let cell = UITableViewCell(style: .default, reuseIdentifier: nil) cell.textLabel?.text = "/" + data[indexPath.row]["filename"].stringValue //cell.textLabel?.font = UIFont.systemFontOfSize(12) cell.accessoryType = .disclosureIndicator return cell } else { let cell = UITableViewCell(style: .default, reuseIdentifier: nil) cell.textLabel?.text = "Add Comment" cell.imageView?.image = UIImage(named: "repo_pen") cell.accessoryType = .disclosureIndicator return cell } } let cell = UITableViewCell(style: .default, reuseIdentifier: nil) cell.textLabel?.text = "home" return cell } func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { tableView.deselectRow(at: indexPath as IndexPath, animated: true) if indexPath.section == 0 { } else if indexPath.section == 1 { } else if (indexPath.section>1 && indexPath.section<_file.count+2) { let data = _file[indexPath.section - 2][indexPath.row] let code = GsCommitsCodeViewController() code.setUrlData(data: data) self.push(v: code) } } func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { if section == 0 { } else if section == 1 { } else if (section>1 && section<_file.count+2) { let data = _file[section - 2] let root = self.getRootVC() let w = root.view.frame.width < root.view.frame.height ? root.view.frame.width : root.view.frame.height //此处有问题,w暂时取最小值 let h = data[0]["dir"].stringValue.textSize(font: UIFont.systemFont(ofSize: 14), width: w) return h } return 0 } func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? { if section == 0 { } else if section == 1 { } else if (section>1 && section<_file.count+2) { let data = _file[section - 2] return data[0]["dir"].stringValue } return "" } }
apache-2.0
f312376c0311f842231178b6b102536c
31.492188
127
0.514186
5.081246
false
false
false
false
wordpress-mobile/AztecEditor-iOS
Aztec/Classes/TextKit/LineAttachment.swift
2
1645
import Foundation import UIKit /// Custom horizontal line drawing attachment. /// open class LineAttachment: NSTextAttachment { fileprivate var glyphImage: UIImage? /// The color to use when drawing progress indicators /// open var color = UIColor.gray // MARK: - NSTextAttachmentContainer override open func image(forBounds imageBounds: CGRect, textContainer: NSTextContainer?, characterIndex charIndex: Int) -> UIImage? { if let cachedImage = glyphImage, imageBounds.size.equalTo(cachedImage.size) { return cachedImage } glyphImage = glyph(forBounds: imageBounds) return glyphImage } fileprivate func glyph(forBounds bounds: CGRect) -> UIImage? { let size = bounds.size UIGraphicsBeginImageContextWithOptions(bounds.size, false, 0) color.setStroke() let path = UIBezierPath() path.lineWidth = 1.0 path.move(to: CGPoint(x:0, y:bounds.height / 2)) path.addLine(to: CGPoint(x: size.width, y: bounds.height / 2)) path.stroke() let result = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return result; } override open func attachmentBounds(for textContainer: NSTextContainer?, proposedLineFragment lineFrag: CGRect, glyphPosition position: CGPoint, characterIndex charIndex: Int) -> CGRect { let padding = textContainer?.lineFragmentPadding ?? 0 let width = lineFrag.width - padding * 2 let height:CGFloat = 22.0 return CGRect(origin: CGPoint.zero, size: CGSize(width: width, height: height)) } }
mpl-2.0
5e9bfd9cba92b618f087e190dc715336
29.462963
191
0.679027
5.046012
false
false
false
false
hooman/swift
test/expr/postfix/call/forward_trailing_closure.swift
11
2641
// RUN: %target-typecheck-verify-swift -swift-version 6 // REQUIRES: asserts func forwardMatch1( a: Int = 0, b: Int = 17, closure1: (Int) -> Int = { $0 }, c: Int = 42, numbers: Int..., closure2: ((Double) -> Double)? = nil, closure3: (String) -> String = { $0 + "!" } ) { } func testForwardMatch1(i: Int, d: Double, s: String) { forwardMatch1() // Matching closure1 forwardMatch1 { _ in i } forwardMatch1 { _ in i } closure2: { d + $0 } forwardMatch1 { _ in i } closure2: { d + $0 } closure3: { $0 + ", " + s + "!" } forwardMatch1 { _ in i } closure3: { $0 + ", " + s + "!" } forwardMatch1(a: 5) { $0 + i } forwardMatch1(a: 5) { $0 + i } closure2: { d + $0 } forwardMatch1(a: 5) { $0 + i } closure2: { d + $0 } closure3: { $0 + ", " + s + "!" } forwardMatch1(a: 5) { $0 + i } closure3: { $0 + ", " + s + "!" } forwardMatch1(b: 1) { $0 + i } forwardMatch1(b: 1) { $0 + i } closure2: { d + $0 } forwardMatch1(b: 1) { $0 + i } closure2: { d + $0 } closure3: { $0 + ", " + s + "!" } forwardMatch1(b: 1) { $0 + i } closure3: { $0 + ", " + s + "!" } // Matching closure2 forwardMatch1(closure1: { $0 + i }) { d + $0 } forwardMatch1(closure1: { $0 + i }, numbers: 1, 2, 3) { d + $0 } forwardMatch1(closure1: { $0 + i }, numbers: 1, 2, 3) { d + $0 } closure3: { $0 + ", " + s + "!" } // Matching closure3 forwardMatch1(closure2: nil) { $0 + ", " + s + "!" } } func forwardMatchWithAutoclosure1( a: String = "hello", b: @autoclosure () -> Int = 17, closure1: () -> String ) { } func testForwardMatchWithAutoclosure1(i: Int, s: String) { forwardMatchWithAutoclosure1 { print(s) return s } forwardMatchWithAutoclosure1(a: s) { print(s) return s } forwardMatchWithAutoclosure1(b: i) { print(s) return s } forwardMatchWithAutoclosure1(a: s, b: i) { print(s) return s } } func forwardMatchWithAutoclosure2( a: String = "hello", closure1: @autoclosure () -> (() -> String), closure2: () -> Int = { 5 } ) { } func testForwardMatchWithAutoclosure2(i: Int, s: String) { forwardMatchWithAutoclosure2 { print(s) return s } forwardMatchWithAutoclosure2(a: s) { print(s) return s } forwardMatchWithAutoclosure2(a: s, closure1: { s }) { print(i) return i } } // Match a closure parameter to a variadic parameter. func acceptsVariadicClosureParameter(closures: ((Int, Int) -> Int)...) { } func testVariadicClosureParameter() { acceptsVariadicClosureParameter { x, y in x % y } acceptsVariadicClosureParameter() { x, y in x % y } acceptsVariadicClosureParameter(closures: +, -, *, /) { x, y in x % y } }
apache-2.0
81b307e1a5045750893e4b800fcbd2c3
27.095745
100
0.573268
2.918232
false
false
false
false
yunlzheng/practice-space
swift/simpleTable/FoodPin/FoodPin/RestaurantTableViewController.swift
1
8185
// // RestaurantTableViewController.swift // FoodPin // // Created by apple on 15/7/4. // Copyright (c) 2015年 yunlong. All rights reserved. // import UIKit class RestaurantTableViewController: UITableViewController { var restaurants:[Restaurant] = [ Restaurant(name: "Cafe Deadend", type: "Coffee & Tea Shop", location: "G/F, 72 Po HingFong, Sheung Wan, Hong Kong", image: "cafedeadend.jpg", isVisited: true), Restaurant(name: "Homei", type: "Cafe", location: "Shop B, G/F, 22-24A Tai Ping SanStreet SOHO, Sheung Wan, Hong Kong", image: "homei.jpg", isVisited: false), Restaurant(name: "Teakha", type: "Tea House", location: "Shop B, 18 Tai Ping Shan RoadSOHO, Sheung Wan, Hong Kong", image: "teakha.jpg", isVisited: false), Restaurant(name: "Cafe loisl", type: "Austrian / Causual Drink", location: "Shop B, 20Tai Ping Shan Road SOHO, Sheung Wan, Hong Kong", image: "cafeloisl.jpg", isVisited: false), Restaurant(name: "Petite Oyster", type: "French", location: "24 Tai Ping Shan RoadSOHO, Sheung Wan, Hong Kong", image: "petiteoyster.jpg", isVisited: false), Restaurant(name: "For Kee Restaurant", type: "Bakery", location: "Shop J-K., 200Hollywood Road, SOHO, Sheung Wan, Hong Kong", image: "forkeerestaurant.jpg", isVisited: false), Restaurant(name: "Po's Atelier", type: "Bakery",location: "G/F, 62 Po Hing Fong,Sheung Wan, Hong Kong", image: "posatelier.jpg", isVisited: false), Restaurant(name: "Bourke Street Backery", type: "Chocolate", location: "633 Bourke StSydney New South Wales 2010 Surry Hills", image: "bourkestreetbakery.jpg", isVisited: false), Restaurant(name: "Haigh's Chocolate", type: "Cafe", location: "412-414 George St SydneyNew South Wales", image: "haighschocolate.jpg", isVisited: false), Restaurant(name: "Palomino Espresso", type: "American / Seafood", location: "Shop 1 61York St Sydney New South Wales", image: "palominoespresso.jpg", isVisited: false), Restaurant(name: "Upstate", type: "American", location: "95 1st Ave New York, NY10003", image: "upstate.jpg", isVisited: false), Restaurant(name: "Traif", type: "American", location: "229 S 4th St Brooklyn, NY11211", image: "traif.jpg", isVisited: false), Restaurant(name: "Graham Avenue Meats", type: "Breakfast & Brunch", location: "445Graham Ave Brooklyn, NY 11211", image: "grahamavenuemeats.jpg", isVisited: false), Restaurant(name: "Waffle & Wolf", type: "Coffee & Tea", location: "413 Graham AveBrooklyn, NY 11211", image: "wafflewolf.jpg", isVisited: false), Restaurant(name: "Five Leaves", type: "Coffee & Tea", location: "18 Bedford AveBrooklyn, NY 11222", image: "fiveleaves.jpg", isVisited: false), Restaurant(name: "Cafe Lore", type: "Latin American", location: "Sunset Park 4601 4thAve Brooklyn, NY 11220", image: "cafelore.jpg", isVisited: false), Restaurant(name: "Confessional", type: "Spanish", location: "308 E 6th St New York, NY10003", image: "confessional.jpg", isVisited: false), Restaurant(name: "Barrafina", type: "Spanish", location: "54 Frith Street London W1D4SL United Kingdom", image: "barrafina.jpg", isVisited: false), Restaurant(name: "Donostia", type: "Spanish", location: "10 Seymour Place London W1H7ND United Kingdom", image: "donostia.jpg", isVisited: false), Restaurant(name: "Royal Oak", type: "British", location: "2 Regency Street London SW1P4BZ United Kingdom", image: "royaloak.jpg", isVisited: false), Restaurant(name: "Thai Cafe", type: "Thai", location: "22 Charlwood Street London SW1V2DY Pimlico", image: "thaicafe.jpg", isVisited: false) ] override func viewDidLoad() { super.viewDidLoad() // Empty back button title self.navigationItem.backBarButtonItem = UIBarButtonItem(title: "", style: .Plain, target: nil, action: nil) //self.tableView.estimatedRowHeight = 36.0 //self.tableView.rowHeight = UITableViewAutomaticDimension } override func viewWillAppear(animated: Bool) { navigationController?.hidesBarsOnSwipe = true } override func preferredStatusBarStyle() -> UIStatusBarStyle { return .LightContent } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return restaurants.count } override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { } override func tableView(tableView: UITableView, editActionsForRowAtIndexPath indexPath: NSIndexPath) -> [AnyObject]? { let shareAction = UITableViewRowAction(style: UITableViewRowActionStyle.Default, title: "Share", handler: { (action: UITableViewRowAction!, indexPath: NSIndexPath!) -> Void in let shareMenu = UIAlertController(title: nil, message: "Share Using.", preferredStyle: .ActionSheet) let qqAction = UIAlertAction(title: "QQ", style: UIAlertActionStyle.Default, handler: nil) let weiboAction = UIAlertAction(title: "Weibo", style: UIAlertActionStyle.Default, handler: nil) let weChatAction = UIAlertAction(title: "WeChat", style: UIAlertActionStyle.Default, handler: nil) let cancleAction = UIAlertAction(title: "Cancle", style: UIAlertActionStyle.Cancel, handler: nil) shareMenu.addAction(qqAction) shareMenu.addAction(weiboAction) shareMenu.addAction(weChatAction) shareMenu.addAction(cancleAction) self.presentViewController(shareMenu, animated: true, completion: nil) }) let deleteAction = UITableViewRowAction(style: UITableViewRowActionStyle.Default, title: "Delete", handler: { (action: UITableViewRowAction!, indexPath: NSIndexPath!) -> Void in self.restaurants.removeAtIndex(indexPath.row) self.tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade) }) shareAction.backgroundColor = UIColor(red: 255.0/255.0, green: 166.0/255.0, blue: 51.0/255.0, alpha: 1.0) deleteAction.backgroundColor = UIColor(red: 51.0/255.0, green: 51.0/255.0, blue: 51.0/255.0, alpha: 1.0) return [shareAction, deleteAction] } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cellIdentifiler = "Cell" let cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifiler, forIndexPath: indexPath) as CustomTableViewCell let restaurant = restaurants[indexPath.row] cell.thumbnailImageView.image = UIImage(named: restaurant.image) cell.thumbnailImageView.layer.cornerRadius = cell.thumbnailImageView.frame.size.width / 2 cell.thumbnailImageView.clipsToBounds = true cell.nameLabel.text = restaurant.name cell.locationLabel.text = restaurant.location cell.typeLabel.text = restaurant.type if restaurant.isVisited { cell.iconImageView.hidden = false }else { cell.iconImageView.hidden = true } return cell } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { print(segue.identifier) if segue.identifier == "showRestaurantDetail" { if let indexPath = self.tableView.indexPathForSelectedRow() { let destinationController = segue.destinationViewController as DetailViewController destinationController.restaurant = self.restaurants[indexPath.row] } } } override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } }
mit
bea946a6566a1969d39ccbcb2efd9c4c
54.666667
186
0.656239
4.345725
false
false
false
false
smud/Smud
Sources/Smud/Data/AreaMapRange.swift
1
1865
// // AreaMapElement.swift // // This source file is part of the SMUD open source project // // Copyright (c) 2016 SMUD project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See LICENSE.txt for license information // See CONTRIBUTORS.txt for the list of SMUD project authors // import Foundation public struct AreaMapRange { public var from: AreaMapPosition public var to: AreaMapPosition public init(_ position: AreaMapPosition) { self.from = position self.to = position } public init(from: AreaMapPosition, to: AreaMapPosition) { self.from = from self.to = to } public var size: AreaMapPosition { return to - from + AreaMapPosition(1, 1, 1) } public func size(axis: AreaMapPosition.Axis) -> Int { return to.get(axis: axis) - from.get(axis: axis) + 1 } public mutating func expand(with position: AreaMapPosition) { self.from = lowerBound(self.from, position) self.to = upperBound(self.to, position) } public func expanded(with position: AreaMapPosition) -> AreaMapRange { return AreaMapRange(from: lowerBound(self.from, position), to: upperBound(self.to, position)) } public mutating func unite(with range: AreaMapRange) { self.from = lowerBound(self.from, range.from) self.to = upperBound(self.to, range.to) } public func united(with range: AreaMapRange) -> AreaMapRange { return AreaMapRange(from: lowerBound(self.from, range.from), to: upperBound(self.to, range.to)) } public mutating func shift(by offset: AreaMapPosition) { self.from += offset self.to += offset } public func shifted(by offset: AreaMapPosition) -> AreaMapRange { return AreaMapRange(from: self.from + offset, to: self.to + offset) } }
apache-2.0
e09d57c871d502316f680bd4eba5a7c4
28.603175
103
0.665952
3.853306
false
false
false
false
firebase/firebase-ios-sdk
FirebaseFunctions/Sources/Internal/FunctionsComponent.swift
1
4017
// Copyright 2022 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import Foundation import FirebaseAppCheckInterop import FirebaseAuthInterop import FirebaseCore import FirebaseMessagingInterop // Avoids exposing internal FirebaseCore APIs to Swift users. @_implementationOnly import FirebaseCoreExtension @objc(FIRFunctionsProvider) protocol FunctionsProvider { @objc func functions(for app: FirebaseApp, region: String?, customDomain: String?, type: AnyClass) -> Functions // TODO: See if we can avoid the `type` parameter by either making it a `Functions` argument to // allow subclasses, or avoid it entirely and fix tests. This was done for FunctionsCombineUnit, // although we may be able to now port to using `@testable` instead of using the mock. } @objc(FIRFunctionsComponent) class FunctionsComponent: NSObject, Library, FunctionsProvider { // MARK: - Private Variables /// The app associated with all functions instances in this container. private let app: FirebaseApp /// A map of active instances, grouped by app. Keys are FirebaseApp names and values are arrays /// containing all instances of Functions associated with the given app. private var instances: [String: [Functions]] = [:] /// Lock to manage access to the instances array to avoid race conditions. private var instancesLock: os_unfair_lock = .init() // MARK: - Initializers required init(app: FirebaseApp) { self.app = app } // MARK: - Library conformance static func componentsToRegister() -> [Component] { let appCheckInterop = Dependency(with: AppCheckInterop.self, isRequired: false) let authInterop = Dependency(with: AuthInterop.self, isRequired: false) let messagingInterop = Dependency(with: MessagingInterop.self, isRequired: false) return [Component(FunctionsProvider.self, instantiationTiming: .lazy, dependencies: [ appCheckInterop, authInterop, messagingInterop, ]) { container, isCacheable in guard let app = container.app else { return nil } isCacheable.pointee = true return self.init(app: app) }] } // MARK: - FunctionsProvider conformance func functions(for app: FirebaseApp, region: String?, customDomain: String?, type: AnyClass) -> Functions { os_unfair_lock_lock(&instancesLock) // Unlock before the function returns. defer { os_unfair_lock_unlock(&instancesLock) } if let associatedInstances = instances[app.name] { for instance in associatedInstances { // Domains may be nil, so handle with care. var equalDomains = false if let instanceCustomDomain = instance.customDomain { equalDomains = instanceCustomDomain == customDomain } else { equalDomains = customDomain == nil } // Check if it's a match. if instance.region == region, equalDomains { return instance } } } let newInstance = Functions(app: app, region: region ?? FunctionsConstants.defaultRegion, customDomain: customDomain) let existingInstances = instances[app.name, default: []] instances[app.name] = existingInstances + [newInstance] return newInstance } }
apache-2.0
6d90b588413d6c7bb40047ec5c542e26
36.194444
98
0.665422
4.910758
false
false
false
false
tigerpixel/PGNParser
Sources/PGNParser/DraughtsMove.swift
1
2697
// // DraughtsMove.swift // PGNParser // // Created by Liam on 11/04/2017. // Copyright © 2017 Tigerpixel Ltd. All rights reserved. // import ParserCombinator /// The positions on the board conform to an integer number. typealias BoardPosition = Int /** Describes a single move performed by one player. */ public struct DraughtsPieceMove { /// The location of the piece which should be moved. let origin: BoardPosition /// The resting position of the piece after the move is made. let destination: BoardPosition /// A list of intermediate positions the piece passed through to get to its destination. let intermediatePositions: [BoardPosition] /// A flag to indicate if any opponenets pieces were captured during the move. let isCapture: Bool } extension DraughtsPieceMove { /** A constructor with the parameters in the order of draughts portable game notation. This constructor simplifies the creation of a parser for the move. It should remain in an extension so that it does not replace the default constructor. - parameter origin: The location of the piece that is to be moved. - parameter isCapture: True if the piece captures another piece, false if none are captured. - parameter intermediates: Any position which the piece moved through between its origin and destination. - parameter destination: The location at which the piece resides after the move. */ init(origin: BoardPosition, isCapture: Bool, intermediates: [BoardPosition], destination: BoardPosition) { self.origin = origin self.isCapture = isCapture self.intermediatePositions = intermediates self.destination = destination } } /** A description of the movement of pieces by both players. A move in technical draughts terms refers to a round of moves by both players. Black is optional as it may not have moved in this round. */ public struct DraughtsMove { let white: DraughtsPieceMove let black: DraughtsPieceMove? let comment: String? } extension DraughtsMove { /** Parse the input draughts portable game notation string into an array of draughts moves. Can apply functions to values that are wrapped in a parser context. - parameter fromPortableGameNotation: The pgn string describing the moves for a draughts game. - returns: A result of the parse. If successful it will contain the move objects. */ public static func parse(fromPortableGameNotation notation: String) -> ParseResult<[DraughtsMove]> { DraughtsNotationParser.portableGameNotation().run(withInput: notation) } }
mit
32cbd8758f27f50be3a6d1f7cd62da25
29.988506
110
0.718472
4.448845
false
false
false
false
m-nakada/mogif
Sources/GIFGenerator.swift
1
1692
// // GIFGenerator.swift // MojiGIF // // Created by m-nakada on 5/3/16. // Copyright © 2016 m-nakada. All rights reserved. // import Foundation struct GIFGenerator { private let images: [CharacterImage] private let frameDelay: Double private let loopCount: Int // 0 means loop forever private let url: URL private let GIFDictKey = kCGImagePropertyGIFDictionary as String private let GIFLoopCountKey = kCGImagePropertyGIFLoopCount as String private let GIFDelayTimeKey = kCGImagePropertyGIFDelayTime as String init(images: [CharacterImage], loopCount: Int, frameDelay: Double, url: URL) { self.images = images self.loopCount = loopCount self.frameDelay = frameDelay self.url = url } func generate() { guard let destination = CGImageDestinationCreateWithURL(url as CFURL, kUTTypeGIF, images.count, nil) else { print("[Error] CGImageDestinationCreateWithURL() url: \(url)") exit(EXIT_FAILURE) } // Set Loop Count let loopCountProperty = [GIFDictKey: [GIFLoopCountKey: loopCount]] CGImageDestinationSetProperties(destination, loopCountProperty as CFDictionary) // Set Images for (index, element) in images.enumerated() { let delay = (index == images.endIndex - 1) ? frameDelay * 1 : frameDelay let frameProperty = [GIFDictKey: [GIFDelayTimeKey: delay]] if let cgImage = element.cgImage { CGImageDestinationAddImage(destination, cgImage, frameProperty as CFDictionary) } } // Finalize if CGImageDestinationFinalize(destination) { print("\(url.absoluteString)") } else { print("Fail!") exit(EXIT_FAILURE) } } }
mit
aeb8f87145782ffe996874085f45f7d9
29.196429
111
0.691307
4.347044
false
false
false
false
magistral-io/MagistralSwift
MagistralSwift/MqttClient.swift
1
4275
// // MqttClient.swift // MagistralSwift // // Created by rizarse on 05/08/16. // Copyright © 2016 magistral.io. All rights reserved. // import Foundation import SwiftMQTT class MqttClient : MQTTSession, MQTTSessionDelegate { typealias MessageListener = (MQTTSession, Message) -> Void var msgListeners : [MessageListener] = []; func addMessageListener(_ listener : @escaping MessageListener) { msgListeners.append(listener); } // DELETE LISTENERS func removeMessageListeners() { msgListeners.removeAll(); } // Overrides var disconnectListener : MQTTDisconnectBlock?; var socketErrorListener : MQTTSocketErrorBlock?; public typealias MQTTDisconnectBlock = (SwiftMQTT.MQTTSession) -> Swift.Void public typealias MQTTSocketErrorBlock = (SwiftMQTT.MQTTSession) -> Swift.Void func connect(completion: MQTTSessionCompletionBlock?, disconnect: MQTTDisconnectBlock?, socketerr: MQTTSocketErrorBlock?) { super.connect { connected, error in completion?(connected, error); } disconnectListener = disconnect; socketErrorListener = socketerr; } func publish(_ topic : String, channel : Int, msg : [UInt8], callback : io.magistral.client.pub.Callback?) { publish(Data(msg), in: topic + ":" + String(channel), delivering: .atLeastOnce, retain: false) { published, error in callback?(io.magistral.client.pub.PubMeta(topic: topic, channel: channel), published ? nil : MagistralException.publishError) } } func subscribe(_ topic : String, channel: Int, group : String, qos: MQTTQoS, callback : io.magistral.client.sub.Callback?) { super.subscribe(to: topic + ":" + String(channel), delivering: qos) { succeeded, error -> Void in callback?(io.magistral.client.sub.SubMeta(topic: topic, channel: channel, group: group, endPoints: []), succeeded ? nil : MagistralException.subscriptionError) } } func unsubscribe(_ topic : String, callback : io.magistral.client.sub.Callback?) { super.unSubscribe(from: topic) { succeeded, error -> Void in callback?(io.magistral.client.sub.SubMeta(topic: topic, channel: -1, group: "", endPoints: []), succeeded ? nil : MagistralException.unsubscriptionError) } } func unsubscribe(_ topic : String, channel: Int, callback : io.magistral.client.sub.Callback?) { super.unSubscribe(from: topic + ":" + String(channel)) { succeeded, error -> Void in callback?(io.magistral.client.sub.SubMeta(topic: topic, channel: -1, group: "", endPoints: []), succeeded ? nil : MagistralException.unsubscriptionError) } } private func getCurrentMillis() -> Int64 { return Int64(UInt64(Date().timeIntervalSince1970 * 1000)) } func mqttDidReceive(message data: Data, in topic: String, from session: SwiftMQTT.MQTTSession) { for l in msgListeners { let bytes = [UInt8](data); let str = topic; let index = self.bytes2long(bytes: bytes); let tch = str.substring(from: str.index(str.startIndex, offsetBy: 41)); var elements = tch.components(separatedBy: "/") if let myNumber = NumberFormatter().number(from: elements.popLast()!) { let ch = myNumber.intValue let merged = elements.joined(separator: "/"); let t = merged.components(separatedBy: "-").joined(separator: "."); l(session, Message(topic: t, channel: ch, msg: bytes, index: index, timestamp: UInt64(self.getCurrentMillis()))) } } } private func bytes2long(bytes: [UInt8]) -> UInt64 { var value : UInt64 = 0 let data = NSData(bytes: bytes, length: 8) data.getBytes(&value, length: 8) value = UInt64(bigEndian: value) return value; } func mqttDidDisconnect(session: SwiftMQTT.MQTTSession) { disconnectListener?(session) } func mqttSocketErrorOccurred(session: SwiftMQTT.MQTTSession) { socketErrorListener?(session) } }
mit
e8e2bd3e46fcfb2c315316639c13a61e
37.854545
171
0.627047
4.308468
false
false
false
false
ReactiveKit/ReactiveGitter
ReactiveGitter/AppDelegate.swift
1
2387
// // AppDelegate.swift // ReactiveGitter // // Created by Srdan Rasic on 14/01/2017. // Copyright © 2017 ReactiveKit. All rights reserved. // import UIKit import Bond import Scenes import Interactors import Networking @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? var authorizationCodeParser: TokenService.AuthorizationCodeParser! var tokenService: TokenService! func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { applyTheme() let window = UIWindow(frame: UIScreen.main.bounds) let authorizationCodeParser = TokenService.AuthorizationCodeParser() let tokenService = TokenService() tokenService.token.bind(to: window) { window, token in if let token = token { let client = SafeClient(wrapping: APIClient(token: token)) let scene = RoomList(client: client).createScene() let navigationController = UINavigationController(rootViewController: scene.viewController) client.errors.bind(to: navigationController.reactive.userErrors) window.rootViewController = navigationController scene.logOut.bind(to: tokenService, context: .immediateOnMain) { tokenService, _ in tokenService.updateToken(nil) } } else { let client = SafeClient(wrapping: AuthenticationAPIClient()) let authorizationCode = authorizationCodeParser.parsedCode let scene = Authentication(client: client, authorizationCode: authorizationCode).createScene() client.errors.bind(to: scene.viewController.reactive.userErrors) window.rootViewController = scene.viewController scene.tokenAcquired.bind(to: tokenService, context: .immediateOnMain) { tokenService, token in tokenService.updateToken(token) } } } self.window = window self.authorizationCodeParser = authorizationCodeParser self.tokenService = tokenService window.makeKeyAndVisible() return true } func application(_ app: UIApplication, open url: URL, options: [UIApplicationOpenURLOptionsKey : Any] = [:]) -> Bool { return authorizationCodeParser.parseAndHandleToken(url) } func applyTheme() { UIView.appearance().tintColor = UIColor(red: 232/255, green: 33/255, blue: 102/255, alpha: 1) } }
mit
ec73f9f25d791b358f5f67da8f3aeabb
34.61194
142
0.728835
4.839757
false
false
false
false
ahoppen/swift
test/AutoDiff/SILOptimizer/activity_analysis.swift
2
46419
// RUN: %target-swift-emit-sil -verify -Xllvm -debug-only=differentiation 2>&1 %s | %FileCheck %s // REQUIRES: asserts import _Differentiation // Check that `@noDerivative` struct projections have "NONE" activity. struct HasNoDerivativeProperty: Differentiable { var x: Float @noDerivative var y: Float } @differentiable(reverse) func testNoDerivativeStructProjection(_ s: HasNoDerivativeProperty) -> Float { var tmp = s tmp.y = tmp.x return tmp.x } // CHECK-LABEL: [AD] Activity info for ${{.*}}testNoDerivativeStructProjection{{.*}} at parameter indices (0) and result indices (0): // CHECK: [ACTIVE] %0 = argument of bb0 : $HasNoDerivativeProperty // CHECK: [ACTIVE] %2 = alloc_stack [lexical] $HasNoDerivativeProperty, var, name "tmp" // CHECK: [ACTIVE] %4 = begin_access [read] [static] %2 : $*HasNoDerivativeProperty // CHECK: [ACTIVE] %5 = struct_element_addr %4 : $*HasNoDerivativeProperty, #HasNoDerivativeProperty.x // CHECK: [VARIED] %6 = load [trivial] %5 : $*Float // CHECK: [ACTIVE] %8 = begin_access [modify] [static] %2 : $*HasNoDerivativeProperty // CHECK: [NONE] %9 = struct_element_addr %8 : $*HasNoDerivativeProperty, #HasNoDerivativeProperty.y // CHECK: [ACTIVE] %12 = begin_access [read] [static] %2 : $*HasNoDerivativeProperty // CHECK: [ACTIVE] %13 = struct_element_addr %12 : $*HasNoDerivativeProperty, #HasNoDerivativeProperty.x // CHECK: [ACTIVE] %14 = load [trivial] %13 : $*Float // Check that non-differentiable `tuple_element_addr` projections are non-varied. @differentiable(reverse where T : Differentiable) func testNondifferentiableTupleElementAddr<T>(_ x: T) -> T { var tuple = (1, 1, (x, 1), 1) tuple.0 = 1 tuple.2.0 = x tuple.3 = 1 return tuple.2.0 } // CHECK-LABEL: [AD] Activity info for ${{.*}}testNondifferentiableTupleElementAddr{{.*}} at parameter indices (0) and result indices (0): // CHECK: [ACTIVE] %0 = argument of bb0 : $*T // CHECK: [ACTIVE] %1 = argument of bb0 : $*T // CHECK: [ACTIVE] %3 = alloc_stack [lexical] $(Int, Int, (T, Int), Int), var, name "tuple" // CHECK: [USEFUL] %4 = tuple_element_addr %3 : $*(Int, Int, (T, Int), Int), 0 // CHECK: [USEFUL] %5 = tuple_element_addr %3 : $*(Int, Int, (T, Int), Int), 1 // CHECK: [ACTIVE] %6 = tuple_element_addr %3 : $*(Int, Int, (T, Int), Int), 2 // CHECK: [USEFUL] %7 = tuple_element_addr %3 : $*(Int, Int, (T, Int), Int), 3 // CHECK: [ACTIVE] %18 = tuple_element_addr %6 : $*(T, Int), 0 // CHECK: [USEFUL] %19 = tuple_element_addr %6 : $*(T, Int), 1 // CHECK: [ACTIVE] %35 = begin_access [modify] [static] %3 : $*(Int, Int, (T, Int), Int) // CHECK: [USEFUL] %36 = tuple_element_addr %35 : $*(Int, Int, (T, Int), Int), 0 // CHECK: [ACTIVE] %41 = begin_access [modify] [static] %3 : $*(Int, Int, (T, Int), Int) // CHECK: [ACTIVE] %42 = tuple_element_addr %41 : $*(Int, Int, (T, Int), Int), 2 // CHECK: [ACTIVE] %43 = tuple_element_addr %42 : $*(T, Int), 0 // CHECK: [ACTIVE] %51 = begin_access [modify] [static] %3 : $*(Int, Int, (T, Int), Int) // CHECK: [USEFUL] %52 = tuple_element_addr %51 : $*(Int, Int, (T, Int), Int), 3 // CHECK: [ACTIVE] %55 = begin_access [read] [static] %3 : $*(Int, Int, (T, Int), Int) // CHECK: [ACTIVE] %56 = tuple_element_addr %55 : $*(Int, Int, (T, Int), Int), 2 // CHECK: [ACTIVE] %57 = tuple_element_addr %56 : $*(T, Int), 0 // TF-781: check active local address + nested conditionals. @differentiable(reverse, wrt: x) func TF_781(_ x: Float, _ y: Float) -> Float { var result = y if true { if true { result = result * x // check activity of `result` and this `apply` } } return result } // CHECK-LABEL: [AD] Activity info for ${{.*}}TF_781{{.*}} at parameter indices (0) and result indices (0) // CHECK: [ACTIVE] %0 = argument of bb0 : $Float // CHECK: [USEFUL] %1 = argument of bb0 : $Float // CHECK: [ACTIVE] %4 = alloc_stack [lexical] $Float, var, name "result" // CHECK: [ACTIVE] %19 = begin_access [read] [static] %4 : $*Float // CHECK: [ACTIVE] %20 = load [trivial] %19 : $*Float // CHECK: [ACTIVE] %23 = apply %22(%20, %0, %18) : $@convention(method) (Float, Float, @thin Float.Type) -> Float // CHECK: [ACTIVE] %24 = begin_access [modify] [static] %4 : $*Float // CHECK: [ACTIVE] %31 = begin_access [read] [static] %4 : $*Float // CHECK: [ACTIVE] %32 = load [trivial] %31 : $*Float // TF-954: check nested conditionals and addresses. @differentiable(reverse) func TF_954(_ x: Float) -> Float { var outer = x outerIf: if true { var inner = outer inner = inner * x // check activity of this `apply` if false { break outerIf } outer = inner } return outer } // CHECK-LABEL: [AD] Activity info for ${{.*}}TF_954{{.*}} at parameter indices (0) and result indices (0) // CHECK: bb0: // CHECK: [ACTIVE] %0 = argument of bb0 : $Float // CHECK: [ACTIVE] %2 = alloc_stack [lexical] $Float, var, name "outer" // CHECK: bb1: // CHECK: [ACTIVE] %10 = alloc_stack [lexical] $Float, var, name "inner" // CHECK: [ACTIVE] %11 = begin_access [read] [static] %2 : $*Float // CHECK: [USEFUL] %14 = metatype $@thin Float.Type // CHECK: [ACTIVE] %15 = begin_access [read] [static] %10 : $*Float // CHECK: [ACTIVE] %16 = load [trivial] %15 : $*Float // CHECK: [NONE] // function_ref static Float.* infix(_:_:) // CHECK: %18 = function_ref @$sSf1moiyS2f_SftFZ : $@convention(method) (Float, Float, @thin Float.Type) -> Float // CHECK: [ACTIVE] %19 = apply %18(%16, %0, %14) : $@convention(method) (Float, Float, @thin Float.Type) -> Float // CHECK: [ACTIVE] %20 = begin_access [modify] [static] %10 : $*Float // CHECK: bb3: // CHECK: [ACTIVE] %31 = begin_access [read] [static] %10 : $*Float // CHECK: [ACTIVE] %32 = load [trivial] %31 : $*Float // CHECK: [ACTIVE] %34 = begin_access [modify] [static] %2 : $*Float // CHECK: bb5: // CHECK: [ACTIVE] %40 = begin_access [read] [static] %2 : $*Float // CHECK: [ACTIVE] %41 = load [trivial] %40 : $*Float //===----------------------------------------------------------------------===// // Branching cast instructions //===----------------------------------------------------------------------===// @differentiable(reverse) func checked_cast_branch(_ x: Float) -> Float { // expected-warning @+1 {{'is' test is always true}} if Int.self is Any.Type { return x + x } return x * x } // CHECK-LABEL: [AD] Activity info for ${{.*}}checked_cast_branch{{.*}} at parameter indices (0) and result indices (0) // CHECK: bb0: // CHECK: [ACTIVE] %0 = argument of bb0 : $Float // CHECK: [NONE] %2 = metatype $@thin Int.Type // CHECK: [NONE] %3 = metatype $@thick Int.Type // CHECK: bb1: // CHECK: [NONE] %5 = argument of bb1 : $@thick Any.Type // CHECK: [NONE] %6 = integer_literal $Builtin.Int1, -1 // CHECK: bb2: // CHECK: [NONE] %8 = argument of bb2 : $@thick Int.Type // CHECK: [NONE] %9 = integer_literal $Builtin.Int1, 0 // CHECK: bb3: // CHECK: [NONE] %11 = argument of bb3 : $Builtin.Int1 // CHECK: [NONE] %12 = metatype $@thin Bool.Type // CHECK: [NONE] // function_ref Bool.init(_builtinBooleanLiteral:) // CHECK: [NONE] %14 = apply %13(%11, %12) : $@convention(method) (Builtin.Int1, @thin Bool.Type) -> Bool // CHECK: [NONE] %15 = struct_extract %14 : $Bool, #Bool._value // CHECK: bb4: // CHECK: [USEFUL] %17 = metatype $@thin Float.Type // CHECK: [NONE] // function_ref static Float.+ infix(_:_:) // CHECK: [ACTIVE] %19 = apply %18(%0, %0, %17) : $@convention(method) (Float, Float, @thin Float.Type) -> Float // CHECK: bb5: // CHECK: [USEFUL] %21 = metatype $@thin Float.Type // CHECK: [NONE] // function_ref static Float.* infix(_:_:) // CHECK: [ACTIVE] %23 = apply %22(%0, %0, %21) : $@convention(method) (Float, Float, @thin Float.Type) -> Float // CHECK-LABEL: sil hidden [ossa] @${{.*}}checked_cast_branch{{.*}} : $@convention(thin) (Float) -> Float { // CHECK: checked_cast_br %3 : $@thick Int.Type to Any.Type, bb1, bb2 // CHECK: } @differentiable(reverse) func checked_cast_addr_nonactive_result<T: Differentiable>(_ x: T) -> T { if let _ = x as? Float { // Do nothing with `y: Float?` value. } return x } // CHECK-LABEL: [AD] Activity info for ${{.*}}checked_cast_addr_nonactive_result{{.*}} at parameter indices (0) and result indices (0) // CHECK: bb0: // CHECK: [ACTIVE] %0 = argument of bb0 : $*T // CHECK: [ACTIVE] %1 = argument of bb0 : $*T // CHECK: [VARIED] %3 = alloc_stack $T // CHECK: [VARIED] %5 = alloc_stack $Float // CHECK: bb1: // CHECK: [VARIED] %7 = load [trivial] %5 : $*Float // CHECK: [VARIED] %8 = enum $Optional<Float>, #Optional.some!enumelt, %7 : $Float // CHECK: bb2: // CHECK: [NONE] %11 = enum $Optional<Float>, #Optional.none!enumelt // CHECK: bb3: // CHECK: [VARIED] %14 = argument of bb3 : $Optional<Float> // CHECK: bb4: // CHECK: bb5: // CHECK: [VARIED] %18 = argument of bb5 : $Float // CHECK: bb6: // CHECK: [NONE] %22 = tuple () // CHECK-LABEL: sil hidden [ossa] @${{.*}}checked_cast_addr_nonactive_result{{.*}} : $@convention(thin) <T where T : Differentiable> (@in_guaranteed T) -> @out T { // CHECK: checked_cast_addr_br take_always T in %3 : $*T to Float in %5 : $*Float, bb1, bb2 // CHECK: } // expected-error @+1 {{function is not differentiable}} @differentiable(reverse) // expected-note @+1 {{when differentiating this function definition}} func checked_cast_addr_active_result<T: Differentiable>(x: T) -> T { // expected-note @+1 {{expression is not differentiable}} if let y = x as? Float { // Use `y: Float?` value in an active way. return y as! T } return x } // CHECK-LABEL: [AD] Activity info for ${{.*}}checked_cast_addr_active_result{{.*}} at parameter indices (0) and result indices (0) // CHECK: bb0: // CHECK: [ACTIVE] %0 = argument of bb0 : $*T // CHECK: [ACTIVE] %1 = argument of bb0 : $*T // CHECK: [ACTIVE] %3 = alloc_stack $T // CHECK: [ACTIVE] %5 = alloc_stack $Float // CHECK: bb1: // CHECK: [ACTIVE] %7 = load [trivial] %5 : $*Float // CHECK: [ACTIVE] %8 = enum $Optional<Float>, #Optional.some!enumelt, %7 : $Float // CHECK: bb2: // CHECK: [USEFUL] %11 = enum $Optional<Float>, #Optional.none!enumelt // CHECK: bb3: // CHECK: [ACTIVE] %14 = argument of bb3 : $Optional<Float> // CHECK: bb4: // CHECK: [ACTIVE] %16 = argument of bb4 : $Float // CHECK: [ACTIVE] %19 = alloc_stack $Float // CHECK: bb5: // CHECK: bb6: // CHECK: [NONE] %27 = tuple () // CHECK-LABEL: sil hidden [ossa] @${{.*}}checked_cast_addr_active_result{{.*}} : $@convention(thin) <T where T : Differentiable> (@in_guaranteed T) -> @out T { // CHECK: checked_cast_addr_br take_always T in %3 : $*T to Float in %5 : $*Float, bb1, bb2 // CHECK: } //===----------------------------------------------------------------------===// // Array literal differentiation //===----------------------------------------------------------------------===// // Check `array.uninitialized_intrinsic` applications. @differentiable(reverse) func testArrayUninitializedIntrinsic(_ x: Float, _ y: Float) -> [Float] { return [x, y] } // CHECK-LABEL: [AD] Activity info for ${{.*}}testArrayUninitializedIntrinsic{{.*}} at parameter indices (0, 1) and result indices (0) // CHECK: [ACTIVE] %0 = argument of bb0 : $Float // CHECK: [ACTIVE] %1 = argument of bb0 : $Float // CHECK: [USEFUL] %4 = integer_literal $Builtin.Word, 2 // CHECK: [NONE] // function_ref _allocateUninitializedArray<A>(_:) // CHECK: [ACTIVE] %6 = apply %5<Float>(%4) : $@convention(thin) <τ_0_0> (Builtin.Word) -> (@owned Array<τ_0_0>, Builtin.RawPointer) // CHECK: [ACTIVE] (**%7**, %8) = destructure_tuple %6 : $(Array<Float>, Builtin.RawPointer) // CHECK: [VARIED] (%7, **%8**) = destructure_tuple %6 : $(Array<Float>, Builtin.RawPointer) // CHECK: [ACTIVE] %9 = pointer_to_address %8 : $Builtin.RawPointer to [strict] $*Float // CHECK: [VARIED] %11 = integer_literal $Builtin.Word, 1 // CHECK: [ACTIVE] %12 = index_addr %9 : $*Float, %11 : $Builtin.Word // CHECK: [NONE] // function_ref _finalizeUninitializedArray<A>(_:) // CHECK: [ACTIVE] %15 = apply %14<Float>(%7) : $@convention(thin) <τ_0_0> (@owned Array<τ_0_0>) -> @owned Array<τ_0_0> @differentiable(reverse where T: Differentiable) func testArrayUninitializedIntrinsicGeneric<T>(_ x: T, _ y: T) -> [T] { return [x, y] } // CHECK-LABEL: [AD] Activity info for ${{.*}}testArrayUninitializedIntrinsicGeneric{{.*}} at parameter indices (0, 1) and result indices (0) // CHECK: [ACTIVE] %0 = argument of bb0 : $*T // CHECK: [ACTIVE] %1 = argument of bb0 : $*T // CHECK: [USEFUL] %4 = integer_literal $Builtin.Word, 2 // CHECK: [NONE] // function_ref _allocateUninitializedArray<A>(_:) // CHECK: [ACTIVE] %6 = apply %5<T>(%4) : $@convention(thin) <τ_0_0> (Builtin.Word) -> (@owned Array<τ_0_0>, Builtin.RawPointer) // CHECK: [ACTIVE] (**%7**, %8) = destructure_tuple %6 : $(Array<T>, Builtin.RawPointer) // CHECK: [VARIED] (%7, **%8**) = destructure_tuple %6 : $(Array<T>, Builtin.RawPointer) // CHECK: [ACTIVE] %9 = pointer_to_address %8 : $Builtin.RawPointer to [strict] $*T // CHECK: [VARIED] %11 = integer_literal $Builtin.Word, 1 // CHECK: [ACTIVE] %12 = index_addr %9 : $*T, %11 : $Builtin.Word // CHECK: [NONE] // function_ref _finalizeUninitializedArray<A>(_:) // CHECK: [ACTIVE] %15 = apply %14<T>(%7) : $@convention(thin) <τ_0_0> (@owned Array<τ_0_0>) -> @owned Array<τ_0_0> // TF-952: Test array literal initialized from an address (e.g. `var`). @differentiable(reverse) func testArrayUninitializedIntrinsicAddress(_ x: Float, _ y: Float) -> [Float] { var result = x result = result * y return [result, result] } // CHECK-LABEL: [AD] Activity info for ${{.*}}testArrayUninitializedIntrinsicAddress{{.*}} at parameter indices (0, 1) and result indices (0) // CHECK: [ACTIVE] %0 = argument of bb0 : $Float // CHECK: [ACTIVE] %1 = argument of bb0 : $Float // CHECK: [ACTIVE] %4 = alloc_stack [lexical] $Float, var, name "result" // CHECK: [ACTIVE] %7 = begin_access [read] [static] %4 : $*Float // CHECK: [ACTIVE] %8 = load [trivial] %7 : $*Float // CHECK: [NONE] // function_ref static Float.* infix(_:_:) // CHECK: [ACTIVE] %11 = apply %10(%8, %1, %6) : $@convention(method) (Float, Float, @thin Float.Type) -> Float // CHECK: [ACTIVE] %12 = begin_access [modify] [static] %4 : $*Float // CHECK: [USEFUL] %15 = integer_literal $Builtin.Word, 2 // CHECK: [NONE] // function_ref _allocateUninitializedArray<A>(_:) // CHECK: [ACTIVE] %17 = apply %16<Float>(%15) : $@convention(thin) <τ_0_0> (Builtin.Word) -> (@owned Array<τ_0_0>, Builtin.RawPointer) // CHECK: [ACTIVE] (**%18**, %19) = destructure_tuple %17 : $(Array<Float>, Builtin.RawPointer) // CHECK: [VARIED] (%18, **%19**) = destructure_tuple %17 : $(Array<Float>, Builtin.RawPointer) // CHECK: [ACTIVE] %20 = pointer_to_address %19 : $Builtin.RawPointer to [strict] $*Float // CHECK: [ACTIVE] %21 = begin_access [read] [static] %4 : $*Float // CHECK: [VARIED] %24 = integer_literal $Builtin.Word, 1 // CHECK: [ACTIVE] %25 = index_addr %20 : $*Float, %24 : $Builtin.Word // CHECK: [ACTIVE] %26 = begin_access [read] [static] %4 : $*Float // CHECK: [NONE] // function_ref _finalizeUninitializedArray<A>(_:) // CHECK: [ACTIVE] %30 = apply %29<Float>(%18) : $@convention(thin) <τ_0_0> (@owned Array<τ_0_0>) -> @owned Array<τ_0_0> // TF-952: Test array literal initialized with `apply` direct results. @differentiable(reverse) func testArrayUninitializedIntrinsicFunctionResult(_ x: Float, _ y: Float) -> [Float] { return [x * y, x * y] } // CHECK-LABEL: [AD] Activity info for ${{.*}}testArrayUninitializedIntrinsicFunctionResult{{.*}} at parameter indices (0, 1) and result indices (0) // CHECK: [ACTIVE] %0 = argument of bb0 : $Float // CHECK: [ACTIVE] %1 = argument of bb0 : $Float // CHECK: [USEFUL] %4 = integer_literal $Builtin.Word, 2 // CHECK: [NONE] // function_ref _allocateUninitializedArray<A>(_:) // CHECK: [ACTIVE] %6 = apply %5<Float>(%4) : $@convention(thin) <τ_0_0> (Builtin.Word) -> (@owned Array<τ_0_0>, Builtin.RawPointer) // CHECK: [ACTIVE] (**%7**, %8) = destructure_tuple %6 : $(Array<Float>, Builtin.RawPointer) // CHECK: [VARIED] (%7, **%8**) = destructure_tuple %6 : $(Array<Float>, Builtin.RawPointer) // CHECK: [ACTIVE] %9 = pointer_to_address %8 : $Builtin.RawPointer to [strict] $*Float // CHECK: [NONE] // function_ref static Float.* infix(_:_:) // CHECK: [ACTIVE] %12 = apply %11(%0, %1, %10) : $@convention(method) (Float, Float, @thin Float.Type) -> Float // CHECK: [VARIED] %14 = integer_literal $Builtin.Word, 1 // CHECK: [ACTIVE] %15 = index_addr %9 : $*Float, %14 : $Builtin.Word // CHECK: [USEFUL] %16 = metatype $@thin Float.Type // CHECK: [NONE] // function_ref static Float.* infix(_:_:) // CHECK: [ACTIVE] %18 = apply %17(%0, %1, %16) : $@convention(method) (Float, Float, @thin Float.Type) -> Float // CHECK: [NONE] // function_ref _finalizeUninitializedArray<A>(_:) // CHECK: [ACTIVE] %21 = apply %20<Float>(%7) : $@convention(thin) <τ_0_0> (@owned Array<τ_0_0>) -> @owned Array<τ_0_0> // TF-975: Test nested array literals. @differentiable(reverse) func testArrayUninitializedIntrinsicNested(_ x: Float, _ y: Float) -> [Float] { let array = [x, y] return [array[0], array[1]] } // CHECK-LABEL: [AD] Activity info for ${{.*}}testArrayUninitializedIntrinsicNested{{.*}} at parameter indices (0, 1) and result indices (0) // CHECK: [ACTIVE] %0 = argument of bb0 : $Float // CHECK: [ACTIVE] %1 = argument of bb0 : $Float // CHECK: [USEFUL] %4 = integer_literal $Builtin.Word, 2 // CHECK: [NONE] // function_ref _allocateUninitializedArray<A>(_:) // CHECK: [ACTIVE] %6 = apply %5<Float>(%4) : $@convention(thin) <τ_0_0> (Builtin.Word) -> (@owned Array<τ_0_0>, Builtin.RawPointer) // CHECK: [ACTIVE] (**%7**, %8) = destructure_tuple %6 : $(Array<Float>, Builtin.RawPointer) // CHECK: [VARIED] (%7, **%8**) = destructure_tuple %6 : $(Array<Float>, Builtin.RawPointer) // CHECK: [ACTIVE] %9 = pointer_to_address %8 : $Builtin.RawPointer to [strict] $*Float // CHECK: [VARIED] %11 = integer_literal $Builtin.Word, 1 // CHECK: [ACTIVE] %12 = index_addr %9 : $*Float, %11 : $Builtin.Word // CHECK: [NONE] // function_ref _finalizeUninitializedArray<A>(_:) // CHECK: [ACTIVE] [[ARRAY:%.*]] = apply %14<Float>(%7) : $@convention(thin) <τ_0_0> (@owned Array<τ_0_0>) -> @owned Array<τ_0_0> // CHECK: [USEFUL] [[INT_LIT:%.*]] = integer_literal $Builtin.Word, 2 // CHECK: [NONE] // function_ref _allocateUninitializedArray<A>(_:) // CHECK: [ACTIVE] [[TUP:%.*]] = apply %19<Float>([[INT_LIT]]) : $@convention(thin) <τ_0_0> (Builtin.Word) -> (@owned Array<τ_0_0>, Builtin.RawPointer) // CHECK: [ACTIVE] (**[[LHS:%.*]]**, [[RHS:%.*]]) = destructure_tuple [[TUP]] : $(Array<Float>, Builtin.RawPointer) // CHECK: [VARIED] ([[LHS]], **[[RHS]]**) = destructure_tuple [[TUP]] : $(Array<Float>, Builtin.RawPointer) // CHECK: [ACTIVE] [[FLOAT_PTR:%.*]] = pointer_to_address [[RHS]] : $Builtin.RawPointer to [strict] $*Float // CHECK: [USEFUL] [[ZERO_LITERAL:%.*]] = integer_literal $Builtin.IntLiteral, 0 // CHECK: [USEFUL] [[META:%.*]] = metatype $@thin Int.Type // CHECK: [NONE] // function_ref Int.init(_builtinIntegerLiteral:) // CHECK: [USEFUL] [[RESULT_2:%.*]] = apply %26([[ZERO_LITERAL]], [[META]]) : $@convention(method) (Builtin.IntLiteral, @thin Int.Type) -> Int // CHECK: [NONE] // function_ref Array.subscript.getter // CHECK: [NONE] %29 = apply %28<Float>([[FLOAT_PTR]], [[RESULT_2]], %16) : $@convention(method) <τ_0_0> (Int, @guaranteed Array<τ_0_0>) -> @out τ_0_0 // CHECK: [VARIED] [[ONE_LITERAL:%.*]] = integer_literal $Builtin.Word, 1 // CHECK: [ACTIVE] [[INDEX_ADDR:%.*]] = index_addr [[FLOAT_PTR]] : $*Float, [[ONE_LITERAL]] : $Builtin.Word // CHECK: [USEFUL] [[ONE_LITERAL_AGAIN:%.*]] = integer_literal $Builtin.IntLiteral, 1 // CHECK: [USEFUL] [[META_AGAIN:%.*]] = metatype $@thin Int.Type // CHECK: [NONE] // function_ref Int.init(_builtinIntegerLiteral:) // CHECK: [USEFUL] %35 = apply %34([[ONE_LITERAL_AGAIN]], [[META_AGAIN]]) : $@convention(method) (Builtin.IntLiteral, @thin Int.Type) -> Int // CHECK: [NONE] // function_ref Array.subscript.getter // CHECK: [NONE] %37 = apply %36<Float>(%31, %35, %16) : $@convention(method) <τ_0_0> (Int, @guaranteed Array<τ_0_0>) -> @out τ_0_0 // CHECK: [NONE] // function_ref _finalizeUninitializedArray<A>(_:) // CHECK: [ACTIVE] %39 = apply %38<Float>(%21) : $@convention(thin) <τ_0_0> (@owned Array<τ_0_0>) -> @owned Array<τ_0_0> // TF-978: Test array literal initialized with `apply` indirect results. struct Wrapper<T: Differentiable>: Differentiable { var value: T } @differentiable(reverse) func testArrayUninitializedIntrinsicApplyIndirectResult<T>(_ x: T, _ y: T) -> [Wrapper<T>] { return [Wrapper(value: x), Wrapper(value: y)] } // CHECK-LABEL: [AD] Activity info for ${{.*}}testArrayUninitializedIntrinsicApplyIndirectResult{{.*}} at parameter indices (0, 1) and result indices (0) // CHECK: [ACTIVE] %0 = argument of bb0 : $*T // CHECK: [ACTIVE] %1 = argument of bb0 : $*T // CHECK: [USEFUL] %4 = integer_literal $Builtin.Word, 2 // CHECK: [NONE] // function_ref _allocateUninitializedArray<A>(_:) // CHECK: [ACTIVE] %6 = apply %5<Wrapper<T>>(%4) : $@convention(thin) <τ_0_0> (Builtin.Word) -> (@owned Array<τ_0_0>, Builtin.RawPointer) // CHECK: [ACTIVE] (**%7**, %8) = destructure_tuple %6 : $(Array<Wrapper<T>>, Builtin.RawPointer) // CHECK: [VARIED] (%7, **%8**) = destructure_tuple %6 : $(Array<Wrapper<T>>, Builtin.RawPointer) // CHECK: [ACTIVE] %9 = pointer_to_address %8 : $Builtin.RawPointer to [strict] $*Wrapper<T> // CHECK: [USEFUL] %10 = metatype $@thin Wrapper<T>.Type // CHECK: [ACTIVE] %11 = alloc_stack $T // CHECK: [NONE] // function_ref Wrapper.init(value:) // CHECK: [NONE] %14 = apply %13<T>(%9, %11, %10) : $@convention(method) <τ_0_0 where τ_0_0 : Differentiable> (@in τ_0_0, @thin Wrapper<τ_0_0>.Type) -> @out Wrapper<τ_0_0> // CHECK: [VARIED] %16 = integer_literal $Builtin.Word, 1 // CHECK: [ACTIVE] %17 = index_addr %9 : $*Wrapper<T>, %16 : $Builtin.Word // CHECK: [USEFUL] %18 = metatype $@thin Wrapper<T>.Type // CHECK: [ACTIVE] %19 = alloc_stack $T // CHECK: [NONE] // function_ref Wrapper.init(value:) // CHECK: [NONE] %22 = apply %21<T>(%17, %19, %18) : $@convention(method) <τ_0_0 where τ_0_0 : Differentiable> (@in τ_0_0, @thin Wrapper<τ_0_0>.Type) -> @out Wrapper<τ_0_0> // CHECK: [NONE] // function_ref _finalizeUninitializedArray<A>(_:) // CHECK: [ACTIVE] %25 = apply %24<Wrapper<T>>(%7) : $@convention(thin) <τ_0_0> (@owned Array<τ_0_0>) -> @owned Array<τ_0_0> //===----------------------------------------------------------------------===// // `inout` argument differentiation //===----------------------------------------------------------------------===// struct Mut: Differentiable {} extension Mut { @differentiable(reverse, wrt: x) mutating func mutatingMethod(_ x: Mut) {} } // CHECK-LABEL: [AD] Activity info for ${{.*}}3MutV14mutatingMethodyyACF at parameter indices (0) and result indices (0) // CHECK: [VARIED] %0 = argument of bb0 : $Mut // CHECK: [USEFUL] %1 = argument of bb0 : $*Mut // TODO(TF-985): Find workaround to avoid marking non-wrt `inout` argument as // active. @differentiable(reverse, wrt: x) func nonActiveInoutArg(_ nonactive: inout Mut, _ x: Mut) { nonactive.mutatingMethod(x) nonactive = x } // CHECK-LABEL: [AD] Activity info for ${{.*}}17nonActiveInoutArgyyAA3MutVz_ADtF at parameter indices (1) and result indices (0) // CHECK: [ACTIVE] %0 = argument of bb0 : $*Mut // CHECK: [ACTIVE] %1 = argument of bb0 : $Mut // CHECK: [ACTIVE] %4 = begin_access [modify] [static] %0 : $*Mut // CHECK: [NONE] // function_ref Mut.mutatingMethod(_:) // CHECK: [NONE] %6 = apply %5(%1, %4) : $@convention(method) (Mut, @inout Mut) -> () // CHECK: [ACTIVE] %8 = begin_access [modify] [static] %0 : $*Mut @differentiable(reverse, wrt: x) func activeInoutArgMutatingMethod(_ x: Mut) -> Mut { var result = x result.mutatingMethod(result) return result } // CHECK-LABEL: [AD] Activity info for ${{.*}}28activeInoutArgMutatingMethodyAA3MutVADF at parameter indices (0) and result indices (0) // CHECK: [ACTIVE] %0 = argument of bb0 : $Mut // CHECK: [ACTIVE] %2 = alloc_stack [lexical] $Mut, var, name "result" // CHECK: [ACTIVE] %4 = begin_access [read] [static] %2 : $*Mut // CHECK: [ACTIVE] %5 = load [trivial] %4 : $*Mut // CHECK: [ACTIVE] %7 = begin_access [modify] [static] %2 : $*Mut // CHECK: [NONE] // function_ref Mut.mutatingMethod(_:) // CHECK: [NONE] %9 = apply %8(%5, %7) : $@convention(method) (Mut, @inout Mut) -> () // CHECK: [ACTIVE] %11 = begin_access [read] [static] %2 : $*Mut // CHECK: [ACTIVE] %12 = load [trivial] %11 : $*Mut @differentiable(reverse, wrt: x) func activeInoutArgMutatingMethodVar(_ nonactive: inout Mut, _ x: Mut) { var result = nonactive result.mutatingMethod(x) nonactive = result } // CHECK_LABEL: [AD] Activity info for ${{.*}}31activeInoutArgMutatingMethodVaryyAA3MutVz_ADtF at (parameters=(1) results=(0)) // CHECK: [ACTIVE] %0 = argument of bb0 : $*Mut // CHECK: [ACTIVE] %1 = argument of bb0 : $Mut // CHECK: [ACTIVE] %4 = alloc_stack [lexical] $Mut, var, name "result" // CHECK: [ACTIVE] %5 = begin_access [read] [static] %0 : $*Mut // CHECK: [ACTIVE] %8 = begin_access [modify] [static] %4 : $*Mut // CHECK: [NONE] // function_ref Mut.mutatingMethod(_:) // CHECK: %9 = function_ref @${{.*}}3MutV14mutatingMethodyyACF : $@convention(method) (Mut, @inout Mut) -> () // CHECK: [NONE] %10 = apply %9(%1, %8) : $@convention(method) (Mut, @inout Mut) -> () // CHECK: [ACTIVE] %12 = begin_access [read] [static] %4 : $*Mut // CHECK: [ACTIVE] %13 = load [trivial] %12 : $*Mut // CHECK: [ACTIVE] %15 = begin_access [modify] [static] %0 : $*Mut // CHECK: [NONE] %19 = tuple () @differentiable(reverse, wrt: x) func activeInoutArgMutatingMethodTuple(_ nonactive: inout Mut, _ x: Mut) { var result = (nonactive, x) result.0.mutatingMethod(result.0) nonactive = result.0 } // CHECK-LABEL: [AD] Activity info for ${{.*}}33activeInoutArgMutatingMethodTupleyyAA3MutVz_ADtF at parameter indices (1) and result indices (0) // CHECK: [ACTIVE] %0 = argument of bb0 : $*Mut // CHECK: [ACTIVE] %1 = argument of bb0 : $Mut // CHECK: [ACTIVE] %4 = alloc_stack [lexical] $(Mut, Mut), var, name "result" // CHECK: [ACTIVE] %5 = tuple_element_addr %4 : $*(Mut, Mut), 0 // CHECK: [ACTIVE] %6 = tuple_element_addr %4 : $*(Mut, Mut), 1 // CHECK: [ACTIVE] %7 = begin_access [read] [static] %0 : $*Mut // CHECK: [ACTIVE] %11 = begin_access [read] [static] %4 : $*(Mut, Mut) // CHECK: [ACTIVE] %12 = tuple_element_addr %11 : $*(Mut, Mut), 0 // CHECK: [ACTIVE] %13 = load [trivial] %12 : $*Mut // CHECK: [ACTIVE] %15 = begin_access [modify] [static] %4 : $*(Mut, Mut) // CHECK: [ACTIVE] %16 = tuple_element_addr %15 : $*(Mut, Mut), 0 // CHECK: [NONE] // function_ref Mut.mutatingMethod(_:) // CHECK: [NONE] %18 = apply %17(%13, %16) : $@convention(method) (Mut, @inout Mut) -> () // CHECK: [ACTIVE] %20 = begin_access [read] [static] %4 : $*(Mut, Mut) // CHECK: [ACTIVE] %21 = tuple_element_addr %20 : $*(Mut, Mut), 0 // CHECK: [ACTIVE] %22 = load [trivial] %21 : $*Mut // CHECK: [ACTIVE] %24 = begin_access [modify] [static] %0 : $*Mut // Check `inout` arguments. @differentiable(reverse) func activeInoutArg(_ x: Float) -> Float { var result = x result += x return result } // CHECK-LABEL: [AD] Activity info for ${{.*}}activeInoutArg{{.*}} at parameter indices (0) and result indices (0) // CHECK: [ACTIVE] %0 = argument of bb0 : $Float // CHECK: [ACTIVE] %2 = alloc_stack [lexical] $Float, var, name "result" // CHECK: [ACTIVE] %5 = begin_access [modify] [static] %2 : $*Float // CHECK: [NONE] // function_ref static Float.+= infix(_:_:) // CHECK: [NONE] %7 = apply %6(%5, %0, %4) : $@convention(method) (@inout Float, Float, @thin Float.Type) -> () // CHECK: [ACTIVE] %9 = begin_access [read] [static] %2 : $*Float // CHECK: [ACTIVE] %10 = load [trivial] %9 : $*Float @differentiable(reverse) func activeInoutArgNonactiveInitialResult(_ x: Float) -> Float { var result: Float = 1 result += x return result } // CHECK-LABEL: [AD] Activity info for ${{.*}}activeInoutArgNonactiveInitialResult{{.*}} at parameter indices (0) and result indices (0) // CHECK: [ACTIVE] %0 = argument of bb0 : $Float // CHECK: [ACTIVE] %2 = alloc_stack [lexical] $Float, var, name "result" // CHECK: [NONE] // function_ref Float.init(_builtinIntegerLiteral:) // CHECK: [USEFUL] %6 = apply %5(%3, %4) : $@convention(method) (Builtin.IntLiteral, @thin Float.Type) -> Float // CHECK: [USEFUL] %8 = metatype $@thin Float.Type // CHECK: [ACTIVE] %9 = begin_access [modify] [static] %2 : $*Float // CHECK: [NONE] // function_ref static Float.+= infix(_:_:) // CHECK: [NONE] %11 = apply %10(%9, %0, %8) : $@convention(method) (@inout Float, Float, @thin Float.Type) -> () // CHECK: [ACTIVE] %13 = begin_access [read] [static] %2 : $*Float // CHECK: [ACTIVE] %14 = load [trivial] %13 : $*Float //===----------------------------------------------------------------------===// // Throwing function differentiation (`try_apply`) //===----------------------------------------------------------------------===// // TF-433: Test `try_apply`. func rethrowing(_ x: () throws -> Void) rethrows -> Void {} @differentiable(reverse) func testTryApply(_ x: Float) -> Float { rethrowing({}) return x } // TF-433: differentiation diagnoses `try_apply` before activity info is printed. // CHECK-LABEL: [AD] Activity info for ${{.*}}testTryApply{{.*}} at parameter indices (0) and result indices (0) // CHECK: bb0: // CHECK: [ACTIVE] %0 = argument of bb0 : $Float // CHECK: [NONE] // function_ref closure #1 in testTryApply(_:) // CHECK: [NONE] %3 = thin_to_thick_function %2 : $@convention(thin) () -> @error Error to $@noescape @callee_guaranteed () -> @error Error // CHECK: [NONE] // function_ref rethrowing(_:) // CHECK: bb1: // CHECK: [NONE] %6 = argument of bb1 : $() // CHECK: bb2: // CHECK: [NONE] %8 = argument of bb2 : $Error //===----------------------------------------------------------------------===// // Coroutine differentiation (`begin_apply`) //===----------------------------------------------------------------------===// struct HasCoroutineAccessors: Differentiable { var stored: Float var computed: Float { // `_read` is a coroutine: `(Self) -> () -> ()`. _read { yield stored } // `_modify` is a coroutine: `(inout Self) -> () -> ()`. _modify { yield &stored } } } // expected-error @+1 {{function is not differentiable}} @differentiable(reverse) // expected-note @+1 {{when differentiating this function definition}} func testAccessorCoroutines(_ x: HasCoroutineAccessors) -> HasCoroutineAccessors { var x = x // expected-note @+1 {{differentiation of coroutine calls is not yet supported}} x.computed = x.computed return x } // CHECK-LABEL: [AD] Activity info for ${{.*}}testAccessorCoroutines{{.*}} at parameter indices (0) and result indices (0) // CHECK: [ACTIVE] %0 = argument of bb0 : $HasCoroutineAccessors // CHECK: [ACTIVE] %2 = alloc_stack [lexical] $HasCoroutineAccessors, var, name "x" // CHECK: [ACTIVE] %4 = begin_access [read] [static] %2 : $*HasCoroutineAccessors // CHECK: [ACTIVE] %5 = load [trivial] %4 : $*HasCoroutineAccessors // CHECK: [NONE] // function_ref HasCoroutineAccessors.computed.read // CHECK: [ACTIVE] (**%7**, %8) = begin_apply %6(%5) : $@yield_once @convention(method) (HasCoroutineAccessors) -> @yields Float // CHECK: [VARIED] (%7, **%8**) = begin_apply %6(%5) : $@yield_once @convention(method) (HasCoroutineAccessors) -> @yields Float // CHECK: [ACTIVE] %9 = alloc_stack $Float // CHECK: [ACTIVE] %11 = load [trivial] %9 : $*Float // CHECK: [ACTIVE] %14 = begin_access [modify] [static] %2 : $*HasCoroutineAccessors // CHECK: [NONE] // function_ref HasCoroutineAccessors.computed.modify // CHECK: %15 = function_ref @${{.*}}21HasCoroutineAccessorsV8computedSfvM : $@yield_once @convention(method) (@inout HasCoroutineAccessors) -> @yields @inout Float // CHECK: [ACTIVE] (**%16**, %17) = begin_apply %15(%14) : $@yield_once @convention(method) (@inout HasCoroutineAccessors) -> @yields @inout Float // CHECK: [VARIED] (%16, **%17**) = begin_apply %15(%14) : $@yield_once @convention(method) (@inout HasCoroutineAccessors) -> @yields @inout Float // CHECK: [ACTIVE] %22 = begin_access [read] [static] %2 : $*HasCoroutineAccessors // CHECK: [ACTIVE] %23 = load [trivial] %22 : $*HasCoroutineAccessors // TF-1078: Test `begin_apply` active `inout` argument. // `Array.subscript.modify` is the applied coroutine. // expected-error @+1 {{function is not differentiable}} @differentiable(reverse) // expected-note @+1 {{when differentiating this function definition}} func testBeginApplyActiveInoutArgument(array: [Float], x: Float) -> Float { var array = array // Array subscript assignment below calls `Array.subscript.modify`. // expected-note @+1 {{differentiation of coroutine calls is not yet supported}} array[0] = x return array[0] } // CHECK-LABEL: [AD] Activity info for ${{.*}}testBeginApplyActiveInoutArgument{{.*}} at parameter indices (0, 1) and result indices (0) // CHECK: [ACTIVE] %0 = argument of bb0 : $Array<Float> // CHECK: [ACTIVE] %1 = argument of bb0 : $Float // CHECK: [ACTIVE] %4 = alloc_stack [lexical] $Array<Float>, var, name "array" // CHECK: [ACTIVE] %5 = copy_value %0 : $Array<Float> // CHECK: [USEFUL] %7 = integer_literal $Builtin.IntLiteral, 0 // CHECK: [USEFUL] %8 = metatype $@thin Int.Type // CHECK: [NONE] // function_ref Int.init(_builtinIntegerLiteral:) // CHECK: [USEFUL] %10 = apply %9(%7, %8) : $@convention(method) (Builtin.IntLiteral, @thin Int.Type) -> Int // CHECK: [ACTIVE] %11 = begin_access [modify] [static] %4 : $*Array<Float> // CHECK: [NONE] // function_ref Array.subscript.modify // CHECK: [ACTIVE] (**%13**, %14) = begin_apply %12<Float>(%10, %11) : $@yield_once @convention(method) <τ_0_0> (Int, @inout Array<τ_0_0>) -> @yields @inout τ_0_0 // CHECK: [VARIED] (%13, **%14**) = begin_apply %12<Float>(%10, %11) : $@yield_once @convention(method) <τ_0_0> (Int, @inout Array<τ_0_0>) -> @yields @inout τ_0_0 // CHECK: [USEFUL] %18 = integer_literal $Builtin.IntLiteral, 0 // CHECK: [USEFUL] %19 = metatype $@thin Int.Type // CHECK: [NONE] // function_ref Int.init(_builtinIntegerLiteral:) // CHECK: [USEFUL] %21 = apply %20(%18, %19) : $@convention(method) (Builtin.IntLiteral, @thin Int.Type) -> Int // CHECK: [ACTIVE] %22 = begin_access [read] [static] %4 : $*Array<Float> // CHECK: [ACTIVE] %23 = load_borrow %22 : $*Array<Float> // CHECK: [ACTIVE] %24 = alloc_stack $Float // CHECK: [NONE] // function_ref Array.subscript.getter // CHECK: [NONE] %26 = apply %25<Float>(%24, %21, %23) : $@convention(method) <τ_0_0> (Int, @guaranteed Array<τ_0_0>) -> @out τ_0_0 // CHECK: [ACTIVE] %27 = load [trivial] %24 : $*Float // TF-1115: Test `begin_apply` active `inout` argument with non-active initial result. // expected-error @+1 {{function is not differentiable}} @differentiable(reverse) // expected-note @+1 {{when differentiating this function definition}} func testBeginApplyActiveButInitiallyNonactiveInoutArgument(x: Float) -> Float { // `var array` is initially non-active. var array: [Float] = [0] // Array subscript assignment below calls `Array.subscript.modify`. // expected-note @+1 {{differentiation of coroutine calls is not yet supported}} array[0] = x return array[0] } // CHECK-LABEL: [AD] Activity info for ${{.*}}testBeginApplyActiveButInitiallyNonactiveInoutArgument{{.*}} at parameter indices (0) and result indices (0) // CHECK: [ACTIVE] %0 = argument of bb0 : $Float // CHECK: [ACTIVE] %2 = alloc_stack [lexical] $Array<Float>, var, name "array" // CHECK: [USEFUL] %3 = integer_literal $Builtin.Word, 1 // CHECK: [NONE] // function_ref _allocateUninitializedArray<A>(_:) // CHECK: [USEFUL] %5 = apply %4<Float>(%3) : $@convention(thin) <τ_0_0> (Builtin.Word) -> (@owned Array<τ_0_0>, Builtin.RawPointer) // CHECK: [USEFUL] (**%6**, %7) = destructure_tuple %5 : $(Array<Float>, Builtin.RawPointer) // CHECK: [NONE] (%6, **%7**) = destructure_tuple %5 : $(Array<Float>, Builtin.RawPointer) // CHECK: [USEFUL] %8 = pointer_to_address %7 : $Builtin.RawPointer to [strict] $*Float // CHECK: [USEFUL] %9 = integer_literal $Builtin.IntLiteral, 0 // CHECK: [USEFUL] %10 = metatype $@thin Float.Type // CHECK: [NONE] // function_ref Float.init(_builtinIntegerLiteral:) // CHECK: [USEFUL] %12 = apply %11(%9, %10) : $@convention(method) (Builtin.IntLiteral, @thin Float.Type) -> Float // CHECK: [NONE] // function_ref _finalizeUninitializedArray<A>(_:) // CHECK: [USEFUL] %15 = apply %14<Float>(%6) : $@convention(thin) <τ_0_0> (@owned Array<τ_0_0>) -> @owned Array<τ_0_0> // CHECK: [USEFUL] %17 = integer_literal $Builtin.IntLiteral, 0 // CHECK: [USEFUL] %18 = metatype $@thin Int.Type // CHECK: [NONE] // function_ref Int.init(_builtinIntegerLiteral:) // CHECK: [USEFUL] %20 = apply %19(%17, %18) : $@convention(method) (Builtin.IntLiteral, @thin Int.Type) -> Int // CHECK: [ACTIVE] %21 = begin_access [modify] [static] %2 : $*Array<Float> // CHECK: [NONE] // function_ref Array.subscript.modify // CHECK: [ACTIVE] (**%23**, %24) = begin_apply %22<Float>(%20, %21) : $@yield_once @convention(method) <τ_0_0> (Int, @inout Array<τ_0_0>) -> @yields @inout τ_0_0 // CHECK: [VARIED] (%23, **%24**) = begin_apply %22<Float>(%20, %21) : $@yield_once @convention(method) <τ_0_0> (Int, @inout Array<τ_0_0>) -> @yields @inout τ_0_0 // CHECK: [USEFUL] %28 = integer_literal $Builtin.IntLiteral, 0 // CHECK: [USEFUL] %29 = metatype $@thin Int.Type // CHECK: [NONE] // function_ref Int.init(_builtinIntegerLiteral:) // CHECK: [USEFUL] %31 = apply %30(%28, %29) : $@convention(method) (Builtin.IntLiteral, @thin Int.Type) -> Int // CHECK: [ACTIVE] %32 = begin_access [read] [static] %2 : $*Array<Float> // CHECK: [ACTIVE] %33 = load_borrow %32 : $*Array<Float> // CHECK: [ACTIVE] %34 = alloc_stack $Float // CHECK: [NONE] // function_ref Array.subscript.getter // CHECK: [NONE] %36 = apply %35<Float>(%34, %31, %33) : $@convention(method) <τ_0_0> (Int, @guaranteed Array<τ_0_0>) -> @out τ_0_0 // CHECK: [ACTIVE] %37 = load [trivial] %34 : $*Float //===----------------------------------------------------------------------===// // Class differentiation //===----------------------------------------------------------------------===// class C: Differentiable { @differentiable(reverse) var float: Float init(_ float: Float) { self.float = float } @differentiable(reverse) func method(_ x: Float) -> Float { x * float } // CHECK-LABEL: [AD] Activity info for ${{.*}}1CC6methodyS2fF at parameter indices (0, 1) and result indices (0) // CHECK: bb0: // CHECK: [ACTIVE] %0 = argument of bb0 : $Float // CHECK: [ACTIVE] %1 = argument of bb0 : $C // CHECK: [USEFUL] %4 = metatype $@thin Float.Type // CHECK: [VARIED] %5 = class_method %1 : $C, #C.float!getter : (C) -> () -> Float, $@convention(method) (@guaranteed C) -> Float // CHECK: [ACTIVE] %6 = apply %5(%1) : $@convention(method) (@guaranteed C) -> Float // CHECK: [NONE] // function_ref static Float.* infix(_:_:) // CHECK: %7 = function_ref @$sSf1moiyS2f_SftFZ : $@convention(method) (Float, Float, @thin Float.Type) -> Float // CHECK: [ACTIVE] %8 = apply %7(%0, %6, %4) : $@convention(method) (Float, Float, @thin Float.Type) -> Float } // TF-1176: Test class property `modify` accessor. @differentiable(reverse) func testClassModifyAccessor(_ c: inout C) { c.float *= c.float } // FIXME(TF-1176): Some values are incorrectly not marked as active: `%16`, etc. // CHECK-LABEL: [AD] Activity info for ${{.*}}testClassModifyAccessor{{.*}} at parameter indices (0) and result indices (0) // CHECK: [ACTIVE] %0 = argument of bb0 : $*C // CHECK: [NONE] %2 = metatype $@thin Float.Type // CHECK: [ACTIVE] %3 = begin_access [read] [static] %0 : $*C // CHECK: [VARIED] %4 = load [copy] %3 : $*C // CHECK: [ACTIVE] %6 = begin_access [read] [static] %0 : $*C // CHECK: [VARIED] %7 = load [copy] %6 : $*C // CHECK: [VARIED] %9 = class_method %7 : $C, #C.float!getter : (C) -> () -> Float, $@convention(method) (@guaranteed C) -> Float // CHECK: [VARIED] %10 = apply %9(%7) : $@convention(method) (@guaranteed C) -> Float // CHECK: [VARIED] %12 = class_method %4 : $C, #C.float!modify : (C) -> () -> (), $@yield_once @convention(method) (@guaranteed C) -> @yields @inout Float // CHECK: [VARIED] (**%13**, %14) = begin_apply %12(%4) : $@yield_once @convention(method) (@guaranteed C) -> @yields @inout Float // CHECK: [VARIED] (%13, **%14**) = begin_apply %12(%4) : $@yield_once @convention(method) (@guaranteed C) -> @yields @inout Float // CHECK: [NONE] // function_ref static Float.*= infix(_:_:) // CHECK: [NONE] %16 = apply %15(%13, %10, %2) : $@convention(method) (@inout Float, Float, @thin Float.Type) -> () //===----------------------------------------------------------------------===// // Enum differentiation //===----------------------------------------------------------------------===// // expected-error @+1 {{function is not differentiable}} @differentiable(reverse) // expected-note @+1 {{when differentiating this function definition}} func testActiveOptional(_ x: Float) -> Float { var maybe: Float? = 10 // expected-note @+1 {{expression is not differentiable}} maybe = x return maybe! } // CHECK-LABEL: [AD] Activity info for ${{.*}}testActiveOptional{{.*}} at parameter indices (0) and result indices (0) // CHECK: bb0: // CHECK: [ACTIVE] %0 = argument of bb0 : $Float // CHECK: [ACTIVE] %2 = alloc_stack [lexical] $Optional<Float>, var, name "maybe" // CHECK: [USEFUL] %3 = integer_literal $Builtin.IntLiteral, 10 // CHECK: [USEFUL] %4 = metatype $@thin Float.Type // CHECK: [NONE] // function_ref Float.init(_builtinIntegerLiteral:) // CHECK: [USEFUL] %6 = apply %5(%3, %4) : $@convention(method) (Builtin.IntLiteral, @thin Float.Type) -> Float // CHECK: [USEFUL] %7 = enum $Optional<Float>, #Optional.some!enumelt, %6 : $Float // CHECK: [ACTIVE] %9 = enum $Optional<Float>, #Optional.some!enumelt, %0 : $Float // CHECK: [ACTIVE] %10 = begin_access [modify] [static] %2 : $*Optional<Float> // CHECK: [ACTIVE] %13 = begin_access [read] [static] %2 : $*Optional<Float> // CHECK: [ACTIVE] %14 = load [trivial] %13 : $*Optional<Float> // CHECK: bb1: // CHECK: [NONE] // function_ref _diagnoseUnexpectedNilOptional(_filenameStart:_filenameLength:_filenameIsASCII:_line:_isImplicitUnwrap:) // CHECK: [NONE] %24 = apply %23(%17, %18, %19, %20, %22) : $@convention(thin) (Builtin.RawPointer, Builtin.Word, Builtin.Int1, Builtin.Word, Builtin.Int1) -> () // CHECK: bb2: // CHECK: [ACTIVE] %26 = argument of bb2 : $Float enum DirectEnum: Differentiable & AdditiveArithmetic { case case0 case case1(Float) case case2(Float, Float) typealias TangentVector = Self static var zero: Self { fatalError() } static func +(_ lhs: Self, _ rhs: Self) -> Self { fatalError() } static func -(_ lhs: Self, _ rhs: Self) -> Self { fatalError() } } // expected-error @+1 {{function is not differentiable}} @differentiable(reverse, wrt: e) // expected-note @+2 {{when differentiating this function definition}} // expected-note @+1 {{differentiating enum values is not yet supported}} func testActiveEnumValue(_ e: DirectEnum, _ x: Float) -> Float { switch e { case .case0: return x case let .case1(y1): return y1 case let .case2(y1, y2): return y1 + y2 } } // CHECK-LABEL: [AD] Activity info for ${{.*}}testActiveEnumValue{{.*}} at parameter indices (0) and result indices (0) // CHECK: bb0: // CHECK: [ACTIVE] %0 = argument of bb0 : $DirectEnum // CHECK: [USEFUL] %1 = argument of bb0 : $Float // CHECK: bb1: // CHECK: bb2: // CHECK: [ACTIVE] %6 = argument of bb2 : $Float // CHECK: bb3: // CHECK: [ACTIVE] %9 = argument of bb3 : $(Float, Float) // CHECK: [ACTIVE] (**%10**, %11) = destructure_tuple %9 : $(Float, Float) // CHECK: [ACTIVE] (%10, **%11**) = destructure_tuple %9 : $(Float, Float) // CHECK: [USEFUL] %14 = metatype $@thin Float.Type // CHECK: [NONE] // function_ref static Float.+ infix(_:_:) // CHECK: %15 = function_ref @$sSf1poiyS2f_SftFZ : $@convention(method) (Float, Float, @thin Float.Type) -> Float // CHECK: [ACTIVE] %16 = apply %15(%10, %11, %14) : $@convention(method) (Float, Float, @thin Float.Type) -> Float // CHECK: bb4: // CHECK: [ACTIVE] %18 = argument of bb4 : $Float enum IndirectEnum<T: Differentiable>: Differentiable & AdditiveArithmetic { case case1(T) case case2(Float, T) typealias TangentVector = Self static func ==(_ lhs: Self, _ rhs: Self) -> Bool { fatalError() } static var zero: Self { fatalError() } static func +(_ lhs: Self, _ rhs: Self) -> Self { fatalError() } static func -(_ lhs: Self, _ rhs: Self) -> Self { fatalError() } } // expected-error @+1 {{function is not differentiable}} @differentiable(reverse, wrt: e) // expected-note @+2 {{when differentiating this function definition}} // expected-note @+1 {{differentiating enum values is not yet supported}} func testActiveEnumAddr<T>(_ e: IndirectEnum<T>) -> T { switch e { case let .case1(y1): return y1 case let .case2(_, y2): return y2 } } // CHECK-LABEL: [AD] Activity info for ${{.*}}testActiveEnumAddr{{.*}} at parameter indices (0) and result indices (0) // CHECK: bb0: // CHECK: [ACTIVE] %0 = argument of bb0 : $*T // CHECK: [ACTIVE] %1 = argument of bb0 : $*IndirectEnum<T> // CHECK: [ACTIVE] %3 = alloc_stack $IndirectEnum<T> // CHECK: bb1: // CHECK: [ACTIVE] %6 = unchecked_take_enum_data_addr %3 : $*IndirectEnum<T>, #IndirectEnum.case1!enumelt // CHECK: [ACTIVE] %7 = alloc_stack [lexical] $T, let, name "y1" // CHECK: bb2: // CHECK: [ACTIVE] {{.*}} = unchecked_take_enum_data_addr {{.*}} : $*IndirectEnum<T>, #IndirectEnum.case2!enumelt // CHECK: [ACTIVE] {{.*}} = tuple_element_addr {{.*}} : $*(Float, T), 0 // CHECK: [VARIED] {{.*}} = load [trivial] {{.*}} : $*Float // CHECK: [ACTIVE] {{.*}} = tuple_element_addr {{.*}} : $*(Float, T), 1 // CHECK: [ACTIVE] {{.*}} = alloc_stack [lexical] $T, let, name "y2" // CHECK: bb3: // CHECK: [NONE] {{.*}} = tuple ()
apache-2.0
2ac962d2f583888ec84da2fc5f96cf33
53.33177
174
0.615795
3.119405
false
false
false
false
kaizeiyimi/XLYAnimatedImage
XLYAnimatedImage/codes/XLYAnimatedImagePlayer.swift
1
10393
// // XLYAnimatedImagePlayer.swift // XLYAnimatedImage // // Created by kaizei on 16/1/13. // Copyright © 2016年 kaizei. All rights reserved. // import UIKit open class AnimatedImagePlayer { open var preloadCount = 2 // preload 2 frames is enough now. open var speed: Double = 1 open var paused: Bool { get { return link.isPaused } set { if let image = self.image , image.frameCount >= 2 { link.isPaused = newValue } } } open var skipFramesEnabled = true open var displayLinkFrameInterval: Int { get { return link.frameInterval } set { link.frameInterval = newValue } } open var onTimeElapse: ((TimeInterval) -> Void)? open private(set) var frameIndex: Int = 0 open private(set) var time: TimeInterval = 0 { didSet { onTimeElapse?(time) } } open private(set) var currentImage: UIImage! open var image: AnimatedImage? { didSet { if image !== oldValue { OSSpinLockLock(&spinLock) operationQueue.cancelAllOperations() cache.removeAll() OSSpinLockUnlock(&spinLock) move(toTime: 0) if let image = image { display(image.firtImage, 0) link.isPaused = image.frameCount < 2 currentImage = image.firtImage } else { stop() } } else { if let image = currentImage { display(image, frameIndex) } } } } var display: (_ image: UIImage, _ index: Int) -> Void var stop: () -> Void private let link: CADisplayLink private var spinLock = OS_SPINLOCK_INIT private var cache: [Int: UIImage?] = [:] private var miss = true private let operationQueue = OperationQueue() public init(runloopMode: RunLoop.Mode = .common, display: @escaping (_ image: UIImage, _ index: Int) -> Void, stop: @escaping () -> Void) { self.display = display self.stop = stop let wrapper = WeakWrapper() link = CADisplayLink(target: wrapper, selector: #selector(self.linkFired(_:))) wrapper.target = self link.add(to: RunLoop.main, forMode: runloopMode) link.frameInterval = 1 link.isPaused = true NotificationCenter.default.addObserver(self, selector: #selector(self.clearCache(_:)), name: UIApplication.didReceiveMemoryWarningNotification, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(self.clearCache(_:)), name: UIApplication.didEnterBackgroundNotification, object: nil) } deinit { link.invalidate() if image != nil { stop() } operationQueue.cancelAllOperations() NotificationCenter.default.removeObserver(self) } // MARK: Public open func move(toFrame index: Int) { guard let image = image , image.frameCount >= 2 else { self.frameIndex = 0 self.time = 0 return } frameIndex = index % image.frameCount self.time = image.durations[0...frameIndex].reduce(0) { $0 + $1 } miss = true update(forNextTime: self.time, loadImmediately: true) } open func move(toTime time: TimeInterval) { guard let image = image , image.frameCount >= 2 else { self.frameIndex = 0 self.time = 0 return } let time = time - floor(time / image.totalTime) * image.totalTime var index = 0, temp = 0.0 for i in 0..<image.frameCount { temp += image.durations[i] if time < temp { index = i break } } self.frameIndex = index self.time = time miss = true update(forNextTime: self.time, loadImmediately: true) } open func setImage(_ image: AnimatedImage?, replay: Bool = false) { self.image = image if replay { move(toTime: 0) } } open func replaceHandlers(display: @escaping (_ image: UIImage, _ index: Int) -> Void, stop: @escaping () -> Void) { self.display = display self.stop = stop } // MARK: private @objc private func clearCache(_ notify: Notification) { OSSpinLockLock(&spinLock) if let frameCount = image?.frameCount { let kept = (1...preloadCount).map { (($0 + frameIndex) % frameCount, cache[($0 + frameIndex) % frameCount]) } cache.removeAll(keepingCapacity: true) kept.forEach { cache[$0.0] = $0.1 } } else { cache.removeAll() } OSSpinLockUnlock(&spinLock) } @objc private func linkFired(_ link: CADisplayLink) { guard let image = image , image.frameCount >= 2 else { link.isPaused = true self.frameIndex = 0 self.time = 0 return } let nextTime = time - floor(time / image.totalTime) * image.totalTime + link.duration * Double(link.frameInterval) * speed update(forNextTime: nextTime) } private func update(forNextTime nextTime: TimeInterval, loadImmediately: Bool = false) { guard let image = image else { return } // load image at index. only fetch from cache let showImageAtIndex = {[unowned self] (index: Int) -> Void in OSSpinLockLock(&self.spinLock) let state = self.cache[index] OSSpinLockUnlock(&self.spinLock) if let state = state { self.miss = false if let image = state { self.currentImage = image self.display(image, index) } } else { self.miss = true } } if skipFramesEnabled { var index = 0, temp = 0.0 for i in 0..<image.frameCount { temp += image.durations[i] if nextTime < temp { index = i break } } if (index != frameIndex && !miss) || (index == frameIndex && miss) { time = nextTime frameIndex = index showImageAtIndex(index) } else if index == frameIndex && !miss { time = nextTime } else if index != frameIndex && miss { showImageAtIndex(frameIndex) } } else { let frameEndTime = image.durations[0...frameIndex].reduce(0){ $0 + $1 } let shouldShowNext = (nextTime >= frameEndTime) || (nextTime < frameEndTime - image.durations[frameIndex]) if !shouldShowNext && miss { time = nextTime showImageAtIndex(frameIndex) } else if !shouldShowNext && !miss { time = nextTime } else if shouldShowNext && miss { showImageAtIndex(frameIndex) } else if shouldShowNext && !miss { let nextDuration = image.durations[(frameIndex + 1) % image.frameCount] time = min(nextTime, frameEndTime + nextDuration) frameIndex = (frameIndex + 1) % image.frameCount if frameIndex == 0 { time = min(nextTime, image.durations[0]) } showImageAtIndex(frameIndex) } } // preload OSSpinLockLock(&self.spinLock) let cacheCount = cache.count OSSpinLockUnlock(&self.spinLock) if cacheCount < image.frameCount && (operationQueue.operationCount == 0 || loadImmediately) { if loadImmediately { operationQueue.cancelAllOperations() } let operation = BlockOperation() operation.addExecutionBlock {[weak self, unowned operation, frameCount = image.frameCount, current = frameIndex, max = (frameIndex + preloadCount) % image.frameCount] in guard let this = self else { return } if operation.isCancelled { return } let indies = NSMutableIndexSet() if current < max { indies.add(in: NSMakeRange(current, max - current + 1)) } else { indies.add(in: NSMakeRange(current, frameCount - current)) indies.add(in: NSMakeRange(0, max + 1)) } if operation.isCancelled { return } for index in indies { if operation.isCancelled { return } OSSpinLockLock(&this.spinLock) let state = this.cache[index] OSSpinLockUnlock(&this.spinLock) if state == nil { let image = image.image(at: index) OSSpinLockLock(&this.spinLock) if !operation.isCancelled { this.cache[index] = Optional<UIImage?>.some(image) } OSSpinLockUnlock(&this.spinLock) } } if loadImmediately && !operation.isCancelled { DispatchQueue.main.async {[weak self] in if let this = self , this.frameIndex == current { showImageAtIndex(current) } } } } operationQueue.addOperation(operation) } } } final private class WeakWrapper: NSObject { weak var target: AnyObject? init(_ target: AnyObject) { self.target = target } override init() {} override func forwardingTarget(for aSelector: Selector) -> Any? { return target } }
mit
3a33b92b86a71fc0e41d3e88f11b6351
33.983165
164
0.509143
5.171727
false
false
false
false
elmoswelt/SwiftExtensions
Source/NSColor/NSColorExtensions.swift
1
2934
// // NSColorExtensions.swift // SwiftExtensions // // The MIT License (MIT) // // Created by Elmar Tampe on 13/11/14. // // Copyright (c) 2014 Elmar Tampe. 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 import Cocoa extension NSColor { // ------------------------------------------------------------------------------------------ //MARK: - String to Integer conversion // ------------------------------------------------------------------------------------------ class func colorWithHexValue(hexValue: NSString) -> NSColor { var hexString = hexValue.stringByReplacingOccurrencesOfString("#", withString: "0x") var hexStringValueAsInt: uint = 0 let scanner = NSScanner(string: hexString) var color: NSColor? if scanner.scanHexInt(&hexStringValueAsInt) { color = NSColor.colorWithIntegerHexValue(hexStringValueAsInt) } return color! } // ------------------------------------------------------------------------------------------ //MARK: - RGBA Color creation // ------------------------------------------------------------------------------------------ class func colorWithIntegerHexValue(hexValueAsInt: uint) -> NSColor { if hexValueAsInt == 0 { return NSColor.blackColor()} let digitCount:NSInteger = NSInteger((log10(Double(hexValueAsInt)) + 1)) let alpha = ((digitCount == 10) ? (((CGFloat)((hexValueAsInt & 0xFF000000) >> 24)) / 255.0) : 1.0) let red = ((CGFloat)((hexValueAsInt & 0xFF0000) >> 16)) / 255.0 let green = ((CGFloat)((hexValueAsInt & 0xFF00) >> 8)) / 255.0 let blue = ((CGFloat)(hexValueAsInt & 0xFF)) / 255.0 return NSColor(calibratedRed: red, green: green, blue: blue, alpha: alpha) } }
mit
37701c6c56d8a18fff216be10f22ecb4
40.914286
106
0.585549
4.89
false
false
false
false
QQLS/YouTobe
YouTube/Class/Base/Model/BQModelTransformer.swift
1
1490
// // BQModelTransformer.swift // YouTube // // Created by xiupai on 2017/3/20. // Copyright © 2017年 QQLS. All rights reserved. // import UIKit import ObjectMapper /** * 字符串转换为 Int */ let TransformerStringToInt = TransformOf<Int, String>(fromJSON: { (value: String?) -> Int? in guard let value = value else { return 0 } return Int(value) }) { (value: Int?) -> String? in guard let value = value else { return nil } return String(value) } /** * 字符串转换为 Float */ let TransformerStringToFloat = TransformOf<Float, String>(fromJSON: { (value: String?) -> Float? in guard let value = value else { return 0 } return Float(value) }) { (value: Float?) -> String? in guard let value = value else { return nil } return String(value) } /** * 字符串转换为 CGFloat */ let TransformerStringToCGFloat = TransformOf<CGFloat, String>(fromJSON: { (value: String?) -> CGFloat? in guard let value = value else { return 0 } return CGFloat(Int(value)!) }) { (value: CGFloat?) -> String? in guard let value = value else { return nil } return String(describing: value) } /** * 时间戳转换为 String */ let TransformerTimestampToTime = TransformOf<String, Int>(fromJSON: { (value: Int?) -> String? in guard let value = value else { return "" } return value.time }) { (value: String?) -> Int? in return nil }
apache-2.0
351c12fdd02c3f7a771b445e6844a1e8
19.855072
105
0.608061
3.680307
false
false
false
false
kemalenver/SwiftHackerRank
Algorithms/Sorting.playground/Pages/Sorting - Insertion Sort - Part 1.xcplaygroundpage/Contents.swift
1
499
let inputs = ["5", "2 4 6 8 3"] var n = Int(inputs[0])! var array = inputs[1].split(separator: " ").map{ Int(String($0))! } for i in 1..<n { let value = array[i] var position = i-1 while position >= 0 && array[position] > value { array[position+1] = array[position] position-=1 print(array.map { "\($0)" }.joined(separator: " ")) } array[position+1] = value } print(array.map { "\($0)" }.joined(separator: " "))
mit
2035615e5f1e19e815127ca7599b02fc
18.96
67
0.503006
3.304636
false
false
false
false
mlgoogle/iosstar
iOSStar/Scenes/News/CustomView/NewsNavigationView.swift
4
3194
// // NewsNavigationView.swift // iOSStar // // Created by J-bb on 17/4/25. // Copyright © 2017年 YunDian. All rights reserved. // import UIKit import SnapKit class NewsNavigationView: UIView { lazy var imageView:UIImageView = { let imageView = UIImageView() imageView.image = UIImage(named: "8") return imageView }() lazy var PMLabel:UILabel = { let label = UILabel() label.text = "P M" label.textColor = UIColor(hexString: "e1eeff") label.font = UIFont.systemFont(ofSize: 14.0) return label }() lazy var timeLabel:UILabel = { let label = UILabel() label.text = "16:20" label.textColor = UIColor(hexString: "e1eeff") label.font = UIFont.systemFont(ofSize: 10.0) return label }() lazy var dateLabel:UILabel = { let label = UILabel() label.text = "2017/04/25" label.textColor = UIColor(hexString: "fafafa") label.font = UIFont.systemFont(ofSize: 16.0) return label }() override init(frame: CGRect) { super.init(frame: frame) addSubview(imageView) addSubview(PMLabel) addSubview(timeLabel) addSubview(dateLabel) imageView.snp.makeConstraints { (make) in make.top.equalTo(10) make.left.equalTo(10) make.bottom.equalTo(-10) make.width.equalTo(24) } PMLabel.snp.makeConstraints { (make) in make.left.equalTo(imageView.snp.right).offset(10) make.top.equalTo(imageView) make.width.equalTo(26) make.height.equalTo(10) } timeLabel.snp.makeConstraints { (make) in make.left.equalTo(PMLabel) make.top.equalTo(PMLabel.snp.bottom).offset(5) make.width.equalTo(30) make.height.equalTo(8) } dateLabel.snp.makeConstraints { (make) in make.centerX.equalTo(self) make.centerY.equalTo(self) } setTime() } func setTitle(title:String) { dateLabel.text = title.substring(to:title.index(title.startIndex, offsetBy: 10)) } func setTime() { let date = Date() let formatter = DateFormatter() formatter.dateFormat = "HH" let hour = formatter.string(from: date) if Int(hour)! > 11 { PMLabel.text = "P M" } else { PMLabel.text = "A M" } if Int(hour)! > 6 && Int(hour)! < 18{ imageView.image = UIImage(named: "news_day") } else { imageView.image = UIImage(named: "news_night") } formatter.dateFormat = "HH:mm" timeLabel.text = formatter.string(from: date) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } /* // Only override draw() if you perform custom drawing. // An empty implementation adversely affects performance during animation. override func draw(_ rect: CGRect) { // Drawing code } */ }
gpl-3.0
c749e0e164022e5ab552628a08ca77ce
26.042373
88
0.557505
4.182176
false
false
false
false
takeotsuchida/Watch-Connectivity
Connectivity WatchKit Extension/GlanceController.swift
1
1608
// // GlanceController.swift // Connectivity WatchKit Extension // // Created by Takeo Tsuchida on 2015/07/31. // Copyright © 2015年 MUMPK Limited Partnership. All rights reserved. // import WatchKit import Foundation import WatchConnectivity class GlanceController: WKInterfaceController { @IBOutlet var transferredImage: WKInterfaceImage! @IBOutlet var contextLabel: WKInterfaceLabel! override func awakeWithContext(context: AnyObject?) { super.awakeWithContext(context) // Configure interface objects here. } override func willActivate() { // This method is called when watch view controller is about to be visible to user super.willActivate() if let context = WCSession.defaultSession().receivedApplicationContext as? [String:String], message = context[dataId] { contextLabel.setText(message) } let url = try! NSFileManager.defaultManager().URLForDirectory(.DocumentDirectory, inDomain: .UserDomainMask, appropriateForURL: nil, create: false) let urls = try! NSFileManager.defaultManager().contentsOfDirectoryAtURL(url, includingPropertiesForKeys: nil, options: .SkipsHiddenFiles) for url in urls { if let data = NSData(contentsOfURL: url), image = UIImage(data: data) { self.transferredImage.setImage(image) break } } } override func didDeactivate() { // This method is called when watch view controller is no longer visible super.didDeactivate() } }
gpl-2.0
8d4af349b00b54a62454a4cfb37733be
32.4375
145
0.672897
5.245098
false
false
false
false
colemancda/SwiftyGPIO
Sources/SunXi.swift
1
2333
/* SwiftyGPIO Copyright (c) 2016 Umberto Raimondi Licensed under the MIT license, as follows: 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.) */ /// GPIO for SunXi (e.g. OrangePi) hardware. /// /// - SeeAlso: [SunXi Wiki](http://linux-sunxi.org/GPIO) public struct SunXiGPIO: CustomStringConvertible, Equatable { // MARK: - Properties public var letter: Letter public var pin: UInt // MARK: - Initialization public init(letter: Letter, pin: UInt) { self.letter = letter self.pin = pin } // MARK: - Computed Properties public var description: String { return pinName } public var pinName: String { return "P" + "\(letter)" + "\(pin)" } public var gpioPin: Int { return (letter.rawValue * 32) + Int(pin) } } // MARK: - Equatable public func == (lhs: SunXiGPIO, rhs: SunXiGPIO) -> Bool { return lhs.letter == rhs.letter && lhs.pin == rhs.pin } // MARK: - Supporting Types public extension SunXiGPIO { public enum Letter: Int { case A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X, Y, Z } } // MARK: - Extensions public extension GPIO { convenience init(sunXi: SunXiGPIO) { self.init(name: sunXi.pinName, id: sunXi.gpioPin) } }
mit
28a8eac1af82bbc4a274c62a11f1f369
25.213483
89
0.672525
3.981229
false
false
false
false
huonw/swift
test/decl/protocol/special/coding/struct_codable_member_type_lookup.swift
1
21858
// RUN: %target-typecheck-verify-swift -verify-ignore-unknown // A top-level CodingKeys type to fall back to in lookups below. public enum CodingKeys : String, CodingKey { case topLevel } // MARK: - Synthesized CodingKeys Enum // Structs which get synthesized Codable implementations should have visible // CodingKey enums during member type lookup. struct SynthesizedStruct : Codable { let value: String = "foo" // Qualified type lookup should always be unambiguous. public func qualifiedFoo(_ key: SynthesizedStruct.CodingKeys) {} // expected-error {{method cannot be declared public because its parameter uses a private type}} internal func qualifiedBar(_ key: SynthesizedStruct.CodingKeys) {} // expected-error {{method cannot be declared internal because its parameter uses a private type}} fileprivate func qualfiedBaz(_ key: SynthesizedStruct.CodingKeys) {} // expected-warning {{method should not be declared fileprivate because its parameter uses a private type}} private func qualifiedQux(_ key: SynthesizedStruct.CodingKeys) {} // Unqualified lookups should find the synthesized CodingKeys type instead // of the top-level type above. public func unqualifiedFoo(_ key: CodingKeys) { // expected-error {{method cannot be declared public because its parameter uses a private type}} print(CodingKeys.value) // Not found on top-level. } internal func unqualifiedBar(_ key: CodingKeys) { // expected-error {{method cannot be declared internal because its parameter uses a private type}} print(CodingKeys.value) // Not found on top-level. } fileprivate func unqualifiedBaz(_ key: CodingKeys) { // expected-warning {{method should not be declared fileprivate because its parameter uses a private type}} print(CodingKeys.value) // Not found on top-level. } private func unqualifiedQux(_ key: CodingKeys) { print(CodingKeys.value) // Not found on top-level. } // Unqualified lookups should find the most local CodingKeys type available. public func nestedUnqualifiedFoo(_ key: CodingKeys) { // expected-error {{method cannot be declared public because its parameter uses a private type}} enum CodingKeys : String, CodingKey { case nested } // CodingKeys should refer to the local unqualified enum. func foo(_ key: CodingKeys) { print(CodingKeys.nested) // Not found on synthesized type or top-level type. } foo(CodingKeys.nested) } internal func nestedUnqualifiedBar(_ key: CodingKeys) { // expected-error {{method cannot be declared internal because its parameter uses a private type}} enum CodingKeys : String, CodingKey { case nested } // CodingKeys should refer to the local unqualified enum. func bar(_ key: CodingKeys) { print(CodingKeys.nested) // Not found on synthesized type or top-level type. } bar(CodingKeys.nested) } fileprivate func nestedUnqualifiedBaz(_ key: CodingKeys) { // expected-warning {{method should not be declared fileprivate because its parameter uses a private type}} enum CodingKeys : String, CodingKey { case nested } // CodingKeys should refer to the local unqualified enum. func baz(_ key: CodingKeys) { print(CodingKeys.nested) // Not found on synthesized type or top-level type. } baz(CodingKeys.nested) } private func nestedUnqualifiedQux(_ key: CodingKeys) { enum CodingKeys : String, CodingKey { case nested } // CodingKeys should refer to the local unqualified enum. func qux(_ key: CodingKeys) { print(CodingKeys.nested) // Not found on synthesized type or top-level type. } qux(CodingKeys.nested) } // Lookup within nested types should look outside of the type. struct Nested { // Qualified lookup should remain as-is. public func qualifiedFoo(_ key: SynthesizedStruct.CodingKeys) {} // expected-error {{method cannot be declared public because its parameter uses a private type}} internal func qualifiedBar(_ key: SynthesizedStruct.CodingKeys) {} // expected-error {{method cannot be declared internal because its parameter uses a private type}} fileprivate func qualfiedBaz(_ key: SynthesizedStruct.CodingKeys) {} // expected-warning {{method should not be declared fileprivate because its parameter uses a private type}} private func qualifiedQux(_ key: SynthesizedStruct.CodingKeys) {} // Unqualified lookups should find the SynthesizedStruct's synthesized // CodingKeys type instead of the top-level type above. public func unqualifiedFoo(_ key: CodingKeys) { // expected-error {{method cannot be declared public because its parameter uses a private type}} print(CodingKeys.value) // Not found on top-level. } internal func unqualifiedBar(_ key: CodingKeys) { // expected-error {{method cannot be declared internal because its parameter uses a private type}} print(CodingKeys.value) // Not found on top-level. } fileprivate func unqualifiedBaz(_ key: CodingKeys) { // expected-warning {{method should not be declared fileprivate because its parameter uses a private type}} print(CodingKeys.value) // Not found on top-level. } private func unqualifiedQux(_ key: CodingKeys) { print(CodingKeys.value) // Not found on top-level. } // Unqualified lookups should find the most local CodingKeys type available. public func nestedUnqualifiedFoo(_ key: CodingKeys) { // expected-error {{method cannot be declared public because its parameter uses a private type}} enum CodingKeys : String, CodingKey { case nested } // CodingKeys should refer to the local unqualified enum. func foo(_ key: CodingKeys) { print(CodingKeys.nested) // Not found on synthesized type or top-level type. } foo(CodingKeys.nested) } internal func nestedUnqualifiedBar(_ key: CodingKeys) { // expected-error {{method cannot be declared internal because its parameter uses a private type}} enum CodingKeys : String, CodingKey { case nested } // CodingKeys should refer to the local unqualified enum. func bar(_ key: CodingKeys) { print(CodingKeys.nested) // Not found on synthesized type or top-level type. } bar(CodingKeys.nested) } fileprivate func nestedUnqualifiedBaz(_ key: CodingKeys) { // expected-warning {{method should not be declared fileprivate because its parameter uses a private type}} enum CodingKeys : String, CodingKey { case nested } // CodingKeys should refer to the local unqualified enum. func baz(_ key: CodingKeys) { print(CodingKeys.nested) // Not found on synthesized type or top-level type. } baz(CodingKeys.nested) } private func nestedUnqualifiedQux(_ key: CodingKeys) { enum CodingKeys : String, CodingKey { case nested } // CodingKeys should refer to the local unqualified enum. func qux(_ key: CodingKeys) { print(CodingKeys.nested) // Not found on synthesized type or top-level type. } qux(CodingKeys.nested) } } } // MARK: - No CodingKeys Enum // Structs which don't get synthesized Codable implementations should expose the // appropriate CodingKeys type. struct NonSynthesizedStruct : Codable { // No synthesized type since we implemented both methods. init(from decoder: Decoder) throws {} func encode(to encoder: Encoder) throws {} // Qualified type lookup should clearly fail -- we shouldn't get a synthesized // type here. public func qualifiedFoo(_ key: NonSynthesizedStruct.CodingKeys) {} // expected-error {{'CodingKeys' is not a member type of 'NonSynthesizedStruct'}} internal func qualifiedBar(_ key: NonSynthesizedStruct.CodingKeys) {} // expected-error {{'CodingKeys' is not a member type of 'NonSynthesizedStruct'}} fileprivate func qualfiedBaz(_ key: NonSynthesizedStruct.CodingKeys) {} // expected-error {{'CodingKeys' is not a member type of 'NonSynthesizedStruct'}} private func qualifiedQux(_ key: NonSynthesizedStruct.CodingKeys) {} // expected-error {{'CodingKeys' is not a member type of 'NonSynthesizedStruct'}} // Unqualified lookups should find the public top-level CodingKeys type. public func unqualifiedFoo(_ key: CodingKeys) { print(CodingKeys.topLevel) } internal func unqualifiedBar(_ key: CodingKeys) { print(CodingKeys.topLevel) } fileprivate func unqualifiedBaz(_ key: CodingKeys) { print(CodingKeys.topLevel) } private func unqualifiedQux(_ key: CodingKeys) { print(CodingKeys.topLevel) } // Unqualified lookups should find the most local CodingKeys type available. public func nestedUnqualifiedFoo(_ key: CodingKeys) { enum CodingKeys : String, CodingKey { case nested } // CodingKeys should refer to the local unqualified enum. func foo(_ key: CodingKeys) { print(CodingKeys.nested) // Not found on top-level type. } foo(CodingKeys.nested) } internal func nestedUnqualifiedBar(_ key: CodingKeys) { enum CodingKeys : String, CodingKey { case nested } // CodingKeys should refer to the local unqualified enum. func bar(_ key: CodingKeys) { print(CodingKeys.nested) // Not found on top-level type. } bar(CodingKeys.nested) } fileprivate func nestedUnqualifiedBaz(_ key: CodingKeys) { enum CodingKeys : String, CodingKey { case nested } // CodingKeys should refer to the local unqualified enum. func baz(_ key: CodingKeys) { print(CodingKeys.nested) // Not found on top-level type. } baz(CodingKeys.nested) } private func nestedUnqualifiedQux(_ key: CodingKeys) { enum CodingKeys : String, CodingKey { case nested } // CodingKeys should refer to the local unqualified enum. func qux(_ key: CodingKeys) { print(CodingKeys.nested) // Not found on top-level type. } qux(CodingKeys.nested) } } // MARK: - Explicit CodingKeys Enum // Structs which explicitly define their own CodingKeys types should have // visible CodingKey enums during member type lookup. struct ExplicitStruct : Codable { let value: String = "foo" public enum CodingKeys { case a case b case c } init(from decoder: Decoder) throws {} func encode(to encoder: Encoder) throws {} // Qualified type lookup should always be unambiguous. public func qualifiedFoo(_ key: ExplicitStruct.CodingKeys) {} internal func qualifiedBar(_ key: ExplicitStruct.CodingKeys) {} fileprivate func qualfiedBaz(_ key: ExplicitStruct.CodingKeys) {} private func qualifiedQux(_ key: ExplicitStruct.CodingKeys) {} // Unqualified lookups should find the synthesized CodingKeys type instead // of the top-level type above. public func unqualifiedFoo(_ key: CodingKeys) { print(CodingKeys.a) // Not found on top-level. } internal func unqualifiedBar(_ key: CodingKeys) { print(CodingKeys.a) // Not found on top-level. } fileprivate func unqualifiedBaz(_ key: CodingKeys) { print(CodingKeys.a) // Not found on top-level. } private func unqualifiedQux(_ key: CodingKeys) { print(CodingKeys.a) // Not found on top-level. } // Unqualified lookups should find the most local CodingKeys type available. public func nestedUnqualifiedFoo(_ key: CodingKeys) { enum CodingKeys : String, CodingKey { case nested } // CodingKeys should refer to the local unqualified enum. func foo(_ key: CodingKeys) { print(CodingKeys.nested) // Not found on synthesized type or top-level type. } foo(CodingKeys.nested) } internal func nestedUnqualifiedBar(_ key: CodingKeys) { enum CodingKeys : String, CodingKey { case nested } // CodingKeys should refer to the local unqualified enum. func bar(_ key: CodingKeys) { print(CodingKeys.nested) // Not found on synthesized type or top-level type. } bar(CodingKeys.nested) } fileprivate func nestedUnqualifiedBaz(_ key: CodingKeys) { enum CodingKeys : String, CodingKey { case nested } // CodingKeys should refer to the local unqualified enum. func baz(_ key: CodingKeys) { print(CodingKeys.nested) // Not found on synthesized type or top-level type. } baz(CodingKeys.nested) } private func nestedUnqualifiedQux(_ key: CodingKeys) { enum CodingKeys : String, CodingKey { case nested } // CodingKeys should refer to the local unqualified enum. func qux(_ key: CodingKeys) { print(CodingKeys.nested) // Not found on synthesized type or top-level type. } qux(CodingKeys.nested) } // Lookup within nested types should look outside of the type. struct Nested { // Qualified lookup should remain as-is. public func qualifiedFoo(_ key: ExplicitStruct.CodingKeys) {} internal func qualifiedBar(_ key: ExplicitStruct.CodingKeys) {} fileprivate func qualfiedBaz(_ key: ExplicitStruct.CodingKeys) {} private func qualifiedQux(_ key: ExplicitStruct.CodingKeys) {} // Unqualified lookups should find the ExplicitStruct's synthesized // CodingKeys type instead of the top-level type above. public func unqualifiedFoo(_ key: CodingKeys) { print(CodingKeys.a) // Not found on top-level. } internal func unqualifiedBar(_ key: CodingKeys) { print(CodingKeys.a) // Not found on top-level. } fileprivate func unqualifiedBaz(_ key: CodingKeys) { print(CodingKeys.a) // Not found on top-level. } private func unqualifiedQux(_ key: CodingKeys) { print(CodingKeys.a) // Not found on top-level. } // Unqualified lookups should find the most local CodingKeys type available. public func nestedUnqualifiedFoo(_ key: CodingKeys) { enum CodingKeys : String, CodingKey { case nested } // CodingKeys should refer to the local unqualified enum. func foo(_ key: CodingKeys) { print(CodingKeys.nested) // Not found on synthesized type or top-level type. } foo(CodingKeys.nested) } internal func nestedUnqualifiedBar(_ key: CodingKeys) { enum CodingKeys : String, CodingKey { case nested } // CodingKeys should refer to the local unqualified enum. func bar(_ key: CodingKeys) { print(CodingKeys.nested) // Not found on synthesized type or top-level type. } bar(CodingKeys.nested) } fileprivate func nestedUnqualifiedBaz(_ key: CodingKeys) { enum CodingKeys : String, CodingKey { case nested } // CodingKeys should refer to the local unqualified enum. func baz(_ key: CodingKeys) { print(CodingKeys.nested) // Not found on synthesized type or top-level type. } baz(CodingKeys.nested) } private func nestedUnqualifiedQux(_ key: CodingKeys) { enum CodingKeys : String, CodingKey { case nested } // CodingKeys should refer to the local unqualified enum. func qux(_ key: CodingKeys) { print(CodingKeys.nested) // Not found on synthesized type or top-level type. } qux(CodingKeys.nested) } } } // MARK: - CodingKeys Enums in Extensions // Structs which get a CodingKeys type in an extension should be able to see // that type during member type lookup. struct ExtendedStruct : Codable { let value: String = "foo" // Don't get an auto-synthesized type. init(from decoder: Decoder) throws {} func encode(to encoder: Encoder) throws {} // Qualified type lookup should always be unambiguous. public func qualifiedFoo(_ key: ExtendedStruct.CodingKeys) {} internal func qualifiedBar(_ key: ExtendedStruct.CodingKeys) {} fileprivate func qualfiedBaz(_ key: ExtendedStruct.CodingKeys) {} private func qualifiedQux(_ key: ExtendedStruct.CodingKeys) {} // Unqualified lookups should find the synthesized CodingKeys type instead // of the top-level type above. public func unqualifiedFoo(_ key: CodingKeys) { print(CodingKeys.a) // Not found on top-level. } internal func unqualifiedBar(_ key: CodingKeys) { print(CodingKeys.a) // Not found on top-level. } fileprivate func unqualifiedBaz(_ key: CodingKeys) { print(CodingKeys.a) // Not found on top-level. } private func unqualifiedQux(_ key: CodingKeys) { print(CodingKeys.a) // Not found on top-level. } // Unqualified lookups should find the most local CodingKeys type available. public func nestedUnqualifiedFoo(_ key: CodingKeys) { enum CodingKeys : String, CodingKey { case nested } // CodingKeys should refer to the local unqualified enum. func foo(_ key: CodingKeys) { print(CodingKeys.nested) // Not found on synthesized type or top-level type. } foo(CodingKeys.nested) } internal func nestedUnqualifiedBar(_ key: CodingKeys) { enum CodingKeys : String, CodingKey { case nested } // CodingKeys should refer to the local unqualified enum. func bar(_ key: CodingKeys) { print(CodingKeys.nested) // Not found on synthesized type or top-level type. } bar(CodingKeys.nested) } fileprivate func nestedUnqualifiedBaz(_ key: CodingKeys) { enum CodingKeys : String, CodingKey { case nested } // CodingKeys should refer to the local unqualified enum. func baz(_ key: CodingKeys) { print(CodingKeys.nested) // Not found on synthesized type or top-level type. } baz(CodingKeys.nested) } private func nestedUnqualifiedQux(_ key: CodingKeys) { enum CodingKeys : String, CodingKey { case nested } // CodingKeys should refer to the local unqualified enum. func qux(_ key: CodingKeys) { print(CodingKeys.nested) // Not found on synthesized type or top-level type. } qux(CodingKeys.nested) } // Lookup within nested types should look outside of the type. struct Nested { // Qualified lookup should remain as-is. public func qualifiedFoo(_ key: ExtendedStruct.CodingKeys) {} internal func qualifiedBar(_ key: ExtendedStruct.CodingKeys) {} fileprivate func qualfiedBaz(_ key: ExtendedStruct.CodingKeys) {} private func qualifiedQux(_ key: ExtendedStruct.CodingKeys) {} // Unqualified lookups should find the ExtendedStruct's synthesized // CodingKeys type instead of the top-level type above. public func unqualifiedFoo(_ key: CodingKeys) { print(CodingKeys.a) // Not found on top-level. } internal func unqualifiedBar(_ key: CodingKeys) { print(CodingKeys.a) // Not found on top-level. } fileprivate func unqualifiedBaz(_ key: CodingKeys) { print(CodingKeys.a) // Not found on top-level. } private func unqualifiedQux(_ key: CodingKeys) { print(CodingKeys.a) // Not found on top-level. } // Unqualified lookups should find the most local CodingKeys type available. public func nestedUnqualifiedFoo(_ key: CodingKeys) { enum CodingKeys : String, CodingKey { case nested } // CodingKeys should refer to the local unqualified enum. func foo(_ key: CodingKeys) { print(CodingKeys.nested) // Not found on synthesized type or top-level type. } foo(CodingKeys.nested) } internal func nestedUnqualifiedBar(_ key: CodingKeys) { enum CodingKeys : String, CodingKey { case nested } // CodingKeys should refer to the local unqualified enum. func bar(_ key: CodingKeys) { print(CodingKeys.nested) // Not found on synthesized type or top-level type. } bar(CodingKeys.nested) } fileprivate func nestedUnqualifiedBaz(_ key: CodingKeys) { enum CodingKeys : String, CodingKey { case nested } // CodingKeys should refer to the local unqualified enum. func baz(_ key: CodingKeys) { print(CodingKeys.nested) // Not found on synthesized type or top-level type. } baz(CodingKeys.nested) } private func nestedUnqualifiedQux(_ key: CodingKeys) { enum CodingKeys : String, CodingKey { case nested } // CodingKeys should refer to the local unqualified enum. func qux(_ key: CodingKeys) { print(CodingKeys.nested) // Not found on synthesized type or top-level type. } qux(CodingKeys.nested) } } } extension ExtendedStruct { enum CodingKeys : String, CodingKey { case a, b, c } } struct A { struct Inner : Codable { var value: Int = 42 func foo() { print(CodingKeys.value) // Not found on A.CodingKeys or top-level type. } } } extension A { enum CodingKeys : String, CodingKey { case a } } struct B : Codable { // So B conforms to Codable using CodingKeys.b below. var b: Int = 0 struct Inner { var value: Int = 42 func foo() { print(CodingKeys.b) // Not found on top-level type. } } } extension B { enum CodingKeys : String, CodingKey { case b } } struct C : Codable { struct Inner : Codable { var value: Int = 42 func foo() { print(CodingKeys.value) // Not found on C.CodingKeys or top-level type. } } } extension C.Inner { enum CodingKeys : String, CodingKey { case value } } struct GenericCodableStruct<T : Codable> : Codable {} func foo(_: GenericCodableStruct<Int>.CodingKeys) // expected-error {{'CodingKeys' is inaccessible due to 'private' protection level}} struct sr6886 { struct Nested : Codable {} let Nested: Nested // Don't crash with a coding key that is the same as a nested type name } // Don't crash if we have a static property with the same name as an ivar that // we will encode. We check the actual codegen in a SILGen test. struct StaticInstanceNameDisambiguation : Codable { static let version: Float = 0.42 let version: Int = 42 }
apache-2.0
5520719a773215cc2185cb86eb0eb65a
31.968326
180
0.692287
4.767285
false
false
false
false
ualch9/onebusaway-iphone
Carthage/Checkouts/SwiftEntryKit/Source/MessageViews/EKFormMessageView.swift
3
4205
// // EKFormMessageView.swift // SwiftEntryKit // // Created by Daniel Huri on 5/15/18. // import UIKit public class EKFormMessageView: UIView { private let scrollViewVerticalOffset: CGFloat = 20 // MARK: Props private let titleLabel = UILabel() private let scrollView = UIScrollView() private let textFieldsContent: [EKProperty.TextFieldContent] private var textFieldViews: [EKTextField] = [] private var buttonBarView: EKButtonBarView! // MARK: Setup public init(with title: EKProperty.LabelContent, textFieldsContent: [EKProperty.TextFieldContent], buttonContent: EKProperty.ButtonContent) { self.textFieldsContent = textFieldsContent super.init(frame: UIScreen.main.bounds) setupScrollView() setupTitleLabel(with: title) setupTextFields(with: textFieldsContent) setupButton(with: buttonContent) setupTapGestureRecognizer() scrollView.layoutIfNeeded() set(.height, of: scrollView.contentSize.height + scrollViewVerticalOffset * 2, priority: .defaultHigh) } required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } private func setupTextFields(with textFieldsContent: [EKProperty.TextFieldContent]) { var textFieldIndex = 0 textFieldViews = textFieldsContent.map { content -> EKTextField in let textField = EKTextField(with: content) scrollView.addSubview(textField) textField.tag = textFieldIndex textFieldIndex += 1 return textField } textFieldViews.first!.layout(.top, to: .bottom, of: titleLabel, offset: 20) textFieldViews.spread(.vertically, offset: 5) textFieldViews.layoutToSuperview(axis: .horizontally) } // Setup tap gesture private func setupTapGestureRecognizer() { let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(tapGestureRecognized)) tapGestureRecognizer.numberOfTapsRequired = 1 addGestureRecognizer(tapGestureRecognizer) } private func setupScrollView() { addSubview(scrollView) scrollView.layoutToSuperview(axis: .horizontally, offset: 20) scrollView.layoutToSuperview(axis: .vertically, offset: scrollViewVerticalOffset) scrollView.layoutToSuperview(.width, .height, offset: -scrollViewVerticalOffset * 2) } private func setupTitleLabel(with content: EKProperty.LabelContent) { scrollView.addSubview(titleLabel) titleLabel.layoutToSuperview(.top, .width) titleLabel.layoutToSuperview(axis: .horizontally) titleLabel.forceContentWrap(.vertically) titleLabel.content = content } private func setupButton(with buttonContent: EKProperty.ButtonContent) { var buttonContent = buttonContent let action = buttonContent.action buttonContent.action = { [weak self] in self?.extractTextFieldsContent() action?() } let buttonsBarContent = EKProperty.ButtonBarContent(with: buttonContent, separatorColor: .clear, expandAnimatedly: true) buttonBarView = EKButtonBarView(with: buttonsBarContent) buttonBarView.clipsToBounds = true scrollView.addSubview(buttonBarView) buttonBarView.expand() buttonBarView.layout(.top, to: .bottom, of: textFieldViews.last!, offset: 20) buttonBarView.layoutToSuperview(.centerX) buttonBarView.layoutToSuperview(.width, offset: -40) buttonBarView.layoutToSuperview(.bottom) buttonBarView.layer.cornerRadius = 5 } private func extractTextFieldsContent() { for (content, textField) in zip(textFieldsContent, textFieldViews) { content.contentWrapper.text = textField.text } } /** Makes a specific text field the first responder */ public func becomeFirstResponder(with textFieldIndex: Int) { textFieldViews[textFieldIndex].makeFirstResponder() } // Tap Gesture @objc func tapGestureRecognized() { endEditing(true) } }
apache-2.0
f674e7805824a445638731e6a049bf29
36.882883
145
0.684899
5.316056
false
false
false
false
behoernchen/Iconizer
Iconizer/Controller/MainWindowController.swift
1
6408
// // MainWindowController.swift // Iconizer // https://github.com/raphaelhanneken/iconizer // // The MIT License (MIT) // // Copyright (c) 2015 Raphael Hanneken // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import Cocoa /// Handles the MainWindow view. class MainWindowController: NSWindowController, NSWindowDelegate { /// Points to the SegmentedControl, which determines which view is currently selected. @IBOutlet weak var exportType: NSSegmentedControl! /// Represents the currently selected view. var currentView: NSViewController? // Override the windowNibName property. override var windowNibName: String { return "MainWindow" } // MARK: Window delegate override func windowDidLoad() { super.windowDidLoad() // Unwrap the window property. I don't even know if window can be nil, but // as you know: Everytime we force unwrap something, a kitty dies. if let window = self.window { // Hide the window title, to get the unified toolbar. window.titleVisibility = .Hidden } // Get the user defaults. let prefManager = PreferenceManager() // Change the content view to the last selected view... self.changeView(ViewControllerTag(rawValue: prefManager.selectedExportType)) // ...and set the selectedSegment of NSSegmentedControl to the corresponding value. self.exportType.selectedSegment = prefManager.selectedExportType } // Save the user preferences before the application terminates. func windowWillClose(notification: NSNotification) { let prefManager = PreferenceManager() prefManager.selectedExportType = self.exportType.selectedSegment } // MARK: Actions /// Select the export type. /// /// - parameter sender: NSSegmentedControl; 'Mode' set to 'Select One'. @IBAction func selectView(sender: NSSegmentedControl) { changeView(ViewControllerTag(rawValue: sender.selectedSegment)) } /// Kick off exporting for the selected export type. /// /// - parameter sender: NSButton responsible for exporting. @IBAction func export(sender: NSButton) { // Unwrap the export view. guard let currentView = self.currentView else { return } // Create a new NSSavePanel. let exportSheet = NSSavePanel() // Configure the save panel. exportSheet.prompt = "Export" // Open the save panel. exportSheet.beginSheetModalForWindow(self.window!) { (result: Int) in // The user clicked "Export". if result == NSFileHandlingPanelOKButton { // Unwrap the file url and get rid of the last path component. guard let url = exportSheet.URL?.URLByDeletingLastPathComponent else { return } do { // Generate the required images. try currentView.generateRequiredImages() // Save the currently generated asset catalog to the // selected file URL. try currentView.saveAssetCatalogNamed(exportSheet.nameFieldStringValue, toURL: url) } catch { // Something went somewhere terribly wrong... print(error) return } // Open the generated asset catalog in Finder. NSWorkspace.sharedWorkspace().openURL(url.URLByAppendingPathComponent("Iconizer Assets", isDirectory: true)) } } } // MARK: Changing View /// Swaps the current ViewController with a new one. /// /// - parameter view: Takes a ViewControllerTag. func changeView(view: ViewControllerTag?) { // Unwrap the current view, if any... if let currentView = self.currentView { // ...and remove it from the superview. currentView.view.removeFromSuperview() } // Check which ViewControllerTag is given. And set self.currentView to // the correspondig view. if let view = view { switch view { case .kAppIconViewControllerTag: self.currentView = AppIconViewController() case .kImageSetViewControllerTag: self.currentView = ImageSetViewController() case .kLaunchImageViewControllerTag: self.currentView = LaunchImageViewController() } } // Unwrap the selected ViewController and the main window. if let currentView = self.currentView, let window = self.window { // Resize the main window to fit the selected view. resizeWindowForContentSize(currentView.view.frame.size) // Set the main window's contentView to the selected view. window.contentView = currentView.view } } /// Resizes the main window to the given size. /// /// - parameter size: The new size of the main window. func resizeWindowForContentSize(size: NSSize) { // Unwrap the main window object. guard let window = self.window else { // Is this even possible??? return } // Get the content rect of the main window. let windowContentRect = window.contentRectForFrameRect(window.frame) // Create a new content rect for the given size (except width). let newContentRect = NSMakeRect(NSMinX(windowContentRect), NSMaxY(windowContentRect) - size.height, windowContentRect.size.width, size.height) // Create a new frame rect from the content rect. let newWindowFrame = window.frameRectForContentRect(newContentRect) // Set the window frame to the new frame. window.setFrame(newWindowFrame, display: true, animate: true) } }
mit
7b111718e0c1cd069af4e0893e359f88
34.016393
149
0.705212
4.818045
false
false
false
false
jianweihehe/JWDouYuZB
JWDouYuZB/JWDouYuZB/Classes/Main/View/CollectionPrettyCell.swift
1
1073
// // CollectionPrettyCell.swift // JWDouYuZB // // Created by [email protected] on 2017/1/9. // Copyright © 2017年 简伟. All rights reserved. // import UIKit import Kingfisher class CollectionPrettyCell: UICollectionViewCell { @IBOutlet var readCountButton: UIButton! @IBOutlet var titleLabel: UILabel! @IBOutlet var locationButton: UIButton! @IBOutlet var backImageView: UIImageView! var anchor: AnchorModel? { didSet{ titleLabel.text = anchor?.room_name locationButton.setTitle(anchor?.anchor_city, for: .normal) var onlineStr : String = "" if (anchor?.online)! >= 10000 { onlineStr = "\(Int((anchor?.online)! / 10000))万在线" } else { onlineStr = "\((anchor?.online)!)在线" } readCountButton.setTitle(onlineStr, for: .normal) guard let iconURL = URL(string: (anchor?.vertical_src)!) else { return } backImageView.kf.setImage(with: iconURL) } } }
mit
62823cf234162ef6756806bc7f5d4733
27.540541
84
0.589962
4.493617
false
false
false
false
blockchain/My-Wallet-V3-iOS
Modules/DelegatedSelfCustody/Sources/DelegatedSelfCustodyDomain/Models/DelegatedCustodyBalances.swift
1
791
// Copyright © Blockchain Luxembourg S.A. All rights reserved. import MoneyKit public struct DelegatedCustodyBalances: Equatable { public struct Balance: Equatable { let index: Int let name: String let balance: MoneyValue public init(index: Int, name: String, balance: MoneyValue) { self.index = index self.name = name self.balance = balance } } public let balances: [Balance] public func balance(index: Int, currency: CryptoCurrency) -> MoneyValue? { balances .first(where: { $0.index == index && $0.balance.currency == currency }) .map(\.balance) } public init(balances: [DelegatedCustodyBalances.Balance]) { self.balances = balances } }
lgpl-3.0
e91ee5450d8a1c07ebd9be2d34fc1e7e
26.241379
83
0.608861
4.488636
false
false
false
false
cnbin/LayerPlayer
LayerPlayer/CATransformLayerViewController.swift
3
6433
// // CATransformLayerViewController.swift // LayerPlayer // // Created by Scott Gardner on 11/20/14. // Copyright (c) 2014 Scott Gardner. All rights reserved. // import UIKit func degreesToRadians(degrees: Double) -> CGFloat { return CGFloat(degrees * M_PI / 180.0) } func radiansToDegrees(radians: Double) -> CGFloat { return CGFloat(radians / M_PI * 180.0) } class CATransformLayerViewController: UIViewController { @IBOutlet weak var boxTappedLabel: UILabel! @IBOutlet weak var viewForTransformLayer: UIView! @IBOutlet var colorAlphaSwitches: [UISwitch]! enum Color: Int { case Red, Orange, Yellow, Green, Blue, Purple } let sideLength = CGFloat(160.0) let reducedAlpha = CGFloat(0.8) var transformLayer: CATransformLayer! let swipeMeTextLayer = CATextLayer() var redColor = UIColor.redColor() var orangeColor = UIColor.orangeColor() var yellowColor = UIColor.yellowColor() var greenColor = UIColor.greenColor() var blueColor = UIColor.blueColor() var purpleColor = UIColor.purpleColor() var trackBall: TrackBall? // MARK: - Quick reference func setUpSwipeMeTextLayer() { swipeMeTextLayer.frame = CGRect(x: 0.0, y: sideLength / 4.0, width: sideLength, height: sideLength / 2.0) swipeMeTextLayer.string = "Swipe Me" swipeMeTextLayer.alignmentMode = kCAAlignmentCenter swipeMeTextLayer.foregroundColor = UIColor.whiteColor().CGColor let fontName = "Noteworthy-Light" as CFString let fontRef = CTFontCreateWithName(fontName, 24.0, nil) swipeMeTextLayer.font = fontRef swipeMeTextLayer.contentsScale = UIScreen.mainScreen().scale } // MARK: - View life cycle override func viewDidLoad() { super.viewDidLoad() setUpSwipeMeTextLayer() buildCube() } // MARK: - IBActions @IBAction func colorAlphaSwitchChanged(sender: UISwitch) { let alpha = sender.on ? reducedAlpha : 1.0 switch (colorAlphaSwitches as NSArray).indexOfObject(sender) { case Color.Red.rawValue: redColor = colorForColor(redColor, withAlpha: alpha) case Color.Orange.rawValue: orangeColor = colorForColor(orangeColor, withAlpha: alpha) case Color.Yellow.rawValue: yellowColor = colorForColor(yellowColor, withAlpha: alpha) case Color.Green.rawValue: greenColor = colorForColor(greenColor, withAlpha: alpha) case Color.Blue.rawValue: blueColor = colorForColor(blueColor, withAlpha: alpha) case Color.Purple.rawValue: purpleColor = colorForColor(purpleColor, withAlpha: alpha) default: break } transformLayer.removeFromSuperlayer() buildCube() } // MARK: - Triggered actions override func touchesBegan(touches: NSSet, withEvent event: UIEvent) { if let location = touches.anyObject()?.locationInView(viewForTransformLayer) { if trackBall != nil { trackBall?.setStartPointFromLocation(location) } else { trackBall = TrackBall(location: location, inRect: viewForTransformLayer.bounds) } for layer in transformLayer.sublayers { if let hitLayer = layer.hitTest(location) { showBoxTappedLabel() break } } } } override func touchesMoved(touches: NSSet, withEvent event: UIEvent) { if let location = touches.anyObject()?.locationInView(viewForTransformLayer) { if let transform = trackBall?.rotationTransformForLocation(location) { viewForTransformLayer.layer.sublayerTransform = transform } } } override func touchesEnded(touches: NSSet, withEvent event: UIEvent) { if let location = touches.anyObject()?.locationInView(viewForTransformLayer) { trackBall?.finalizeTrackBallForLocation(location) } } func showBoxTappedLabel() { boxTappedLabel.alpha = 1.0 boxTappedLabel.hidden = false UIView.animateWithDuration(0.5, animations: { self.boxTappedLabel.alpha = 0.0 }, completion: { [unowned self] _ in self.boxTappedLabel.hidden = true }) } // MARK: - Helpers func buildCube() { transformLayer = CATransformLayer() var layer = sideLayerWithColor(redColor) layer.addSublayer(swipeMeTextLayer) transformLayer.addSublayer(layer) layer = sideLayerWithColor(orangeColor) var transform = CATransform3DMakeTranslation(sideLength / 2.0, 0.0, sideLength / -2.0) transform = CATransform3DRotate(transform, degreesToRadians(90.0), 0.0, 1.0, 0.0) layer.transform = transform transformLayer.addSublayer(layer) layer = sideLayerWithColor(yellowColor) layer.transform = CATransform3DMakeTranslation(0.0, 0.0, -sideLength) transformLayer.addSublayer(layer) layer = sideLayerWithColor(greenColor) transform = CATransform3DMakeTranslation(sideLength / -2.0, 0.0, sideLength / -2.0) transform = CATransform3DRotate(transform, degreesToRadians(90.0), 0.0, 1.0, 0.0) layer.transform = transform transformLayer.addSublayer(layer) layer = sideLayerWithColor(blueColor) transform = CATransform3DMakeTranslation(0.0, sideLength / -2.0, sideLength / -2.0) transform = CATransform3DRotate(transform, degreesToRadians(90.0), 1.0, 0.0, 0.0) layer.transform = transform transformLayer.addSublayer(layer) layer = sideLayerWithColor(purpleColor) transform = CATransform3DMakeTranslation(0.0, sideLength / 2.0, sideLength / -2.0) transform = CATransform3DRotate(transform, degreesToRadians(90.0), 1.0, 0.0, 0.0) layer.transform = transform transformLayer.addSublayer(layer) transformLayer.anchorPointZ = sideLength / -2.0 viewForTransformLayer.layer.addSublayer(transformLayer) } func sideLayerWithColor(color: UIColor) -> CALayer { let layer = CALayer() layer.frame = CGRect(origin: CGPointZero, size: CGSize(width: sideLength, height: sideLength)) layer.position = CGPoint(x: CGRectGetMidX(viewForTransformLayer.bounds), y: CGRectGetMidY(viewForTransformLayer.bounds)) layer.backgroundColor = color.CGColor return layer } func colorForColor(var color: UIColor, withAlpha newAlpha: CGFloat) -> UIColor { var red = CGFloat() var green = red, blue = red, alpha = red if color.getRed(&red, green: &green, blue: &blue, alpha: &alpha) { color = UIColor(red: red, green: green, blue: blue, alpha: newAlpha) } return color } }
mit
e63f7350c069a35332fd514dd93317ae
32.331606
124
0.702472
4.268746
false
false
false
false
blockchain/My-Wallet-V3-iOS
Modules/CryptoAssets/Sources/StellarKit/StellarTransactionDispatcher.swift
1
10948
// Copyright © Blockchain Luxembourg S.A. All rights reserved. import BigInt import FeatureTransactionDomain import MoneyKit import PlatformKit import RxSwift import stellarsdk import ToolKit protocol StellarTransactionDispatcherAPI { func dryRunTransaction(sendDetails: SendDetails) -> Completable func isExchangeAddresses(address: String) -> Single<Bool> func isAddressValid(address: String) -> Bool func sendFunds(sendDetails: SendDetails, secondPassword: String?) -> Single<SendConfirmationDetails> } final class StellarTransactionDispatcher: StellarTransactionDispatcherAPI { // MARK: Types private typealias StellarTransaction = stellarsdk.Transaction // MARK: Private Properties private let walletOptions: WalletOptionsAPI private let accountRepository: StellarWalletAccountRepositoryAPI private let horizonProxy: HorizonProxyAPI private let minSend = CryptoValue(amount: 1, currency: .stellar) private var sendTimeOutSeconds: Single<Int> { walletOptions.walletOptions .map(\.xlmMetadata?.sendTimeOutSeconds) .map { $0 ?? 10 } .catchAndReturn(10) } init( accountRepository: StellarWalletAccountRepositoryAPI, walletOptions: WalletOptionsAPI, horizonProxy: HorizonProxyAPI ) { self.walletOptions = walletOptions self.accountRepository = accountRepository self.horizonProxy = horizonProxy } // MARK: Methods func dryRunTransaction(sendDetails: SendDetails) -> Completable { checkInput(sendDetails: sendDetails) .andThen(checkDestinationAddress(sendDetails: sendDetails)) .andThen(checkMinimumSend(sendDetails: sendDetails)) .andThen(checkDestinationAccount(sendDetails: sendDetails)) .andThen(checkSourceAccount(sendDetails: sendDetails)) .andThen(transaction(sendDetails: sendDetails).asCompletable()) } func isExchangeAddresses(address: String) -> Single<Bool> { walletOptions.walletOptions .map(\.xlmExchangeAddresses) .map { addresses -> Bool in guard let addresses = addresses else { return false } return addresses .contains(where: { $0.caseInsensitiveCompare(address) == .orderedSame }) } } func isAddressValid(address: String) -> Bool { do { _ = try stellarsdk.KeyPair(accountId: address) return true } catch { return false } } func sendFunds(sendDetails: SendDetails, secondPassword: String?) -> Single<SendConfirmationDetails> { Single .zip( accountRepository.loadKeyPair(with: secondPassword).asObservable().take(1).asSingle(), transaction(sendDetails: sendDetails) ) .flatMap(weak: self) { (self, payload) -> Single<TransactionPostResponseEnum> in let (keyPair, transaction) = payload let sdkKeyPair = try stellarsdk.KeyPair(secretSeed: keyPair.secret) return self.horizonProxy .sign(transaction: transaction, keyPair: sdkKeyPair) .andThen(self.horizonProxy.submitTransaction(transaction: transaction)) } .map { response -> SendConfirmationDetails in try response.toSendConfirmationDetails(sendDetails: sendDetails) } } // MARK: Private Methods private func checkInput(sendDetails: SendDetails) -> Completable { guard sendDetails.value.currencyType == .stellar else { return .error(SendFailureReason.unknown) } guard sendDetails.fee.currencyType == .stellar else { return .error(SendFailureReason.unknown) } return .empty() } private func checkDestinationAddress(sendDetails: SendDetails) -> Completable { do { _ = try stellarsdk.KeyPair(accountId: sendDetails.toAddress) } catch { return .error(SendFailureReason.badDestinationAccountID) } return .empty() } private func checkSourceAccount(sendDetails: SendDetails) -> Completable { horizonProxy.accountResponse(for: sendDetails.fromAddress) .asSingle() .map(weak: self) { (self, response) -> AccountResponse in let total = try sendDetails.value + sendDetails.fee let minBalance = self.horizonProxy.minimumBalance(subentryCount: response.subentryCount) if try response.totalBalance < (total + minBalance) { throw SendFailureReason.insufficientFunds(response.totalBalance.moneyValue, total.moneyValue) } return response } .asCompletable() } private func checkMinimumSend(sendDetails: SendDetails) -> Completable { do { if try sendDetails.value < minSend { return .error(SendFailureReason.belowMinimumSend(minSend.moneyValue)) } } catch { return .error(SendFailureReason.unknown) } return .empty() } private func checkDestinationAccount(sendDetails: SendDetails) -> Completable { let minBalance = horizonProxy.minimumBalance(subentryCount: 0) return horizonProxy.accountResponse(for: sendDetails.toAddress) .asCompletable() .catch { error -> Completable in switch error { case StellarNetworkError.notFound: if try sendDetails.value < minBalance { return .error(SendFailureReason.belowMinimumSendNewAccount(minBalance.moneyValue)) } return .empty() default: throw error } } } private func submitTransaction( transaction: StellarTransaction, with configuration: StellarConfiguration ) -> Single<TransactionPostResponseEnum> { Single.create(weak: self) { _, observer -> Disposable in do { try configuration.sdk.transactions .submitTransaction(transaction: transaction) { response in observer(.success(response)) } } catch { observer(.error(error)) } return Disposables.create() } } private func transaction(sendDetails: SendDetails) -> Single<StellarTransaction> { horizonProxy.accountResponse(for: sendDetails.fromAddress) .asSingle() .flatMap(weak: self) { (self, sourceAccount) -> Single<StellarTransaction> in guard sendDetails.value.currencyType == .stellar else { return .error(PlatformKitError.illegalArgument) } guard sendDetails.fee.currencyType == .stellar else { return .error(PlatformKitError.illegalArgument) } return self.createTransaction(sendDetails: sendDetails, sourceAccount: sourceAccount) } } private func createTransaction( sendDetails: SendDetails, sourceAccount: AccountResponse ) -> Single<StellarTransaction> { Single .zip(operation(sendDetails: sendDetails), sendTimeOutSeconds) .map { operation, sendTimeOutSeconds -> StellarTransaction in var timeBounds: TimeBounds? let expirationDate = Calendar.current.date( byAdding: .second, value: sendTimeOutSeconds, to: Date() ) if let expirationDate = expirationDate?.timeIntervalSince1970 { timeBounds = TimeBounds( minTime: 0, maxTime: UInt64(expirationDate) ) } let transaction = try StellarTransaction( sourceAccount: sourceAccount, operations: [operation], memo: sendDetails.horizonMemo, preconditions: TransactionPreconditions(timeBounds: timeBounds), maxOperationFee: UInt32(sendDetails.fee.minorString)! ) return transaction } } /// Returns the appropriate operation depending if the destination account already exists or not. private func operation(sendDetails: SendDetails) -> Single<stellarsdk.Operation> { horizonProxy.accountResponse(for: sendDetails.toAddress) .asSingle() .map { response -> stellarsdk.Operation in try stellarsdk.PaymentOperation( sourceAccountId: sendDetails.fromAddress, destinationAccountId: response.accountId, asset: stellarsdk.Asset(type: stellarsdk.AssetType.ASSET_TYPE_NATIVE)!, amount: sendDetails.value.displayMajorValue ) } .catch { error -> Single<stellarsdk.Operation> in // Build operation switch error { case StellarNetworkError.notFound: let destination = try KeyPair(accountId: sendDetails.toAddress) let createAccountOperation = stellarsdk.CreateAccountOperation( sourceAccountId: sendDetails.fromAddress, destination: destination, startBalance: sendDetails.value.displayMajorValue ) return .just(createAccountOperation) default: throw error } } } } extension stellarsdk.TransactionPostResponseEnum { fileprivate func toSendConfirmationDetails(sendDetails: SendDetails) throws -> SendConfirmationDetails { switch self { case .success(let details): let feeCharged = CryptoValue( amount: BigInt(details.transactionResult.feeCharged), currency: .stellar ) return SendConfirmationDetails( sendDetails: sendDetails, fees: feeCharged, transactionHash: details.transactionHash ) case .destinationRequiresMemo: throw StellarNetworkError.destinationRequiresMemo case .failure(let error): throw error.stellarNetworkError } } } extension SendDetails { fileprivate var horizonMemo: stellarsdk.Memo { switch memo { case nil: return .none case .id(let id): return .id(id) case .text(let text): return .text(text) } } }
lgpl-3.0
773b9ffca0f24ed75d908f29ef5c1794
37.010417
113
0.599342
5.395269
false
false
false
false
kyleYang/KYNavigationFadeManager
KYNavigationFadeManager/ViewController.swift
1
5665
// // ViewController.swift // KYNavigationFadeManager // // Created by kyleYang on 05/06/2017. // Copyright (c) 2017 kyleYang. All rights reserved. // import UIKit class ViewController: UIViewController { @IBOutlet weak var tableView: UITableView! fileprivate let titleArray : [String] = ["透明无title","透明有title"] override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. self.tableView.register(UITableViewCell.self, forCellReuseIdentifier: "tablecell") } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } } extension ViewController : UITableViewDelegate,UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return titleArray.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "tablecell") cell?.textLabel?.text = titleArray[indexPath.row] if(indexPath.row == 0){ cell?.imageView?.image = UIImage(named:"lx_common_share") }else if (indexPath.row == 1){ cell?.imageView?.image = UIImage(named:"lx_common_share")?.imageWithColor(color: UIColor.green) }else if (indexPath.row == 2){ cell?.imageView?.image = UIImage(named:"lx_common_share")?.imageWithColor(color: UIColor.green) }else{ cell?.imageView?.image = UIImage(named:"lx_common_share")?.imageWithColor(color: UIColor(patternImage:UIImage(named:"lx_common_share")!).withAlphaComponent(1)) } return cell! } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { if (indexPath.row == 0){ let vc = TableViewController(nibName: nil, bundle: nil); vc.title = "透明无title" vc.shouldeHiddenTitle = true self.navigationController?.pushViewController(vc, animated: true) }else if (indexPath.row == 1){ let vc = TableViewController(nibName: nil, bundle: nil); vc.title = "透明有title" vc.shouldeHiddenTitle = false self.navigationController?.pushViewController(vc, animated: true) } } } extension UIImage{ class func pureImage(color : UIColor,size : CGSize? = nil)->UIImage{ var rect = CGRect(x: 0, y: 0, width: 1, height: 1) if let _ = size { rect.size = size! } UIGraphicsBeginImageContext(rect.size) let context = UIGraphicsGetCurrentContext(); color.setFill() context!.fill(rect); let image = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); return image!; } func imageWithColor(color: UIColor) -> UIImage? { var image = withRenderingMode(.alwaysTemplate) UIGraphicsBeginImageContextWithOptions(size, false, scale) color.set() image.draw(in: CGRect(x: 0, y: 0, width: size.width, height: size.height)) image = UIGraphicsGetImageFromCurrentImageContext()! UIGraphicsEndImageContext() return image } } fileprivate func < <T : Comparable>(lhs: T?, rhs: T?) -> Bool { switch (lhs, rhs) { case let (l?, r?): return l < r case (nil, _?): return true default: return false } } fileprivate func >= <T : Comparable>(lhs: T?, rhs: T?) -> Bool { switch (lhs, rhs) { case let (l?, r?): return l >= r default: return !(lhs < rhs) } } fileprivate func <= <T : Comparable>(lhs: T?, rhs: T?) -> Bool { switch (lhs, rhs) { case let (l?, r?): return l <= r default: return !(rhs < lhs) } } extension UIColor{ func changeAlpah(_ alpha : CGFloat) -> UIColor { let cgColor = self.cgColor let numComponents = cgColor.numberOfComponents var newColor : UIColor! if (numComponents == 4){ let components = cgColor.components! let red = components[0] let green = components[1] let blue = components[2] newColor = UIColor(red: red, green: green, blue: blue, alpha: alpha) return newColor }else if(numComponents == 2){ let components = cgColor.components! let white = components[0] newColor = UIColor(white: white, alpha: alpha) return newColor } return self } convenience init(red: Int, green: Int, blue: Int, alpha: Float? = 1.0) { assert(red >= 0 && red <= 255, "Invalid red component") assert(green >= 0 && green <= 255, "Invalid green component") assert(blue >= 0 && blue <= 255, "Invalid blue component") assert(alpha >= 0.0 && alpha <= 1.0, "Invalid alpha component") self.init(red: CGFloat(red) / 255.0, green: CGFloat(green) / 255.0, blue: CGFloat(blue) / 255.0, alpha: CGFloat(alpha!)) } convenience init(rgb: UInt32,alpha: Float? = 1.0) { self.init( red: Int(rgb >> 16) & 0xff, green: Int(rgb >> 8) & 0xff, blue: Int(rgb) & 0xff, alpha:alpha ) } convenience init(rgba: UInt32) { self.init( red: Int(rgba >> 24) & 0xff, green: Int(rgba >> 16) & 0xff, blue: Int(rgba >> 8) & 0xff, alpha: Float(rgba & 0xff) / 255.0 ) } }
mit
2f96fe28c494bb08de6278e8fc71558d
29.005319
171
0.592448
4.292998
false
false
false
false
noppoMan/aws-sdk-swift
Sources/Soto/Services/RoboMaker/RoboMaker_Paginator.swift
1
29984
//===----------------------------------------------------------------------===// // // This source file is part of the Soto for AWS open source project // // Copyright (c) 2017-2020 the Soto project authors // Licensed under Apache License v2.0 // // See LICENSE.txt for license information // See CONTRIBUTORS.txt for the list of Soto project authors // // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// // THIS FILE IS AUTOMATICALLY GENERATED by https://github.com/soto-project/soto/tree/main/CodeGenerator. DO NOT EDIT. import SotoCore // MARK: Paginators extension RoboMaker { /// Returns a list of deployment jobs for a fleet. You can optionally provide filters to retrieve specific deployment jobs. /// /// Provide paginated results to closure `onPage` for it to combine them into one result. /// This works in a similar manner to `Array.reduce<Result>(_:_:) -> Result`. /// /// Parameters: /// - input: Input for request /// - initialValue: The value to use as the initial accumulating value. `initialValue` is passed to `onPage` the first time it is called. /// - logger: Logger used flot logging /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each paginated response. It combines an accumulating result with the contents of response. This combined result is then returned /// along with a boolean indicating if the paginate operation should continue. public func listDeploymentJobsPaginator<Result>( _ input: ListDeploymentJobsRequest, _ initialValue: Result, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (Result, ListDeploymentJobsResponse, EventLoop) -> EventLoopFuture<(Bool, Result)> ) -> EventLoopFuture<Result> { return client.paginate( input: input, initialValue: initialValue, command: listDeploymentJobs, tokenKey: \ListDeploymentJobsResponse.nextToken, on: eventLoop, onPage: onPage ) } /// Provide paginated results to closure `onPage`. /// /// - Parameters: /// - input: Input for request /// - logger: Logger used flot logging /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each block of entries. Returns boolean indicating whether we should continue. public func listDeploymentJobsPaginator( _ input: ListDeploymentJobsRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (ListDeploymentJobsResponse, EventLoop) -> EventLoopFuture<Bool> ) -> EventLoopFuture<Void> { return client.paginate( input: input, command: listDeploymentJobs, tokenKey: \ListDeploymentJobsResponse.nextToken, on: eventLoop, onPage: onPage ) } /// Returns a list of fleets. You can optionally provide filters to retrieve specific fleets. /// /// Provide paginated results to closure `onPage` for it to combine them into one result. /// This works in a similar manner to `Array.reduce<Result>(_:_:) -> Result`. /// /// Parameters: /// - input: Input for request /// - initialValue: The value to use as the initial accumulating value. `initialValue` is passed to `onPage` the first time it is called. /// - logger: Logger used flot logging /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each paginated response. It combines an accumulating result with the contents of response. This combined result is then returned /// along with a boolean indicating if the paginate operation should continue. public func listFleetsPaginator<Result>( _ input: ListFleetsRequest, _ initialValue: Result, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (Result, ListFleetsResponse, EventLoop) -> EventLoopFuture<(Bool, Result)> ) -> EventLoopFuture<Result> { return client.paginate( input: input, initialValue: initialValue, command: listFleets, tokenKey: \ListFleetsResponse.nextToken, on: eventLoop, onPage: onPage ) } /// Provide paginated results to closure `onPage`. /// /// - Parameters: /// - input: Input for request /// - logger: Logger used flot logging /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each block of entries. Returns boolean indicating whether we should continue. public func listFleetsPaginator( _ input: ListFleetsRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (ListFleetsResponse, EventLoop) -> EventLoopFuture<Bool> ) -> EventLoopFuture<Void> { return client.paginate( input: input, command: listFleets, tokenKey: \ListFleetsResponse.nextToken, on: eventLoop, onPage: onPage ) } /// Returns a list of robot application. You can optionally provide filters to retrieve specific robot applications. /// /// Provide paginated results to closure `onPage` for it to combine them into one result. /// This works in a similar manner to `Array.reduce<Result>(_:_:) -> Result`. /// /// Parameters: /// - input: Input for request /// - initialValue: The value to use as the initial accumulating value. `initialValue` is passed to `onPage` the first time it is called. /// - logger: Logger used flot logging /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each paginated response. It combines an accumulating result with the contents of response. This combined result is then returned /// along with a boolean indicating if the paginate operation should continue. public func listRobotApplicationsPaginator<Result>( _ input: ListRobotApplicationsRequest, _ initialValue: Result, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (Result, ListRobotApplicationsResponse, EventLoop) -> EventLoopFuture<(Bool, Result)> ) -> EventLoopFuture<Result> { return client.paginate( input: input, initialValue: initialValue, command: listRobotApplications, tokenKey: \ListRobotApplicationsResponse.nextToken, on: eventLoop, onPage: onPage ) } /// Provide paginated results to closure `onPage`. /// /// - Parameters: /// - input: Input for request /// - logger: Logger used flot logging /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each block of entries. Returns boolean indicating whether we should continue. public func listRobotApplicationsPaginator( _ input: ListRobotApplicationsRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (ListRobotApplicationsResponse, EventLoop) -> EventLoopFuture<Bool> ) -> EventLoopFuture<Void> { return client.paginate( input: input, command: listRobotApplications, tokenKey: \ListRobotApplicationsResponse.nextToken, on: eventLoop, onPage: onPage ) } /// Returns a list of robots. You can optionally provide filters to retrieve specific robots. /// /// Provide paginated results to closure `onPage` for it to combine them into one result. /// This works in a similar manner to `Array.reduce<Result>(_:_:) -> Result`. /// /// Parameters: /// - input: Input for request /// - initialValue: The value to use as the initial accumulating value. `initialValue` is passed to `onPage` the first time it is called. /// - logger: Logger used flot logging /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each paginated response. It combines an accumulating result with the contents of response. This combined result is then returned /// along with a boolean indicating if the paginate operation should continue. public func listRobotsPaginator<Result>( _ input: ListRobotsRequest, _ initialValue: Result, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (Result, ListRobotsResponse, EventLoop) -> EventLoopFuture<(Bool, Result)> ) -> EventLoopFuture<Result> { return client.paginate( input: input, initialValue: initialValue, command: listRobots, tokenKey: \ListRobotsResponse.nextToken, on: eventLoop, onPage: onPage ) } /// Provide paginated results to closure `onPage`. /// /// - Parameters: /// - input: Input for request /// - logger: Logger used flot logging /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each block of entries. Returns boolean indicating whether we should continue. public func listRobotsPaginator( _ input: ListRobotsRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (ListRobotsResponse, EventLoop) -> EventLoopFuture<Bool> ) -> EventLoopFuture<Void> { return client.paginate( input: input, command: listRobots, tokenKey: \ListRobotsResponse.nextToken, on: eventLoop, onPage: onPage ) } /// Returns a list of simulation applications. You can optionally provide filters to retrieve specific simulation applications. /// /// Provide paginated results to closure `onPage` for it to combine them into one result. /// This works in a similar manner to `Array.reduce<Result>(_:_:) -> Result`. /// /// Parameters: /// - input: Input for request /// - initialValue: The value to use as the initial accumulating value. `initialValue` is passed to `onPage` the first time it is called. /// - logger: Logger used flot logging /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each paginated response. It combines an accumulating result with the contents of response. This combined result is then returned /// along with a boolean indicating if the paginate operation should continue. public func listSimulationApplicationsPaginator<Result>( _ input: ListSimulationApplicationsRequest, _ initialValue: Result, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (Result, ListSimulationApplicationsResponse, EventLoop) -> EventLoopFuture<(Bool, Result)> ) -> EventLoopFuture<Result> { return client.paginate( input: input, initialValue: initialValue, command: listSimulationApplications, tokenKey: \ListSimulationApplicationsResponse.nextToken, on: eventLoop, onPage: onPage ) } /// Provide paginated results to closure `onPage`. /// /// - Parameters: /// - input: Input for request /// - logger: Logger used flot logging /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each block of entries. Returns boolean indicating whether we should continue. public func listSimulationApplicationsPaginator( _ input: ListSimulationApplicationsRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (ListSimulationApplicationsResponse, EventLoop) -> EventLoopFuture<Bool> ) -> EventLoopFuture<Void> { return client.paginate( input: input, command: listSimulationApplications, tokenKey: \ListSimulationApplicationsResponse.nextToken, on: eventLoop, onPage: onPage ) } /// Returns a list simulation job batches. You can optionally provide filters to retrieve specific simulation batch jobs. /// /// Provide paginated results to closure `onPage` for it to combine them into one result. /// This works in a similar manner to `Array.reduce<Result>(_:_:) -> Result`. /// /// Parameters: /// - input: Input for request /// - initialValue: The value to use as the initial accumulating value. `initialValue` is passed to `onPage` the first time it is called. /// - logger: Logger used flot logging /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each paginated response. It combines an accumulating result with the contents of response. This combined result is then returned /// along with a boolean indicating if the paginate operation should continue. public func listSimulationJobBatchesPaginator<Result>( _ input: ListSimulationJobBatchesRequest, _ initialValue: Result, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (Result, ListSimulationJobBatchesResponse, EventLoop) -> EventLoopFuture<(Bool, Result)> ) -> EventLoopFuture<Result> { return client.paginate( input: input, initialValue: initialValue, command: listSimulationJobBatches, tokenKey: \ListSimulationJobBatchesResponse.nextToken, on: eventLoop, onPage: onPage ) } /// Provide paginated results to closure `onPage`. /// /// - Parameters: /// - input: Input for request /// - logger: Logger used flot logging /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each block of entries. Returns boolean indicating whether we should continue. public func listSimulationJobBatchesPaginator( _ input: ListSimulationJobBatchesRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (ListSimulationJobBatchesResponse, EventLoop) -> EventLoopFuture<Bool> ) -> EventLoopFuture<Void> { return client.paginate( input: input, command: listSimulationJobBatches, tokenKey: \ListSimulationJobBatchesResponse.nextToken, on: eventLoop, onPage: onPage ) } /// Returns a list of simulation jobs. You can optionally provide filters to retrieve specific simulation jobs. /// /// Provide paginated results to closure `onPage` for it to combine them into one result. /// This works in a similar manner to `Array.reduce<Result>(_:_:) -> Result`. /// /// Parameters: /// - input: Input for request /// - initialValue: The value to use as the initial accumulating value. `initialValue` is passed to `onPage` the first time it is called. /// - logger: Logger used flot logging /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each paginated response. It combines an accumulating result with the contents of response. This combined result is then returned /// along with a boolean indicating if the paginate operation should continue. public func listSimulationJobsPaginator<Result>( _ input: ListSimulationJobsRequest, _ initialValue: Result, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (Result, ListSimulationJobsResponse, EventLoop) -> EventLoopFuture<(Bool, Result)> ) -> EventLoopFuture<Result> { return client.paginate( input: input, initialValue: initialValue, command: listSimulationJobs, tokenKey: \ListSimulationJobsResponse.nextToken, on: eventLoop, onPage: onPage ) } /// Provide paginated results to closure `onPage`. /// /// - Parameters: /// - input: Input for request /// - logger: Logger used flot logging /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each block of entries. Returns boolean indicating whether we should continue. public func listSimulationJobsPaginator( _ input: ListSimulationJobsRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (ListSimulationJobsResponse, EventLoop) -> EventLoopFuture<Bool> ) -> EventLoopFuture<Void> { return client.paginate( input: input, command: listSimulationJobs, tokenKey: \ListSimulationJobsResponse.nextToken, on: eventLoop, onPage: onPage ) } /// Lists world export jobs. /// /// Provide paginated results to closure `onPage` for it to combine them into one result. /// This works in a similar manner to `Array.reduce<Result>(_:_:) -> Result`. /// /// Parameters: /// - input: Input for request /// - initialValue: The value to use as the initial accumulating value. `initialValue` is passed to `onPage` the first time it is called. /// - logger: Logger used flot logging /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each paginated response. It combines an accumulating result with the contents of response. This combined result is then returned /// along with a boolean indicating if the paginate operation should continue. public func listWorldExportJobsPaginator<Result>( _ input: ListWorldExportJobsRequest, _ initialValue: Result, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (Result, ListWorldExportJobsResponse, EventLoop) -> EventLoopFuture<(Bool, Result)> ) -> EventLoopFuture<Result> { return client.paginate( input: input, initialValue: initialValue, command: listWorldExportJobs, tokenKey: \ListWorldExportJobsResponse.nextToken, on: eventLoop, onPage: onPage ) } /// Provide paginated results to closure `onPage`. /// /// - Parameters: /// - input: Input for request /// - logger: Logger used flot logging /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each block of entries. Returns boolean indicating whether we should continue. public func listWorldExportJobsPaginator( _ input: ListWorldExportJobsRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (ListWorldExportJobsResponse, EventLoop) -> EventLoopFuture<Bool> ) -> EventLoopFuture<Void> { return client.paginate( input: input, command: listWorldExportJobs, tokenKey: \ListWorldExportJobsResponse.nextToken, on: eventLoop, onPage: onPage ) } /// Lists world generator jobs. /// /// Provide paginated results to closure `onPage` for it to combine them into one result. /// This works in a similar manner to `Array.reduce<Result>(_:_:) -> Result`. /// /// Parameters: /// - input: Input for request /// - initialValue: The value to use as the initial accumulating value. `initialValue` is passed to `onPage` the first time it is called. /// - logger: Logger used flot logging /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each paginated response. It combines an accumulating result with the contents of response. This combined result is then returned /// along with a boolean indicating if the paginate operation should continue. public func listWorldGenerationJobsPaginator<Result>( _ input: ListWorldGenerationJobsRequest, _ initialValue: Result, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (Result, ListWorldGenerationJobsResponse, EventLoop) -> EventLoopFuture<(Bool, Result)> ) -> EventLoopFuture<Result> { return client.paginate( input: input, initialValue: initialValue, command: listWorldGenerationJobs, tokenKey: \ListWorldGenerationJobsResponse.nextToken, on: eventLoop, onPage: onPage ) } /// Provide paginated results to closure `onPage`. /// /// - Parameters: /// - input: Input for request /// - logger: Logger used flot logging /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each block of entries. Returns boolean indicating whether we should continue. public func listWorldGenerationJobsPaginator( _ input: ListWorldGenerationJobsRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (ListWorldGenerationJobsResponse, EventLoop) -> EventLoopFuture<Bool> ) -> EventLoopFuture<Void> { return client.paginate( input: input, command: listWorldGenerationJobs, tokenKey: \ListWorldGenerationJobsResponse.nextToken, on: eventLoop, onPage: onPage ) } /// Lists world templates. /// /// Provide paginated results to closure `onPage` for it to combine them into one result. /// This works in a similar manner to `Array.reduce<Result>(_:_:) -> Result`. /// /// Parameters: /// - input: Input for request /// - initialValue: The value to use as the initial accumulating value. `initialValue` is passed to `onPage` the first time it is called. /// - logger: Logger used flot logging /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each paginated response. It combines an accumulating result with the contents of response. This combined result is then returned /// along with a boolean indicating if the paginate operation should continue. public func listWorldTemplatesPaginator<Result>( _ input: ListWorldTemplatesRequest, _ initialValue: Result, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (Result, ListWorldTemplatesResponse, EventLoop) -> EventLoopFuture<(Bool, Result)> ) -> EventLoopFuture<Result> { return client.paginate( input: input, initialValue: initialValue, command: listWorldTemplates, tokenKey: \ListWorldTemplatesResponse.nextToken, on: eventLoop, onPage: onPage ) } /// Provide paginated results to closure `onPage`. /// /// - Parameters: /// - input: Input for request /// - logger: Logger used flot logging /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each block of entries. Returns boolean indicating whether we should continue. public func listWorldTemplatesPaginator( _ input: ListWorldTemplatesRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (ListWorldTemplatesResponse, EventLoop) -> EventLoopFuture<Bool> ) -> EventLoopFuture<Void> { return client.paginate( input: input, command: listWorldTemplates, tokenKey: \ListWorldTemplatesResponse.nextToken, on: eventLoop, onPage: onPage ) } /// Lists worlds. /// /// Provide paginated results to closure `onPage` for it to combine them into one result. /// This works in a similar manner to `Array.reduce<Result>(_:_:) -> Result`. /// /// Parameters: /// - input: Input for request /// - initialValue: The value to use as the initial accumulating value. `initialValue` is passed to `onPage` the first time it is called. /// - logger: Logger used flot logging /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each paginated response. It combines an accumulating result with the contents of response. This combined result is then returned /// along with a boolean indicating if the paginate operation should continue. public func listWorldsPaginator<Result>( _ input: ListWorldsRequest, _ initialValue: Result, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (Result, ListWorldsResponse, EventLoop) -> EventLoopFuture<(Bool, Result)> ) -> EventLoopFuture<Result> { return client.paginate( input: input, initialValue: initialValue, command: listWorlds, tokenKey: \ListWorldsResponse.nextToken, on: eventLoop, onPage: onPage ) } /// Provide paginated results to closure `onPage`. /// /// - Parameters: /// - input: Input for request /// - logger: Logger used flot logging /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each block of entries. Returns boolean indicating whether we should continue. public func listWorldsPaginator( _ input: ListWorldsRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (ListWorldsResponse, EventLoop) -> EventLoopFuture<Bool> ) -> EventLoopFuture<Void> { return client.paginate( input: input, command: listWorlds, tokenKey: \ListWorldsResponse.nextToken, on: eventLoop, onPage: onPage ) } } extension RoboMaker.ListDeploymentJobsRequest: AWSPaginateToken { public func usingPaginationToken(_ token: String) -> RoboMaker.ListDeploymentJobsRequest { return .init( filters: self.filters, maxResults: self.maxResults, nextToken: token ) } } extension RoboMaker.ListFleetsRequest: AWSPaginateToken { public func usingPaginationToken(_ token: String) -> RoboMaker.ListFleetsRequest { return .init( filters: self.filters, maxResults: self.maxResults, nextToken: token ) } } extension RoboMaker.ListRobotApplicationsRequest: AWSPaginateToken { public func usingPaginationToken(_ token: String) -> RoboMaker.ListRobotApplicationsRequest { return .init( filters: self.filters, maxResults: self.maxResults, nextToken: token, versionQualifier: self.versionQualifier ) } } extension RoboMaker.ListRobotsRequest: AWSPaginateToken { public func usingPaginationToken(_ token: String) -> RoboMaker.ListRobotsRequest { return .init( filters: self.filters, maxResults: self.maxResults, nextToken: token ) } } extension RoboMaker.ListSimulationApplicationsRequest: AWSPaginateToken { public func usingPaginationToken(_ token: String) -> RoboMaker.ListSimulationApplicationsRequest { return .init( filters: self.filters, maxResults: self.maxResults, nextToken: token, versionQualifier: self.versionQualifier ) } } extension RoboMaker.ListSimulationJobBatchesRequest: AWSPaginateToken { public func usingPaginationToken(_ token: String) -> RoboMaker.ListSimulationJobBatchesRequest { return .init( filters: self.filters, maxResults: self.maxResults, nextToken: token ) } } extension RoboMaker.ListSimulationJobsRequest: AWSPaginateToken { public func usingPaginationToken(_ token: String) -> RoboMaker.ListSimulationJobsRequest { return .init( filters: self.filters, maxResults: self.maxResults, nextToken: token ) } } extension RoboMaker.ListWorldExportJobsRequest: AWSPaginateToken { public func usingPaginationToken(_ token: String) -> RoboMaker.ListWorldExportJobsRequest { return .init( filters: self.filters, maxResults: self.maxResults, nextToken: token ) } } extension RoboMaker.ListWorldGenerationJobsRequest: AWSPaginateToken { public func usingPaginationToken(_ token: String) -> RoboMaker.ListWorldGenerationJobsRequest { return .init( filters: self.filters, maxResults: self.maxResults, nextToken: token ) } } extension RoboMaker.ListWorldTemplatesRequest: AWSPaginateToken { public func usingPaginationToken(_ token: String) -> RoboMaker.ListWorldTemplatesRequest { return .init( maxResults: self.maxResults, nextToken: token ) } } extension RoboMaker.ListWorldsRequest: AWSPaginateToken { public func usingPaginationToken(_ token: String) -> RoboMaker.ListWorldsRequest { return .init( filters: self.filters, maxResults: self.maxResults, nextToken: token ) } }
apache-2.0
17fc51729f633254405e011151066c8f
42.266955
168
0.646045
5.179478
false
false
false
false
Zewo/Core
Tests/AxisTests/URL/URLTests.swift
2
891
import XCTest import Foundation @testable import Axis public class URLTests : XCTestCase { func testQueryItems() { let url = URL(string: "http://zewo.io?a=b&c=d%20e")! let queryItems = url.queryItems //this is weird. If you run `XCTAssertEqual(URLQueryItem, URLQueryItem)` //just for Axis, everything works, but for Zewo it does not. let v0 = URLQueryItem(name: "a", value: "b") let v1 = URLQueryItem(name: "c", value: "d e") XCTAssertEqual(queryItems[0].name, v0.name) XCTAssertEqual(queryItems[0].value, v0.value) XCTAssertEqual(queryItems[1].name, v1.name) XCTAssertEqual(queryItems[1].value, v1.value) } } extension URLTests { public static var allTests: [(String, (URLTests) -> () throws -> Void)] { return [ ("testQueryItems", testQueryItems), ] } }
mit
b6349e0b86b3d84f98500ded0f9fc8d7
32
80
0.619529
3.907895
false
true
false
false
hejunbinlan/BFKit-Swift
Source/Extensions/UIKit/UITableView+BFKit.swift
3
3738
// // UITableView+BFKit.swift // BFKit // // The MIT License (MIT) // // Copyright (c) 2015 Fabrizio Brancati. 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 import UIKit /// This extesion adds some useful functions to UITableView public extension UITableView { // MARK: - Instance functions - /** Retrive all the IndexPaths for the section :param: section The section :returns: Return an array with all the IndexPaths */ public func getIndexPathsForSection(section: Int) -> Array<NSIndexPath> { var indexPaths: Array<NSIndexPath> = Array() let rows: Int = self.numberOfRowsInSection(section) for var i = 0; i < rows; i++ { let indexPath: NSIndexPath = NSIndexPath(forRow: i, inSection: section) indexPaths.append(indexPath) } return indexPaths } /** Retrive the next index path for the given row at section :param: row Row of the index path :param: section Section of the index path :returns: Returns the next index path */ public func getNextIndexPath(row: Int, forSection section: Int) -> NSIndexPath { let indexPath: Array<NSIndexPath> = self.getIndexPathsForSection(section) return indexPath[row + 1] } /** Retrive the previous index path for the given row at section :param: row Row of the index path :param: section Section of the index path :returns: Returns the previous index path */ public func getPreviousIndexPath(row: Int, forSection section: Int) -> NSIndexPath { let indexPath: Array<NSIndexPath> = self.getIndexPathsForSection(section) return indexPath[row - 1] } // MARK: - Init functions - /** Create an UITableView and set some parameters :param: frame TableView's frame :param: style TableView's style :param: cellSeparatorStyle Cell separator style :param: separatorInset Cell separator inset :param: dataSource TableView's data source :param: delegate TableView's delegate :returns: Returns the created UITableView */ public convenience init(frame: CGRect, style: UITableViewStyle, cellSeparatorStyle: UITableViewCellSeparatorStyle, separatorInset: UIEdgeInsets, dataSource: UITableViewDataSource?, delegate: UITableViewDelegate?) { self.init(frame: frame) self.separatorStyle = cellSeparatorStyle self.separatorInset = separatorInset self.dataSource = dataSource self.delegate = delegate } }
mit
92a1751c800731245d3185f2dbe093d7
34.6
216
0.681915
4.810811
false
false
false
false
NickKech/Spaceship
Spaceship-iOS/LabelNode.swift
3
2117
// // LabelNode.swift // // Created by Nikolaos Kechagias on 28/4/15. // Copyright (c) 2015 Nikolaos Kechagias. All rights reserved. // /* 1 */ import SpriteKit /* 2 */ class LabelNode: SKNode { private var label: SKLabelNode! private var shadow: SKLabelNode! var text: String = "" { didSet { label.text = text shadow.text = text } } var fontSize: CGFloat! { didSet { label.fontSize = fontSize shadow.fontSize = fontSize } } var fontColor: SKColor = SKColor.white { didSet { label.fontColor = fontColor } } var shadowColor: SKColor = SKColor.black { didSet { shadow.fontColor = shadowColor } } var verticalAlignmentMode = SKLabelVerticalAlignmentMode.center { didSet { label.verticalAlignmentMode = verticalAlignmentMode shadow.verticalAlignmentMode = verticalAlignmentMode } } var horizontalAlignmentMode = SKLabelHorizontalAlignmentMode.center { didSet { label.horizontalAlignmentMode = horizontalAlignmentMode shadow.horizontalAlignmentMode = horizontalAlignmentMode } } /* 3 */ init(fontNamed: String) { super.init() /* Add Label */ addLabel(fontNamed: fontNamed) /* Add Shadow */ addShadow(fontNamed: fontNamed) } /* 4 */ required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func addLabel(fontNamed: String) { label = SKLabelNode(fontNamed: fontNamed) label.fontColor = fontColor label.zPosition = 1 label.position = CGPoint(x: 0, y: 0) addChild(label) } func addShadow(fontNamed: String) { shadow = SKLabelNode(fontNamed: fontNamed) shadow.fontColor = shadowColor shadow.zPosition = 0 shadow.position = CGPoint(x: 1, y: -1) addChild(shadow) } }
mit
ee1a199939ae0f26da0c33e1f177218b
22.786517
73
0.569202
4.900463
false
false
false
false
syncloud/ios
Syncloud/UserStorage.swift
1
1145
import Foundation class UserStorage { let cacheFileUrl: URL init() { let documentDirectoryURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first! as URL self.cacheFileUrl = documentDirectoryURL.appendingPathComponent("user.json") } func load() -> User? { do { let json = try String(contentsOf: self.cacheFileUrl, encoding: String.Encoding.utf8) let jsonData = json.data(using: String.Encoding.utf8) if let jsonData = jsonData { let jsonDict = try JSONSerialization.jsonObject(with: jsonData, options: []) as? NSDictionary return User(json: jsonDict!) } } catch { } return nil } func save(_ user: User) { let json = Serialize.toJSON(user) do { try json!.write(to: self.cacheFileUrl, atomically: true, encoding: String.Encoding.utf8) } catch {} } func erase() { let manager = FileManager.default do { try manager.removeItem(at: self.cacheFileUrl) } catch {} } }
gpl-3.0
94f9934fe169919386f0338ece3fded3
29.945946
119
0.582533
4.635628
false
false
false
false
askfromap/PassCodeLock-Swift3
PasscodeLock/PasscodeLock/SetPasscodeState.swift
1
923
// // SetPasscodeState.swift // PasscodeLock // // Created by Yanko Dimitrov on 8/28/15. // Copyright © 2015 Yanko Dimitrov. All rights reserved. // import Foundation struct SetPasscodeState: PasscodeLockStateType { let title: String let description: String let isCancellableAction = true var isTouchIDAllowed = false init(title: String, description: String) { self.title = title self.description = description } init() { title = localizedStringFor("PasscodeLockSetTitle", comment: "Set passcode title") description = localizedStringFor("PasscodeLockSetDescription", comment: "Set passcode description") } func acceptPasscode(_ passcode: String, fromLock lock: PasscodeLockType) { let nextState = ConfirmPasscodeState(passcode: passcode) lock.changeStateTo(nextState) } }
mit
71d909bf94cc99188409aa607c2d2dc3
24.611111
107
0.659436
5.038251
false
false
false
false
AirChen/ACSwiftDemoes
Target4-ScrollView/ViewController.swift
1
1466
// // ViewController.swift // Target4-ScrollView // // Created by Air_chen on 2016/10/29. // Copyright © 2016年 Air_chen. All rights reserved. // import UIKit class ViewController: UIViewController { var scrollView: UIScrollView! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. @IBOutlet weak var nameField: UITextField! let screenSize = UIScreen.main.bounds.size self.scrollView = UIScrollView(frame: CGRect.init(x: 0, y: 0, width: screenSize.width, height: screenSize.height)) self.view.addSubview(self.scrollView) let rightV = RightView(frame: CGRect.init(x: 2*screenSize.width, y: 0, width: screenSize.width, height: screenSize.height)) let leftV = LeftView(frame: CGRect.init(x: 0, y: 0, width: screenSize.width, height: screenSize.height)) let midV = CameraView(frame: CGRect.init(x: screenSize.width, y: 0, width: screenSize.width, height: screenSize.height)) self.scrollView.addSubview(rightV) self.scrollView.addSubview(midV) self.scrollView.addSubview(leftV) self.scrollView.contentSize = CGSize.init(width: screenSize.width * 3, height: screenSize.height) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
mit
b1d2e95f8e6fdfa84a9db3a3e93f27af
32.25
131
0.673274
4.204023
false
false
false
false
ostatnicky/kancional-ios
Pods/SwiftyBeaver/Sources/BaseDestination.swift
1
17813
// // BaseDestination.swift // SwiftyBeaver // // Created by Sebastian Kreutzberger (Twitter @skreutzb) on 05.12.15. // Copyright © 2015 Sebastian Kreutzberger // Some rights reserved: http://opensource.org/licenses/MIT // import Foundation import Dispatch // store operating system / platform #if os(iOS) let OS = "iOS" #elseif os(OSX) let OS = "OSX" #elseif os(watchOS) let OS = "watchOS" #elseif os(tvOS) let OS = "tvOS" #elseif os(Linux) let OS = "Linux" #elseif os(FreeBSD) let OS = "FreeBSD" #elseif os(Windows) let OS = "Windows" #elseif os(Android) let OS = "Android" #else let OS = "Unknown" #endif /// destination which all others inherit from. do not directly use open class BaseDestination: Hashable, Equatable { /// output format pattern, see documentation for syntax open var format = "$DHH:mm:ss.SSS$d $C$L$c $N.$F:$l - $M" /// runs in own serial background thread for better performance open var asynchronously = true /// do not log any message which has a lower level than this one open var minLevel = SwiftyBeaver.Level.verbose /// set custom log level words for each level open var levelString = LevelString() /// set custom log level colors for each level open var levelColor = LevelColor() public struct LevelString { public var verbose = "VERBOSE" public var debug = "DEBUG" public var info = "INFO" public var warning = "WARNING" public var error = "ERROR" } // For a colored log level word in a logged line // empty on default public struct LevelColor { public var verbose = "" // silver public var debug = "" // green public var info = "" // blue public var warning = "" // yellow public var error = "" // red } var reset = "" var escape = "" var filters = [FilterType]() let formatter = DateFormatter() let startDate = Date() // each destination class must have an own hashValue Int lazy public var hashValue: Int = self.defaultHashValue open var defaultHashValue: Int {return 0} // each destination instance must have an own serial queue to ensure serial output // GCD gives it a prioritization between User Initiated and Utility var queue: DispatchQueue? //dispatch_queue_t? var debugPrint = false // set to true to debug the internal filter logic of the class public init() { let uuid = NSUUID().uuidString let queueLabel = "swiftybeaver-queue-" + uuid queue = DispatchQueue(label: queueLabel, target: queue) } /// send / store the formatted log message to the destination /// returns the formatted log message for processing by inheriting method /// and for unit tests (nil if error) open func send(_ level: SwiftyBeaver.Level, msg: String, thread: String, file: String, function: String, line: Int, context: Any? = nil) -> String? { if format.hasPrefix("$J") { return messageToJSON(level, msg: msg, thread: thread, file: file, function: function, line: line, context: context) } else { return formatMessage(format, level: level, msg: msg, thread: thread, file: file, function: function, line: line, context: context) } } //////////////////////////////// // MARK: Format //////////////////////////////// /// returns the log message based on the format pattern func formatMessage(_ format: String, level: SwiftyBeaver.Level, msg: String, thread: String, file: String, function: String, line: Int, context: Any? = nil) -> String { var text = "" let phrases: [String] = format.components(separatedBy: "$") for phrase in phrases where !phrase.isEmpty { let firstChar = phrase[phrase.startIndex] let rangeAfterFirstChar = phrase.index(phrase.startIndex, offsetBy: 1)..<phrase.endIndex let remainingPhrase = phrase[rangeAfterFirstChar] switch firstChar { case "L": text += levelWord(level) + remainingPhrase case "M": text += msg + remainingPhrase case "T": text += thread + remainingPhrase case "N": // name of file without suffix text += fileNameWithoutSuffix(file) + remainingPhrase case "n": // name of file with suffix text += fileNameOfFile(file) + remainingPhrase case "F": text += function + remainingPhrase case "l": text += String(line) + remainingPhrase case "D": // start of datetime format #if swift(>=3.2) text += formatDate(String(remainingPhrase)) #else text += formatDate(remainingPhrase) #endif case "d": text += remainingPhrase case "U": text += uptime() + remainingPhrase case "Z": // start of datetime format in UTC timezone #if swift(>=3.2) text += formatDate(String(remainingPhrase), timeZone: "UTC") #else text += formatDate(remainingPhrase, timeZone: "UTC") #endif case "z": text += remainingPhrase case "C": // color code ("" on default) text += escape + colorForLevel(level) + remainingPhrase case "c": text += reset + remainingPhrase case "X": // add the context if let cx = context { text += String(describing: cx).trimmingCharacters(in: .whitespacesAndNewlines) + remainingPhrase } /* if let contextString = context as? String { text += contextString + remainingPhrase }*/ default: text += phrase } } return text.trimmingCharacters(in: .whitespacesAndNewlines) } /// returns the log payload as optional JSON string func messageToJSON(_ level: SwiftyBeaver.Level, msg: String, thread: String, file: String, function: String, line: Int, context: Any? = nil) -> String? { var dict: [String: Any] = [ "timestamp": Date().timeIntervalSince1970, "level": level.rawValue, "message": msg, "thread": thread, "file": file, "function": function, "line": line ] if let cx = context { dict["context"] = cx } return jsonStringFromDict(dict) } /// returns the string of a level func levelWord(_ level: SwiftyBeaver.Level) -> String { var str = "" switch level { case SwiftyBeaver.Level.debug: str = levelString.debug case SwiftyBeaver.Level.info: str = levelString.info case SwiftyBeaver.Level.warning: str = levelString.warning case SwiftyBeaver.Level.error: str = levelString.error default: // Verbose is default str = levelString.verbose } return str } /// returns color string for level func colorForLevel(_ level: SwiftyBeaver.Level) -> String { var color = "" switch level { case SwiftyBeaver.Level.debug: color = levelColor.debug case SwiftyBeaver.Level.info: color = levelColor.info case SwiftyBeaver.Level.warning: color = levelColor.warning case SwiftyBeaver.Level.error: color = levelColor.error default: color = levelColor.verbose } return color } /// returns the filename of a path func fileNameOfFile(_ file: String) -> String { let fileParts = file.components(separatedBy: "/") if let lastPart = fileParts.last { return lastPart } return "" } /// returns the filename without suffix (= file ending) of a path func fileNameWithoutSuffix(_ file: String) -> String { let fileName = fileNameOfFile(file) if !fileName.isEmpty { let fileNameParts = fileName.components(separatedBy: ".") if let firstPart = fileNameParts.first { return firstPart } } return "" } /// returns a formatted date string /// optionally in a given abbreviated timezone like "UTC" func formatDate(_ dateFormat: String, timeZone: String = "") -> String { if !timeZone.isEmpty { formatter.timeZone = TimeZone(abbreviation: timeZone) } formatter.dateFormat = dateFormat //let dateStr = formatter.string(from: NSDate() as Date) let dateStr = formatter.string(from: Date()) return dateStr } /// returns a uptime string func uptime() -> String { let interval = Date().timeIntervalSince(startDate) let hours = Int(interval) / 3600 let minutes = Int(interval / 60) - Int(hours * 60) let seconds = Int(interval) - (Int(interval / 60) * 60) let milliseconds = Int(interval.truncatingRemainder(dividingBy: 1) * 1000) return String(format: "%0.2d:%0.2d:%0.2d.%03d", arguments: [hours, minutes, seconds, milliseconds]) } /// returns the json-encoded string value /// after it was encoded by jsonStringFromDict func jsonStringValue(_ jsonString: String?, key: String) -> String { guard let str = jsonString else { return "" } // remove the leading {"key":" from the json string and the final } let offset = key.length + 5 let endIndex = str.index(str.startIndex, offsetBy: str.length - 2) let range = str.index(str.startIndex, offsetBy: offset)..<endIndex #if swift(>=3.2) return String(str[range]) #else return str[range] #endif } /// turns dict into JSON-encoded string func jsonStringFromDict(_ dict: [String: Any]) -> String? { var jsonString: String? // try to create JSON string do { let jsonData = try JSONSerialization.data(withJSONObject: dict, options: []) jsonString = String(data: jsonData, encoding: .utf8) } catch { print("SwiftyBeaver could not create JSON from dict.") } return jsonString } //////////////////////////////// // MARK: Filters //////////////////////////////// /// Add a filter that determines whether or not a particular message will be logged to this destination public func addFilter(_ filter: FilterType) { filters.append(filter) } /// Remove a filter from the list of filters public func removeFilter(_ filter: FilterType) { let index = filters.index { return ObjectIdentifier($0) == ObjectIdentifier(filter) } guard let filterIndex = index else { return } filters.remove(at: filterIndex) } /// Answer whether the destination has any message filters /// returns boolean and is used to decide whether to resolve /// the message before invoking shouldLevelBeLogged func hasMessageFilters() -> Bool { return !getFiltersTargeting(Filter.TargetType.Message(.Equals([], true)), fromFilters: self.filters).isEmpty } /// checks if level is at least minLevel or if a minLevel filter for that path does exist /// returns boolean and can be used to decide if a message should be logged or not func shouldLevelBeLogged(_ level: SwiftyBeaver.Level, path: String, function: String, message: String? = nil) -> Bool { if filters.isEmpty { if level.rawValue >= minLevel.rawValue { if debugPrint { print("filters is empty and level >= minLevel") } return true } else { if debugPrint { print("filters is empty and level < minLevel") } return false } } let (matchedExclude, allExclude) = passedExcludedFilters(level, path: path, function: function, message: message) if allExclude > 0 && matchedExclude != allExclude { if debugPrint { print("filters is not empty and message was excluded") } return false } let (matchedRequired, allRequired) = passedRequiredFilters(level, path: path, function: function, message: message) let (matchedNonRequired, allNonRequired) = passedNonRequiredFilters(level, path: path, function: function, message: message) // If required filters exist, we should validate or invalidate the log if all of them pass or not if allRequired > 0 { return matchedRequired == allRequired } // If a non-required filter matches, the log is validated if allNonRequired > 0 { // Non-required filters exist if matchedNonRequired > 0 { return true } // At least one non-required filter matched else { return false } // No non-required filters matched } if level.rawValue < minLevel.rawValue { if debugPrint { print("filters is not empty and level < minLevel") } return false } return true } func getFiltersTargeting(_ target: Filter.TargetType, fromFilters: [FilterType]) -> [FilterType] { return fromFilters.filter { filter in return filter.getTarget() == target } } /// returns a tuple of matched and all filters func passedRequiredFilters(_ level: SwiftyBeaver.Level, path: String, function: String, message: String?) -> (Int, Int) { let requiredFilters = self.filters.filter { filter in return filter.isRequired() && !filter.isExcluded() } let matchingFilters = applyFilters(requiredFilters, level: level, path: path, function: function, message: message) if debugPrint { print("matched \(matchingFilters) of \(requiredFilters.count) required filters") } return (matchingFilters, requiredFilters.count) } /// returns a tuple of matched and all filters func passedNonRequiredFilters(_ level: SwiftyBeaver.Level, path: String, function: String, message: String?) -> (Int, Int) { let nonRequiredFilters = self.filters.filter { filter in return !filter.isRequired() && !filter.isExcluded() } let matchingFilters = applyFilters(nonRequiredFilters, level: level, path: path, function: function, message: message) if debugPrint { print("matched \(matchingFilters) of \(nonRequiredFilters.count) non-required filters") } return (matchingFilters, nonRequiredFilters.count) } /// returns a tuple of matched and all exclude filters func passedExcludedFilters(_ level: SwiftyBeaver.Level, path: String, function: String, message: String?) -> (Int, Int) { let excludeFilters = self.filters.filter { filter in return filter.isExcluded() } let matchingFilters = applyFilters(excludeFilters, level: level, path: path, function: function, message: message) if debugPrint { print("matched \(matchingFilters) of \(excludeFilters.count) exclude filters") } return (matchingFilters, excludeFilters.count) } func applyFilters(_ targetFilters: [FilterType], level: SwiftyBeaver.Level, path: String, function: String, message: String?) -> Int { return targetFilters.filter { filter in let passes: Bool if !filter.reachedMinLevel(level) { return false } switch filter.getTarget() { case .Path(_): passes = filter.apply(path) case .Function(_): passes = filter.apply(function) case .Message(_): guard let message = message else { return false } passes = filter.apply(message) } return passes }.count } /** Triggered by main flush() method on each destination. Runs in background thread. Use for destinations that buffer log items, implement this function to flush those buffers to their final destination (web server...) */ func flush() { // no implementation in base destination needed } } public func == (lhs: BaseDestination, rhs: BaseDestination) -> Bool { return ObjectIdentifier(lhs) == ObjectIdentifier(rhs) }
mit
7d4e80315877cc09786ec206a5d5e322
34.271287
120
0.560016
5.105188
false
false
false
false
MaTriXy/androidtool-mac
AndroidTool/Styles.swift
2
825
// // Styles.swift // Shellpad/androidtool // // Created by Morten Just Petersen on 10/31/15. // Copyright © 2015 Morten Just Petersen. All rights reserved. // import Cocoa class Styles: NSObject { override init() { super.init() } func terminalAtts() -> [String:AnyObject]{ var atts = [String:AnyObject]() atts[NSForegroundColorAttributeName] = NSColor(red:0.671, green:0.671, blue:0.671, alpha:1) atts[NSFontAttributeName] = NSFont(name: "Monaco", size: 8.0) return atts } func commandAtts() -> [String:AnyObject]{ var atts = [String:AnyObject]() atts[NSForegroundColorAttributeName] = NSColor(red:1, green:1, blue:1, alpha:1) atts[NSFontAttributeName] = NSFont(name: "Monaco", size: 8.0); return atts } }
apache-2.0
7e72cdbac65ae1fd84730bfa3a6f44dd
26.466667
99
0.621359
3.646018
false
false
false
false
swiftsanyue/TestKitchen
TestKitchen/TestKitchen/classes/common(公共类)/UILabel+common.swift
1
625
// // UILabel+common.swift // TestKitchen // // Created by ZL on 16/10/21. // Copyright © 2016年 zl. All rights reserved. // import Foundation import UIKit extension UILabel { class func createLabel(text:String?,textAlignment:NSTextAlignment?,font:UIFont?)->UILabel { let label = UILabel() if let tmpText = text { label.text = tmpText } if let tmpAlignment = textAlignment{ label.textAlignment = tmpAlignment } if let tmpFont = font { //系统的是17 label.font = tmpFont } return label } }
mit
3ba4bcc8b5458c1118fd9ca837b596c2
18.1875
95
0.578176
4.323944
false
false
false
false
exercism/xswift
exercises/octal/Sources/Octal/OctalExample.swift
2
933
#if os(Linux) import Glibc #elseif os(OSX) import Darwin #endif extension Int { init(_ value: Octal) { self = value.toDecimal } } struct Octal { private var stringValue = "" fileprivate var toDecimal: Int = 0 private func isValidOctal() -> Bool { return (Int(stringValue) ?? -1) > -1 ? true : false } private func oct2int(_ input: String) -> Int { let orderedInput = Array(input.reversed()) var tempInt: Int = 0 for (inx, each) in orderedInput.enumerated() { let tempCharInt = Int("\(each)") ?? 0 if tempCharInt > 7 { return 0 } let tempOctPower = Int(pow(Double(8), Double(inx))) tempInt += tempOctPower * tempCharInt } return tempInt } init( _ sv: String) { self.stringValue = sv if isValidOctal() { self.toDecimal = oct2int(sv) } } }
mit
fbbe2da3e5c7af701d2b76885dfbd09f
21.214286
63
0.546624
3.762097
false
false
false
false
gabrielafonsogoncalves/GoogleMapsRouteExample
GoogleMapsTestSwift/Classes/Builders/GBBuilder.swift
1
1155
// // GBBuilder.swift // GoogleMapsTestSwift // // Created by Gabriel Alejandro Afonso Goncalves on 8/3/15. // Copyright (c) 2015 Gabriel Alejandro Afonso Goncalves. All rights reserved. // import Foundation class GBBuilder: NSObject { var builders: [String: AnyObject] = [String: AnyObject]() var loaded: Bool = false func build(className: String, fromDictionary dictionary: [String: AnyObject]?) -> AnyObject? { if dictionary == nil { return nil } if !loaded { self.loadBuilders() } if let builder = self.builders[className] as? GBObjectBuilder { return builder.buildFromDictionary(dictionary!) } return nil } private func loadBuilders() { var tripBuilder = GBTripBuilder() tripBuilder.context = self builders.updateValue(tripBuilder, forKey: NSStringFromClass(GBTrip)) var polylineBuilder = GBPolylineBuilder() polylineBuilder.context = self builders.updateValue(polylineBuilder, forKey: NSStringFromClass(GBPolyline)) } }
mit
58837702d0916f95b9fadc4456588382
26.52381
98
0.621645
4.852941
false
false
false
false
russbishop/swift
test/PrintAsObjC/imports.swift
1
1446
// Please keep this file in alphabetical order! // RUN: rm -rf %t // RUN: mkdir %t // RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) -I %S/Inputs/custom-modules/ -emit-module -o %t %s -disable-objc-attr-requires-foundation-module // RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) -I %S/Inputs/custom-modules/ -parse-as-library %t/imports.swiftmodule -parse -emit-objc-header-path %t/imports.h -import-objc-header %S/../Inputs/empty.h -disable-objc-attr-requires-foundation-module // RUN: FileCheck %s < %t/imports.h // RUN: FileCheck -check-prefix=NEGATIVE %s < %t/imports.h // RUN: %check-in-clang %t/imports.h -I %S/Inputs/custom-modules/ // REQUIRES: objc_interop // CHECK-DAG: @import ctypes.bits; // CHECK-DAG: @import Foundation; // CHECK-DAG: @import Base; // CHECK-DAG: @import Base.ImplicitSub.ExSub; // CHECK-DAG: @import Base.ExplicitSub; // CHECK-DAG: @import Base.ExplicitSub.ExSub; // NEGATIVE-NOT: ctypes; // NEGATIVE-NOT: ImSub; // NEGATIVE-NOT: ImplicitSub; import ctypes.bits import Foundation import Base import Base.ImplicitSub import Base.ImplicitSub.ImSub import Base.ImplicitSub.ExSub import Base.ExplicitSub import Base.ExplicitSub.ImSub import Base.ExplicitSub.ExSub @objc class Test { let word: DWORD = 0 let number: TimeInterval = 0.0 let baseI: BaseI = 0 let baseII: BaseII = 0 let baseIE: BaseIE = 0 let baseE: BaseE = 0 let baseEI: BaseEI = 0 let baseEE: BaseEE = 0 }
apache-2.0
4cd13b193ee569578c4d1f3b6f59a0c2
31.133333
261
0.722683
3.025105
false
false
false
false
EBGToo/SBUnits
Tests/QuantityTest.swift
1
5199
// // QuantityTest.swift // SBUnits // // Created by Ed Gamble on 11/4/15. // Copyright © 2015 Edward B. Gamble Jr. All rights reserved. // // See the LICENSE file at the project root for license information. // See the CONTRIBUTORS file at the project root for a list of contributors. // import XCTest @testable import SBUnits class QuantityTest: XCTestCase { override func setUp() { super.setUp() } override func tearDown() { super.tearDown() } func assertNearly<D: SBUnits.Dimension> (_ q1: Quantity<D>, _ q2: Quantity<D>) { XCTAssertTrue(abs((q1 - q2).valueToRoot) < .ulpOfOne) } func testDescription() { let q1 = Quantity<Mass>(value: 1.0, unit: kilogram) XCTAssertEqual(q1.description, "1.0 kg") debugPrint(q1) print (q1) let q2 = Quantity<Length>(value: 1.0, unit: meter) debugPrint(q2) print (q2) let q3 = Quantity<Length>(value: 0.001, unit: kilometer) debugPrint(q3) print (q3) XCTAssertEqual(q2.valueToRoot, q3.valueToRoot) } func testMass () { // Metric XCTAssertEqual(Quantity<Mass>(value: 1.0, unit: kilogram), Quantity<Mass>(value: 1000, unit: gram)) XCTAssertEqual(Quantity<Mass>(value: 1.0, unit: kilogram), Quantity<Mass>(value: 1000 * 1000, unit: milligram)) // Imperial XCTAssertEqual(Quantity<Mass>(value: 1.0, unit: pound), Quantity<Mass>(value: 16, unit: ounce)) // Metric <==> Imperial XCTAssertEqual(Quantity<Mass>(value: 1.0, unit: pound), Quantity<Mass>(value: 0.45359237, unit: kilogram)) XCTAssertEqual(Quantity<Mass>(value: 1.0, unit: ounce), Quantity<Mass>(value: 0.45359237 / 16, unit: kilogram)) XCTAssertEqual(Quantity<Mass>(value: 1.0, unit: ounce), Quantity<Mass>(value: 1000 * 0.45359237 / 16, unit: gram)) } func testLength () { // Metric XCTAssertEqual(Quantity<Length>(value: 1.0, unit: meter), Quantity<Length>(value: 100, unit: centimeter)) XCTAssertEqual(Quantity<Length>(value: 1.0, unit: meter), Quantity<Length>(value: 1000, unit: millimeter)) XCTAssertEqual(Quantity<Length>(value: 1.0, unit: centimeter), Quantity<Length>(value: 10, unit: millimeter)) XCTAssertEqual(Quantity<Length>(value: 1.0, unit: kilometer), Quantity<Length>(value: 1000, unit: meter)) XCTAssertEqual(Quantity<Length>(value: 1.0, unit: kilometer), Quantity<Length>(value: 1000.0 * 1000.0, unit: millimeter)) // Imperial XCTAssertEqual(Quantity<Length>(value: 1.0, unit: yard), Quantity<Length>(value: 3, unit: foot)) XCTAssertEqual(Quantity<Length>(value: 1.0, unit: yard), Quantity<Length>(value: 36, unit: inch)) XCTAssertEqual(Quantity<Length>(value: 1.0, unit: mile), Quantity<Length>(value: 1760, unit: yard)) XCTAssertEqual(Quantity<Length>(value: 1.0, unit: mile), Quantity<Length>(value: 5280, unit: foot)) XCTAssertEqual(Quantity<Length>(value: 1.0, unit: mile), Quantity<Length>(value: 12 * 5280, unit: inch)) XCTAssertEqual(Quantity<Length>(value: 1.0, unit: foot), Quantity<Length>(value: 12, unit: inch)) // Metric <==> Imperial assertNearly(Quantity<Length>(value: 1.0, unit: inch), Quantity<Length>(value: 2.54, unit: centimeter)) assertNearly(Quantity<Length>(value: 1.0, unit: inch), Quantity<Length>(value: 25.4, unit: millimeter)) assertNearly(Quantity<Length>(value: 1.0, unit: mile), Quantity<Length>(value: 1609.344, unit: meter)) assertNearly(Quantity<Length>(value: 1.0, unit: mile), Quantity<Length>(value: 1.609344, unit: kilometer)) } func testTime () { XCTAssertEqual(Quantity<Time>(value: 1, unit: minute), Quantity<Time>(value: 60, unit: second)) XCTAssertEqual(Quantity<Time>(value: 1, unit: hour), Quantity<Time>(value: 60, unit: minute)) XCTAssertEqual(Quantity<Time>(value: 1, unit: hour), Quantity<Time>(value: 60 * 60, unit: second)) XCTAssertEqual(Quantity<Time>(value: 1, unit: hour), Quantity<Time>(value: 60 * 60 * 1e3, unit: millisecond)) } func testTemperature() { XCTAssertEqual(Quantity<Temperature>(value: 0, unit: celsius), Quantity<Temperature>(value: 32, unit: fahrenheit)) XCTAssertEqual(Quantity<Temperature>(value: 0, unit: celsius), Quantity<Temperature>(value: 273.15, unit: kelvin)) XCTAssertEqual(Quantity<Temperature>(value: 0, unit: kelvin), Quantity<Temperature>(value: -273.15, unit: celsius)) } func testAngle () { XCTAssertEqual(Quantity<Angle>(value: 2 * .pi, unit: radian), Quantity<Angle>(value: 360, unit: degree)) XCTAssertEqual(Quantity<Angle>(value: .pi, unit: radian), Quantity<Angle>(value: 180, unit: degree)) XCTAssertEqual(Quantity<Angle>(value: .pi/2, unit: radian), Quantity<Angle>(value: 90, unit: degree)) XCTAssertEqual(Quantity<Angle>(value: .pi/4, unit: radian), Quantity<Angle>(value: 45, unit: degree)) } func testPerformanceExample() { self.measure { } } }
mit
368471f05cc23f27df978b3c0d3f7145
29.046243
82
0.64217
3.657987
false
true
false
false
churowa/car-payment-calculator
CarLoanCalculator/CarLoanCalculator/ViewController.swift
1
1996
// // ViewController.swift // CarLoanCalculator // // Created by Francis Chary on 2014-08-08. // Copyright (c) 2014 Churowa. All rights reserved. // import UIKit class ViewController: UIViewController { // let interestRate: Float = 1.0 // // let interestPerPeriod = interestRate/100/12 // // let numberOfPeriods = 60.0 // // let originalPrincipal = 28498.0 // // let numerator = pow((1.0 + interestPerPeriod), numberOfPeriods) // let denominator = pow((1.0 + interestPerPeriod), numberOfPeriods)-1.0 // // let paymentPerPeriod = originalPrincipal * interestPerPeriod * (numerator/denominator) @IBOutlet var numberOfMonths:UILabel! @IBOutlet var monthsSlider:UISlider! @IBOutlet var paymentText:UILabel! override func viewDidLoad() { super.viewDidLoad() numberOfMonths.text = "\(self.monthsSlider.value)" paymentText.text = "\(self.paymentPerPeriod(monthsSlider.value)) dollares" monthsSlider.addTarget(self, action: "valueChanged:", forControlEvents: UIControlEvents.ValueChanged) } func valueChanged(sender:UISlider) { let months = Int(self.monthsSlider.value) numberOfMonths.text = "\(months)" paymentText.text = "\(self.paymentPerPeriod(Float(months))) dollares" } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func paymentPerPeriod(numberOfPeriods:Float) -> Float { let interestRate:Float = 1.0 let interestPerPeriod:Float = interestRate/100/12 let numPeriods:Float = numberOfPeriods let originalPrincipal:Float = 28498.0 let numerator:Float = pow((1.0 + interestPerPeriod), numPeriods) let denominator:Float = pow((1.0 + interestPerPeriod), numPeriods)-1.0 return originalPrincipal * interestPerPeriod * (numerator/denominator) } }
mit
cefb5959cca06966314c070a442dde95
30.1875
109
0.664329
4.090164
false
false
false
false
PerfectlySoft/Perfect-Authentication
Sources/LocalAuthentication/Schema/Account.swift
1
3187
// // Account.swift // Perfect-OAuth2-Server // // Created by Jonathan Guthrie on 2017-02-06. // // import StORM import PostgresStORM import SwiftRandom import PerfectSMTP public class Account: PostgresStORM { public var id = "" public var username = "" public var password = "" public var email = "" public var usertype: AccountType = .provisional public var passvalidation = "" let _r = URandom() override public func to(_ this: StORMRow) { id = this.data["id"] as? String ?? "" username = this.data["username"] as? String ?? "" password = this.data["password"] as? String ?? "" email = this.data["email"] as? String ?? "" usertype = AccountType.from((this.data["usertype"] as? String)!) passvalidation = this.data["passvalidation"] as? String ?? "" } func rows() -> [Account] { var rows = [Account]() for i in 0..<self.results.rows.count { let row = Account() row.to(self.results.rows[i]) rows.append(row) } return rows } public override init() { super.init() } public init(_ i: String = "", _ u: String, _ p: String = "", _ e: String, _ ut: AccountType = .provisional) { super.init() id = i username = u password = p email = e usertype = ut passvalidation = _r.secureToken } public init(validation: String) { super.init() try? find(["passvalidation": validation]) } // Register User public static func register(_ u: String, _ e: String, _ ut: AccountType = .provisional, baseURL: String) -> OAuth2ServerError { let r = URandom() let acc = Account(r.secureToken, u, "", e, ut) do { try acc.create() } catch { print(error) return .registerError } var h = "<p>Welcome to your new account</p>" h += "<p>To get started with your new account, please <a href=\"\(baseURL)/verifyAccount/\(acc.passvalidation)\">click here</a></p>" h += "<p>If the link does not work copy and paste the following link into your browser:<br>\(baseURL)/verifyAccount/\(acc.passvalidation)</p>" var t = "Welcome to your new account\n" t += "To get started with your new account, please click here: \(baseURL)/verifyAccount/\(acc.passvalidation)" Utility.sendMail(name: u, address: e, subject: "Welcome to your account", html: h, text: t) return .noError } // Register User public static func login(_ u: String, _ p: String) throws -> Account { if let digestBytes = p.digest(.sha256), let hexBytes = digestBytes.encode(.hex), let hexBytesStr = String(validatingUTF8: hexBytes) { let acc = Account() let criteria = ["username":u,"password":hexBytesStr] do { try acc.find(criteria) if acc.usertype == .provisional { throw OAuth2ServerError.loginError } return acc } catch { print(error) throw OAuth2ServerError.loginError } } else { throw OAuth2ServerError.loginError } } } public enum AccountType { case provisional, standard, admin, inactive public static func from(_ str: String) -> AccountType { switch str { case "admin": return .admin case "standard": return .standard case "inactive": return .inactive default: return .provisional } } }
apache-2.0
95405accd90648abc1a76b0b8ee53484
23.898438
144
0.644807
3.209466
false
false
false
false
hyp/NUIGExam
NUIGExam/Exam.swift
1
2749
import Foundation import CoreData import MapKit // A Serializable Exam Entity public class Exam: NSManagedObject { @NSManaged var code: String @NSManaged var name: String @NSManaged var date: NSDate @NSManaged var seatNumber: NSNumber @NSManaged var venue: String @NSManaged var paper: String @NSManaged var duration: NSNumber // the duration of the exam in minutes // Returns true when an exam is 'done' i.e. 60 minutes after it started. public var isFinished: Bool { get { return date.dateByAddingTimeInterval(60*60).compare(NSDate()) == NSComparisonResult.OrderedAscending } } // Returns the physical location of the exam venue public var location: CLLocationCoordinate2D { get { for (name, loc) in locationCoordinates { if let _ = venue.rangeOfString(name, options: .CaseInsensitiveSearch) { return loc } } // NUIG's location return CLLocationCoordinate2D(latitude: 53.278552, longitude: -9.060518) } } // Returns the duration of the exam public var durationString: String { get { if duration.integerValue == 0 { return "Unknown" } return duration.integerValue % 60 == 0 ? "\(duration.integerValue/60) Hours" : "\(duration.integerValue/60) Hours \(duration.integerValue%60) Minutes" } } public class func create(ctx: NSManagedObjectContext, code: String, name: String, date: NSDate, venue: String, duration: Int, paper: String = "Paper 1") -> Exam { let newItem = NSEntityDescription.insertNewObjectForEntityForName("Exam", inManagedObjectContext: ctx) as Exam newItem.code = code newItem.name = name newItem.date = date newItem.seatNumber = NSNumber() newItem.venue = venue newItem.paper = paper newItem.duration = NSNumber(integer: duration) return newItem } } let locationCoordinates = [ "leisureland": CLLocationCoordinate2D(latitude: 53.259039, longitude: -9.082346), "galway bay hotel": CLLocationCoordinate2D(latitude: 53.258217, longitude: -9.084942), "westwood house hotel": CLLocationCoordinate2D(latitude: 53.2825866, longitude: -9.0638771), "westwood hotel": CLLocationCoordinate2D(latitude: 53.2825866, longitude: -9.0638771), "kingfisher": CLLocationCoordinate2D(latitude: 53.282077, longitude: -9.062358), "bailey allen": CLLocationCoordinate2D(latitude: 53.278436, longitude: -9.058013), "the cube": CLLocationCoordinate2D(latitude: 53.278436, longitude: -9.058013) ]
mit
5dd361939449fc95dce571ed893a842d
39.426471
166
0.644234
4.499182
false
false
false
false
malaonline/iOS
mala-ios/View/TeacherFilterView/BaseFilterView.swift
1
6560
// // BaseFilterView.swift // mala-ios // // Created by Elors on 1/16/16. // Copyright © 2016 Mala Online. All rights reserved. // import UIKit internal let FilterViewCellReusedId = "FilterViewCellReusedId" internal let FilterViewSectionHeaderReusedId = "FilterViewSectionHeaderReusedId" internal let FilterViewSectionFooterReusedId = "FilterViewSectionFooterReusedId" /// 结果返回值闭包 typealias FilterDidTapCallBack = (_ model: GradeModel?)->() class BaseFilterView: UICollectionView, UICollectionViewDelegate, UICollectionViewDataSource { // MARK: - Property /// 年级及科目数据模型 var grades: [GradeModel]? = nil /// Cell点击回调闭包 var didTapCallBack: FilterDidTapCallBack? /// 当前选中项下标标记 var selectedIndexPath: IndexPath? // MARK: - Constructed init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout, didTapCallBack: @escaping FilterDidTapCallBack) { super.init(frame: frame, collectionViewLayout: layout) self.didTapCallBack = didTapCallBack configration() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: - Deleagte func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { let cell = collectionView.cellForItem(at: indexPath) if let currentIndexPath = selectedIndexPath { collectionView.cellForItem(at: currentIndexPath)?.isSelected = false } cell?.isSelected = true self.selectedIndexPath = indexPath } // MARK: - DataSource func numberOfSections(in collectionView: UICollectionView) -> Int { // 默认情况为 小学, 初中, 高中 三项 return self.grades?.count ?? 3 } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return gradeModel(section)?.subset?.count ?? 0 } func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView { var reusableView: UICollectionReusableView? // Section 头部视图 if kind == UICollectionElementKindSectionHeader { let sectionHeaderView = collectionView.dequeueReusableSupplementaryView( ofKind: UICollectionElementKindSectionHeader, withReuseIdentifier: FilterViewSectionHeaderReusedId, for: indexPath ) as! FilterSectionHeaderView sectionHeaderView.sectionTitleText = gradeModel(indexPath.section)?.name ?? "年级" reusableView = sectionHeaderView } // Section 尾部视图 if kind == UICollectionElementKindSectionFooter { let sectionFooterView = collectionView.dequeueReusableSupplementaryView( ofKind: UICollectionElementKindSectionFooter, withReuseIdentifier: FilterViewSectionFooterReusedId, for: indexPath ) reusableView = sectionFooterView } return reusableView! } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: FilterViewCellReusedId, for: indexPath) as! FilterViewCell cell.model = gradeModel(indexPath.section, row: indexPath.row)! cell.indexPath = indexPath return cell } // MARK: - Private Method private func configration() { delegate = self dataSource = self register(FilterViewCell.self, forCellWithReuseIdentifier: FilterViewCellReusedId) register(FilterSectionHeaderView.self, forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: FilterViewSectionHeaderReusedId) register(UICollectionReusableView.self, forSupplementaryViewOfKind: UICollectionElementKindSectionFooter, withReuseIdentifier: FilterViewSectionFooterReusedId) self.backgroundColor = UIColor.white } /// 便利方法——通过 Section 或 Row 获取对应数据模型 internal func gradeModel(_ section: Int, row: Int? = nil) -> GradeModel? { if row == nil { return self.grades?[section] }else { return self.grades?[section].subset?[row!] } } } // MARK: - FilterSectionHeaderView class FilterSectionHeaderView: UICollectionReusableView { // MARK: - Property /// Section标题 var sectionTitleText: String = L10n.title { didSet { titleLabel.text = sectionTitleText switch sectionTitleText { case "小学": iconView.image = UIImage(asset: .primarySchool) case "初中": iconView.image = UIImage(asset: .juniorHigh) case "高中": iconView.image = UIImage(asset: .seniorHigh) default: break } } } // MARK: - Components private lazy var iconView: UIImageView = { let iconView = UIImageView(imageName: "primarySchool") return iconView }() private lazy var titleLabel: UILabel = { let titleLabel = UILabel( text: "小学", fontSize: 13, textColor: UIColor(named: .HeaderTitle), textAlignment: .center ) titleLabel.sizeToFit() return titleLabel }() // MARK: - Contructed override init(frame: CGRect) { super.init(frame: frame) setupUserInterface() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: - Private Method private func setupUserInterface() { // SubViews addSubview(iconView) addSubview(titleLabel) // AutoLayout iconView.snp.makeConstraints { (maker) -> Void in maker.top.equalTo(self).offset(4) maker.left.equalTo(self) maker.width.equalTo(20) maker.height.equalTo(20) } titleLabel.snp.makeConstraints { (maker) -> Void in maker.centerY.equalTo(iconView) maker.left.equalTo(iconView.snp.right).offset(9) } } }
mit
ca4f807c991cdb09a378466167fa87f3
33.208556
162
0.639987
5.398312
false
false
false
false
malaonline/iOS
mala-ios/View/MemberPrivilegesView/LearningReportCollectionViewCell/LearningReportTopicDataCell.swift
1
6568
// // LearningReportTopicDataCell.swift // mala-ios // // Created by 王新宇 on 16/5/19. // Copyright © 2016年 Mala Online. All rights reserved. // import UIKit import Charts class LearningReportTopicDataCell: MalaBaseReportCardCell { // MARK: - Property /// 题目数据 private var model: [SingleTimeIntervalData] = MalaConfig.topicSampleData() { didSet { resetData() } } override var asSample: Bool { didSet { if asSample { model = MalaConfig.topicSampleData() }else { hideDescription() model = MalaSubjectReport.month_trend } } } // MARK: - Components /// 折线统计视图 private lazy var lineChartView: LineChartView = { let lineChartView = LineChartView() lineChartView.animate(xAxisDuration: 0.65) lineChartView.chartDescription?.text = "" lineChartView.scaleXEnabled = false lineChartView.scaleYEnabled = false lineChartView.dragEnabled = false lineChartView.drawGridBackgroundEnabled = true lineChartView.pinchZoomEnabled = false lineChartView.rightAxis.enabled = false lineChartView.gridBackgroundColor = UIColor.white let xAxis = lineChartView.xAxis xAxis.labelFont = UIFont.systemFont(ofSize: 10) xAxis.labelTextColor = UIColor(named: .ChartLabel) xAxis.drawGridLinesEnabled = false // xAxis.spaceBetweenLabels = 1 xAxis.labelPosition = .bottom xAxis.gridLineDashLengths = [2,2] xAxis.gridColor = UIColor(named: .ChartLegendGray) xAxis.drawGridLinesEnabled = true xAxis.axisMaximum = 6 xAxis.axisMinimum = 0 xAxis.spaceMin = 1 let leftAxis = lineChartView.leftAxis leftAxis.labelFont = UIFont.systemFont(ofSize: 9) leftAxis.labelTextColor = UIColor(named: .HeaderTitle) leftAxis.gridLineDashLengths = [2,2] leftAxis.gridColor = UIColor(named: .ChartLegendGray) leftAxis.drawGridLinesEnabled = true leftAxis.axisMinimum = 0 leftAxis.labelCount = 5 lineChartView.legend.enabled = true lineChartView.legend.form = .circle lineChartView.legend.formSize = 8 lineChartView.legend.font = NSUIFont.systemFont(ofSize: 10) lineChartView.legend.textColor = UIColor(named: .ChartLabel) lineChartView.legend.horizontalAlignment = .right lineChartView.legend.verticalAlignment = .top lineChartView.legend.orientation = .horizontal return lineChartView }() // MARK: - Instance Method override init(frame: CGRect) { super.init(frame: frame) configure() setupUserInterface() setupSampleData() resetData() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: - Private Method private func configure() { titleLabel.text = "题目数据分析" descDetailLabel.text = "学生4月上旬正确率有上升空间,4月下旬经过大量练习题练习,接触题型增多,通过针对性的专项模块练习,5月下旬正确率明显达到了优秀水平。" } private func setupUserInterface() { // SubViews layoutView.addSubview(lineChartView) // Autolayout lineChartView.snp.makeConstraints { (maker) in maker.top.equalTo(layoutView.snp.bottom).multipliedBy(0.18) maker.left.equalTo(descView) maker.right.equalTo(descView) maker.bottom.equalTo(layoutView).multipliedBy(0.68) } } // 重置数据 private func resetData() { var totalIndex = 0 var rightIndex = 0 // 总练习数据 var yValsTotal = model.reversed().map { (data) -> ChartDataEntry in totalIndex += 1 return ChartDataEntry(x: Double(totalIndex), y: Double(data.total_item)) } packageData(&yValsTotal) let totalSet = LineChartDataSet(values: yValsTotal, label: "答题数量") totalSet.lineWidth = 0 totalSet.fillAlpha = 1 totalSet.setColor(UIColor(named: .ReportTopicData)) totalSet.fillColor = UIColor(named: .ReportTopicData) totalSet.drawCirclesEnabled = false totalSet.drawValuesEnabled = false totalSet.drawFilledEnabled = true // 正确练习数据 var yValsRight = model.reversed().map { (data) -> ChartDataEntry in rightIndex += 1 let item = ChartDataEntry(x: Double(rightIndex), y: Double(data.total_item-data.error_item)) return item } packageData(&yValsRight) let rightSet = LineChartDataSet(values: yValsRight, label: "正确数量") rightSet.lineWidth = 0 rightSet.fillAlpha = 1 rightSet.setColor(UIColor(named: .ChartLegendGreen)) rightSet.fillColor = UIColor(named: .ChartLegendGreen) rightSet.drawCirclesEnabled = false rightSet.drawValuesEnabled = false rightSet.drawFilledEnabled = true // let data = LineChartData(xVals: getXVals(), dataSets: [totalSet, rightSet]) let data = LineChartData(dataSets: [totalSet, rightSet]) data.setValueTextColor(UIColor(named: .ChartLabel)) data.setValueFont(UIFont.systemFont(ofSize: 10)) lineChartView.data = data } // 设置样本数据 private func setupSampleData() { } // 包装数据(在数据首尾分别添加空数据,以保持折线图美观性) private func packageData(_ data: inout [ChartDataEntry]) { data.insert(ChartDataEntry(x: 0, y: 0), at: 0) data.append(ChartDataEntry(x: Double(data.count), y: 0)) } // 获取X轴文字信息 private func getXVals() -> [String] { var xVals = model.map { (data) -> String in return String(format: "%d月%@", data.month, data.periodString) } xVals = xVals.reversed() xVals.insert("", at: 0) xVals.append("") return xVals } override func hideDescription() { descDetailLabel.text = "蓝色区域为学生答题数量,区域越大答题数越多。绿色区域为学生正确数量,和蓝色区域的差别越小学生正确率越高。" } }
mit
87c45c128bcd4013b69c5e455370da00
32.155914
104
0.618615
4.491624
false
false
false
false
malaonline/iOS
mala-ios/Tool/Refresher/ThemeRefreshFooterAnimator.swift
1
3604
// // ThemeRefreshFooterAnimator.swift // mala-ios // // Created by 王新宇 on 03/05/2017. // Copyright © 2017 Mala Online. All rights reserved. // import UIKit import ESPullToRefresh public class ThemeRefreshFooterAnimator: UIView, ESRefreshProtocol, ESRefreshAnimatorProtocol { open var loadingMoreDescription: String = "加载更多" open var noMoreDataDescription: String = "没有更多内容啦~" open var loadingDescription: String = "加载中..." // MARK: - Property public var view: UIView { return self } public var insets: UIEdgeInsets = UIEdgeInsets.zero public var trigger: CGFloat = 48.0 public var executeIncremental: CGFloat = 0.0 public var state: ESRefreshViewState = .pullToRefresh public var duration: TimeInterval = 0.3 // MARK: - Components private lazy var imageView: UIImageView = { let imageView = UIImageView(imageName: "nomoreContent") imageView.isHidden = true return imageView }() private let titleLabel: UILabel = { let label = UILabel() label.font = FontFamily.PingFangSC.Regular.font(14) label.textColor = UIColor(named: .protocolGary) label.textAlignment = .center return label }() private let indicatorView: UIActivityIndicatorView = { let indicatorView = UIActivityIndicatorView.init(activityIndicatorStyle: .gray) indicatorView.isHidden = true return indicatorView }() // MARK: - Instance Method override init(frame: CGRect) { super.init(frame: frame) titleLabel.text = loadingMoreDescription addSubview(titleLabel) addSubview(indicatorView) addSubview(imageView) titleLabel.snp.makeConstraints { (maker) in maker.centerX.equalTo(self) maker.height.equalTo(20) maker.top.equalTo(self).offset(12) } indicatorView.snp.makeConstraints { (maker) in maker.centerY.equalTo(titleLabel) maker.right.equalTo(titleLabel.snp.left).offset(-18) } imageView.snp.makeConstraints { (maker) in maker.top.equalTo(titleLabel.snp.bottom).offset(6) maker.centerX.equalTo(self) maker.height.equalTo(120) maker.width.equalTo(220) } } required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: - ESRefresh Protocol public func refreshAnimationBegin(view: ESRefreshComponent) { indicatorView.startAnimating() indicatorView.isHidden = false imageView.isHidden = true } public func refreshAnimationEnd(view: ESRefreshComponent) { indicatorView.stopAnimating() indicatorView.isHidden = true } public func refresh(view: ESRefreshComponent, progressDidChange progress: CGFloat) { } public func refresh(view: ESRefreshComponent, stateDidChange state: ESRefreshViewState) { guard self.state != state else { return } self.state = state switch state { case .refreshing, .autoRefreshing : titleLabel.text = loadingDescription break case .noMoreData: titleLabel.text = noMoreDataDescription imageView.isHidden = false break case .pullToRefresh: titleLabel.text = loadingMoreDescription break default: break } } }
mit
1ee1d7e446642e35b81d595694e897b2
30.289474
95
0.630502
5.052408
false
false
false
false
a7ex/SipHash
tests/SipHashTests/PrimitiveTypeTests.swift
1
13728
// // PrimitiveTypeTests.swift // SipHash // // Created by Károly Lőrentey on 2016-11-14. // Copyright © 2016 Károly Lőrentey. // import XCTest @testable import SipHash // swiftlint:disable trailing_comma class PrimitiveTypeTests: XCTestCase { func testBoolTrue() { let tests: [(Bool, [UInt8])] = [ (false, [0]), (true, [1]) ] for (value, data) in tests { var hash1 = SipHasher() hash1.append(value) let h1 = hash1.finalize() var hash2 = SipHasher() data.withUnsafeBufferPointer { buffer in hash2.append(UnsafeRawBufferPointer(buffer)) } let h2 = hash2.finalize() XCTAssertEqual(h1, h2, "Mismatching hash for \(value)") } } func testInt() { let tests: [(Int, [UInt8])] switch MemoryLayout<UInt>.size { case 8: tests = [ (0, [0, 0, 0, 0, 0, 0, 0, 0]), (1, [1, 0, 0, 0, 0, 0, 0, 0]), (0x0123456789abcdef, [0xef, 0xcd, 0xab, 0x89, 0x67, 0x45, 0x23, 0x01]), (Int.max, [255, 255, 255, 255, 255, 255, 255, 127]), (-1, [255, 255, 255, 255, 255, 255, 255, 255]), (Int.min, [0, 0, 0, 0, 0, 0, 0, 128]) ] case 4: tests = [ (0, [0, 0, 0, 0]), (1, [1, 0, 0, 0]), (0x12345678, [0x78, 0x56, 0x34, 0x12]), (Int.max, [255, 255, 255, 127]), (-1, [255, 255, 255, 255]), (Int.min, [0, 0, 0, 128]) ] default: fatalError() } for (value, data) in tests { var hash1 = SipHasher() hash1.append(value.littleEndian) let h1 = hash1.finalize() var hash2 = SipHasher() data.withUnsafeBufferPointer { buffer in hash2.append(UnsafeRawBufferPointer(buffer)) } let h2 = hash2.finalize() XCTAssertEqual(h1, h2, "Mismatching hash for \(value)") } } func testUInt() { let tests: [(UInt, [UInt8])] switch MemoryLayout<UInt>.size { case 8: tests = [ (0, [0, 0, 0, 0, 0, 0, 0, 0]), (1, [1, 0, 0, 0, 0, 0, 0, 0]), (0x0123456789abcdef, [0xef, 0xcd, 0xab, 0x89, 0x67, 0x45, 0x23, 0x01]), (UInt.max, [255, 255, 255, 255, 255, 255, 255, 255]) ] case 4: tests = [ (0, [0, 0, 0, 0]), (1, [1, 0, 0, 0]), (0x12345678, [0x78, 0x56, 0x34, 0x12]), (0xffffffff, [255, 255, 255, 255]) ] default: fatalError() } for (value, data) in tests { var hash1 = SipHasher() hash1.append(value.littleEndian) let h1 = hash1.finalize() var hash2 = SipHasher() data.withUnsafeBufferPointer { buffer in hash2.append(UnsafeRawBufferPointer(buffer)) } let h2 = hash2.finalize() XCTAssertEqual(h1, h2, "Mismatching hash for \(value)") } } func testInt64() { let tests: [(Int64, [UInt8])] = [ (0, [0, 0, 0, 0, 0, 0, 0, 0]), (1, [1, 0, 0, 0, 0, 0, 0, 0]), (0x0123456789abcdef, [0xef, 0xcd, 0xab, 0x89, 0x67, 0x45, 0x23, 0x01]), (Int64.max, [255, 255, 255, 255, 255, 255, 255, 127]), (-1, [255, 255, 255, 255, 255, 255, 255, 255]), (Int64.min, [0, 0, 0, 0, 0, 0, 0, 128]) ] for (value, data) in tests { var hash1 = SipHasher() hash1.append(value.littleEndian) let h1 = hash1.finalize() var hash2 = SipHasher() data.withUnsafeBufferPointer { buffer in hash2.append(UnsafeRawBufferPointer(buffer)) } let h2 = hash2.finalize() XCTAssertEqual(h1, h2, "Mismatching hash for \(value)") } } func testUInt64() { let tests: [(UInt64, [UInt8])] = [ (0, [0, 0, 0, 0, 0, 0, 0, 0]), (1, [1, 0, 0, 0, 0, 0, 0, 0]), (0x0123456789abcdef, [0xef, 0xcd, 0xab, 0x89, 0x67, 0x45, 0x23, 0x01]), (UInt64.max, [255, 255, 255, 255, 255, 255, 255, 255]) ] for (value, data) in tests { var hash1 = SipHasher() hash1.append(value.littleEndian) let h1 = hash1.finalize() var hash2 = SipHasher() data.withUnsafeBufferPointer { buffer in hash2.append(UnsafeRawBufferPointer(buffer)) } let h2 = hash2.finalize() XCTAssertEqual(h1, h2, "Mismatching hash for \(value)") } } func testInt32() { let tests: [(Int32, [UInt8])] = [ (0, [0, 0, 0, 0]), (1, [1, 0, 0, 0]), (0x12345678, [0x78, 0x56, 0x34, 0x12]), (Int32.max, [255, 255, 255, 127]), (-1, [255, 255, 255, 255]), (Int32.min, [0, 0, 0, 128]), ] for (value, data) in tests { var hash1 = SipHasher() hash1.append(value.littleEndian) let h1 = hash1.finalize() var hash2 = SipHasher() data.withUnsafeBufferPointer { buffer in hash2.append(UnsafeRawBufferPointer(buffer)) } let h2 = hash2.finalize() XCTAssertEqual(h1, h2, "Mismatching hash for \(value)") } } func testUInt32() { let tests: [(UInt32, [UInt8])] = [ (0, [0, 0, 0, 0]), (1, [1, 0, 0, 0]), (0x12345678, [0x78, 0x56, 0x34, 0x12]), (0xffffffff, [255, 255, 255, 255]) ] for (value, data) in tests { var hash1 = SipHasher() hash1.append(value.littleEndian) let h1 = hash1.finalize() var hash2 = SipHasher() data.withUnsafeBufferPointer { buffer in hash2.append(UnsafeRawBufferPointer(buffer)) } let h2 = hash2.finalize() XCTAssertEqual(h1, h2, "Mismatching hash for \(value)") } } func testInt16() { let tests: [(Int16, [UInt8])] = [ (0, [0, 0]), (1, [1, 0]), (0x1234, [0x34, 0x12]), (0x7fff, [255, 127]), (-1, [0xff, 0xff]), (-42, [214, 0xff]), (Int16.min, [0x00, 0x80]) ] for (value, data) in tests { var hash1 = SipHasher() hash1.append(value.littleEndian) let h1 = hash1.finalize() var hash2 = SipHasher() data.withUnsafeBufferPointer { buffer in hash2.append(UnsafeRawBufferPointer(buffer)) } let h2 = hash2.finalize() XCTAssertEqual(h1, h2, "Mismatching hash for \(value)") } } func testUInt16() { let tests: [(UInt16, [UInt8])] = [ (0, [0, 0]), (1, [1, 0]), (0x1234, [0x34, 0x12]), (0xffff, [255, 255]) ] for (value, data) in tests { var hash1 = SipHasher() hash1.append(value.littleEndian) let h1 = hash1.finalize() var hash2 = SipHasher() data.withUnsafeBufferPointer { buffer in hash2.append(UnsafeRawBufferPointer(buffer)) } let h2 = hash2.finalize() XCTAssertEqual(h1, h2, "Mismatching hash for \(value)") } } func testInt8() { let tests: [(Int8, [UInt8])] = [ (0, [0]), (1, [1]), (42, [42]), (127, [127]), (-1, [255]), (-42, [214]), (-128, [128]) ] for (value, data) in tests { var hash1 = SipHasher() hash1.append(value) let h1 = hash1.finalize() var hash2 = SipHasher() data.withUnsafeBufferPointer { buffer in hash2.append(UnsafeRawBufferPointer(buffer)) } let h2 = hash2.finalize() XCTAssertEqual(h1, h2, "Mismatching hash for \(value)") } } func testUInt8() { let tests: [(UInt8, [UInt8])] = [ (0, [0]), (1, [1]), (42, [42]), (255, [255]) ] for (value, data) in tests { var hash1 = SipHasher() hash1.append(value) let h1 = hash1.finalize() var hash2 = SipHasher() data.withUnsafeBufferPointer { buffer in hash2.append(UnsafeRawBufferPointer(buffer)) } let h2 = hash2.finalize() XCTAssertEqual(h1, h2, "Mismatching hash for \(value)") } } func testFloat() { let zeroA: Int = { var h = SipHasher() h.append(0.0 as Float) return h.finalize() }() let zeroB: Int = { var h = SipHasher() h.append(-0.0 as Float) return h.finalize() }() XCTAssertEqual(zeroA, zeroB, "+0.0 and -0.0 should have the same hash value") let oneHash: Int = { var h = SipHasher() h.append(1.0 as Float) return h.finalize() }() let oneExpected: Int = { var h = SipHasher() let d = [UInt8]([0, 0, 128, 63]) d.withUnsafeBufferPointer { b in h.append(UnsafeRawBufferPointer(b)) } return h.finalize() }() XCTAssertEqual(oneHash, oneExpected) } func testDouble() { let zeroA: Int = { var h = SipHasher() h.append(0.0 as Double) return h.finalize() }() let zeroB: Int = { var h = SipHasher() h.append(-0.0 as Double) return h.finalize() }() XCTAssertEqual(zeroA, zeroB, "+0.0 and -0.0 should have the same hash value") let oneHash: Int = { var h = SipHasher() h.append(1.0 as Double) return h.finalize() }() let oneExpected: Int = { var h = SipHasher() let d = Array<UInt8>([0, 0, 0, 0, 0, 0, 240, 63]) d.withUnsafeBufferPointer { b in h.append(UnsafeRawBufferPointer(b)) } return h.finalize() }() XCTAssertEqual(oneHash, oneExpected) } #if arch(i386) || arch(x86_64) func testFloat80() { let f1: Float80 = 0.0 let f2: Float80 = -0.0 XCTAssertEqual(f1, f2) let zeroA: Int = { var h = SipHasher() h.append(f1) return h.finalize() }() let zeroB: Int = { var h = SipHasher() h.append(f2) return h.finalize() }() XCTAssertEqual(zeroA, zeroB, "+0.0 and -0.0 should have the same hash value") let oneHash: Int = { var h = SipHasher() h.append(1.0 as Float80) return h.finalize() }() let oneExpected: Int = { var h = SipHasher() let d = Array<UInt8>([0, 0, 0, 0, 0, 0, 0, 128, 255, 63]) d.withUnsafeBufferPointer { b in h.append(UnsafeRawBufferPointer(b)) } return h.finalize() }() XCTAssertEqual(oneHash, oneExpected) } #endif #if os(macOS) || os(iOS) || os(watchOS) || os(tvOS) func testCGFloat() { let zeroA: Int = { var h = SipHasher() h.append(0.0 as CGFloat) return h.finalize() }() let zeroB: Int = { var h = SipHasher() h.append(-0.0 as CGFloat) return h.finalize() }() XCTAssertEqual(zeroA, zeroB, "+0.0 and -0.0 should have the same hash value") let oneHash: Int = { var h = SipHasher() h.append(1.0 as CGFloat) return h.finalize() }() let oneExpected: Int = { var h = SipHasher() let d: Array<UInt8> if CGFloat.NativeType.self == Double.self { d = [0, 0, 0, 0, 0, 0, 240, 63] } else if CGFloat.NativeType.self == Float.self { d = [0, 0, 128, 63] } else { fatalError() } d.withUnsafeBufferPointer { b in h.append(UnsafeRawBufferPointer(b)) } return h.finalize() }() XCTAssertEqual(oneHash, oneExpected) } #endif func testOptional_nil() { let expected: Int = { var hasher = SipHasher() hasher.append(0 as UInt8) return hasher.finalize() }() let actual: Int = { var hasher = SipHasher() hasher.append(nil as Int?) return hasher.finalize() }() XCTAssertEqual(actual, expected) } func testOptional_nonnil() { let expected: Int = { var hasher = SipHasher() hasher.append(1 as UInt8) hasher.append(42) return hasher.finalize() }() let actual: Int = { var hasher = SipHasher() hasher.append(42 as Int?) return hasher.finalize() }() XCTAssertEqual(actual, expected) } }
mit
3c51bc5d1ec3bbb295ad1a46cc2da67f
28.074153
87
0.455513
3.889739
false
true
false
false
xiaowen707447083/startDemo
个人测试项目汇总/普通组件测试/ReactiveCocoaTextSwift/Pods/ReactiveCocoa/ReactiveCocoa/Swift/Flatten.swift
39
19053
// // Flatten.swift // ReactiveCocoa // // Created by Neil Pankey on 11/30/15. // Copyright © 2015 GitHub. All rights reserved. // /// Describes how multiple producers should be joined together. public enum FlattenStrategy: Equatable { /// The producers should be merged, so that any value received on any of the /// input producers will be forwarded immediately to the output producer. /// /// The resulting producer will complete only when all inputs have completed. case Merge /// The producers should be concatenated, so that their values are sent in the /// order of the producers themselves. /// /// The resulting producer will complete only when all inputs have completed. case Concat /// Only the events from the latest input producer should be considered for /// the output. Any producers received before that point will be disposed of. /// /// The resulting producer will complete only when the producer-of-producers and /// the latest producer has completed. case Latest } extension SignalType where Value: SignalProducerType, Error == Value.Error { /// Flattens the inner producers sent upon `signal` (into a single signal of /// values), according to the semantics of the given strategy. /// /// If `signal` or an active inner producer fails, the returned signal will /// forward that failure immediately. /// /// `Interrupted` events on inner producers will be treated like `Completed` /// events on inner producers. @warn_unused_result(message="Did you forget to call `observe` on the signal?") public func flatten(strategy: FlattenStrategy) -> Signal<Value.Value, Error> { switch strategy { case .Merge: return self.merge() case .Concat: return self.concat() case .Latest: return self.switchToLatest() } } } extension SignalProducerType where Value: SignalProducerType, Error == Value.Error { /// Flattens the inner producers sent upon `producer` (into a single producer of /// values), according to the semantics of the given strategy. /// /// If `producer` or an active inner producer fails, the returned producer will /// forward that failure immediately. /// /// `Interrupted` events on inner producers will be treated like `Completed` /// events on inner producers. @warn_unused_result(message="Did you forget to call `start` on the producer?") public func flatten(strategy: FlattenStrategy) -> SignalProducer<Value.Value, Error> { switch strategy { case .Merge: return self.merge() case .Concat: return self.concat() case .Latest: return self.switchToLatest() } } } extension SignalType where Value: SignalType, Error == Value.Error { /// Flattens the inner signals sent upon `signal` (into a single signal of /// values), according to the semantics of the given strategy. /// /// If `signal` or an active inner signal emits an error, the returned /// signal will forward that error immediately. /// /// `Interrupted` events on inner signals will be treated like `Completed` /// events on inner signals. @warn_unused_result(message="Did you forget to call `observe` on the signal?") public func flatten(strategy: FlattenStrategy) -> Signal<Value.Value, Error> { return self.map(SignalProducer.init).flatten(strategy) } } extension SignalProducerType where Value: SignalType, Error == Value.Error { /// Flattens the inner signals sent upon `producer` (into a single producer of /// values), according to the semantics of the given strategy. /// /// If `producer` or an active inner signal emits an error, the returned /// producer will forward that error immediately. /// /// `Interrupted` events on inner signals will be treated like `Completed` /// events on inner signals. @warn_unused_result(message="Did you forget to call `start` on the producer?") public func flatten(strategy: FlattenStrategy) -> SignalProducer<Value.Value, Error> { return self.map(SignalProducer.init).flatten(strategy) } } extension SignalType where Value: SignalProducerType, Error == Value.Error { /// Returns a signal which sends all the values from producer signal emitted from /// `signal`, waiting until each inner producer completes before beginning to /// send the values from the next inner producer. /// /// If any of the inner producers fail, the returned signal will forward /// that failure immediately /// /// The returned signal completes only when `signal` and all producers /// emitted from `signal` complete. private func concat() -> Signal<Value.Value, Error> { return Signal<Value.Value, Error> { relayObserver in let disposable = CompositeDisposable() let relayDisposable = CompositeDisposable() disposable += relayDisposable disposable += self.observeConcat(relayObserver, relayDisposable) return disposable } } private func observeConcat(observer: Observer<Value.Value, Error>, _ disposable: CompositeDisposable? = nil) -> Disposable? { let state = ConcatState(observer: observer, disposable: disposable) return self.observe { event in switch event { case let .Next(value): state.enqueueSignalProducer(value.producer) case let .Failed(error): observer.sendFailed(error) case .Completed: // Add one last producer to the queue, whose sole job is to // "turn out the lights" by completing `observer`. state.enqueueSignalProducer(SignalProducer.empty.on(completed: { observer.sendCompleted() })) case .Interrupted: observer.sendInterrupted() } } } } extension SignalProducerType where Value: SignalProducerType, Error == Value.Error { /// Returns a producer which sends all the values from each producer emitted from /// `producer`, waiting until each inner producer completes before beginning to /// send the values from the next inner producer. /// /// If any of the inner producers emit an error, the returned producer will emit /// that error. /// /// The returned producer completes only when `producer` and all producers /// emitted from `producer` complete. private func concat() -> SignalProducer<Value.Value, Error> { return SignalProducer<Value.Value, Error> { observer, disposable in self.startWithSignal { signal, signalDisposable in disposable += signalDisposable signal.observeConcat(observer, disposable) } } } } extension SignalProducerType { /// `concat`s `next` onto `self`. @warn_unused_result(message="Did you forget to call `start` on the producer?") public func concat(next: SignalProducer<Value, Error>) -> SignalProducer<Value, Error> { return SignalProducer<SignalProducer<Value, Error>, Error>(values: [self.producer, next]).flatten(.Concat) } } private final class ConcatState<Value, Error: ErrorType> { /// The observer of a started `concat` producer. let observer: Observer<Value, Error> /// The top level disposable of a started `concat` producer. let disposable: CompositeDisposable? /// The active producer, if any, and the producers waiting to be started. let queuedSignalProducers: Atomic<[SignalProducer<Value, Error>]> = Atomic([]) init(observer: Signal<Value, Error>.Observer, disposable: CompositeDisposable?) { self.observer = observer self.disposable = disposable } func enqueueSignalProducer(producer: SignalProducer<Value, Error>) { if let d = disposable where d.disposed { return } var shouldStart = true queuedSignalProducers.modify { // An empty queue means the concat is idle, ready & waiting to start // the next producer. var queue = $0 shouldStart = queue.isEmpty queue.append(producer) return queue } if shouldStart { startNextSignalProducer(producer) } } func dequeueSignalProducer() -> SignalProducer<Value, Error>? { if let d = disposable where d.disposed { return nil } var nextSignalProducer: SignalProducer<Value, Error>? queuedSignalProducers.modify { // Active producers remain in the queue until completed. Since // dequeueing happens at completion of the active producer, the // first producer in the queue can be removed. var queue = $0 if !queue.isEmpty { queue.removeAtIndex(0) } nextSignalProducer = queue.first return queue } return nextSignalProducer } /// Subscribes to the given signal producer. func startNextSignalProducer(signalProducer: SignalProducer<Value, Error>) { signalProducer.startWithSignal { signal, disposable in let handle = self.disposable?.addDisposable(disposable) ?? nil signal.observe { event in switch event { case .Completed, .Interrupted: handle?.remove() if let nextSignalProducer = self.dequeueSignalProducer() { self.startNextSignalProducer(nextSignalProducer) } default: self.observer.action(event) } } } } } extension SignalType where Value: SignalProducerType, Error == Value.Error { /// Merges a `signal` of SignalProducers down into a single signal, biased toward the producer /// added earlier. Returns a Signal that will forward events from the inner producers as they arrive. private func merge() -> Signal<Value.Value, Error> { return Signal<Value.Value, Error> { relayObserver in let disposable = CompositeDisposable() let relayDisposable = CompositeDisposable() disposable += relayDisposable disposable += self.observeMerge(relayObserver, relayDisposable) return disposable } } private func observeMerge(observer: Observer<Value.Value, Error>, _ disposable: CompositeDisposable) -> Disposable? { let inFlight = Atomic(1) let decrementInFlight: () -> () = { let orig = inFlight.modify { $0 - 1 } if orig == 1 { observer.sendCompleted() } } return self.observe { event in switch event { case let .Next(producer): producer.startWithSignal { innerSignal, innerDisposable in inFlight.modify { $0 + 1 } let handle = disposable.addDisposable(innerDisposable) innerSignal.observe { event in switch event { case .Completed, .Interrupted: handle.remove() decrementInFlight() default: observer.action(event) } } } case let .Failed(error): observer.sendFailed(error) case .Completed: decrementInFlight() case .Interrupted: observer.sendInterrupted() } } } } extension SignalProducerType where Value: SignalProducerType, Error == Value.Error { /// Merges a `signal` of SignalProducers down into a single signal, biased toward the producer /// added earlier. Returns a Signal that will forward events from the inner producers as they arrive. private func merge() -> SignalProducer<Value.Value, Error> { return SignalProducer<Value.Value, Error> { relayObserver, disposable in self.startWithSignal { signal, signalDisposable in disposable.addDisposable(signalDisposable) signal.observeMerge(relayObserver, disposable) } } } } extension SignalType { /// Merges the given signals into a single `Signal` that will emit all values /// from each of them, and complete when all of them have completed. @warn_unused_result(message="Did you forget to call `observe` on the signal?") public static func merge<S: SequenceType where S.Generator.Element == Signal<Value, Error>>(signals: S) -> Signal<Value, Error> { let producer = SignalProducer<Signal<Value, Error>, Error>(values: signals) var result: Signal<Value, Error>! producer.startWithSignal { (signal, _) in result = signal.flatten(.Merge) } return result } } extension SignalType where Value: SignalProducerType, Error == Value.Error { /// Returns a signal that forwards values from the latest signal sent on /// `signal`, ignoring values sent on previous inner signal. /// /// An error sent on `signal` or the latest inner signal will be sent on the /// returned signal. /// /// The returned signal completes when `signal` and the latest inner /// signal have both completed. private func switchToLatest() -> Signal<Value.Value, Error> { return Signal<Value.Value, Error> { observer in let composite = CompositeDisposable() let serial = SerialDisposable() composite += serial composite += self.observeSwitchToLatest(observer, serial) return composite } } private func observeSwitchToLatest(observer: Observer<Value.Value, Error>, _ latestInnerDisposable: SerialDisposable) -> Disposable? { let state = Atomic(LatestState<Value, Error>()) return self.observe { event in switch event { case let .Next(innerProducer): innerProducer.startWithSignal { innerSignal, innerDisposable in state.modify { // When we replace the disposable below, this prevents the // generated Interrupted event from doing any work. var state = $0 state.replacingInnerSignal = true return state } latestInnerDisposable.innerDisposable = innerDisposable state.modify { var state = $0 state.replacingInnerSignal = false state.innerSignalComplete = false return state } innerSignal.observe { event in switch event { case .Interrupted: // If interruption occurred as a result of a new producer // arriving, we don't want to notify our observer. let original = state.modify { var state = $0 if !state.replacingInnerSignal { state.innerSignalComplete = true } return state } if !original.replacingInnerSignal && original.outerSignalComplete { observer.sendCompleted() } case .Completed: let original = state.modify { var state = $0 state.innerSignalComplete = true return state } if original.outerSignalComplete { observer.sendCompleted() } default: observer.action(event) } } } case let .Failed(error): observer.sendFailed(error) case .Completed: let original = state.modify { var state = $0 state.outerSignalComplete = true return state } if original.innerSignalComplete { observer.sendCompleted() } case .Interrupted: observer.sendInterrupted() } } } } extension SignalProducerType where Value: SignalProducerType, Error == Value.Error { /// Returns a signal that forwards values from the latest signal sent on /// `signal`, ignoring values sent on previous inner signal. /// /// An error sent on `signal` or the latest inner signal will be sent on the /// returned signal. /// /// The returned signal completes when `signal` and the latest inner /// signal have both completed. private func switchToLatest() -> SignalProducer<Value.Value, Error> { return SignalProducer<Value.Value, Error> { observer, disposable in let latestInnerDisposable = SerialDisposable() disposable.addDisposable(latestInnerDisposable) self.startWithSignal { signal, signalDisposable in disposable += signalDisposable disposable += signal.observeSwitchToLatest(observer, latestInnerDisposable) } } } } private struct LatestState<Value, Error: ErrorType> { var outerSignalComplete: Bool = false var innerSignalComplete: Bool = true var replacingInnerSignal: Bool = false } extension SignalType { /// Maps each event from `signal` to a new signal, then flattens the /// resulting producers (into a signal of values), according to the /// semantics of the given strategy. /// /// If `signal` or any of the created producers fail, the returned signal /// will forward that failure immediately. @warn_unused_result(message="Did you forget to call `observe` on the signal?") public func flatMap<U>(strategy: FlattenStrategy, transform: Value -> SignalProducer<U, Error>) -> Signal<U, Error> { return map(transform).flatten(strategy) } /// Maps each event from `signal` to a new signal, then flattens the /// resulting signals (into a signal of values), according to the /// semantics of the given strategy. /// /// If `signal` or any of the created signals emit an error, the returned /// signal will forward that error immediately. @warn_unused_result(message="Did you forget to call `observe` on the signal?") public func flatMap<U>(strategy: FlattenStrategy, transform: Value -> Signal<U, Error>) -> Signal<U, Error> { return map(transform).flatten(strategy) } } extension SignalProducerType { /// Maps each event from `self` to a new producer, then flattens the /// resulting producers (into a producer of values), according to the /// semantics of the given strategy. /// /// If `self` or any of the created producers fail, the returned producer /// will forward that failure immediately. @warn_unused_result(message="Did you forget to call `start` on the producer?") public func flatMap<U>(strategy: FlattenStrategy, transform: Value -> SignalProducer<U, Error>) -> SignalProducer<U, Error> { return map(transform).flatten(strategy) } /// Maps each event from `self` to a new producer, then flattens the /// resulting signals (into a producer of values), according to the /// semantics of the given strategy. /// /// If `self` or any of the created signals emit an error, the returned /// producer will forward that error immediately. @warn_unused_result(message="Did you forget to call `start` on the producer?") public func flatMap<U>(strategy: FlattenStrategy, transform: Value -> Signal<U, Error>) -> SignalProducer<U, Error> { return map(transform).flatten(strategy) } } extension SignalType { /// Catches any failure that may occur on the input signal, mapping to a new producer /// that starts in its place. @warn_unused_result(message="Did you forget to call `observe` on the signal?") public func flatMapError<F>(handler: Error -> SignalProducer<Value, F>) -> Signal<Value, F> { return Signal { observer in self.observeFlatMapError(handler, observer, SerialDisposable()) } } private func observeFlatMapError<F>(handler: Error -> SignalProducer<Value, F>, _ observer: Observer<Value, F>, _ serialDisposable: SerialDisposable) -> Disposable? { return self.observe { event in switch event { case let .Next(value): observer.sendNext(value) case let .Failed(error): handler(error).startWithSignal { signal, disposable in serialDisposable.innerDisposable = disposable signal.observe(observer) } case .Completed: observer.sendCompleted() case .Interrupted: observer.sendInterrupted() } } } } extension SignalProducerType { /// Catches any failure that may occur on the input producer, mapping to a new producer /// that starts in its place. @warn_unused_result(message="Did you forget to call `start` on the producer?") public func flatMapError<F>(handler: Error -> SignalProducer<Value, F>) -> SignalProducer<Value, F> { return SignalProducer { observer, disposable in let serialDisposable = SerialDisposable() disposable.addDisposable(serialDisposable) self.startWithSignal { signal, signalDisposable in serialDisposable.innerDisposable = signalDisposable signal.observeFlatMapError(handler, observer, serialDisposable) } } } }
apache-2.0
8055b4a4dd8a6282e81501eaaac39572
32.247818
167
0.717023
4.155071
false
false
false
false
BlenderSleuth/Unlokit
Unlokit/Nodes/GravityNode.swift
1
1376
// // GravityNode.swift // Unlokit // // Created by Ben Sutherland on 26/1/17. // Copyright © 2017 blendersleuthdev. All rights reserved. // import SpriteKit class GravityNode: SKSpriteNode { let radius: CGFloat = 500 required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) let gravityWave = SKShapeNode(circleOfRadius: radius) gravityWave.strokeColor = .black gravityWave.lineWidth = 10 gravityWave.fillColor = .clear gravityWave.alpha = 0 addChild(gravityWave) let group1 = SKAction.group([SKAction.scale(to: 1, duration: 0), SKAction.fadeOut(withDuration: 0)]) let group2 = SKAction.group([SKAction.fadeIn(withDuration: 0.5), SKAction.scale(to: 0.01, duration: 2)]) let sequence1 = SKAction.sequence([group1, group2]) let action = SKAction.repeatForever(sequence1) let fadeIn = SKAction.fadeIn(withDuration: 0.4) let sequence2 = SKAction.group([fadeIn, action]) gravityWave.run(sequence2) let fieldRegion = SKRegion(radius: Float(radius)) let field = SKFieldNode.radialGravityField() field.region = fieldRegion field.strength = 550 field.falloff = 3 field.categoryBitMask = Category.fanGravityField addChild(field) // Debug node //let debugNode = SKShapeNode(circleOfRadius: size.width * 5) //debugNode.strokeColor = .blue //debugNode.lineWidth = 5 //addChild(debugNode) } }
gpl-3.0
ff2e0dedb77511d991e35978827aeff4
25.960784
106
0.724364
3.472222
false
false
false
false
sudiptasahoo/IVP-Luncheon
IVP Luncheon/SSCenteredButton.swift
1
1399
// // SSCenteredButton.swift // IVP Luncheon // // Created by Sudipta on 30/05/17. // Copyright © 2017 Sudipta Sahoo <[email protected]>. This file is part of Indus Valley Partners interview process. This file can not be copied and/or distributed without the express permission of Sudipta Sahoo. All rights reserved. // import UIKit class SSCenteredButton: UIButton { override func titleRect(forContentRect contentRect: CGRect) -> CGRect { let rect = super.titleRect(forContentRect: contentRect) let imageRect = super.imageRect(forContentRect: contentRect) return CGRect(x: 0, y: imageRect.maxY + 10, width: contentRect.width, height: rect.height) } override func imageRect(forContentRect contentRect: CGRect) -> CGRect { let rect = super.imageRect(forContentRect: contentRect) let titleRect = self.titleRect(forContentRect: contentRect) return CGRect(x: contentRect.width/2.0 - rect.width/2.0, y: (contentRect.height - titleRect.height)/2.0 - rect.height/2.0, width: rect.width, height: rect.height) } override init(frame: CGRect) { super.init(frame: frame) centerTitleLabel() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) centerTitleLabel() } private func centerTitleLabel() { self.titleLabel?.textAlignment = .center } }
apache-2.0
f87f4cf36b53a306e1709d7638534e9c
31.511628
236
0.692418
4.123894
false
false
false
false
KingAce023/DreamChasers
Navigate/AppDelegate.swift
1
5140
// // AppDelegate.swift // RIghtSideMenuOpen // // Created by Parth Changela on 13/11/16. // Copyright © 2016 Parth Changela. All rights reserved. // import UIKit import CoreData import Firebase import UserNotifications @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. FirebaseApp.configure() UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .badge, .sound], completionHandler: {(didAllow, error) in}) UNUserNotificationCenter.current().delegate = self return true } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } //----------------------------------------------------- // MARK: - Core Data stack lazy var persistentContainer: NSPersistentContainer = { /* The persistent container for the application. This implementation creates and returns a container, having loaded the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail. */ let container = NSPersistentContainer(name: "SearchBar") container.loadPersistentStores(completionHandler: { (storeDescription, error) in if let error = error as NSError? { // Replace this implementation with code to handle the error appropriately. // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. /* Typical reasons for an error here include: * The parent directory does not exist, cannot be created, or disallows writing. * The persistent store is not accessible, due to permissions or data protection when the device is locked. * The device is out of space. * The store could not be migrated to the current model version. Check the error message to determine what the actual problem was. */ fatalError("Unresolved error \(error), \(error.userInfo)") } }) return container }() // MARK: - Core Data Saving support func saveContext () { let context = persistentContainer.viewContext if context.hasChanges { do { try context.save() } catch { // Replace this implementation with code to handle the error appropriately. // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. let nserror = error as NSError fatalError("Unresolved error \(nserror), \(nserror.userInfo)") } } } } extension AppDelegate: UNUserNotificationCenterDelegate{ func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) { completionHandler(.alert) } }
mit
e6ca89f0fb379ec0e04d7d314cbab2c7
48.413462
285
0.685931
5.996499
false
false
false
false
Snowgan/WeiboDemo
WeiboDemo/XLHomeTableViewController.swift
1
5322
// // XLHomeTableViewController.swift // WeiboDemo // // Created by Jennifer on 29/11/15. // Copyright © 2015 Snowgan. All rights reserved. // import UIKit import XLRefreshSwift class XLHomeTableViewController: UITableViewController { // var isLogin = false var homeStatuses = XLMultiStatus() override func viewDidLoad() { super.viewDidLoad() navigationItem.leftBarButtonItem = UIBarButtonItem(normalImage: UIImage(named: "navigationbar_friendsearch"), highLightedImage: UIImage(named: "navigationbar_friendsearch_highlighted"), target: self, action: nil) navigationItem.rightBarButtonItem = UIBarButtonItem(normalImage: UIImage(named: "navigationbar_pop"), highLightedImage: UIImage(named: "navigationbar_pop_highlighted"), target: self, action: nil) navigationItem.title = NSUserDefaults.standardUserDefaults().objectForKey("userName") as? String tableView.registerClass(XLWeiboCell.self, forCellReuseIdentifier: kXLHomeCellIdentifier) tableView.separatorStyle = .None // self.tableView.separatorInset = UIEdgeInsets(top: 5, left: 10, bottom: 0, right: 10) tableView.backgroundColor = bgColor setupRefresh() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Table view data source override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // #warning Incomplete implementation, return the number of rows return homeStatuses.statusArr.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier(kXLHomeCellIdentifier, forIndexPath: indexPath) as! XLWeiboCell let row = indexPath.row cell.status = homeStatuses.statusArr[row] cell.layout = homeStatuses.statusLayoutArr[row] return cell } override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { let cellH = homeStatuses.statusLayoutArr[indexPath.row].height return cellH + 31 + 7 } /* // 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. } */ func setupRefresh() { tableView.xlheader = XLRefreshHeader(action: { self.refreshStatuses(true) }) tableView.xlfooter = XLRefreshFooter(action: { self.loadMore() }) refreshStatuses(false) } func refreshStatuses(hasHeader: Bool) { let urlString = "https://api.weibo.com/2/statuses/home_timeline.json" var queryDic = [String: AnyObject]() queryDic["access_token"] = NSUserDefaults.standardUserDefaults().objectForKey("accessToken")! XLWeiboAPI.sharedWeiboAPI.requestWithURL(urlString, params: queryDic) { [unowned self] (json) -> () in print("\(json)") self.homeStatuses = XLMultiStatus(withJSON: json) dispatch_async(dispatch_get_main_queue(), { self.tableView.reloadData() if hasHeader { self.tableView.endHeaderRefresh() } }) } } func loadMore() { let urlString = "https://api.weibo.com/2/statuses/home_timeline.json" var queryDic = [String: AnyObject]() queryDic["access_token"] = NSUserDefaults.standardUserDefaults().objectForKey("accessToken")! queryDic["max_id"] = homeStatuses.lastStatusID XLWeiboAPI.sharedWeiboAPI.requestWithURL(urlString, params: queryDic) { [unowned self] (json) -> () in print("\(json)") let loadStatuses = XLMultiStatus(withJSON: json) loadStatuses.statusArr.removeAtIndex(0) loadStatuses.statusLayoutArr.removeAtIndex(0) self.homeStatuses.lastStatusID = loadStatuses.lastStatusID self.homeStatuses.statusArr.appendContentsOf(loadStatuses.statusArr) self.homeStatuses.statusLayoutArr.appendContentsOf(loadStatuses.statusLayoutArr) dispatch_async(dispatch_get_main_queue(), { self.tableView.reloadData() self.tableView.endFooterRefresh() }) } } } extension UIBarButtonItem { convenience init(normalImage: UIImage?, highLightedImage: UIImage?, target: AnyObject?, action: Selector) { let barButton = UIButton() barButton.setImage(normalImage, forState: .Normal) barButton.setImage(highLightedImage, forState: .Highlighted) barButton.bounds.size = barButton.currentImage!.size barButton.addTarget(target, action: action, forControlEvents: .TouchUpInside) self.init(customView: barButton) } }
mit
c0c184851e927eaab5b6ff3ce1574a8b
37.839416
220
0.657771
5.038826
false
false
false
false
cheeyi/flappy-swift
Flappy Swift/GameScene.swift
1
12325
// // GameScene.swift // Flappy Swift // // Created by Julio Montoya on 13/07/14. // Copyright (c) 2015 Julio Montoya. All rights reserved. // // Copyright (c) 2015 AvionicsDev // // 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 SpriteKit // MARK: Math Helpers extension Float { static func clamp(min: CGFloat, max: CGFloat, value: CGFloat) -> CGFloat { if (value > max) { return max } else if (value < min) { return min } else { return value } } static func range(min: CGFloat, max: CGFloat) -> CGFloat { return CGFloat(Float(arc4random()) / 0xFFFFFFFF) * (max - min) + min } } extension CGFloat { func deg_to_rad() -> CGFloat { return CGFloat(M_PI) * self / 180.0 } } class GameScene: SKScene, SKPhysicsContactDelegate { // MARK: Properties // Bird var bird: SKSpriteNode! // Background var background: SKNode! let background_speed = 100.0 // Score var score = 0 var label_score: SKLabelNode! // Instructions var instructions: SKSpriteNode! // Pipe origin let pipe_origin_x: CGFloat = 382.0 // Time Values var delta = NSTimeInterval(0) var last_update_time = NSTimeInterval(0) // Floor height let floor_distance: CGFloat = 72.0 // Physics let FSBoundaryCategory: UInt32 = 1 << 0 let FSPlayerCategory: UInt32 = 1 << 1 let FSPipeCategory: UInt32 = 1 << 2 let FSGapCategory: UInt32 = 1 << 3 // States enum FSGameState: Int { case FSGameStateStarting case FSGameStatePlaying case FSGameStateEnded } var state: FSGameState = .FSGameStateStarting // MARK: - SKScene Initializacion override func didMoveToView(view: SKView) { initWorld() initBackground() initBird() initHUD() runAction(SKAction.repeatActionForever(SKAction.sequence([SKAction.waitForDuration(2.0), SKAction.runBlock { self.initPipes()}]))) } // MARK: - Init Physics func initWorld() { physicsWorld.contactDelegate = self physicsWorld.gravity = CGVector(dx: 0.0, dy: -5.0) // -5G of gravity physicsBody = SKPhysicsBody(edgeLoopFromRect: CGRect(x: 0.0, y: floor_distance, width: size.width, height: size.height - floor_distance)) physicsBody?.categoryBitMask = FSBoundaryCategory physicsBody?.collisionBitMask = FSPlayerCategory } // MARK: - Init Bird func initBird() { bird = SKSpriteNode(imageNamed: "bird1") bird.position = CGPoint(x: 100.0, y: CGRectGetMidY(frame)) bird.physicsBody = SKPhysicsBody(circleOfRadius: bird.size.width/2.5) bird.physicsBody?.categoryBitMask = FSPlayerCategory bird.physicsBody?.contactTestBitMask = FSPipeCategory | FSGapCategory | FSBoundaryCategory bird.physicsBody?.collisionBitMask = FSPipeCategory | FSBoundaryCategory bird.physicsBody?.affectedByGravity = false // at least before game starts bird.physicsBody?.allowsRotation = false bird.physicsBody?.restitution = 0.0 // not bouncy bird.zPosition = 50 addChild(bird) // Add two different textures that animate the bird let textures = [SKTexture(imageNamed: "bird1"), SKTexture(imageNamed: "bird2")] bird.runAction(SKAction.repeatActionForever(SKAction.animateWithTextures(textures, timePerFrame: 0.1))) } // MARK: - Score func initHUD() { label_score = SKLabelNode(fontNamed:"MarkerFelt-Wide") label_score.position = CGPoint(x: CGRectGetMidX(frame), y: CGRectGetMaxY(frame) - 100) label_score.text = "0" label_score.zPosition = 50 addChild(label_score) instructions = SKSpriteNode(imageNamed: "TapToStart") instructions.position = CGPoint(x: CGRectGetMidX(frame), y: CGRectGetMidY(frame) - 10) instructions.zPosition = 50 addChild(instructions) } // MARK: - Background Functions func initBackground() { background = SKNode() addChild(background) for i in 0...2 { let tile = SKSpriteNode(imageNamed: "bg") tile.anchorPoint = CGPointZero tile.position = CGPoint(x: CGFloat(i)*640.0, y: 0.0) tile.name = "bg" tile.zPosition = 10 background.addChild(tile) } } func moveBackground() { let posX = -background_speed * delta background.position = CGPoint(x: background.position.x + CGFloat(posX), y: 0.0) background.enumerateChildNodesWithName("bg") { (node, stop) in let background_screen_position = self.background.convertPoint(node.position, toNode: self) if background_screen_position.x <= -node.frame.size.width { node.position = CGPoint(x: node.position.x + (node.frame.size.width * 2), y: node.position.y) } } } // MARK: - Pipes Functions func initPipes() { let screenSize: CGRect = UIScreen.mainScreen().bounds let isWideScreen: Bool = (screenSize.height > 480) let bottom = getPipeWithSize(CGSize(width: 62, height: Float.range(40, max: isWideScreen ? 360 : 280)), side: false) bottom.position = convertPoint(CGPoint(x: pipe_origin_x, y: CGRectGetMinY(frame) + bottom.size.height/2 + floor_distance), toNode: background) bottom.physicsBody = SKPhysicsBody(rectangleOfSize: bottom.size) bottom.physicsBody?.categoryBitMask = FSPipeCategory; bottom.physicsBody?.contactTestBitMask = FSPlayerCategory; bottom.physicsBody?.collisionBitMask = FSPlayerCategory; bottom.physicsBody?.dynamic = false bottom.zPosition = 20 background.addChild(bottom) let threshold = SKSpriteNode(color: UIColor.clearColor(), size: CGSize(width: 10, height: 100)) threshold.position = convertPoint(CGPoint(x: pipe_origin_x, y: floor_distance + bottom.size.height + threshold.size.height/2), toNode: background) threshold.physicsBody = SKPhysicsBody(rectangleOfSize: threshold.size) threshold.physicsBody?.categoryBitMask = FSGapCategory threshold.physicsBody?.contactTestBitMask = FSPlayerCategory threshold.physicsBody?.collisionBitMask = 0 threshold.physicsBody?.dynamic = false threshold.zPosition = 20 background.addChild(threshold) let topSize = size.height - bottom.size.height - threshold.size.height - floor_distance let top = getPipeWithSize(CGSize(width: 62, height: topSize), side: true) top.position = convertPoint(CGPoint(x: pipe_origin_x, y: CGRectGetMaxY(frame) - top.size.height/2), toNode: background) top.physicsBody = SKPhysicsBody(rectangleOfSize: top.size) top.physicsBody?.categoryBitMask = FSPipeCategory; top.physicsBody?.contactTestBitMask = FSPlayerCategory; top.physicsBody?.collisionBitMask = FSPlayerCategory; top.physicsBody?.dynamic = false top.zPosition = 20 background.addChild(top) } func getPipeWithSize(size: CGSize, side: Bool) -> SKSpriteNode { let textureSize = CGRect(x: 0.0, y: 0.0, width: size.width, height: size.height) let backgroundCGImage = UIImage(named: "pipe")!.CGImage UIGraphicsBeginImageContext(size) let context = UIGraphicsGetCurrentContext() CGContextDrawTiledImage(context, textureSize, backgroundCGImage) let tiledBackground = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() let backgroundTexture = SKTexture(CGImage: tiledBackground.CGImage) let pipe = SKSpriteNode(texture: backgroundTexture) pipe.zPosition = 1 let cap = SKSpriteNode(imageNamed: "bottom") cap.position = CGPoint(x: 0.0, y: side ? -pipe.size.height/2 + cap.size.height/2 : pipe.size.height/2 - cap.size.height/2) cap.zPosition = 5 pipe.addChild(cap) if side == true { let angle: CGFloat = 180.0 cap.zRotation = angle.deg_to_rad() } return pipe } // MARK: - Game Over helpers func gameOver() { state = .FSGameStateEnded bird.physicsBody?.categoryBitMask = 0 bird.physicsBody?.collisionBitMask = FSBoundaryCategory var timer = NSTimer.scheduledTimerWithTimeInterval(4.0, target: self, selector: Selector("restartGame"), userInfo: nil, repeats: false) } func restartGame() { state = .FSGameStateStarting bird.removeFromParent() background.removeAllChildren() background.removeFromParent() instructions.hidden = false removeActionForKey("generator") score = 0 label_score.text = "0" initBird() initBackground() } // MARK: - SKPhysicsContactDelegate func didBeginContact(contact: SKPhysicsContact) { let collision: UInt32 = contact.bodyA.categoryBitMask | contact.bodyB.categoryBitMask if collision == (FSGapCategory | FSPlayerCategory) { score++ label_score.text = "\(score)" } if collision == (FSPlayerCategory | FSPipeCategory) { gameOver() } if collision == (FSPlayerCategory | FSBoundaryCategory) { if bird.position.y < 150 { gameOver() } } } // MARK: - Touch Events override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) { if state == .FSGameStateStarting { state = .FSGameStatePlaying instructions.hidden = true bird.physicsBody?.affectedByGravity = true bird.physicsBody?.applyImpulse(CGVector(dx: 0, dy: 25)) runAction(SKAction.repeatActionForever(SKAction.sequence([SKAction.waitForDuration(2.0), SKAction.runBlock { self.initPipes()}])), withKey: "generator") } else if state == .FSGameStatePlaying { bird.physicsBody?.applyImpulse(CGVector(dx: 0, dy: 25)) } } // MARK: - Frames Per Second override func update(currentTime: CFTimeInterval) { delta = (last_update_time == 0.0) ? 0.0 : currentTime - last_update_time last_update_time = currentTime if state != .FSGameStateEnded { moveBackground() let velocity_x = bird.physicsBody?.velocity.dx let velocity_y = bird.physicsBody?.velocity.dy if velocity_y > 280 { // Max velocity is 280 bird.physicsBody?.velocity = CGVector(dx: velocity_x!, dy: 280) } // Rotate bird based on its vertical velocity vector bird.zRotation = Float.clamp(-1, max: 0.0, value: velocity_y! * (velocity_y < 0 ? 0.003 : 0.001)) } else { bird.zRotation = CGFloat(M_PI) bird.removeAllActions() } } }
mit
5f6e1e47545b18a1316bc5d74f037bd8
35.901198
164
0.630994
4.590317
false
false
false
false
6ag/AppScreenshots
AppScreenshots/Classes/Module/Home/Controller/JFSettingViewController.swift
1
42202
// // JFSettingViewController.swift // AppScreenshots // // Created by zhoujianfeng on 2017/2/4. // Copyright © 2017年 zhoujianfeng. All rights reserved. // import UIKit import pop fileprivate let PhotoItemId = "PhotoItemId" fileprivate let TemplateItemId = "TemplateItemId" class JFSettingViewController: UIViewController { /// 素材模型参数数组 - 原模板 var materialParameterList: [JFMaterialParameter]? /// 素材模型参数数组 - 做的截图 fileprivate var photoMaterialParameterList = [JFMaterialParameter]() fileprivate var contentOffsetY: CGFloat = 0.0 override func viewDidLoad() { super.viewDidLoad() prepareUI() NotificationCenter.default.addObserver(self, selector: #selector(settingViewControllerWillPresent(notification:)), name: NSNotification.Name(SettingViewControllerWillPresent), object: nil) NotificationCenter.default.addObserver(self, selector: #selector(settingViewControllerWillDismiss(notification:)), name: NSNotification.Name(SettingViewControllerWillDismiss), object: nil) } deinit { NotificationCenter.default.removeObserver(self) } /// 设置界面即将显示 /// /// - Parameter notification: 通知 @objc fileprivate func settingViewControllerWillPresent(notification: Notification) { log("设置界面即将显示") } /// 设置界面即将隐藏 /// /// - Parameter notification: 通知 @objc fileprivate func settingViewControllerWillDismiss(notification: Notification) { log("设置界面即将隐藏") } /// 点击了加号 - 弹出各种功能选项 /// /// - Parameter saveButton: 加号按钮 @objc fileprivate func didTapped(moreButton: UIButton) { view.endEditing(true) let configuration = FTConfiguration.shared configuration.menuRowHeight = 45 configuration.menuWidth = layoutHorizontal(iPhone6: 135) configuration.textColor = UIColor.colorWithHexString("c4c4c4") configuration.textFont = UIFont.systemFont(ofSize: layoutFont(iPhone6: 16)) configuration.textAlignment = .center configuration.menuSeparatorColor = UIColor(white: 1, alpha: 0.05) configuration.menuSeparatorInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0) FTPopOverMenu.showForSender( sender: moreButton, with: [NSLocalizedString("option_add_photo", comment: ""), NSLocalizedString("option_remove_photo", comment: ""), NSLocalizedString("option_emptied_photo", comment: ""), NSLocalizedString("option_save_photo", comment: ""), NSLocalizedString("option_diy_custom_made", comment: "")], menuImageArray: ["tianjiatupian", "yichuquanbu", "yichudangqian", "baocuntupian", "diy"], done: { [weak self] (selectedIndex) -> () in switch selectedIndex { case 0: self?.addPhoto() case 1: self?.removeCurrentSelectedPhoto() case 2: self?.removeAllPhoto() case 3: self?.savePhotoToAlbum() case 4: self?.diyPhoto() default: break } }) { print("点击了menu之外") } } /// 文本框值改变 /// /// - Parameter textField: 文本框 @objc fileprivate func textFieldChanged(textField: UITextField) { for materialParameter in photoMaterialParameterList { if materialParameter.isSelected { if textField == titleField { materialParameter.title = textField.text } else { materialParameter.subtitle = textField.text } } } photoCollectionView.reloadData() } /// 切换了分辨率 /// /// - Parameter button: 当前分辨率按钮 @objc fileprivate func didTapped(button: UIButton) { guard let subviews = button.superview?.subviews else { return } for view in subviews { if view.isKind(of: UIButton.classForCoder()) { (view as! UIButton).isSelected = false } } button.isSelected = true } /// 点击了预览 /// /// - Parameter previewButton: 预览按钮 @objc fileprivate func didTapped(previewButton: UIButton) { view.endEditing(true) if photoMaterialParameterList.count == 0 { JFProgressHUD.showInfoWithStatus(NSLocalizedString("tip_add_photo", comment: "")) return } var photoViewList = [JFPhotoView]() var defaultIndex = 0 for (index, materialParameter) in photoMaterialParameterList.enumerated() { let photoView = JFPhotoView(materialParameter: materialParameter) photoViewList.append(photoView) if materialParameter.isSelected { defaultIndex = index } } // 弹出预览可滚动的视图 JFPreviewView(photoViewList: photoViewList, defaultIndex: defaultIndex).show() } // MARK: - 懒加载UI /// 导航视图 fileprivate lazy var navigationView: UIImageView = { let imageView = UIImageView(image: UIImage(named: "nav_bg")) imageView.isUserInteractionEnabled = true return imageView }() /// 更多操作 fileprivate lazy var moreButton: UIButton = { let button = UIButton(type: .custom) button.setImage(UIImage(named: "nav_add_icon"), for: .normal) button.titleLabel?.font = UIFont.systemFont(ofSize: layoutFont(iPhone6: 14)) button.addTarget(self, action: #selector(didTapped(moreButton:)), for: .touchUpInside) return button }() /// 容器 fileprivate lazy var containerView: UIScrollView = { let scrollView = UIScrollView() scrollView.delegate = self scrollView.backgroundColor = BACKGROUND_COLOR return scrollView }() /// 图片背景 fileprivate lazy var photoBgView: UIView = { let view = UIView() view.backgroundColor = UIColor.colorWithHexString("4c4c4c") view.layer.cornerRadius = 5 let label = UILabel() label.text = NSLocalizedString("detail_photo", comment: "") label.font = UIFont.systemFont(ofSize: layoutFont(iPhone6: 16)) label.textColor = UIColor.colorWithHexString("b4b7bb") view.addSubview(label) label.snp.makeConstraints({ (make) in make.left.equalTo(layoutHorizontal(iPhone6: 14)) make.top.equalTo(layoutHorizontal(iPhone6: 16)) }) return view }() /// 图片集合视图 fileprivate lazy var photoCollectionView: UICollectionView = { let layout = UICollectionViewFlowLayout() layout.scrollDirection = .horizontal layout.itemSize = CGSize(width: SettingPhotoItemWidth, height: SettingPhotoItemHeight) layout.minimumInteritemSpacing = layoutHorizontal(iPhone6: 8) let collectionView = UICollectionView(frame: .zero, collectionViewLayout: layout) collectionView.dataSource = self collectionView.delegate = self collectionView.backgroundColor = UIColor.clear collectionView.contentInset = UIEdgeInsets( top: layoutVertical(iPhone6: 14), left: layoutHorizontal(iPhone6: 14), bottom: layoutVertical(iPhone6: 14), right: layoutHorizontal(iPhone6: 14)) collectionView.register(JFPhotoCollectionViewCell.classForCoder(), forCellWithReuseIdentifier: PhotoItemId) return collectionView }() /// 模板背景 fileprivate lazy var templateBgView: UIView = { let view = UIView() view.backgroundColor = UIColor.colorWithHexString("4c4c4c") view.layer.cornerRadius = 5 let label = UILabel() label.text = NSLocalizedString("detail_templete", comment: "") label.font = UIFont.systemFont(ofSize: layoutFont(iPhone6: 16)) label.textColor = UIColor.colorWithHexString("b4b7bb") view.addSubview(label) label.snp.makeConstraints({ (make) in make.left.equalTo(layoutHorizontal(iPhone6: 14)) make.top.equalTo(layoutHorizontal(iPhone6: 16)) }) return view }() /// 模板集合视图 fileprivate lazy var templateCollectionView: UICollectionView = { let layout = UICollectionViewFlowLayout() layout.scrollDirection = .horizontal layout.itemSize = CGSize(width: SettingPhotoItemWidth, height: SettingPhotoItemHeight) layout.minimumInteritemSpacing = layoutHorizontal(iPhone6: 8) let collectionView = UICollectionView(frame: .zero, collectionViewLayout: layout) collectionView.dataSource = self collectionView.delegate = self collectionView.backgroundColor = UIColor.clear collectionView.contentInset = UIEdgeInsets( top: layoutVertical(iPhone6: 14), left: layoutHorizontal(iPhone6: 14), bottom: layoutVertical(iPhone6: 14), right: layoutHorizontal(iPhone6: 14)) collectionView.register(JFTemplateCollectionViewCell.classForCoder(), forCellWithReuseIdentifier: TemplateItemId) return collectionView }() /// 分辨率背景 fileprivate lazy var sizeBgView: UIView = { let view = UIView() view.backgroundColor = UIColor.colorWithHexString("4c4c4c") view.layer.cornerRadius = 5 let label = UILabel() label.text = NSLocalizedString("detail_resolution", comment: "") label.font = UIFont.systemFont(ofSize: layoutFont(iPhone6: 16)) label.textColor = UIColor.colorWithHexString("b4b7bb") let button1 = UIButton(type: .custom) button1.contentHorizontalAlignment = .left button1.titleEdgeInsets = UIEdgeInsets(top: 0, left: 10, bottom: 0, right: 0) button1.setTitleColor(UIColor.colorWithHexString("808080"), for: .normal) button1.titleLabel?.font = UIFont.systemFont(ofSize: layoutFont(iPhone6: 16)) button1.setImage(UIImage(named: "size_weixuanzhong"), for: .normal) button1.setImage(UIImage(named: "size_selected"), for: .selected) button1.setTitle(NSLocalizedString("detail_resolution_3_5_inch", comment: ""), for: .normal) button1.addTarget(self, action: #selector(didTapped(button:)), for: .touchUpInside) let button2 = UIButton(type: .custom) button2.contentHorizontalAlignment = .left button2.titleEdgeInsets = UIEdgeInsets(top: 0, left: 10, bottom: 0, right: 0) button2.setTitleColor(UIColor.colorWithHexString("808080"), for: .normal) button2.titleLabel?.font = UIFont.systemFont(ofSize: layoutFont(iPhone6: 16)) button2.setImage(UIImage(named: "size_weixuanzhong"), for: .normal) button2.setImage(UIImage(named: "size_selected"), for: .selected) button2.setTitle(NSLocalizedString("detail_resolution_4_0_inch", comment: ""), for: .normal) button2.addTarget(self, action: #selector(didTapped(button:)), for: .touchUpInside) let button3 = UIButton(type: .custom) button3.contentHorizontalAlignment = .left button3.titleEdgeInsets = UIEdgeInsets(top: 0, left: 10, bottom: 0, right: 0) button3.setTitleColor(UIColor.colorWithHexString("808080"), for: .normal) button3.titleLabel?.font = UIFont.systemFont(ofSize: layoutFont(iPhone6: 16)) button3.setImage(UIImage(named: "size_weixuanzhong"), for: .normal) button3.setImage(UIImage(named: "size_selected"), for: .selected) button3.setTitle(NSLocalizedString("detail_resolution_4_7_inch", comment: ""), for: .normal) button3.addTarget(self, action: #selector(didTapped(button:)), for: .touchUpInside) let button4 = UIButton(type: .custom) button4.contentHorizontalAlignment = .left button4.titleEdgeInsets = UIEdgeInsets(top: 0, left: 10, bottom: 0, right: 0) button4.setTitleColor(UIColor.colorWithHexString("808080"), for: .normal) button4.titleLabel?.font = UIFont.systemFont(ofSize: layoutFont(iPhone6: 16)) button4.setImage(UIImage(named: "size_weixuanzhong"), for: .normal) button4.setImage(UIImage(named: "size_selected"), for: .selected) button4.setTitle(NSLocalizedString("detail_resolution_5_5_inch", comment: ""), for: .normal) button4.addTarget(self, action: #selector(didTapped(button:)), for: .touchUpInside) let button5 = UIButton(type: .custom) button5.contentHorizontalAlignment = .left button5.titleEdgeInsets = UIEdgeInsets(top: 0, left: 10, bottom: 0, right: 0) button5.setTitleColor(UIColor.colorWithHexString("808080"), for: .normal) button5.titleLabel?.font = UIFont.systemFont(ofSize: layoutFont(iPhone6: 16)) button5.setImage(UIImage(named: "size_weixuanzhong"), for: .normal) button5.setImage(UIImage(named: "size_selected"), for: .selected) button5.setTitle(NSLocalizedString("detail_resolution_5_8_inch", comment: ""), for: .normal) button5.addTarget(self, action: #selector(didTapped(button:)), for: .touchUpInside) button5.isSelected = true view.addSubview(label) view.addSubview(button1) view.addSubview(button2) view.addSubview(button3) view.addSubview(button4) view.addSubview(button5) label.snp.makeConstraints({ (make) in make.left.equalTo(layoutHorizontal(iPhone6: 14)) make.top.equalTo(layoutVertical(iPhone6: 16)) }) button1.snp.makeConstraints({ (make) in make.left.equalTo(layoutHorizontal(iPhone6: 75)) make.top.equalTo(layoutVertical(iPhone6: 16)) make.right.equalTo(0) }) button2.snp.makeConstraints({ (make) in make.left.equalTo(button1.snp.left) make.top.equalTo(button1.snp.bottom).offset(layoutVertical(iPhone6: 16)) make.right.equalTo(0) }) button3.snp.makeConstraints({ (make) in make.left.equalTo(button1.snp.left) make.top.equalTo(button2.snp.bottom).offset(layoutVertical(iPhone6: 16)) make.right.equalTo(0) }) button4.snp.makeConstraints({ (make) in make.left.equalTo(button1.snp.left) make.top.equalTo(button3.snp.bottom).offset(layoutVertical(iPhone6: 16)) make.right.equalTo(0) }) button5.snp.makeConstraints({ (make) in make.left.equalTo(button1.snp.left) make.top.equalTo(button4.snp.bottom).offset(layoutVertical(iPhone6: 16)) make.right.equalTo(0) }) return view }() /// 主标题背景 fileprivate lazy var titleBgView: UIView = { let view = UIView() view.backgroundColor = UIColor.colorWithHexString("4c4c4c") view.layer.cornerRadius = 5 let lineView = UIView() lineView.backgroundColor = UIColor.colorWithHexString("808080") view.addSubview(self.titleField) view.addSubview(lineView) self.titleField.snp.makeConstraints({ (make) in make.left.equalTo(layoutHorizontal(iPhone6: 50)) make.right.equalTo(layoutHorizontal(iPhone6: -50)) make.top.equalTo(layoutVertical(iPhone6: 12)) make.bottom.equalTo(layoutVertical(iPhone6: -12)) }) lineView.snp.makeConstraints({ (make) in make.left.equalTo(self.titleField.snp.left) make.right.equalTo(self.titleField.snp.right) make.height.equalTo(1) make.top.equalTo(self.titleField.snp.bottom) }) return view }() /// 标题 fileprivate lazy var titleField: UITextField = { let textField = UITextField() textField.font = UIFont.systemFont(ofSize: layoutFont(iPhone6: 16)) textField.textAlignment = .center textField.textColor = UIColor.colorWithHexString("d3d3d3") textField.attributedPlaceholder = NSAttributedString(string: NSLocalizedString("detail_main_title", comment: ""), attributes: [NSForegroundColorAttributeName : UIColor.colorWithHexString("808080")]) textField.addTarget(self, action: #selector(textFieldChanged(textField:)), for: .editingChanged) return textField }() /// 副标题背景 fileprivate lazy var subtitleBgView: UIView = { let view = UIView() view.backgroundColor = UIColor.colorWithHexString("4c4c4c") view.layer.cornerRadius = 5 let lineView = UIView() lineView.backgroundColor = UIColor.colorWithHexString("808080") view.addSubview(self.subtitleField) view.addSubview(lineView) self.subtitleField.snp.makeConstraints({ (make) in make.left.equalTo(layoutHorizontal(iPhone6: 50)) make.right.equalTo(layoutHorizontal(iPhone6: -50)) make.top.equalTo(layoutVertical(iPhone6: 12)) make.bottom.equalTo(layoutVertical(iPhone6: -12)) }) lineView.snp.makeConstraints({ (make) in make.left.equalTo(self.subtitleField.snp.left) make.right.equalTo(self.subtitleField.snp.right) make.height.equalTo(1) make.top.equalTo(self.subtitleField.snp.bottom) }) return view }() /// 副标题 fileprivate lazy var subtitleField: UITextField = { let textField = UITextField() textField.font = UIFont.systemFont(ofSize: layoutFont(iPhone6: 16)) textField.textAlignment = .center textField.textColor = UIColor.colorWithHexString("d3d3d3") textField.attributedPlaceholder = NSAttributedString(string: NSLocalizedString("detail_sub_title", comment: ""), attributes: [NSForegroundColorAttributeName : UIColor.colorWithHexString("808080")]) textField.addTarget(self, action: #selector(textFieldChanged(textField:)), for: .editingChanged) return textField }() /// 预览 fileprivate lazy var previewButton: UIButton = { let button = UIButton(type: .custom) button.setTitle(NSLocalizedString("detail_preview", comment: ""), for: .normal) button.setTitleColor(UIColor.colorWithHexString("333333"), for: .normal) button.layer.cornerRadius = 5 button.layer.masksToBounds = true button.layer.borderColor = UIColor.colorWithHexString("f7ce00").cgColor button.layer.borderWidth = 2 button.setBackgroundImage( UIColor .colorWithHexString("f7ce00") .toImage() .redrawRoundedImage( size: CGSize( width: layoutHorizontal(iPhone6: 334), height: layoutVertical(iPhone6: 40)), bgColor: UIColor.colorWithHexString("333333"), cornerRadius: 5), for: .normal) button.addTarget(self, action: #selector(didTapped(previewButton:)), for: .touchUpInside) return button }() } // MARK: - 设置界面 extension JFSettingViewController { /// 准备UI fileprivate func prepareUI() { view.backgroundColor = BACKGROUND_COLOR view.addSubview(navigationView) navigationView.addSubview(moreButton) view.addSubview(containerView) containerView.addSubview(photoBgView) containerView.addSubview(templateBgView) containerView.addSubview(sizeBgView) containerView.addSubview(titleBgView) // 如果没有副标题,则不显示UI if let materialParameter = materialParameterList?.first { if materialParameter.subtitleY > 1 { titleField.returnKeyType = .next titleField.delegate = self subtitleField.returnKeyType = .done subtitleField.delegate = self containerView.addSubview(subtitleBgView) } else { titleField.returnKeyType = .done titleField.delegate = self } } containerView.addSubview(previewButton) photoBgView.addSubview(photoCollectionView) templateBgView.addSubview(templateCollectionView) navigationView.snp.makeConstraints { (make) in make.left.top.right.equalTo(0) make.height.equalTo(layoutVertical(iPhone6: 44) + STATUS_HEIGHT) } moreButton.snp.makeConstraints { (make) in make.top.equalTo(STATUS_HEIGHT) make.right.equalTo(layoutHorizontal(iPhone6: -5)) make.size.equalTo(CGSize(width: layoutHorizontal(iPhone6: 44), height: layoutVertical(iPhone6: 44))) } containerView.snp.makeConstraints { (make) in make.left.right.bottom.equalTo(0) make.top.equalTo(navigationView.snp.bottom) } photoBgView.snp.makeConstraints { (make) in make.centerX.equalTo(containerView) make.top.equalTo(layoutVertical(iPhone6: 22)) make.size.equalTo(CGSize(width: layoutHorizontal(iPhone6: 334), height: layoutVertical(iPhone6: 130))) } templateBgView.snp.makeConstraints { (make) in make.centerX.equalTo(containerView) make.top.equalTo(photoBgView.snp.bottom).offset(layoutVertical(iPhone6: 15)) make.size.equalTo(CGSize(width: layoutHorizontal(iPhone6: 334), height: layoutVertical(iPhone6: 130))) } sizeBgView.snp.makeConstraints { (make) in make.centerX.equalTo(containerView) make.top.equalTo(templateBgView.snp.bottom).offset(layoutVertical(iPhone6: 15)) make.size.equalTo(CGSize(width: layoutHorizontal(iPhone6: 334), height: layoutVertical(iPhone6: 190))) } titleBgView.snp.makeConstraints { (make) in make.centerX.equalTo(containerView) make.top.equalTo(sizeBgView.snp.bottom).offset(layoutVertical(iPhone6: 15)) make.size.equalTo(CGSize(width: layoutHorizontal(iPhone6: 334), height: layoutVertical(iPhone6: 54))) } // 如果没有副标题,则不显示UI if let materialParameter = materialParameterList?.first { if materialParameter.subtitleY > 1 { subtitleBgView.snp.makeConstraints { (make) in make.centerX.equalTo(containerView) make.top.equalTo(titleBgView.snp.bottom).offset(layoutVertical(iPhone6: 15)) make.size.equalTo(CGSize(width: layoutHorizontal(iPhone6: 334), height: layoutVertical(iPhone6: 54))) } previewButton.snp.makeConstraints { (make) in make.centerX.equalTo(containerView) make.top.equalTo(subtitleBgView.snp.bottom).offset(layoutVertical(iPhone6: 15)) make.size.equalTo(CGSize(width: layoutHorizontal(iPhone6: 334), height: layoutVertical(iPhone6: 40))) } } else { previewButton.snp.makeConstraints { (make) in make.centerX.equalTo(containerView) make.top.equalTo(titleBgView.snp.bottom).offset(layoutVertical(iPhone6: 15)) make.size.equalTo(CGSize(width: layoutHorizontal(iPhone6: 334), height: layoutVertical(iPhone6: 40))) } } } photoCollectionView.snp.makeConstraints { (make) in make.left.equalTo(layoutHorizontal(iPhone6: 45)) make.top.equalTo(layoutVertical(iPhone6: 0)) make.height.equalTo(SettingPhotoItemHeight + layoutVertical(iPhone6: 28)) make.width.equalTo((SettingPhotoItemWidth + layoutHorizontal(iPhone6: 8)) * 4 + layoutHorizontal(iPhone6: 28)) } templateCollectionView.snp.makeConstraints { (make) in make.left.equalTo(layoutHorizontal(iPhone6: 45)) make.top.equalTo(layoutVertical(iPhone6: 0)) make.height.equalTo(SettingPhotoItemHeight + layoutVertical(iPhone6: 28)) make.width.equalTo((SettingPhotoItemWidth + layoutHorizontal(iPhone6: 8)) * 4 + layoutHorizontal(iPhone6: 28)) } view.layoutIfNeeded() containerView.contentSize = CGSize(width: 0, height: previewButton.frame.maxY + layoutVertical(iPhone6: 30)) } } // MARK: - 右上角各种事件处理 extension JFSettingViewController { /// DIY图片 fileprivate func diyPhoto() { // 弹出插页广告 if let interstitial = JFAdManager.shared.getReadyIntersitial() { interstitial.present(fromRootViewController: self) return } if photoMaterialParameterList.count == 0 { JFProgressHUD.showInfoWithStatus(NSLocalizedString("tip_add_photo", comment: "")) return } var photoImageList = [UIImage]() for materialParameter in photoMaterialParameterList { let photoView = JFPhotoView(materialParameter: materialParameter) // 视图转换截图 if let image = viewToImage(view: photoView) { photoImageList.append(image) } } let diyVc = JFDiyViewController() diyVc.photoImageList = photoImageList present(diyVc, animated: true, completion: nil) } /// 移除当前选中图片 fileprivate func removeCurrentSelectedPhoto() { // 弹出插页广告 if let interstitial = JFAdManager.shared.getReadyIntersitial() { interstitial.present(fromRootViewController: self) return } if photoMaterialParameterList.count == 0 { JFProgressHUD.showInfoWithStatus(NSLocalizedString("tip_add_photo", comment: "")) return } // 遍历获取当前选中图片的下标 var currentIndex = 0 for (index, photoMaterialParameter) in photoMaterialParameterList.enumerated() { if photoMaterialParameter.isSelected { currentIndex = index } } // 移除当前选中的图片 photoMaterialParameterList.remove(at: currentIndex) // 移除后如果还有一张以上,就默认选中第一张图 if photoMaterialParameterList.count > 0 { collectionView(photoCollectionView, didSelectItemAt: IndexPath(item: 0, section: 0)) } else { photoCollectionView.reloadData() templateCollectionView.reloadData() } } /// 移除所有图片 fileprivate func removeAllPhoto() { // 弹出插页广告 if let interstitial = JFAdManager.shared.getReadyIntersitial() { interstitial.present(fromRootViewController: self) return } if photoMaterialParameterList.count == 0 { JFProgressHUD.showInfoWithStatus(NSLocalizedString("tip_add_photo", comment: "")) return } // 移除所有图片 photoMaterialParameterList.removeAll() titleField.text = nil subtitleField.text = nil photoCollectionView.reloadData() templateCollectionView.reloadData() } /// 保存图片到相册 fileprivate func savePhotoToAlbum() { // 弹出插页广告 if let interstitial = JFAdManager.shared.getReadyIntersitial() { interstitial.present(fromRootViewController: self) return } // 判断有没有分享过,如果没有则要求分享一次 - 如有需要分享则返回true if JFAdManager.shared.showShareAlert(vc: self) { return } if photoMaterialParameterList.count == 0 { JFProgressHUD.showInfoWithStatus(NSLocalizedString("tip_add_photo", comment: "")) return } let alertC = UIAlertController(title: NSLocalizedString("option_save_photo_to_album", comment: ""), message: nil, preferredStyle: .actionSheet) alertC.addAction(UIAlertAction(title: NSLocalizedString("option_current_photo", comment: ""), style: .default, handler: { [weak self] (_) in self?.saveOnImage() })) alertC.addAction(UIAlertAction(title: NSLocalizedString("option_all_pictures", comment: ""), style: .default, handler: { [weak self] (_) in self?.saveMoreImage() })) alertC.addAction(UIAlertAction(title: NSLocalizedString("option_cancel", comment: ""), style: .cancel, handler: nil)) present(alertC, animated: true, completion: nil) } /// 保存单图 fileprivate func saveOnImage() { for materialParameter in photoMaterialParameterList { if materialParameter.isSelected { let photoView = JFPhotoView(materialParameter: materialParameter) // 视图转换截图 if let image = viewToImage(view: photoView) { // 保存图片到相册 UIImageWriteToSavedPhotosAlbum(image, self, #selector(imageSavedToPhotosAlbum(image:didFinishSavingWithError:contextInfo:)), nil) } } } } /// 保存多图 fileprivate func saveMoreImage() { for materialParameter in photoMaterialParameterList { let photoView = JFPhotoView(materialParameter: materialParameter) // 视图转换截图 if let image = viewToImage(view: photoView) { // 保存图片到相册 UIImageWriteToSavedPhotosAlbum(image, self, #selector(imageSavedToPhotosAlbum(image:didFinishSavingWithError:contextInfo:)), nil) } } } /// 图片保存回调 @objc fileprivate func imageSavedToPhotosAlbum(image: UIImage, didFinishSavingWithError error: Error?, contextInfo: Any?) { if error == nil { JFProgressHUD.showSuccessWithStatus(NSLocalizedString("tip_save_success", comment: "")) } else { JFProgressHUD.showErrorWithStatus("\(NSLocalizedString("tip_save_failure", comment: "")) \(error.debugDescription)") } } /// 将做好的应用截图转成UIImage对象 /// /// - Parameter view: 视图 /// - Returns: UIImage fileprivate func viewToImage(view: UIView) -> UIImage? { // 将视图渲染成图片 UIApplication.shared.keyWindow?.insertSubview(view, at: 0) UIGraphicsBeginImageContextWithOptions(SCREEN_BOUNDS.size, true, UIScreen.main.scale) guard let context = UIGraphicsGetCurrentContext() else { return nil } view.layer.render(in: context) let image = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() view.removeFromSuperview() // 获取当前选中的尺寸 var size = CGSize.zero for subview in sizeBgView.subviews { if subview.isKind(of: UIButton.classForCoder()) { let button = subview as! UIButton if button.isSelected { switch button.title(for: .normal) ?? "" { case NSLocalizedString("detail_resolution_3_5_inch", comment: ""): // 3.5 - 640*960 size = CGSize(width: 640, height: 960) case NSLocalizedString("detail_resolution_4_0_inch", comment: ""): // 4.0 - 640*1136 size = CGSize(width: 640, height: 1136) case NSLocalizedString("detail_resolution_4_7_inch", comment: ""): // 4.7 - 750*1334 size = CGSize(width: 750, height: 1334) case NSLocalizedString("detail_resolution_5_5_inch", comment: ""): // 5.5 - 1242*2208 size = CGSize(width: 1242, height: 2208) case NSLocalizedString("detail_resolution_5_8_inch", comment: ""): // 5.8 - 1125*2436 size = CGSize(width: 1125, height: 2436) default: break } } } } // 转换单位 size = CGSize(width: size.width / UIScreen.main.scale, height: size.height / UIScreen.main.scale) // 根据尺寸重绘图片 return image?.redrawImage(size: size) } /// 添加图片 fileprivate func addPhoto() { // 弹出插页广告 if let interstitial = JFAdManager.shared.getReadyIntersitial() { interstitial.present(fromRootViewController: self) return } // 判断设置是否支持图片库 if UIImagePickerController.isSourceTypeAvailable(.photoLibrary) { let photoPickerVc = JFPhotoPickerViewController() photoPickerVc.delegate = self present(photoPickerVc, animated: true, completion: nil) } else { log("读取相册错误") } } } // MARK: - 设置做成的截图视图和模板视图 extension JFSettingViewController: UICollectionViewDelegate, UICollectionViewDataSource { func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { if collectionView == photoCollectionView { return photoMaterialParameterList.count } else { return materialParameterList?.count ?? 0 } } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { if collectionView == photoCollectionView { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: PhotoItemId, for: indexPath) as! JFPhotoCollectionViewCell cell.materialParameter = photoMaterialParameterList[indexPath.item] return cell } else { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: TemplateItemId, for: indexPath) as! JFTemplateCollectionViewCell cell.materialParameter = materialParameterList?[indexPath.item] return cell } } func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { view.endEditing(true) if collectionView == photoCollectionView { // 切换到当前选中item let materialParameter = photoMaterialParameterList[indexPath.item] // 如果点击的还是当前选中的图片则直接返回 if materialParameter.isSelected == true { return } for materialParameter in photoMaterialParameterList { materialParameter.isSelected = false } materialParameter.isSelected = true // 设置文本框 titleField.text = materialParameter.title subtitleField.text = materialParameter.subtitle // 切换模板选中状态 for materialParameter in materialParameterList ?? [JFMaterialParameter]() { materialParameter.isSelected = false } if let sourceImageName = materialParameter.sourceImageName { let num = sourceImageName.substring(with: Range<String.Index>(sourceImageName.index(sourceImageName.endIndex, offsetBy: -5)..<sourceImageName.index(sourceImageName.endIndex, offsetBy: -4))) let index = Int(num) ?? 1 if let materialParameter = materialParameterList?[index - 1] { materialParameter.isSelected = true } } } else { // 切换到当前选中item let materialParameter = materialParameterList?[indexPath.item] // 如果点击的还是当前选中的模板则直接返回 if materialParameter?.isSelected == true { return } for materialParameter in materialParameterList ?? [JFMaterialParameter]() { materialParameter.isSelected = false } materialParameter?.isSelected = true // 如果还没有图片则直接返回 if photoMaterialParameterList.count == 0 { templateCollectionView.reloadData() return } // 切换图片里的模板 var editIndex = 0 var newPhotoMaterialParameter: JFMaterialParameter! for (index, photoMaterialParameter) in photoMaterialParameterList.enumerated() { if photoMaterialParameter.isSelected { editIndex = index // 拷贝新的模板参数 newPhotoMaterialParameter = materialParameter?.copy() as! JFMaterialParameter newPhotoMaterialParameter.title = photoMaterialParameter.title newPhotoMaterialParameter.subtitle = photoMaterialParameter.subtitle newPhotoMaterialParameter.screenShotImage = photoMaterialParameter.screenShotImage newPhotoMaterialParameter.isSelected = photoMaterialParameter.isSelected } } photoMaterialParameterList[editIndex] = newPhotoMaterialParameter } photoCollectionView.reloadData() templateCollectionView.reloadData() } } // MARK: - 图片选择回调 extension JFSettingViewController: JFPhotoPickerViewControllerDelegate { func didSelected(imageList: [UIImage]) { // 一张图片都没有选择,则直接返回 if imageList.count == 0 { return } // 取消上一个选择 for materialParameter in photoMaterialParameterList { materialParameter.isSelected = false } // 添加图片模型 for (index, image) in imageList.enumerated() { for materialParameter in materialParameterList ?? [JFMaterialParameter]() { // 防止内存峰值 autoreleasepool { [weak self] in if materialParameter.isSelected { let photoMaterialParameter = materialParameter.copy() as! JFMaterialParameter photoMaterialParameter.screenShotImage = image.redrawImage(size: CGSize( width: photoMaterialParameter.screenShotWidth, height: photoMaterialParameter.screenShotHeight)) // 每次添加图片,设置添加的首张图片为选中项 if index == 0 { photoMaterialParameter.isSelected = true } else { photoMaterialParameter.isSelected = false } self?.photoMaterialParameterList.append(photoMaterialParameter) } } } } // 清空文本框 titleField.text = nil subtitleField.text = nil photoCollectionView.reloadData() // 如果一次性添加5张图,只偏移4个位置。否则影响美观 var itemIndex = 0 if imageList.count > 4 { itemIndex = photoMaterialParameterList.count - 2 } else { itemIndex = photoMaterialParameterList.count - 1 } photoCollectionView.scrollToItem(at: IndexPath(item: itemIndex, section: 0), at: .right, animated: true) } } // MARK: - UITextFieldDelegate extension JFSettingViewController: UITextFieldDelegate { func textFieldShouldReturn(_ textField: UITextField) -> Bool { if textField.returnKeyType == .next { subtitleField.becomeFirstResponder() } else { textField.resignFirstResponder() } return true } func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool { if photoMaterialParameterList.count == 0 { JFProgressHUD.showInfoWithStatus(NSLocalizedString("tip_add_photo", comment: "")) view.endEditing(true) return false } return true } } // MARK: - UIScrollViewDelegate extension JFSettingViewController: UIScrollViewDelegate { /// 开始拖拽视图记录y方向偏移量 func scrollViewWillBeginDragging(_ scrollView: UIScrollView) { if (scrollView == containerView) { contentOffsetY = scrollView.contentOffset.y } } /// 松开手开始减速 func scrollViewWillBeginDecelerating(_ scrollView: UIScrollView) { if (scrollView == containerView) { if scrollView.contentOffset.y - contentOffsetY > 5.0 { // 向上拖拽 view.endEditing(true) } else if contentOffsetY - scrollView.contentOffset.y > 5.0 { // 向下拖拽 view.endEditing(true) } } } }
mit
70f810828d5adb90544974fb05aa2a3f
39.195866
206
0.60976
5.006006
false
false
false
false
Appsilog/BuffWatch
BuffWatchTests/BuffWatchTests.swift
1
2432
// // BuffWatchTests.swift // BuffWatchTests // // Created by jay on 7/1/15. // Copyright © 2015 Appsilog. All rights reserved. // import XCTest import Foundation @testable import BuffWatch class BuffWatchTests: XCTestCase { let buffer = BufferAPI() func testFakeDataPending(){ let pendingPosts = FakeData.getPending() XCTAssertTrue(pendingPosts.count > 0) } func testFakeDataSent(){ let sentPosts = FakeData.getPending() XCTAssertTrue(sentPosts.count > 0) } func testSentDataHasRightOrder(){ let sent = FakeData.getSent() var currentDate: NSDate = NSDate() for s in sent { print(NSDate(timeIntervalSince1970: s.due_at!).timeIntervalSinceDate(currentDate), appendNewline: true) XCTAssertTrue(NSDate(timeIntervalSince1970: s.due_at!).timeIntervalSinceDate(currentDate) < 0) currentDate = NSDate(timeIntervalSince1970: s.due_at!) } } func testGetPending(){ let bundle = NSBundle(forClass: self.classForCoder) let path = bundle.pathForResource("pending", ofType: "json") let url: NSURL = NSURL(fileURLWithPath: path!) let jsonData: NSData = NSData(contentsOfURL: url)! do{ let json = try NSJSONSerialization.JSONObjectWithData(jsonData, options: NSJSONReadingOptions.MutableContainers) as! NSDictionary let updates = json["updates"] as? [NSDictionary] XCTAssertTrue(buffer.populatePosts(updates).count > 0) }catch{ } } 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. } } }
mit
29229512586b30a9958572a983e97ad4
27.940476
141
0.612505
4.871743
false
true
false
false
DanielFulton/ImageLibraryTests
Pods/Nuke/Sources/ImageTask.swift
1
3296
// The MIT License (MIT) // // Copyright (c) 2016 Alexander Grebenyuk (github.com/kean). import Foundation /** The state of the task. Allowed transitions include: - Suspended -> [Running, Cancelled] - Running -> [Cancelled, Completed] - Cancelled -> [] - Completed -> [] */ public enum ImageTaskState { case Suspended, Running, Cancelled, Completed } /// ImageTask completion block, gets called when task is either completed or cancelled. public typealias ImageTaskCompletion = (ImageResponse) -> Void /// Represents image task progress. public struct ImageTaskProgress { /// Completed unit count. public var completed: Int64 = 0 /// Total unit count. public var total: Int64 = 0 /// The fraction of overall work completed. If the total unit count is 0 fraction completed is also 0. public var fractionCompleted: Double { return total == 0 ? 0.0 : Double(completed) / Double(total) } } /// Abstract class for image tasks. Tasks are always part of the image manager, you create a task by calling one of the methods on ImageManager. public class ImageTask: Hashable { // MARK: Obtainig General Task Information /// The request that task was created with. public let request: ImageRequest /// The response which is set when task is either completed or cancelled. public internal(set) var response: ImageResponse? /// Return hash value for the receiver. public var hashValue: Int { return identifier } /// Uniquely identifies the task within an image manager. public let identifier: Int // MARK: Configuring Task /// Initializes task with a given request and identifier. public init(request: ImageRequest, identifier: Int) { self.request = request self.identifier = identifier } /** Adds a closure to be called on the main thread when task is either completed or cancelled. The closure is called synchronously when the requested image can be retrieved from the memory cache and the request was made from the main thread. The closure is called even if it is added to the already completed or cancelled task. */ public func completion(completion: ImageTaskCompletion) -> Self { fatalError("Abstract method") } // MARK: Obraining Task Progress /// Return current task progress. Initial value is (0, 0). public internal(set) var progress = ImageTaskProgress() /// A progress closure that gets periodically during the lifecycle of the task. public var progressHandler: ((progress: ImageTaskProgress) -> Void)? // MARK: Controlling Task State /// The current state of the task. public internal(set) var state: ImageTaskState = .Suspended /// Resumes the task if suspended. Resume methods are nestable. public func resume() -> Self { fatalError("Abstract method") } /// Cancels the task if it hasn't completed yet. Calls a completion closure with an error value of { ImageManagerErrorDomain, ImageManagerErrorCancelled }. public func cancel() -> Self { fatalError("Abstract method") } } /// Compares two image tasks by reference. public func ==(lhs: ImageTask, rhs: ImageTask) -> Bool { return lhs === rhs }
mit
411cc56b6f068364bb99b827be4d6b51
33.694737
159
0.689927
4.897474
false
false
false
false
ddimitrov90/EverliveSDK
Tests/Pods/EverliveSDK/EverliveSDK/GetAllHandler.swift
2
1938
// // GetAllHandler.swift // EverliveSwift // // Created by Dimitar Dimitrov on 2/17/16. // Copyright © 2016 ddimitrov. All rights reserved. // import Foundation import Alamofire import EVReflection public class GetAllHandler<T: DataItem> : BaseHandler { var paging: Paging? var sorting: Sorting? var expand:QueryProtocol? required public init(connection: EverliveConnection, typeName: String){ super.init(connection: connection, typeName: typeName) } public func execute(completionHandler: ([T]?, EverliveError?) -> Void){ let url = self.prepareUrl() let getAllRequest = EverliveRequest(httpMethod: "GET", url: url) getAllRequest.applyPaging(self.paging) getAllRequest.applySorting(self.sorting) getAllRequest.applyExpand(self.expand) self.connection.executeRequest(getAllRequest) { (response: Result<MultipleResult<T>, NSError>) -> Void in if let result = response.value { completionHandler(result.data, result.getErrorObject()) } } } public func sort(sortDefinition: Sorting) -> GetAllHandler<T> { self.sorting = sortDefinition return self } public func skip(skipNumber:Int) -> GetAllHandler<T> { if self.paging == nil { self.paging = Paging() } self.paging?.skip = skipNumber return self } public func take(takeNumber:Int) -> GetAllHandler<T> { if self.paging == nil { self.paging = Paging() } self.paging?.take = takeNumber return self } public func expand(expandObj: ExpandDefinition) -> GetAllHandler<T> { self.expand = expandObj return self } public func expand(multipleExpand: MultipleExpandDefinition) -> GetAllHandler<T> { self.expand = multipleExpand return self } }
mit
451430c1e3e04b0a04b4efcb57149844
27.925373
113
0.627259
4.452874
false
false
false
false
ahoppen/swift
test/Interpreter/opaque_return_type_protocol_ext.swift
10
2445
// RUN: %empty-directory(%t) // RUN: %target-build-swift -swift-version 5 %s -o %t/a.out // RUN: %target-run %t/a.out | %FileCheck %s // REQUIRES: executable_test @available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) protocol P { associatedtype AT func foo() -> AT } @available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) struct Adapter<T: P>: P { var inner: T @available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) func foo() -> some P { return inner } } @available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) extension P { @available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) func foo() -> some P { return Adapter(inner: self) } } @available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) func getPAT<T: P>(_: T.Type) -> Any.Type { return T.AT.self } @available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) extension Int: P { } // CHECK: {{Adapter<Int>|too old}} if #available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) { print(getPAT(Int.self)) } else { print("i'm getting too old for this sh") } // rdar://problem/54084733 protocol Q { associatedtype A func f() -> A } struct X: Q { typealias A = Array<Int> func f() -> A { return [1, 2, 3] } } @available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) dynamic func g() -> some Q { return X() } func h<T: Q>(x: T) -> (T.A?, T.A?) { return (.some(x.f()), .some(x.f())) } if #available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) { let x = g() // CHECK: {{X()|no really}} print(x) // CHECK: {{[1, 2, 3]|too old}} let y = x.f() print(y) // CHECK: {{[1, 2, 3]|too old}} let z = h(x: x) print(z) } else { print("no really") print("i'm getting way too old for this sh") print("way too old") } @available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) dynamic func opaqueAssocTypeUnderlyingType() -> some Any { return g().f() } extension Optional: Q where Wrapped: Q { func f() -> Wrapped.A? { return map { $0.f() } } } @available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) dynamic func structuralOpaqueAssocTypeUnderlyingType() -> some Any { return Optional(g()).f() } if #available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) { // CHECK: {{[\1, 2, 3\]|too old}} let x = opaqueAssocTypeUnderlyingType() print(x) // CHECK: {{Optional\(\[1, 2, 3\]\)|too damn old}} let y = structuralOpaqueAssocTypeUnderlyingType() print(y) } else { print("nope, still too old") print("too damn old") }
apache-2.0
15550b38c926fa01b538a8226e9767ce
21.431193
68
0.60409
2.839721
false
false
false
false
wj2061/ios7ptl-swift3.0
ch09-Multitasking/JuliaOp/JuliaOp/complex.swift
1
13531
// // complex.swift // complex // // Created by Dan Kogai on 6/12/14. // Copyright (c) 2014 Dan Kogai. All rights reserved. // import Foundation protocol RealType : FloatingPoint, AbsoluteValuable, Equatable, Comparable, Hashable { // Initializers init(_ value: UInt8) init(_ value: Int8) init(_ value: UInt16) init(_ value: Int16) init(_ value: UInt32) init(_ value: Int32) init(_ value: UInt64) init(_ value: Int64) init(_ value: UInt) init(_ value: Int) init(_ value: Double) init(_ value: Float) // Built-in operators prefix static func + (_: Self)->Self prefix static func - (_: Self)->Self static func + (_: Self, _: Self)->Self static func - (_: Self, _: Self)->Self static func * (_: Self, _: Self)->Self static func / (_: Self, _: Self)->Self static func += (_: inout Self, _: Self) static func -= (_: inout Self, _: Self) static func *= (_: inout Self, _: Self) static func /= (_: inout Self, _: Self) // methodized functions for protocol's sake var abs:Self { get } func cos()->Self func exp()->Self func log()->Self func sin()->Self func sqrt()->Self func hypot(_: Self)->Self func atan2(_: Self)->Self func pow(_: Self)->Self //class var LN10:Self { get } //class var epsilon:Self { get } } // Double is default since floating-point literals are Double by default extension Double : RealType { var abs:Double { return Swift.abs(self) } func cos()->Double { return Foundation.cos(self) } func exp()->Double { return Foundation.exp(self) } func log()->Double { return Foundation.log(self) } func sin()->Double { return Foundation.sin(self) } func sqrt()->Double { return Foundation.sqrt(self) } func atan2(_ y:Double)->Double { return Foundation.atan2(self, y) } func hypot(_ y:Double)->Double { return Foundation.hypot(self, y) } func pow(_ y:Double)->Double { return Foundation.pow(self, y) } // these ought to be static let // but give users a chance to overwrite it static var PI = 3.14159265358979323846264338327950288419716939937510 static var π = PI static var E = 2.718281828459045235360287471352662497757247093699 static var e = E static var LN2 = 0.6931471805599453094172321214581765680755001343602552 static var LOG2E = 1 / LN2 static var LN10 = 2.3025850929940456840179914546843642076011014886287729 static var LOG10E = 1/LN10 static var SQRT2 = 1.4142135623730950488016887242096980785696718753769480 static var SQRT1_2 = 1/SQRT2 static var epsilon = 0x1p-52 /// self * 1.0i var i:Complex<Double>{ return Complex<Double>(0.0, self) } } // But when explicitly typed you can use Float extension Float : RealType { var abs:Float { return Swift.abs(self) } func cos()->Float { return Foundation.cos(self) } func exp()->Float { return Foundation.exp(self) } func log()->Float { return Foundation.log(self) } func sin()->Float { return Foundation.sin(self) } func sqrt()->Float { return Foundation.sqrt(self) } func hypot(_ y:Float)->Float { return Foundation.hypot(self, y) } func atan2(_ y:Float)->Float { return Foundation.atan2(self, y) } func pow(_ y:Float)->Float { return Foundation.pow(self, y) } // these ought to be static let // but give users a chance to overwrite it static var PI:Float = 3.14159265358979323846264338327950288419716939937510 static var π:Float = PI static var E:Float = 2.718281828459045235360287471352662497757247093699 static var e:Float = E static var LN2:Float = 0.6931471805599453094172321214581765680755001343602552 static var LOG2E:Float = 1 / LN2 static var LN10:Float = 2.3025850929940456840179914546843642076011014886287729 static var LOG10E:Float = 1/LN10 static var SQRT2:Float = 1.4142135623730950488016887242096980785696718753769480 static var SQRT1_2:Float = 1/SQRT2 static var epsilon:Float = 0x1p-23 /// self * 1.0i var i:Complex<Float>{ return Complex<Float>(0.0 as Float, self) } } // el corazon struct Complex<T:RealType> : Equatable, CustomStringConvertible, Hashable { var (re, im): (T, T) init(_ re:T, _ im:T) { self.re = re self.im = im } init(){ self.init(T(0), T(0)) } init(abs:T, arg:T) { self.re = abs * arg.cos() self.im = abs * arg.sin() } /// real part thereof var real:T { get{ return re } set(r){ re = r } } /// imaginary part thereof var imag:T { get{ return im } set(i){ im = i } } /// absolute value thereof var abs:T { get { return re.hypot(im) } set(r){ let f = r / abs; re *= f; im *= f } } /// argument thereof var arg:T { get { return im.atan2(re) } set(t){ let m = abs; re = m * t.cos(); im = m * t.sin() } } /// norm thereof var norm:T { return re.hypot(im) } /// conjugate thereof var conj:Complex { return Complex(re, -im) } /// projection thereof var proj:Complex { if re.isFinite && im.isFinite { return self } else { return Complex( T(1)/T(0), (im.sign == .minus) ? -T(0) : T(0) ) } } /// (real, imag) var tuple:(T, T) { get { return (re, im) } set(t){ (re, im) = t} } /// z * i var i:Complex { return Complex(-im, re) } /// .description -- conforms to Printable var description:String { let plus = (im.sign == .minus) ? "" : "+" return "(\(re)\(plus)\(im).i)" } /// .hashvalue -- conforms to Hashable var hashValue:Int { // take most significant halves and join let bits = MemoryLayout<Int>.size * 4 let mask = bits == 16 ? 0xffff : 0xffffFFFF return (re.hashValue & ~mask) | (im.hashValue >> bits) } } // operator definitions infix operator ** { associativity right precedence 170 } infix operator **= { associativity right precedence 90 } infix operator =~ { associativity none precedence 130 } infix operator !~ { associativity none precedence 130 } // != is auto-generated thanks to Equatable func == <T>(lhs:Complex<T>, rhs:Complex<T>) -> Bool { return lhs.re == rhs.re && lhs.im == rhs.im } func == <T>(lhs:Complex<T>, rhs:T) -> Bool { return lhs.re == rhs && lhs.im == T(0) } func == <T>(lhs:T, rhs:Complex<T>) -> Bool { return rhs.re == lhs && rhs.im == T(0) } // +, += prefix func + <T>(z:Complex<T>) -> Complex<T> { return z } func + <T>(lhs:Complex<T>, rhs:Complex<T>) -> Complex<T> { return Complex(lhs.re + rhs.re, lhs.im + rhs.im) } func + <T>(lhs:Complex<T>, rhs:T) -> Complex<T> { return lhs + Complex(rhs, T(0)) } func + <T>(lhs:T, rhs:Complex<T>) -> Complex<T> { return Complex(lhs, T(0)) + rhs } func += <T>(lhs:inout Complex<T>, rhs:Complex<T>) { lhs.re += rhs.re ; lhs.im += rhs.im } func += <T>(lhs:inout Complex<T>, rhs:T) { lhs.re += rhs } // -, -= prefix func - <T>(z:Complex<T>) -> Complex<T> { return Complex<T>(-z.re, -z.im) } func - <T>(lhs:Complex<T>, rhs:Complex<T>) -> Complex<T> { return Complex(lhs.re - rhs.re, lhs.im - rhs.im) } func - <T>(lhs:Complex<T>, rhs:T) -> Complex<T> { return lhs - Complex(rhs, T(0)) } func - <T>(lhs:T, rhs:Complex<T>) -> Complex<T> { return Complex(lhs, T(0)) - rhs } func -= <T>(lhs:inout Complex<T>, rhs:Complex<T>) { lhs.re -= rhs.re ; lhs.im -= rhs.im } func -= <T>(lhs:inout Complex<T>, rhs:T) { lhs.re -= rhs } // *, *= func * <T>(lhs:Complex<T>, rhs:Complex<T>) -> Complex<T> { return Complex( lhs.re * rhs.re - lhs.im * rhs.im, lhs.re * rhs.im + lhs.im * rhs.re ) } func * <T>(lhs:Complex<T>, rhs:T) -> Complex<T> { return Complex(lhs.re * rhs, lhs.im * rhs) } func * <T>(lhs:T, rhs:Complex<T>) -> Complex<T> { return Complex(lhs * rhs.re, lhs * rhs.im) } func *= <T>(lhs:inout Complex<T>, rhs:Complex<T>) { lhs = lhs * rhs } func *= <T>(lhs:inout Complex<T>, rhs:T) { lhs = lhs * rhs } // /, /= // // cf. https://github.com/dankogai/swift-complex/issues/3 // func / <T>(lhs:Complex<T>, rhs:Complex<T>) -> Complex<T> { if rhs.re.abs >= rhs.im.abs { let r = rhs.im / rhs.re let d = rhs.re + rhs.im * r return Complex ( (lhs.re + lhs.im * r) / d, (lhs.im - lhs.re * r) / d ) } else { let r = rhs.re / rhs.im let d = rhs.re * r + rhs.im return Complex ( (lhs.re * r + lhs.im) / d, (lhs.im * r - lhs.re) / d ) } } func / <T>(lhs:Complex<T>, rhs:T) -> Complex<T> { return Complex(lhs.re / rhs, lhs.im / rhs) } func / <T>(lhs:T, rhs:Complex<T>) -> Complex<T> { return Complex(lhs, T(0)) / rhs } func /= <T>(lhs:inout Complex<T>, rhs:Complex<T>) { lhs = lhs / rhs } func /= <T>(lhs:inout Complex<T>, rhs:T) { lhs = lhs / rhs } // exp(z) func exp<T>(_ z:Complex<T>) -> Complex<T> { let abs = z.re.exp() let arg = z.im return Complex(abs * arg.cos(), abs * arg.sin()) } // log(z) func log<T>(_ z:Complex<T>) -> Complex<T> { return Complex(z.abs.log(), z.arg) } // log10(z) -- just because C++ has it func log10<T>(_ z:Complex<T>) -> Complex<T> { return log(z) / T(log(10.0)) } func log10<T:RealType>(_ r:T) -> T { return r.log() / T(log(10.0)) } // pow(b, x) func pow<T>(_ lhs:Complex<T>, _ rhs:Complex<T>) -> Complex<T> { if lhs == T(0) { return Complex(T(1), T(0)) } // 0 ** 0 == 1 let z = log(lhs) * rhs return exp(z) } func pow<T>(_ lhs:Complex<T>, _ rhs:T) -> Complex<T> { return pow(lhs, Complex(rhs, T(0))) } func pow<T>(_ lhs:T, _ rhs:Complex<T>) -> Complex<T> { return pow(Complex(lhs, T(0)), rhs) } // **, **= func **<T:RealType>(lhs:T, rhs:T) -> T { return lhs.pow(rhs) } func ** <T>(lhs:Complex<T>, rhs:Complex<T>) -> Complex<T> { return pow(lhs, rhs) } func ** <T>(lhs:T, rhs:Complex<T>) -> Complex<T> { return pow(lhs, rhs) } func ** <T>(lhs:Complex<T>, rhs:T) -> Complex<T> { return pow(lhs, rhs) } func **= <T:RealType>(lhs:inout T, rhs:T) { lhs = lhs.pow(rhs) } func **= <T>(lhs:inout Complex<T>, rhs:Complex<T>) { lhs = pow(lhs, rhs) } func **= <T>(lhs:inout Complex<T>, rhs:T) { lhs = pow(lhs, rhs) } // sqrt(z) func sqrt<T>(_ z:Complex<T>) -> Complex<T> { // return z ** 0.5 let d = z.re.hypot(z.im) let re = ((z.re + d)/T(2)).sqrt() if z.im < T(0) { return Complex(re, -((-z.re + d)/T(2)).sqrt()) } else { return Complex(re, ((-z.re + d)/T(2)).sqrt()) } } // cos(z) func cos<T>(_ z:Complex<T>) -> Complex<T> { // return (exp(i*z) + exp(-i*z)) / 2 return (exp(z.i) + exp(-z.i)) / T(2) } // sin(z) func sin<T>(_ z:Complex<T>) -> Complex<T> { // return (exp(i*z) - exp(-i*z)) / (2*i) return -(exp(z.i) - exp(-z.i)).i / T(2) } // tan(z) func tan<T>(_ z:Complex<T>) -> Complex<T> { // return sin(z) / cos(z) let ezi = exp(z.i), e_zi = exp(-z.i) return (ezi - e_zi) / (ezi + e_zi).i } // atan(z) func atan<T>(_ z:Complex<T>) -> Complex<T> { let l0 = log(T(1) - z.i), l1 = log(T(1) + z.i) return (l0 - l1).i / T(2) } func atan<T:RealType>(_ r:T) -> T { return atan(Complex(r, T(0))).re } // atan2(z, zz) func atan2<T>(_ z:Complex<T>, _ zz:Complex<T>) -> Complex<T> { return atan(z / zz) } // asin(z) func asin<T>(_ z:Complex<T>) -> Complex<T> { return -log(z.i + sqrt(T(1) - z*z)).i } // acos(z) func acos<T>(_ z:Complex<T>) -> Complex<T> { return log(z - sqrt(T(1) - z*z).i).i } // sinh(z) func sinh<T>(_ z:Complex<T>) -> Complex<T> { return (exp(z) - exp(-z)) / T(2) } // cosh(z) func cosh<T>(_ z:Complex<T>) -> Complex<T> { return (exp(z) + exp(-z)) / T(2) } // tanh(z) func tanh<T>(_ z:Complex<T>) -> Complex<T> { let ez = exp(z), e_z = exp(-z) return (ez - e_z) / (ez + e_z) } // asinh(z) func asinh<T>(_ z:Complex<T>) -> Complex<T> { return log(z + sqrt(z*z + T(1))) } // acosh(z) func acosh<T>(_ z:Complex<T>) -> Complex<T> { return log(z + sqrt(z*z - T(1))) } // atanh(z) func atanh<T>(_ z:Complex<T>) -> Complex<T> { let t0 = T(1) + z let t1 = T(1) - z return log(t0 / t1) / T(2) } // for the compatibility's sake w/ C++11 func abs<T>(_ z:Complex<T>) -> T { return z.abs } func arg<T>(_ z:Complex<T>) -> T { return z.arg } func real<T>(_ z:Complex<T>) -> T { return z.real } func imag<T>(_ z:Complex<T>) -> T { return z.imag } func norm<T>(_ z:Complex<T>) -> T { return z.norm } func conj<T>(_ z:Complex<T>) -> Complex<T> { return z.conj } func proj<T>(_ z:Complex<T>) -> Complex<T> { return z.proj } // // approximate comparisons // func =~ <T:RealType>(lhs:T, rhs:T) -> Bool { if lhs == rhs { return true } let t = (rhs - lhs) / rhs let epsilon = MemoryLayout<T>.size < 8 ? 0x1p-23 : 0x1p-52 return t.abs <= T(2) * T(epsilon) } func =~ <T>(lhs:Complex<T>, rhs:Complex<T>) -> Bool { if lhs == rhs { return true } return lhs.abs =~ rhs.abs } func =~ <T>(lhs:Complex<T>, rhs:T) -> Bool { return lhs.abs =~ rhs.abs } func =~ <T>(lhs:T, rhs:Complex<T>) -> Bool { return lhs.abs =~ rhs.abs } func !~ <T:RealType>(lhs:T, rhs:T) -> Bool { return !(lhs =~ rhs) } func !~ <T>(lhs:Complex<T>, rhs:Complex<T>) -> Bool { return !(lhs =~ rhs) } func !~ <T>(lhs:Complex<T>, rhs:T) -> Bool { return !(lhs =~ rhs) } func !~ <T>(lhs:T, rhs:Complex<T>) -> Bool { return !(lhs =~ rhs) } // typealiases typealias Complex64 = Complex<Double> typealias Complex32 = Complex<Float>
mit
529d0cd42bd4c24cdaeb1b378512c9cd
30.172811
86
0.567817
2.814437
false
false
false
false
NPAW/lib-plugin-ios
YouboraLib/YBSwiftTimer.swift
1
3104
// // YBTimer.swift // YouboraLib // // Created by nice on 22/01/2020. // Copyright © 2020 NPAW. All rights reserved. // import Foundation /** * Type of the success block * * - timer: (YBTimer *) The <YBTimer> from where the callback is being invoked. * - diffTime: (long) the time difference between the previous call. */ typealias SwiftTimerCallback = (_ timer: YBSwiftTimer, _ diffTime: Int64) -> Void /** * An Utility class that provides timed events in a defined time interval. */ @objcMembers open class YBSwiftTimer: NSObject { /** * The period at which to execute the callbacks. */ var interval: Double /** * Whether the Timer is running or not. */ private (set) var isRunning: Bool /** * Chrono to inform the callback how much time has passed since the previous call. */ private (set) var chrono: YBChrono var callbacks: [SwiftTimerCallback] /// Timer to control the callbacks private var timer: Timer? /** * Init * Same as calling <initWithCallback:andInterval:> with an interval of 5000 * @param callback the block to execute every <interval> milliseconds * @returns an instance of YBTimer */ convenience init(callback: @escaping SwiftTimerCallback) { self.init(callback: callback, andInterval: 5000) } /** * Init * @param callback the block to execute every <interval> milliseconds * @param intervalMillis interval of the timer * @returns an instance of YBTimer */ init(callback: @escaping SwiftTimerCallback, andInterval intervalMillis: Double) { self.chrono = YBChrono() self.callbacks = [callback] self.isRunning = false self.interval = intervalMillis } /** * Adds a new callback to fire on the timer * @param callback callback that must conform to type TimerCallback */ func addTimerCallback(_ callback: @escaping SwiftTimerCallback) { callbacks.append(callback) } /** * Starts the timer. */ func start() { if !self.isRunning { self.isRunning = true self.scheduleTimer() } } /** * Stops the timer. */ func stop() { if self.isRunning { self.isRunning = false self.timer?.invalidate() self.timer = nil } } private func scheduleTimer() { if Thread.isMainThread { if self.isRunning { self.chrono.start() self.timer = Timer.scheduledTimer(timeInterval: self.interval/1000, target: self, selector: #selector(performCallback), userInfo: nil, repeats: false) } } else { DispatchQueue.main.async { self.scheduleTimer() } } } @objc private func performCallback() { if self.callbacks.count > 0 { let elapsedTime = self.chrono.stop() self.callbacks.forEach { callback in callback(self, elapsedTime) } } self.scheduleTimer() } }
mit
8311c02defd9402fcf049d0f9dcd213d
25.07563
166
0.603932
4.426534
false
false
false
false
vimask/ClientCodeGen
ClientCodeGen/File content generators/Property.swift
1
5776
// // PropertyPresenter.swift // JSONExport // // Created by Ahmed on 11/2/14. // Copyright (c) 2014 Ahmed Ali. [email protected]. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // 1. Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // 2. Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // 3. The name of the contributor can not be used to endorse or promote products derived from this software // without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS // FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL // THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, // INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) // HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, // STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED // OF THE POSSIBILITY OF SUCH DAMAGE. import Foundation /** Represents all the meta data needed to export a JSON property in a valid syntax for the target language */ class Property : Equatable{ /** The native name that is suitable to export the JSON property in the target language */ var nativeName : String /** The JSON property name to fetch the value of this property from a JSON object */ var jsonName : String var constName : String? /** The string representation for the property type */ var type : String /** Whether the property represents a custom type */ var isCustomClass : Bool /** Whether the property represents an array */ var isArray : Bool /** The target language model */ var lang : LangModel /** A sample value which this property represents */ var sampleValue : AnyObject! /** If this property is an array, this property should contain the type for its elements */ var elementsType = "" /** For array properties, depetermines if the elements type is a custom type */ var elementsAreOfCustomType = false /** Returns a valid property declaration using the LangModel.instanceVarDefinition value */ func toString(_ forHeaderFile: Bool = false) -> String { var string : String! if forHeaderFile{ if lang.headerFileData.instanceVarWithSpeicalDefinition != nil && lang.headerFileData.typesNeedSpecialDefinition.index(of: type) != nil{ string = lang.headerFileData.instanceVarWithSpeicalDefinition }else{ string = lang.headerFileData.instanceVarDefinition } }else{ if lang.instanceVarWithSpeicalDefinition != nil && lang.typesNeedSpecialDefinition.index(of: type) != nil{ string = lang.instanceVarWithSpeicalDefinition }else{ string = lang.instanceVarDefinition } } string = string.replacingOccurrences(of: varType, with: type) string = string.replacingOccurrences(of: varName, with: nativeName) string = string.replacingOccurrences(of: jsonKeyName, with: jsonName) return string } func toConstVar(_ className: String) -> String { var string : String! if lang.constVarDefinition != nil { string = lang.constVarDefinition } else { string = "" } self.constName = "k"+className+nativeName.uppercaseFirstChar() string = string.replacingOccurrences(of: constKeyName, with: constName!) string = string.replacingOccurrences(of: jsonKeyName, with: jsonName) return string } /** The designated initializer for the class */ init(jsonName: String, nativeName: String, type: String, isArray: Bool, isCustomClass: Bool, lang: LangModel) { self.jsonName = jsonName.replacingOccurrences(of: " ", with: "") self.nativeName = nativeName.replacingOccurrences(of: " ", with: "") self.type = type self.isArray = isArray self.isCustomClass = isCustomClass self.lang = lang } /** Convenience initializer which calls the designated initializer with isArray = false and isCustomClass = false */ convenience init(jsonName: String, nativeName: String, type: String, lang: LangModel){ self.init(jsonName: jsonName, nativeName: nativeName, type: type, isArray: false, isCustomClass: false, lang: lang) } } //For Equatable implementation func ==(lhs: Property, rhs: Property) -> Bool { var matched = ObjectIdentifier(lhs) == ObjectIdentifier(rhs) if !matched{ matched = (lhs.nativeName == rhs.nativeName && lhs.jsonName == rhs.jsonName && lhs.type == rhs.type && lhs.isCustomClass == rhs.isCustomClass && lhs.isArray == rhs.isArray && lhs.elementsType == rhs.elementsType && lhs.elementsAreOfCustomType == rhs.elementsAreOfCustomType) } return matched }
mit
5b1fa19b807e412478eb97ba1fc848f1
33.795181
282
0.665166
4.639357
false
false
false
false
phimage/SLF4Swift
Backend/Swell/Swell.swift
1
3933
// // Swell.swift // SLF4Swift /* The MIT License (MIT) Copyright (c) 2015 Eric Marchand (phimage) 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 #if EXTERNAL import SLF4Swift #endif import Swell open class SwellSLF: LoggerType { open class var instance = SwellSLF(logger: Swell.getLogger("Shared")) open var level: SLFLogLevel { get { return SwellSLF.toLevel(self.logger.level) } set { self.logger.level = SwellSLF.fromLevel(newValue) } } open var name: LoggerKeyType { return self.logger.name } open var logger: Logger public init(logger: Logger) { self.logger = logger } open func info(_ message: LogMessageType) { self.logger.info(message) } open func error(_ message: LogMessageType) { self.logger.error(message) } open func severe(_ message: LogMessageType) { self.logger.severe(message) } open func warn(_ message: LogMessageType) { self.logger.warn(message) } open func debug(_ message: LogMessageType) { self.logger.debug(message) } open func verbose(_ message: LogMessageType) { self.logger.trace(message) } open func log(_ level: SLFLogLevel,_ message: LogMessageType) { self.logger.log(SwellSLF.fromLevel(level), message: message) } open func isLoggable(_ level: SLFLogLevel) -> Bool { return level <= self.level } open static func toLevel(_ level:LogLevel) -> SLFLogLevel { let predef = PredefinedLevel(rawValue: level.level)! switch(predef){ case .severe: return SLFLogLevel.Severe case .error: return SLFLogLevel.Error case .warn: return SLFLogLevel.Warn case .info: return SLFLogLevel.Info case .debug: return SLFLogLevel.Debug case .trace: return SLFLogLevel.Verbose } } open static func fromLevel(_ level:SLFLogLevel) -> LogLevel { switch(level){ case .Off: return LogLevel.getLevel(PredefinedLevel.severe) // XXX not working case .Severe: return LogLevel.getLevel(PredefinedLevel.severe) case .Error: return LogLevel.getLevel(PredefinedLevel.error) case .Warn: return LogLevel.getLevel(PredefinedLevel.warn) case .Info: return LogLevel.getLevel(PredefinedLevel.info) case .Debug: return LogLevel.getLevel(PredefinedLevel.debug) case .Verbose: return LogLevel.getLevel(PredefinedLevel.trace) case .All: return LogLevel.getLevel(PredefinedLevel.trace) } } } open class SwellSLFFactory: SLFLoggerFactory { open class var instance = SwellSLFFactory() public override init(){ super.init() } open override func doCreateLogger(_ name: LoggerKeyType) -> LoggerType { let logger = Swell.getLogger(name) return SwellSLF(logger: logger) } }
mit
ffa7416d4e30c0bcb5dcbeb298ac2ea7
30.97561
86
0.687007
4.261105
false
false
false
false
arcturus/magnet-client
ios/NotificationsHelper.swift
1
1150
// // NotificationsHelper.swift // magnet // // Created by Francisco Jordano on 12/07/2016. // import Foundation import UIKit @objc(NotificationsHelper) class NotificationsHelper: NSObject { static var enabled: Bool = true @objc class func register() { let notificationsSettings = UIUserNotificationSettings(forTypes: [.Alert, .Badge], categories: nil) UIApplication.sharedApplication().registerUserNotificationSettings(notificationsSettings) } class func updateNotifications() { guard enabled else { return } UIApplication.sharedApplication().cancelAllLocalNotifications() // Clean any badge UIApplication.sharedApplication().applicationIconBadgeNumber = 0 let notification = UILocalNotification() notification.alertBody = "Content found nearby" UIApplication.sharedApplication().presentLocalNotificationNow(notification) } @objc class func clearNotifications() { UIApplication.sharedApplication().cancelAllLocalNotifications() self.updateNotifications() } @objc class func enable() { enabled = true } @objc class func disable() { enabled = false } }
mpl-2.0
77f2ffa861c9c44432f12abadc71b455
26.404762
103
0.737391
5.373832
false
false
false
false
ArnavChawla/InteliChat
Carthage/Checkouts/swift-sdk/Source/DiscoveryV1/Models/TrainingExample.swift
1
1496
/** * 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 /** TrainingExample. */ public struct TrainingExample: Codable { public var documentID: String? public var crossReference: String? public var relevance: Int? // Map each property name to the key that shall be used for encoding/decoding. private enum CodingKeys: String, CodingKey { case documentID = "document_id" case crossReference = "cross_reference" case relevance = "relevance" } /** Initialize a `TrainingExample` with member variables. - parameter documentID: - parameter crossReference: - parameter relevance: - returns: An initialized `TrainingExample`. */ public init(documentID: String? = nil, crossReference: String? = nil, relevance: Int? = nil) { self.documentID = documentID self.crossReference = crossReference self.relevance = relevance } }
mit
06c78cb4edc7a303f9508504749a485d
28.92
98
0.697193
4.426036
false
false
false
false
MR-Zong/ZGResource
Project/FamilyEducationApp-master/家教/CustomFrauleinViewCell.swift
1
3867
// // CustomCollectionViewCell.swift // 家教 // // Created by goofygao on 15/10/19. // Copyright © 2015年 goofyy. All rights reserved. // import UIKit protocol CustomFrauleinViewCellDelegate { func getRowNumber(dict:NSDictionary) } class CustomFrauleinViewCell: UITableViewCell { var delegate:CustomFrauleinViewCellDelegate? //头像 @IBOutlet weak var avaterImage: UIImageView! //家教标题 @IBOutlet weak var StudentFrauleinTittle: UILabel! //家教星级 @IBOutlet weak var FrauleinLevel: UIView! //最近家教次数 @IBOutlet weak var recentFrauleinTime: UILabel! //家教地点 @IBOutlet weak var FrauleinPlace: UILabel! //家教详细信息 @IBOutlet weak var FrauleinDetailContent: UILabel! //家教期望资金 @IBOutlet weak var FrauleinWantMoney: UILabel! //家教学生性别 @IBOutlet weak var FrauleinStudentSex: UIImageView! //toolBar父视图 @IBOutlet weak var barView: UIView! //收藏按钮 @IBOutlet weak var collectButton: UIButton! //评论按钮 @IBOutlet weak var commentButton: UIButton! //喜欢按钮 @IBOutlet weak var likeButton: UIButton! override func layoutSubviews() { super.layoutSubviews() //设置cell层颜色 self.backgroundColor = UIColor(white: 1, alpha: 0.9) self.layer.cornerRadius = 10 self.layer.masksToBounds = true avaterImage.layer.cornerRadius = avaterImage.bounds.height/2 avaterImage.layer.masksToBounds = true barView.layer.borderWidth = 1 barView.layer.borderColor = UIColor(white: 0.5, alpha: 0.5).CGColor collectButton.layer.borderWidth = 1 collectButton.layer.borderColor = UIColor(white: 0.5, alpha: 0.1).CGColor commentButton.layer.borderWidth = 1 commentButton.layer.borderColor = UIColor(white: 0.5, alpha: 0.1).CGColor likeButton.layer.borderWidth = 1 likeButton.layer.borderColor = UIColor(white: 0.5, alpha: 0.1).CGColor collectButton.addTarget(self, action: "collectionAction:", forControlEvents: UIControlEvents.TouchDown) } override func setSelected(selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // self.delegate?.getRowNumber(<#T##dict: NSDictionary##NSDictionary#>) } //获取高度 func heightForCell(status:String)-> CGFloat{ //设置数据 self.FrauleinDetailContent.text = status //刷新布局 self.layoutIfNeeded() //返回最最下方控件的最大Y值,就是高度啦 return CGRectGetMaxY(barView.frame) } func collectionAction(sender:UIButton) { let timeS:Int = Int((sender.titleLabel?.text)!)! + 1 sender.setTitle("\(timeS)", forState: UIControlState.Normal) let animationImage = UIImageView() animationImage.image = UIImage(named: "collect_selecte.png") animationImage.center = sender.center animationImage.bounds.size = CGSizeMake(20, 20) sender.addSubview(animationImage) UIView.animateWithDuration(1.5, delay: 0, options: UIViewAnimationOptions.CurveEaseOut, animations: { () -> Void in animationImage.center.x = sender.center.x - 15 animationImage.center.y = sender.center.y - 15 animationImage.bounds.size = CGSizeMake(40, 40) animationImage.alpha = 0 }, completion: nil) sender.enabled = false } @IBAction func shareAction(sender: UIButton) { let alertSheet = UIActionSheet(title: "请选择要分享的平台", delegate: nil, cancelButtonTitle: "取消分享", destructiveButtonTitle: nil, otherButtonTitles: "QQ空间", "微信","新浪微博") alertSheet.showInView(self.contentView) } }
gpl-2.0
16e8a8458d9383887e0a02fa34b01972
34.705882
169
0.669687
4.092135
false
false
false
false
cpmpercussion/microjam
chirpey/BrowseController.swift
1
11310
// // BrowseController.swift // microjam // // Created by Henrik Brustad on 09/08/2017. // Copyright © 2017 Charles Martin. All rights reserved. // import UIKit import CloudKit private let reuseIdentifier = "browseCell" protocol BrowseControllerDelegate { func didSelect(performance: ChirpPerformance) } /// A CollectionViewController for browsing through multiple MicroJams. Not used in present Beta. class BrowseController: UICollectionViewController, UICollectionViewDelegateFlowLayout { var loadedPerformances = [ChirpPerformance]() var filters = [Filter]() var queryCursor: CKQueryOperation.Cursor? var resultsLimit = 24 var delegate: BrowseControllerDelegate? lazy var filterView : FilterView = { let view = FilterView(frame: .zero) view.translatesAutoresizingMaskIntoConstraints = false view.backgroundColor = .white view.layer.cornerRadius = 8 view.clipsToBounds = true view.delegate = self return view }() let dimView : UIView = { let view = UIView() view.backgroundColor = UIColor(white: 0, alpha: 0.6) return view }() let topViewContainer : UIView = { let view = UIView() view.translatesAutoresizingMaskIntoConstraints = false view.backgroundColor = UIColor(white: 0.6, alpha: 1) return view }() let searchButton : UIButton = { let button = UIButton(type: .system) button.setTitle("Search", for: .normal) button.setTitleColor(UIColor.white, for: .normal) button.translatesAutoresizingMaskIntoConstraints = false return button }() let filterButton : UIButton = { let button = UIButton(type: .system) button.addTarget(self, action: #selector(toggleFilterView), for: .touchUpInside) button.setTitle("Filters", for: .normal) button.setTitleColor(UIColor.white, for: .normal) button.translatesAutoresizingMaskIntoConstraints = false return button }() override func viewDidLoad() { super.viewDidLoad() collectionView!.register(BrowseCell.self, forCellWithReuseIdentifier: reuseIdentifier) collectionView!.backgroundColor = UIColor.white collectionView!.contentInset = UIEdgeInsets(top: 44, left: 0, bottom: 0, right: 0) collectionView!.scrollIndicatorInsets = UIEdgeInsets(top: 44, left: 0, bottom: 0, right: 0) setupViews() fetchPerformances() } private func setupViews() { view.addSubview(topViewContainer) topViewContainer.topAnchor.constraint(equalTo: view.topAnchor, constant: 64).isActive = true topViewContainer.rightAnchor.constraint(equalTo: view.rightAnchor).isActive = true topViewContainer.widthAnchor.constraint(equalTo: view.widthAnchor).isActive = true topViewContainer.heightAnchor.constraint(equalToConstant: 44).isActive = true topViewContainer.addSubview(searchButton) topViewContainer.addSubview(filterButton) searchButton.leftAnchor.constraint(equalTo: topViewContainer.leftAnchor).isActive = true searchButton.topAnchor.constraint(equalTo: topViewContainer.topAnchor).isActive = true searchButton.widthAnchor.constraint(equalTo: topViewContainer.widthAnchor, multiplier: 0.5).isActive = true searchButton.heightAnchor.constraint(equalTo: topViewContainer.heightAnchor).isActive = true filterButton.rightAnchor.constraint(equalTo: topViewContainer.rightAnchor).isActive = true filterButton.topAnchor.constraint(equalTo: topViewContainer.topAnchor).isActive = true filterButton.widthAnchor.constraint(equalTo: topViewContainer.widthAnchor, multiplier: 0.5).isActive = true filterButton.heightAnchor.constraint(equalTo: topViewContainer.heightAnchor).isActive = true // Dim entire screen tabBarController!.view.addSubview(dimView) tabBarController!.view.addSubview(filterView) dimView.frame = (navigationController?.view.bounds)! dimView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(dimViewTapped))) dimView.isHidden = true filterView.centerYAnchor.constraint(equalTo: tabBarController!.view.centerYAnchor).isActive = true filterView.leftAnchor.constraint(equalTo: tabBarController!.view.leftAnchor, constant: 32).isActive = true filterView.rightAnchor.constraint(equalTo: tabBarController!.view.rightAnchor, constant: -32).isActive = true filterView.heightAnchor.constraint(equalTo: filterView.widthAnchor, multiplier: 4/3).isActive = true filterView.isHidden = true } @objc func dimViewTapped() { toggleFilterView() } @objc func toggleFilterView() { if dimView.isHidden { dimView.isHidden = false filterView.isHidden = false } else { dimView.isHidden = true filterView.isHidden = true } } @objc func previewPerformance(sender: UIButton) { // The button is in the contentView of the cell, need to get the content view's superview... //if let superView = sender.superview?.superview { //let cell = superView as! BrowseCell // FIXME: Revise this statement to use a chirpplayer object. //ChirpView.play(performance: cell.performance!) //} } // MARK: UICollectionViewDataSource override func numberOfSections(in collectionView: UICollectionView) -> Int { return 1 } override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return loadedPerformances.count } override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath) as! BrowseCell let performance = loadedPerformances[indexPath.item] cell.performance = performance cell.performanceImageView.image = performance.image cell.performerNameLabel.text = "By: " + performance.performer cell.listenButton.addTarget(self, action: #selector(previewPerformance(sender:)), for: .touchUpInside) return cell } // MARK: UICollectionViewDelegate override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { if let delegate = delegate { let cell = collectionView.cellForItem(at: indexPath) as! BrowseCell delegate.didSelect(performance: cell.performance!) } } override func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) { if indexPath.item >= loadedPerformances.count - 1 { print("Should get more data...") loadMorePerformances() } } // MARK: UICollectionViewFlowLayoutDelegate func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { return CGSize(width: view.frame.width, height: 170) } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat { return 0 } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat { return 0 } } extension BrowseController: FilterViewDelegate { func didAdd(filterWithCategory category: String, andValue value: String) { filters.append(Filter(category: category, value: value)) print("Added filter for: ", category, value) } func didRemove(filterWithCategory category: String, andValue value: String) { if let i = filters.firstIndex(where: { filter in return filter.value == value }) { print("Removing filter at index: ", i) filters.remove(at: i) } } func didEndEditing() { fetchPerformances() toggleFilterView() } } // MARK: Database handling extension BrowseController { func getFilterPredicate() -> NSPredicate { if filters.isEmpty { return NSPredicate(value: true) } var predicates = [NSPredicate]() // Creating predicates for all filters in the list for filter in filters { let predicate = NSPredicate(format: "%K == %@", argumentArray: [filter.category, filter.value.lowercased()]) predicates.append(predicate) } // A series of AND predicates return NSCompoundPredicate(andPredicateWithSubpredicates: predicates) } func loadPerformances(withQueryOperation operation: CKQueryOperation) { let performanceStore = (UIApplication.shared.delegate as! AppDelegate).performanceStore operation.recordFetchedBlock = { record in if let performance = performanceStore.performanceFrom(record: record) { self.loadedPerformances.append(performance) } } operation.queryCompletionBlock = { (cursor, error) in if let error = error { print(error) return } // Used for continuing a search self.queryCursor = cursor // Reloading data on main thread when operation is complete DispatchQueue.main.async { self.collectionView!.reloadData() } } } func loadMorePerformances() { let publicDB = CKContainer.default().publicCloudDatabase if let cursor = queryCursor { let operation = CKQueryOperation(cursor: cursor) operation.resultsLimit = resultsLimit loadPerformances(withQueryOperation: operation) publicDB.add(operation) } } func fetchPerformances() { // TODO: Find a better way to update the loaded performances // Should look through the loaded performances and see if some passes the filters let publicDB = CKContainer.default().publicCloudDatabase loadedPerformances = [ChirpPerformance]() let predicate = getFilterPredicate() let query = CKQuery(recordType: PerfCloudKeys.type, predicate: predicate) query.sortDescriptors = [NSSortDescriptor(key: PerfCloudKeys.date, ascending: false)] let queryOperation = CKQueryOperation(query: query) queryOperation.resultsLimit = resultsLimit loadPerformances(withQueryOperation: queryOperation) publicDB.add(queryOperation) } }
mit
0d52871d39bb0b1e0c18cf93e332a360
34.901587
175
0.659917
5.551792
false
false
false
false
JohnKim/stalk.messenger
stalk-messenger/ios/RNSwiftSocketIO/SocketIOClient/SocketPacket.swift
7
6921
// // SocketPacket.swift // Socket.IO-Client-Swift // // Created by Erik Little on 1/18/15. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import Foundation struct SocketPacket { enum PacketType: Int { case connect, disconnect, event, ack, error, binaryEvent, binaryAck } private let placeholders: Int private static let logType = "SocketPacket" let nsp: String let id: Int let type: PacketType var binary: [Data] var data: [Any] var args: [Any] { if type == .event || type == .binaryEvent && data.count != 0 { return Array(data.dropFirst()) } else { return data } } var description: String { return "SocketPacket {type: \(String(type.rawValue)); data: " + "\(String(describing: data)); id: \(id); placeholders: \(placeholders); nsp: \(nsp)}" } var event: String { return String(describing: data[0]) } var packetString: String { return createPacketString() } init(type: PacketType, data: [Any] = [Any](), id: Int = -1, nsp: String, placeholders: Int = 0, binary: [Data] = [Data]()) { self.data = data self.id = id self.nsp = nsp self.type = type self.placeholders = placeholders self.binary = binary } mutating func addData(_ data: Data) -> Bool { if placeholders == binary.count { return true } binary.append(data) if placeholders == binary.count { fillInPlaceholders() return true } else { return false } } private func completeMessage(_ message: String) -> String { let restOfMessage: String if data.count == 0 { return message + "[]" } do { let jsonSend = try data.toJSON() guard let jsonString = String(data: jsonSend, encoding: .utf8) else { return message + "[]" } restOfMessage = jsonString } catch { DefaultSocketLogger.Logger.error("Error creating JSON object in SocketPacket.completeMessage", type: SocketPacket.logType) restOfMessage = "[]" } return message + restOfMessage } private func createPacketString() -> String { let typeString = String(type.rawValue) // Binary count? let binaryCountString = typeString + (type == .binaryEvent || type == .binaryAck ? "\(String(binary.count))-" : "") // Namespace? let nspString = binaryCountString + (nsp != "/" ? "\(nsp)," : "") // Ack number? let idString = nspString + (id != -1 ? String(id) : "") return completeMessage(idString) } // Called when we have all the binary data for a packet // calls _fillInPlaceholders, which replaces placeholders with the // corresponding binary private mutating func fillInPlaceholders() { data = data.map(_fillInPlaceholders) } // Helper method that looks for placeholders // If object is a collection it will recurse // Returns the object if it is not a placeholder or the corresponding // binary data private func _fillInPlaceholders(_ object: Any) -> Any { switch object { case let dict as [String: Any]: if dict["_placeholder"] as? Bool ?? false { return binary[dict["num"] as! Int] } else { return dict.reduce([String: Any](), {cur, keyValue in var cur = cur cur[keyValue.0] = _fillInPlaceholders(keyValue.1) return cur }) } case let arr as [Any]: return arr.map(_fillInPlaceholders) default: return object } } } extension SocketPacket { private static func findType(_ binCount: Int, ack: Bool) -> PacketType { switch binCount { case 0 where !ack: return .event case 0 where ack: return .ack case _ where !ack: return .binaryEvent case _ where ack: return .binaryAck default: return .error } } static func packetFromEmit(_ items: [Any], id: Int, nsp: String, ack: Bool) -> SocketPacket { let (parsedData, binary) = deconstructData(items) let packet = SocketPacket(type: findType(binary.count, ack: ack), data: parsedData, id: id, nsp: nsp, binary: binary) return packet } } private extension SocketPacket { // Recursive function that looks for NSData in collections static func shred(_ data: Any, binary: inout [Data]) -> Any { let placeholder = ["_placeholder": true, "num": binary.count] as [String : Any] switch data { case let bin as Data: binary.append(bin) return placeholder case let arr as [Any]: return arr.map({shred($0, binary: &binary)}) case let dict as [String: Any]: return dict.reduce([String: Any](), {cur, keyValue in var mutCur = cur mutCur[keyValue.0] = shred(keyValue.1, binary: &binary) return mutCur }) default: return data } } // Removes binary data from emit data // Returns a type containing the de-binaryed data and the binary static func deconstructData(_ data: [Any]) -> ([Any], [Data]) { var binary = [Data]() return (data.map({shred($0, binary: &binary)}), binary) } }
mit
97b37df7235353ccc254c62436f4d2e8
31.492958
123
0.567982
4.641851
false
false
false
false
10533176/TafelTaferelen
Tafel Taferelen/FirstLaunchViewController.swift
1
1935
// // FirstLaunchViewController.swift // Tafel Taferelen // // Created by Femke van Son on 24-01-17. // Copyright © 2017 Femke van Son. All rights reserved. // import UIKit import Firebase class FirstLaunchViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() let appLaunchedBefore = isAppAlreadyLaunchedOnce() DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(3), execute: { if appLaunchedBefore == true { self.userAllreadyLoggedIn() } else { let vc = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "introPage") self.present(vc, animated: true, completion: nil) } }) } // MARK: Functions to check if app launched before, if so, checks if user allready logged in. func isAppAlreadyLaunchedOnce()->Bool{ let defaults = UserDefaults.standard if defaults.string(forKey: "isAppAlreadyLaunchedOnce") != nil{ return true }else{ defaults.set(true, forKey: "isAppAlreadyLaunchedOnce") return false } } func userAllreadyLoggedIn() { FIRAuth.auth()?.addStateDidChangeListener { auth, user in if user != nil { let vc = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "userVC") self.present(vc, animated: true, completion: nil) } else { let vc = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "logIn") self.present(vc, animated: true, completion: nil) } } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
mit
0243cd23b0a84d5ffe278c613166948d
31.233333
119
0.600827
4.908629
false
false
false
false
CloudKitSpace/CKSIncrementalStore
Example/SeamDemo/NoteDetailViewController.swift
3
4417
// // DetailViewController.swift // SeamDemo // // Created by Nofel Mahmood on 18/11/2015. // Copyright © 2015 CloudKitSpace. All rights reserved. // import UIKit import CoreData // MARK: UIImagePickerControllerDelegate extension NoteDetailViewController: UIImagePickerControllerDelegate { func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) { let textAttachment = NSTextAttachment() textAttachment.image = image let attributedString = NSAttributedString(attachment: textAttachment) let mutableAttributedTextViewString = NSMutableAttributedString(attributedString: textView.attributedText) mutableAttributedTextViewString.appendAttributedString(attributedString) textView.attributedText = mutableAttributedTextViewString dismissViewControllerAnimated(true, completion: nil) } func imagePickerControllerDidCancel(picker: UIImagePickerController) { dismissViewControllerAnimated(true, completion: nil) } } extension NoteDetailViewController: UINavigationControllerDelegate { } class NoteDetailViewController: UIViewController { @IBOutlet var textView: UITextView! lazy var imagePickerController: UIImagePickerController = { let imagePickerController = UIImagePickerController() imagePickerController.delegate = self imagePickerController.sourceType = .SavedPhotosAlbum return imagePickerController }() var tempContext: NSManagedObjectContext! var note: Note! var noteObjectID: NSManagedObjectID? var folderObjectID: NSManagedObjectID! override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) textView.becomeFirstResponder() } override func viewDidLoad() { super.viewDidLoad() if let noteObjectID = noteObjectID { note = tempContext.objectWithID(noteObjectID) as! Note } else { note = Note.new(inContext: tempContext) as! Note note.folder = tempContext.objectWithID(folderObjectID) as? Folder } textView.text = note.text } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillShow:", name: UIKeyboardWillShowNotification, object: nil) NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillHide:", name: UIKeyboardWillHideNotification, object: nil) } override func viewWillDisappear(animated: Bool) { super.viewWillDisappear(animated) NSNotificationCenter.defaultCenter().removeObserver(self, name: UIKeyboardWillShowNotification, object: nil) NSNotificationCenter.defaultCenter().removeObserver(self, name: UIKeyboardWillHideNotification, object: nil) } // MARK: Keyboard func keyboardWillShow(notification: NSNotification) { guard let userInfo = notification.userInfo else { return } var keyboardFrame = userInfo["UIKeyboardFrameEndUserInfoKey"]!.CGRectValue keyboardFrame = textView.convertRect(keyboardFrame, fromView: nil) let intersect = CGRectIntersection(keyboardFrame, textView.bounds) if !CGRectIsNull(intersect) { let duration = userInfo["UIKeyboardAnimationDurationUserInfoKey"]!.doubleValue UIView.animateWithDuration(duration, animations: { self.textView.contentInset = UIEdgeInsetsMake(0, 0, intersect.size.height, 0) self.textView.scrollIndicatorInsets = UIEdgeInsetsMake(0, 0, intersect.size.height, 0) }) } } func keyboardWillHide(notification: NSNotification) { guard let userInfo = notification.userInfo else { return } let duration = userInfo["UIKeyboardAnimationDurationUserInfoKey"]!.doubleValue UIView.animateWithDuration(duration) { self.textView.contentInset = UIEdgeInsetsZero self.textView.scrollIndicatorInsets = UIEdgeInsetsZero } } // MARK: IBAction @IBAction func cameraButtonDidPress() { presentViewController(imagePickerController, animated: true, completion: nil) } @IBAction func doneButtonDidPress(sender: AnyObject) { textView.resignFirstResponder() if let noteText = textView.text where noteText.isEmpty == false { note.text = noteText tempContext.performBlockAndWait { do { try self.tempContext.save() } catch { print("Error saving ", error) } } } } }
mit
29fc0671b7366809bbd3b53e358f5539
35.196721
140
0.752944
5.647059
false
false
false
false
gustavoavena/MOPT
MOPT/LoginScreenViewController.swift
1
5883
// // ViewController.swift // login_test // // Created by Rodrigo Hilkner on 3/29/17. // Copyright © 2017 Rodrigo Hilkner. All rights reserved. // import UIKit import FBSDKLoginKit import CloudKit import Dispatch class LoginScreenViewController: UIViewController, FBSDKLoginButtonDelegate { fileprivate var userDelegate: UserServices fileprivate let ckHandler: CloudKitHandler //creating facebook login button instance let loginButtonObject: FBSDKLoginButton! = { let button = FBSDKLoginButton() button.readPermissions = ["public_profile", "email"] return button }() @IBOutlet weak var startupButton: UIButton! required init?(coder aDecoder: NSCoder) { self.ckHandler = CloudKitHandler() self.userDelegate = UserServices() super.init(coder: aDecoder) } override func viewDidLoad() { super.viewDidLoad() self.startupButton.isUserInteractionEnabled = false //checking if user is already logged in if (FBSDKAccessToken.current() != nil) { print("Usuario logado no Facebook.") //TODO chamar funcao que trava tudo self.userDelegate.fetchFacebookUserInfo() { (response, error) in //TODO atuala guard error == nil else { print("Error fetching user's facebook info.") return } if let userInfo = response { print("Fetched user's Facebook info.") var user = Cache.get(objectType: .user, objectWithID: userInfo["id"] as! ObjectID) as? User if user == nil { let urlString = "http://graph.facebook.com/\(userInfo["id"] as! String)/picture?type=large" user = User.create(ID: userInfo["id"] as! ObjectID, name: userInfo["name"] as! String, email: userInfo["email"] as! String, profilePictureURL: urlString) } let currentUser = CurrentUser.shared() currentUser.userID = user!.ID // FIXME: make sure currentUser is never nil // Logged user in self.startupButton.isUserInteractionEnabled = true // let userName = userInfo["name"] as! String // let userEmail = userInfo["email"] as! String // let userID = userInfo["id"] as! String // let userPictureURL = URL(string: "http://graph.facebook.com/\(userID)/picture?type=large")! // // let userRecordID = CKRecordID(recordName: userID) // self.ckHandler.fetchByRecordID(recordID: userRecordID) { // (response, error) in // // if let userRecord = response { // let currentUser = CurrentUser.shared() // currentUser.userRecordID = userRecord.recordID // Logged user in // let userServices = UserServices() // userServices.downloadImage(imageURL: userPictureURL, userRecordID: userRecord.recordID) // // } else { // self.userDelegate.createUser(fbID: userID, name: userName, email: userEmail, profilePictureURL: userPictureURL) // } // self.startupButton.isUserInteractionEnabled = true // } } } } self.view.addSubview(loginButtonObject) loginButtonObject.center = self.view.center //delegating loginButton to LoginScreenViewController self.loginButtonObject.delegate = self } //loginButton: called when user logs in func loginButton(_ loginButton: FBSDKLoginButton!, didCompleteWith result: FBSDKLoginManagerLoginResult!, error: Error!) { if ((error) != nil) { print("Error: \(error.localizedDescription)") } else if result.isCancelled { print("Login cancelled") } else { //getting user's facebook informations (id, name, email) self.userDelegate.fetchFacebookUserInfo(completionHandler: { (response, error) in guard error == nil else { print("Error fetching user's facebook info.") return } if let userInfo = response { let userName = userInfo["name"] as! String let userEmail = userInfo["email"] as! String let userID = userInfo["id"] as! String let userPictureURL = URL(string: "http://graph.facebook.com/\(userID)/picture?type=large")! let userRecordID = CKRecordID(recordName: userID) // self.ckHandler.fetchByRecordID(recordID: userRecordID) { // (response, error) in // // // if let userRecord = response { // let currentUser = CurrentUser.shared() // currentUser.userRecordID = userRecord.recordID // Logged user in // } else { // self.userDelegate.createUser(fbID: userID, name: userName, email: userEmail, profilePictureURL: userPictureURL) // } // self.startupButton.isUserInteractionEnabled = true // } } }) } } //loginButtonDidLogOut: called when user logs out public func loginButtonDidLogOut(_ loginButton: FBSDKLoginButton!) { print("tchauzinho") } }
mit
30b972f1079076d4fac1afc33f7461c3
36.705128
159
0.539952
5.352138
false
false
false
false
Sharelink/Bahamut
Bahamut/BahamutCommon/RegexUtil.swift
1
3022
// // RegexHelper.swift // Sharelink // // Created by AlexChow on 15/8/14. // Copyright © 2015年 GStudio. All rights reserved. // import Foundation // FIXME: comparison operators with optionals were removed from the Swift Standard Libary. // Consider refactoring the code to use the non-optional operators. fileprivate func < <T : Comparable>(lhs: T?, rhs: T?) -> Bool { switch (lhs, rhs) { case let (l?, r?): return l < r case (nil, _?): return true default: return false } } // FIXME: comparison operators with optionals were removed from the Swift Standard Libary. // Consider refactoring the code to use the non-optional operators. fileprivate func > <T : Comparable>(lhs: T?, rhs: T?) -> Bool { switch (lhs, rhs) { case let (l?, r?): return l > r default: return rhs < lhs } } public struct RegexMatcher { let regex: NSRegularExpression? init(_ pattern: String) { do { try regex = NSRegularExpression(pattern: pattern, options: .caseInsensitive) }catch let error as NSError { regex = nil debugLog(error.description) } } func match(_ input: String) -> Bool { let range = NSMakeRange(0, input.lengthOfBytes(using: String.Encoding.utf8)) let matches = regex?.matches(in: input, options: [],range: range) return matches?.count > 0 } func matchFirstString(_ input:String) -> String?{ let range = NSMakeRange(0, input.distance(from: input.startIndex, to: input.endIndex)) if let res = regex?.firstMatch(in: input, options: [], range: range),res.range.length > 0{ let locationIndex = input.index(input.startIndex, offsetBy: res.range.location) let endIndex = input.index(locationIndex, offsetBy: res.range.length) return input.substring(with: Range<String.Index>(uncheckedBounds: (lower: locationIndex, upper: endIndex))) }else{ return nil } } } /* infix operator.isRegexMatch(pattern:{ associativity none precedence 130 } */ extension String{ func isRegexMatch(pattern:String) -> Bool { if let _ = self.range(of: pattern, options: .regularExpression) { return true } return false } } //MARK: String Util extension String{ func isMobileNumber() -> Bool{ return self.isRegexMatch(pattern:"^((13[0-9])|(15[^4,\\D])|(18[0-9]))\\d{8}$") } func isEmail() -> Bool{ return self.isRegexMatch(pattern:"^\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*$") } func isPassword() -> Bool{ return self.isRegexMatch(pattern:"^[\\@A-Za-z0-9\\!\\#\\$\\%\\^\\&\\*\\.\\~]{6,22}$") } func isUsername() -> Bool{ return self.isRegexMatch(pattern:"^[_a-zA-Z0-9\\u4e00-\\u9fa5]{2,23}$") } func isNickName() -> Bool{ return self.isRegexMatch(pattern:"^[_a-zA-Z0-9]{1,23}|[_a-zA-Z0-9\\u4e00-\\u9fa5]{1,12}$") } }
mit
4fa9631444ed7a7ad3a88574b3109ad1
27.214953
119
0.59258
3.672749
false
false
false
false
zmarvin/EnjoyMusic
Pods/Macaw/Source/model/geom2d/Locus.swift
1
609
import Foundation open class Locus { public init() { } // GENERATED NOT open func bounds() -> Rect { return Rect() } // GENERATED NOT open func stroke(with: Stroke) -> Shape { return Shape(form: self, stroke: with) } // GENERATED NOT open func fill(with: Fill) -> Shape { return Shape(form: self, fill: with) } // GENERATED NOT open func stroke(fill: Fill = Color.black, width: Double = 1, cap: LineCap = .butt, join: LineJoin = .miter, dashes: [Double] = []) -> Shape { return Shape(form: self, stroke: Stroke(fill: fill, width: width, cap: cap, join: join, dashes: dashes)) } }
mit
0b4a0901fd01e56bbcb5a919c2b0e98c
20.75
143
0.64532
3.091371
false
false
false
false
proversity-org/edx-app-ios
Source/Core/Test/Code/MockResponseCache.swift
2
943
// // MockResponseCache.swift // edX // // Created by Akiva Leffert on 6/19/15. // Copyright (c) 2015 edX. All rights reserved. // import edXCore class MockResponseCache: NSObject, ResponseCache { fileprivate var backing : [String: ResponseCacheEntry] = [:] func fetchCacheEntryWithRequest(_ request: URLRequest, completion: @escaping (ResponseCacheEntry?) -> Void) { let key = responseCacheKeyForRequest(request) completion(key.flatMap{ backing[$0] }) } func setCacheResponse(_ response: HTTPURLResponse, withData data: Data?, forRequest request: URLRequest, completion: (() -> Void)?) { if let key = responseCacheKeyForRequest(request) { backing[key] = ResponseCacheEntry(data : data, response : response) } completion?() } func clear() { backing = [:] } var isEmpty : Bool { return backing.count == 0 } }
apache-2.0
6f88f04f92615d858c891484be95c926
26.735294
137
0.629905
4.490476
false
false
false
false
salmojunior/TMDb
TMDb/TMDb/Source/Infrastructure/Extensions/ImageViewExtension.swift
1
711
// // ImageViewExtension.swift // CITAppStore // // Created by SalmoJunior on 21/02/17. // Copyright © 2017 Salmo Junior. All rights reserved. // import UIKit extension UIImageView { /// Make a safe copy of UIImageView /// /// - Returns: clone of current UIImageView func clone() -> UIImageView { let cloneImageView = UIImageView(image: self.image) cloneImageView.frame = self.frame cloneImageView.clipsToBounds = self.clipsToBounds cloneImageView.contentMode = self.contentMode cloneImageView.isOpaque = self.isOpaque cloneImageView.layer.cornerRadius = self.layer.cornerRadius return cloneImageView } }
mit
e4245244b5edc79bd806ca9be585464b
25.296296
67
0.664789
4.701987
false
false
false
false
marklin2012/iOS_Animation
Section1/Chapter3/O2UIViewAnimation_completed/O2UIViewAnimation/ViewController.swift
1
6695
// // ViewController.swift // O2UIViewAnimation // // Created by O2.LinYi on 16/3/10. // Copyright © 2016年 jd.com. All rights reserved. // import UIKit // a delay function func delay(seconds seconds: Double, completion: () -> ()) { let popTime = dispatch_time(DISPATCH_TIME_NOW, Int64(Double(NSEC_PER_SEC) * seconds)) dispatch_after(popTime, dispatch_get_main_queue()) { () -> Void in completion() } } class ViewController: UIViewController, UITextFieldDelegate { @IBOutlet weak var loginBtn: UIButton! @IBOutlet weak var passwordField: UITextField! @IBOutlet weak var usernameField: UITextField! @IBOutlet weak var headingLabel: UILabel! @IBOutlet weak var cloud1: UIImageView! @IBOutlet weak var cloud2: UIImageView! @IBOutlet weak var cloud3: UIImageView! @IBOutlet weak var cloud4: UIImageView! // MARK: - further UI let spinner = UIActivityIndicatorView(activityIndicatorStyle: .WhiteLarge) let status = UIImageView(image: UIImage(named: "banner")) let label = UILabel() let messages = ["Connectiong ...", "Authorizing ...", "Sending credentials ...", "Failed"] var statusPosition = CGPoint.zero // MARK: - Lift cycle override func viewDidLoad() { super.viewDidLoad() // set up the UI loginBtn.layer.cornerRadius = 8.0 loginBtn.layer.masksToBounds = true spinner.frame = CGRect(x: -20, y: 6, width: 20, height: 20) spinner.startAnimating() spinner.alpha = 0 loginBtn.addSubview(spinner) status.hidden = true status.center = loginBtn.center view.addSubview(status) label.frame = CGRect(x: 0, y: 0, width: status.frame.size.width, height: status.frame.size.height) label.font = UIFont(name: "HelveticaNeue", size: 18) label.textColor = UIColor(red: 0.89, green: 0.38, blue: 0, alpha: 1) label.textAlignment = .Center status.addSubview(label) statusPosition = status.center } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) // set first position to move out the screen headingLabel.center.x -= view.bounds.width usernameField.center.x -= view.bounds.width passwordField.center.x -= view.bounds.width cloud1.alpha = 0.0 cloud2.alpha = 0.0 cloud3.alpha = 0.0 cloud4.alpha = 0.0 loginBtn.center.y += 30 loginBtn.alpha = 0 // present animation UIView.animateWithDuration(0.5) { () -> Void in self.headingLabel.center.x += self.view.bounds.width // usernameField.center.x += view.bounds.width } UIView.animateWithDuration(0.5, delay: 0.3, usingSpringWithDamping: 0.9, initialSpringVelocity: 0, options: [], animations: { () -> Void in self.usernameField.center.x += self.view.bounds.width }, completion: nil) UIView.animateWithDuration(0.5, delay: 0.4, usingSpringWithDamping: 0.9, initialSpringVelocity: 0, options: [.CurveEaseInOut ], animations: { () -> Void in self.passwordField.center.x += self.view.bounds.width }, completion: nil) UIView.animateWithDuration(0.5, delay: 0.5, options: [], animations: { () -> Void in self.cloud1.alpha = 1 }, completion: nil) UIView.animateWithDuration(0.5, delay: 0.7, options: [], animations: { () -> Void in self.cloud2.alpha = 1 }, completion: nil) UIView.animateWithDuration(0.5, delay: 0.9, options: [], animations: { () -> Void in self.cloud3.alpha = 1 }, completion: nil) UIView.animateWithDuration(0.5, delay: 1.1, options: [], animations: { () -> Void in self.cloud4.alpha = 1 }, completion: nil) UIView.animateWithDuration(0.5, delay: 0.5, usingSpringWithDamping: 0.5, initialSpringVelocity: 1, options: [], animations: { () -> Void in self.loginBtn.center.y -= 30 self.loginBtn.alpha = 1.0 }, completion: nil) } // MARK: - further methods @IBAction func login() { view.endEditing(true) // add animation UIView.animateWithDuration(1.5, delay: 0, usingSpringWithDamping: 0.2, initialSpringVelocity: 0, options: [], animations: { () -> Void in self.loginBtn.bounds.size.width += 80 }, completion: { _ in self.showMessage(index: 0) }) UIView.animateWithDuration(0.33, delay: 0, usingSpringWithDamping: 0.7, initialSpringVelocity: 0, options: [], animations: { () -> Void in self.loginBtn.center.y += 60 self.loginBtn.backgroundColor = UIColor(red: 0.85, green: 0.83, blue: 0.45, alpha: 1) self.spinner.center = CGPoint(x: 40, y: self.loginBtn.frame.size.height/2) self.spinner.alpha = 1 }, completion: nil) } func showMessage(index index: Int) { label.text = messages[index] UIView.transitionWithView(status, duration: 0.33, options: [.CurveEaseOut, .TransitionCurlDown], animations: { () -> Void in self.status.hidden = false }, completion: { _ in // transition completion delay(seconds: 2) { () -> () in if index < self.messages.count-1 { self.removeMessage(index: index) } else { // reset form } } }) } func removeMessage(index index: Int) { UIView.animateWithDuration(0.33, delay: 0, options: [], animations: { () -> Void in self.status.center.x += self.view.frame.size.width }, completion: { _ in self.status.hidden = true self.status.center = self.statusPosition self.showMessage(index: index+1) }) } // MARK: - UITextFieldDelegate func textFieldShouldReturn(textField: UITextField) -> Bool { let nextField = (textField === usernameField) ? passwordField : usernameField nextField.becomeFirstResponder() return true } }
mit
6e244253ec20f937529ebf00fb0753af
33.494845
147
0.56844
4.55548
false
false
false
false
apple/swift-experimental-string-processing
Sources/_StringProcessing/Engine/MECapture.swift
1
2543
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2021-2022 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 // //===----------------------------------------------------------------------===// @_implementationOnly import _RegexParser /* TODO: Specialized data structure for all captures: - We want to be able to refer to COW prefixes for which simple appends do not invalidate - We want a compact save-point representation TODO: Conjectures: - We should be able to remove the entire capture history, lazily recomputing it on-request from the initial stored save point - We should be able to keep these flat and simple, lazily constructing structured types on-request */ extension Processor { struct _StoredCapture { var range: Range<Position>? = nil var value: Any? = nil // An in-progress capture start fileprivate var currentCaptureBegin: Position? = nil fileprivate func _invariantCheck() { if range == nil { assert(value == nil) } } // MARK: - IPI var deconstructed: (range: Range<Position>, value: Any?)? { guard let r = range else { return nil } return (r, value) } /// Start a new capture. If the previously started one was un-ended, /// will clear it and restart. mutating func startCapture( _ idx: Position ) { _invariantCheck() defer { _invariantCheck() } currentCaptureBegin = idx } mutating func endCapture(_ idx: Position) { _invariantCheck() defer { _invariantCheck() } guard let low = currentCaptureBegin else { fatalError("Invariant violated: ending unstarted capture") } range = low..<idx value = nil // TODO: cleaner IPI around this... currentCaptureBegin = nil } mutating func registerValue( _ value: Any, overwriteInitial: SavePoint? = nil ) { _invariantCheck() defer { _invariantCheck() } self.value = value } } } struct MECaptureList { var values: Array<Processor._StoredCapture> var referencedCaptureOffsets: [ReferenceID: Int] func latestUntyped(from input: String) -> Array<Substring?> { values.map { guard let range = $0.range else { return nil } return input[range] } } }
apache-2.0
8210434da8a3b51119175e9b0b79ff06
23.68932
80
0.610303
4.573741
false
false
false
false
nvzqz/Sage
Sources/Move.swift
1
7118
// // Move.swift // Sage // // Copyright 2016-2017 Nikolai Vazquez // // 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. // /// A chess move from a start `Square` to an end `Square`. public struct Move: Hashable, CustomStringConvertible { /// The move's start square. public var start: Square /// The move's end square. public var end: Square /// The move's change in file. public var fileChange: Int { return end.file.rawValue - start.file.rawValue } /// The move's change in rank. public var rankChange: Int { return end.rank.rawValue - start.rank.rawValue } /// The move is a real change in location. public var isChange: Bool { return start != end } /// The move is diagonal. public var isDiagonal: Bool { let fileChange = self.fileChange return fileChange != 0 && abs(fileChange) == abs(rankChange) } /// The move is horizontal. public var isHorizontal: Bool { return start.file != end.file && start.rank == end.rank } /// The move is vertical. public var isVertical: Bool { return start.file == end.file && start.rank != end.rank } /// The move is horizontal or vertical. public var isAxial: Bool { return isHorizontal || isVertical } /// The move is leftward. public var isLeftward: Bool { return end.file < start.file } /// The move is rightward. public var isRightward: Bool { return end.file > start.file } /// The move is downward. public var isDownward: Bool { return end.rank < start.rank } /// The move is upward. public var isUpward: Bool { return end.rank > start.rank } /// The move is a knight jump two spaces horizontally and one space vertically, or two spaces vertically and one /// space horizontally. public var isKnightJump: Bool { let fileChange = abs(self.fileChange) let rankChange = abs(self.rankChange) return (fileChange == 2 && rankChange == 1) || (rankChange == 2 && fileChange == 1) } /// The move's direction in file, if any. public var fileDirection: File.Direction? { #if swift(>=3) if self.isLeftward { return .left } else if self.isRightward { return .right } else { return .none } #else if self.isLeftward { return .Left } else if self.isRightward { return .Right } else { return .None } #endif } /// The move's direction in rank, if any. public var rankDirection: Rank.Direction? { #if swift(>=3) if self.isUpward { return .up } else if self.isDownward { return .down } else { return .none } #else if self.isUpward { return .Up } else if self.isDownward { return .Down } else { return .None } #endif } /// A textual representation of `self`. public var description: String { return "\(start) >>> \(end)" } /// The hash value. public var hashValue: Int { return start.hashValue + (end.hashValue << 6) } /// Create a move with start and end squares. public init(start: Square, end: Square) { self.start = start self.end = end } /// Create a move with start and end locations. public init(start: Location, end: Location) { self.start = Square(location: start) self.end = Square(location: end) } /// A castle move for `color` in `direction`. public init(castle color: Color, direction: File.Direction) { let rank: Rank = color.isWhite ? 1 : 8 #if swift(>=3) self = Move(start: Square(file: .e, rank: rank), end: Square(file: direction == .left ? .c : .g, rank: rank)) #else self = Move(start: Square(file: .E, rank: rank), end: Square(file: direction == .Left ? .C : .G, rank: rank)) #endif } /// Returns the castle squares for a rook. internal func _castleSquares() -> (old: Square, new: Square) { let rank = start.rank let movedLeft = self.isLeftward #if swift(>=3) let old = Square(file: movedLeft ? .a : .h, rank: rank) let new = Square(file: movedLeft ? .d : .f, rank: rank) #else let old = Square(file: movedLeft ? .A : .H, rank: rank) let new = Square(file: movedLeft ? .D : .F, rank: rank) #endif return (old, new) } /// Returns a move with the end and start of `self` reversed. public func reversed() -> Move { return Move(start: end, end: start) } /// Returns the result of rotating `self` 180 degrees. public func rotated() -> Move { let start = Square(file: self.start.file.opposite(), rank: self.start.rank.opposite()) let end = Square(file: self.end.file.opposite(), rank: self.end.rank.opposite()) return start >>> end } /// Returns `true` if `self` is castle move for `color`. /// /// - parameter color: The color to check the rank against. If `nil`, the rank can be either 1 or 8. The default /// value is `nil`. public func isCastle(for color: Color? = nil) -> Bool { let startRank = start.rank if let color = color { guard startRank == Rank(startFor: color) else { return false } } else { guard startRank == 1 || startRank == 8 else { return false } } let endFile = end.file return startRank == end.rank && start.file == ._e && (endFile == ._c || endFile == ._g) } } #if swift(>=3) infix operator >>> #else infix operator >>> { } #endif /// Returns `true` if both moves are the same. public func == (lhs: Move, rhs: Move) -> Bool { return lhs.start == rhs.start && lhs.end == rhs.end } /// Returns a `Move` from the two squares. public func >>> (start: Square, end: Square) -> Move { return Move(start: start, end: end) } /// Returns a `Move` from the two locations. public func >>> (start: Location, rhs: Location) -> Move { return Square(location: start) >>> Square(location: rhs) }
apache-2.0
7565956c17c5592f93b17186a58201d9
29.161017
116
0.559146
4.107328
false
false
false
false
cnstoll/Snowman
Snowman/Drawing/LetterDrawing.swift
1
4332
// // LetterDrawing.swift // Snowman WatchKit Extension // // Created by Conrad Stoll on 7/26/17. // Copyright © 2017 Conrad Stoll. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import Foundation import UIKit public let LetterDrawingLoggingEnabled = false protocol LetterDrawing { var drawingHeight : CGFloat { get set } var drawingWidth : CGFloat { get set } var strokeWidth : CGFloat { get set } var path : UIBezierPath { get } func addPoint(_ point : CGPoint) -> UIBezierPath func addSegment() func generateImageVectorForAlphaChannel() -> [NSNumber] } extension UIImage { func pixelAlpha() -> [NSNumber] { var pixels = [NSNumber]() for w in 0...Int(self.size.width) - 1 { for h in 0...Int(self.size.height) - 1 { let point = CGPoint(x: w, y: h) let alpha = getPixelAlphaValue(at: point) let number = NSNumber(value: Float(alpha)) pixels.append(number) } } return pixels } func crop(rect: CGRect) -> UIImage { var rect = rect rect.origin.x*=self.scale rect.origin.y*=self.scale rect.size.width*=self.scale rect.size.height*=self.scale let imageRef = self.cgImage!.cropping(to: rect) let image = UIImage(cgImage: imageRef!, scale: self.scale, orientation: self.imageOrientation) return image } func scaleImage() -> UIImage? { let newSize = CGSize(width: 28, height: 28) let newRect = CGRect(x: 2, y: 2, width: newSize.width - 4.0, height: newSize.height - 4.0).integral UIGraphicsBeginImageContextWithOptions(newSize, false, 1) if let context = UIGraphicsGetCurrentContext() { context.interpolationQuality = .high let flipVertical = CGAffineTransform(a: 1, b: 0, c: 0, d: -1, tx: 0, ty: newSize.height) context.concatenate(flipVertical) context.draw(self.cgImage!, in: newRect) let newImage = UIImage(cgImage: context.makeImage()!) UIGraphicsEndImageContext() return newImage } return nil } func scaleImage(toSize newSize: CGSize) -> UIImage? { let newRect = CGRect(x: 0, y: 0, width: newSize.width, height: newSize.height).integral UIGraphicsBeginImageContextWithOptions(newSize, false, 1) if let context = UIGraphicsGetCurrentContext() { context.interpolationQuality = .high let flipVertical = CGAffineTransform(a: 1, b: 0, c: 0, d: -1, tx: 0, ty: newSize.height) context.concatenate(flipVertical) context.draw(self.cgImage!, in: newRect) let newImage = UIImage(cgImage: context.makeImage()!) UIGraphicsEndImageContext() return newImage } return nil } func getPixelAlphaValue(at point: CGPoint) -> CGFloat { guard let cgImage = cgImage, let pixelData = cgImage.dataProvider?.data else { return 0.0 } let data: UnsafePointer<UInt8> = CFDataGetBytePtr(pixelData) let bytesPerPixel = cgImage.bitsPerPixel / 8 let pixelInfo: Int = ((cgImage.bytesPerRow * Int(point.y)) + (Int(point.x) * bytesPerPixel)) // We don't need to know about color for this // let b = CGFloat(data[pixelInfo]) / CGFloat(255.0) // let g = CGFloat(data[pixelInfo+1]) / CGFloat(255.0) // let r = CGFloat(data[pixelInfo+2]) / CGFloat(255.0) // All we need is the alpha values let a = CGFloat(data[pixelInfo+3]) / CGFloat(255.0) return a } }
apache-2.0
8dd8e98067c6f885682346b0a7cfca61
34.793388
107
0.60725
4.414883
false
false
false
false
coshx/caravel
caravel-test/EventDataController.swift
1
7493
// // EventDataController.swift // caravel-test // // Created by Adrien on 29/05/15. // Copyright (c) 2015 Coshx Labs. All rights reserved. // import Foundation import UIKit import Caravel open class EventDataController: BaseController { @IBOutlet weak var _webView: UIWebView! fileprivate func _raise(_ name: String) { NSException(name: NSExceptionName(rawValue: name), reason: "", userInfo: nil).raise() } open override func viewDidLoad() { super.viewDidLoad() let tuple = setUp("event_data", webView: _webView) let action = {(bus: EventBus) in bus.post("Bool", data: true) bus.post("Int", data: 42) bus.post("Float", data: 19.92) bus.post("Double", data: 20.15) bus.post("String", data: "Churchill") bus.post("HazardousString", data: "There is a \" and a '") bus.post("Array", data: [1, 2, 3, 5]) bus.post("Dictionary", data: ["foo": 45, "bar": 89]) bus.post("ComplexArray", data: [["name": "Alice", "age": 24], ["name": "Bob", "age": 23]]) bus.post("ComplexDictionary", data: ["name": "Paul", "address": ["street": "Hugo", "city": "Bordeaux"], "games": ["Fifa", "Star Wars"]]) bus.register("True") {name, data in if let b = data as? Bool { if b != true { self._raise("True - wrong value") } } else { self._raise("True - wrong type") } } bus.register("False") {name, data in if let b = data as? Bool { if b != false { self._raise("False - wrong value") } } else { self._raise("False - wrong type") } } bus.register("Int") {name, data in if let i = data as? Int { if i != 987 { self._raise("Int - wrong value") } } else { self._raise("Int - wrong type") } } bus.register("Double") {name, data in if let d = data as? Double { if d != 15.15 { self._raise("Double - wrong value") } } else { self._raise("Double - wrong type") } } bus.register("String") {name, data in if let s = data as? String { if s != "Napoleon" { self._raise("String - wrong value") } } else { self._raise("String - wrong type") } } bus.register("UUID") {name, data in if let s = data as? String { if s != "9658ae60-9e0d-4da7-a63d-46fe75ff1db1" { self._raise("UUID - wrong value") } } else { self._raise("UUID - wrong type") } } bus.register("Array") {name, data in if let a = data as? NSArray { if a.count != 3 { self._raise("Array - wrong length") } if a[0] as! Int != 3 { self._raise("Array - wrong first element") } if a[1] as! Int != 1 { self._raise("Array - wrong second element") } if a[2] as! Int != 4 { self._raise("Array - wrong third element") } } else { self._raise("Array - wrong type") } } bus.register("Dictionary") {name, data in if let d = data as? NSDictionary { if d.count != 2 { self._raise("Dictionary - wrong length") } if d.value(forKey: "movie") as! String != "Once upon a time in the West" { self._raise("Dictionary - wrong first pair") } if d.value(forKey: "actor") as! String != "Charles Bronson" { self._raise("Dictionary - wrong second pair") } } else { self._raise("Dictionary - wrong type") } } bus.register("ComplexArray") {name, data in if let a = data as? NSArray { if a.count != 3 { self._raise("ComplexArray - wrong length") } if a[0] as! Int != 87 { self._raise("ComplexArray - wrong first element") } if let d = a[1] as? NSDictionary { if d.value(forKey: "name") as! String != "Bruce Willis" { self._raise("ComplexArray - wrong second element") } } else { self._raise("ComplexArray - wrong typed second element") } if a[2] as! String != "left-handed" { self._raise("ComplexArray - wrong third element") } } else { self._raise("ComplexArray - wrong type") } } bus.register("ComplexDictionary") {name, data in if let d = data as? NSDictionary { if d.value(forKey: "name") as! String != "John Malkovich" { self._raise("ComplexDictionary - wrong first pair") } if let a = d.value(forKey: "movies") as? NSArray { if a.count != 2 { self._raise("ComplexDictionary - wrong length") } if a[0] as! String != "Dangerous Liaisons" { self._raise("ComplexDictionary - wrong first element in array") } if a[1] as! String != "Burn after reading" { self._raise("ComplexDictionary - wrong second element in array") } } else { self._raise("ComplexDictionary - wrong typed second element") } if d.value(forKey: "kids") as! Int != 2 { self._raise("ComplexDictionary - wrong third pair") } } else { self._raise("ComplexDictionary - wrong type") } } bus.post("Ready") } if BaseController.isUsingWKWebView { Caravel.getDefault(self, wkWebView: getWKWebView(), draft: tuple.1!, whenReady: action) } else { Caravel.getDefault(self, webView: _webView, whenReady: action) } tuple.0() } }
mit
880e909ef85a4976f1398b0699aed86f
37.623711
148
0.395035
5.028859
false
false
false
false
rafaelcpalmeida/UFP-iOS
UFP/UFP/TeachersViewController.swift
1
3994
// // TeachersViewController.swift // UFP // // Created by Rafael Almeida on 1/06/17. // Copyright © 2017 Rafael Almeida. All rights reserved. // import UIKit import SwiftyJSON class TeachersViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, UISearchResultsUpdating, UISearchBarDelegate { @IBOutlet weak var activityIndicator: UIActivityIndicatorView! @IBOutlet weak var teachersTable: UITableView! let apiController = APIController() let tableCellIdentifier = "tableCell" let searchController = UISearchController(searchResultsController: nil) var teachers = [Teacher]() var filteredTeachers = [Teacher]() override func viewDidLoad() { super.viewDidLoad() teachersTable.delegate = self teachersTable.dataSource = self searchController.searchResultsUpdater = self searchController.searchBar.delegate = self definesPresentationContext = true searchController.dimsBackgroundDuringPresentation = false searchController.searchBar.searchBarStyle = UISearchBarStyle.minimal teachersTable.tableHeaderView = searchController.searchBar apiController.getTeachers(completionHandler: { (json, error) in self.activityIndicator.stopAnimating() if(json["status"] == "Ok") { for (_, data) in json["message"] { self.teachers.append(Teacher(name: data["nome"].stringValue, identifier: data["sigla"].stringValue)) } } else { } self.teachersTable.reloadData() }) } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if searchController.isActive && searchController.searchBar.text != "" { return filteredTeachers.count } return teachers.count } internal func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: tableCellIdentifier, for: indexPath as IndexPath) let teacher: Teacher if searchController.isActive && searchController.searchBar.text != "" { teacher = self.filteredTeachers[indexPath.row] } else { teacher = self.teachers[indexPath.row] } cell.textLabel?.text = teacher.name return cell } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { self.performSegue(withIdentifier: "showTeacherDetails", sender: nil) tableView.deselectRow(at: indexPath, animated: true) } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if let indexPath = teachersTable.indexPathForSelectedRow { let detailVC = segue.destination as! TeacherDetailsViewController let teacher: Teacher if searchController.isActive && searchController.searchBar.text != "" { teacher = self.filteredTeachers[indexPath.row] } else { teacher = self.teachers[indexPath.row] } detailVC.teacherInitials = teacher.identifier } } func filterContentForSearchText(searchText: String) { filteredTeachers = teachers.filter({( teacher : Teacher) -> Bool in return teacher.name.lowercased().contains(searchText.lowercased()) }) self.teachersTable.reloadData() } func searchBar(_ searchBar: UISearchBar, selectedScopeButtonIndexDidChange selectedScope: Int) { filterContentForSearchText(searchText: searchBar.text!) } func updateSearchResults(for searchController: UISearchController) { filterContentForSearchText(searchText: searchController.searchBar.text!) } }
mit
290c3cca271b1cc57e3cc3230013ff71
35.3
138
0.647132
5.924332
false
false
false
false
andrebocchini/SwiftChatty
SwiftChatty/Requests/Messages/SendMessageRequest.swift
1
732
// // SendMessageRequest.swift // SwiftChatty // // Created by Andre Bocchini on 1/24/16. // Copyright © 2016 Andre Bocchini. All rights reserved. import Alamofire /// -SeeAlso: http://winchatty.com/v2/readme#_Toc421451693 public struct SendMessageRequest: Request { public let endpoint: ApiEndpoint = .SendMessage public let httpMethod: HTTPMethod = .post public var account: Account public var customParameters: [String : Any] = [:] public init(withAccount account: Account, to: String, subject: String, body: String) { self.account = account self.customParameters["to"] = to self.customParameters["subject"] = subject self.customParameters["body"] = body } }
mit
af293b20bd55c35cb6b0aed899879183
27.115385
90
0.683995
4.153409
false
false
false
false
RainbowMango/UIImagePickerControllerDemo
UIImagePickerControllerDemo/UIImagePickerControllerDemo/AppDelegate.swift
1
6184
// // AppDelegate.swift // UIImagePickerControllerDemo // // Created by ruby on 14-12-26. // Copyright (c) 2014年 ruby. All rights reserved. // import UIKit import CoreData @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Override point for customization after application launch. return true } func applicationWillResignActive(application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. // Saves changes in the application's managed object context before the application terminates. self.saveContext() } // MARK: - Core Data stack lazy var applicationDocumentsDirectory: NSURL = { // The directory the application uses to store the Core Data store file. This code uses a directory named "com.ruby.UIImagePickerControllerDemo" in the application's documents Application Support directory. let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask) return urls[urls.count-1] as NSURL }() lazy var managedObjectModel: NSManagedObjectModel = { // The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model. let modelURL = NSBundle.mainBundle().URLForResource("UIImagePickerControllerDemo", withExtension: "momd")! return NSManagedObjectModel(contentsOfURL: modelURL)! }() lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator? = { // The persistent store coordinator for the application. This implementation creates and return a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail. // Create the coordinator and store var coordinator: NSPersistentStoreCoordinator? = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel) let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("UIImagePickerControllerDemo.sqlite") var error: NSError? = nil var failureReason = "There was an error creating or loading the application's saved data." if coordinator!.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil, error: &error) == nil { coordinator = nil // Report any error we got. let dict = NSMutableDictionary() dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data" dict[NSLocalizedFailureReasonErrorKey] = failureReason dict[NSUnderlyingErrorKey] = error error = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict) // Replace this with code to handle the error appropriately. // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. NSLog("Unresolved error \(error), \(error!.userInfo)") abort() } return coordinator }() lazy var managedObjectContext: NSManagedObjectContext? = { // Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail. let coordinator = self.persistentStoreCoordinator if coordinator == nil { return nil } var managedObjectContext = NSManagedObjectContext() managedObjectContext.persistentStoreCoordinator = coordinator return managedObjectContext }() // MARK: - Core Data Saving support func saveContext () { if let moc = self.managedObjectContext { var error: NSError? = nil if moc.hasChanges && !moc.save(&error) { // Replace this implementation with code to handle the error appropriately. // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. NSLog("Unresolved error \(error), \(error!.userInfo)") abort() } } } }
apache-2.0
764da23c81d701195fb2892a3c969d79
54.693694
290
0.719185
5.837583
false
false
false
false
jaften/calendar-Swift-2.0-
CVCalendar/CVCalendarMonthView.swift
2
6586
// // CVCalendarMonthView.swift // CVCalendar // // Created by E. Mozharovsky on 12/26/14. // Copyright (c) 2014 GameApp. All rights reserved. // import UIKit public final class CVCalendarMonthView: UIView { // MARK: - Non public properties private var interactiveView: UIView! public override var frame: CGRect { didSet { if let calendarView = calendarView { if calendarView.calendarMode == CalendarMode.MonthView { updateInteractiveView() } } } } private var touchController: CVCalendarTouchController { return calendarView.touchController } // MARK: - Public properties public var calendarView: CVCalendarView! public var date: NSDate! public var numberOfWeeks: Int! public var weekViews: [CVCalendarWeekView]! public var weeksIn: [[Int : [Int]]]? public var weeksOut: [[Int : [Int]]]? public var currentDay: Int? public var potentialSize: CGSize { get { return CGSizeMake(bounds.width, CGFloat(weekViews.count) * weekViews[0].bounds.height + calendarView.appearance.spaceBetweenWeekViews! * CGFloat(weekViews.count)) } } // MARK: - Initialization public init(calendarView: CVCalendarView, date: NSDate) { super.init(frame: CGRectZero) self.calendarView = calendarView self.date = date commonInit() } public override init(frame: CGRect) { super.init(frame: frame) } public required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } public func mapDayViews(body: (DayView) -> Void) { for weekView in self.weekViews { for dayView in weekView.dayViews { body(dayView) } } } } // MARK: - Creation and destruction extension CVCalendarMonthView { public func commonInit() { let calendarManager = calendarView.manager safeExecuteBlock({ self.numberOfWeeks = calendarManager.monthDateRange(self.date).countOfWeeks self.weeksIn = calendarManager.weeksWithWeekdaysForMonthDate(self.date).weeksIn self.weeksOut = calendarManager.weeksWithWeekdaysForMonthDate(self.date).weeksOut self.currentDay = Manager.dateRange(NSDate()).day }, collapsingOnNil: true, withObjects: date) } } // MARK: Content reload extension CVCalendarMonthView { public func reloadViewsWithRect(frame: CGRect) { self.frame = frame safeExecuteBlock({ for (index, weekView) in self.weekViews.enumerate() { if let size = self.calendarView.view.weekViewSize { weekView.frame = CGRectMake(0, size.height * CGFloat(index), size.width, size.height) weekView.reloadDayViews() } } }, collapsingOnNil: true, withObjects: weekViews) } } // MARK: - Content fill & update extension CVCalendarMonthView { public func updateAppearance(frame: CGRect) { self.frame = frame createWeekViews() } public func createWeekViews() { weekViews = [CVCalendarWeekView]() safeExecuteBlock({ for i in 0..<self.numberOfWeeks! { let weekView = CVCalendarWeekView(monthView: self, index: i) self.safeExecuteBlock({ self.weekViews!.append(weekView) }, collapsingOnNil: true, withObjects: self.weekViews) self.addSubview(weekView) } }, collapsingOnNil: true, withObjects: numberOfWeeks) } } // MARK: - Interactive view management & update extension CVCalendarMonthView { public func updateInteractiveView() { safeExecuteBlock({ let mode = self.calendarView!.calendarMode! if mode == .MonthView { if let interactiveView = self.interactiveView { interactiveView.frame = self.bounds interactiveView.removeFromSuperview() self.addSubview(interactiveView) } else { self.interactiveView = UIView(frame: self.bounds) self.interactiveView.backgroundColor = .clearColor() let tapRecognizer = UITapGestureRecognizer(target: self, action: "didTouchInteractiveView:") let pressRecognizer = UILongPressGestureRecognizer(target: self, action: "didPressInteractiveView:") pressRecognizer.minimumPressDuration = 0.3 self.interactiveView.addGestureRecognizer(pressRecognizer) self.interactiveView.addGestureRecognizer(tapRecognizer) self.addSubview(self.interactiveView) } } }, collapsingOnNil: false, withObjects: calendarView) } public func didPressInteractiveView(recognizer: UILongPressGestureRecognizer) { let location = recognizer.locationInView(self.interactiveView) let state: UIGestureRecognizerState = recognizer.state switch state { case .Began: touchController.receiveTouchLocation(location, inMonthView: self, withSelectionType: .Range(.Started)) case .Changed: touchController.receiveTouchLocation(location, inMonthView: self, withSelectionType: .Range(.Changed)) case .Ended: touchController.receiveTouchLocation(location, inMonthView: self, withSelectionType: .Range(.Ended)) default: break } } public func didTouchInteractiveView(recognizer: UITapGestureRecognizer) { let location = recognizer.locationInView(self.interactiveView) touchController.receiveTouchLocation(location, inMonthView: self, withSelectionType: .Single) } } // MARK: - Safe execution extension CVCalendarMonthView { public func safeExecuteBlock(block: Void -> Void, collapsingOnNil collapsing: Bool, withObjects objects: AnyObject?...) { for object in objects { if object == nil { if collapsing { fatalError("Object { \(object) } must not be nil!") } else { return } } } block() } }
mit
7035fea06b15e82b84a0e31d3c8db2d6
32.779487
174
0.602338
5.736934
false
false
false
false
JasperMeurs/photon-garage-door-opener
iOS/photon-garage-door-opener/photon-garage-door-opener/ViewController.swift
1
2309
// // ViewController.swift // photon-garage-door-opener // // Created by Jasper Meurs on 04/10/15. // Copyright © 2015 Jasper Meurs. All rights reserved. // import UIKit class ViewController: UIViewController { var myPhoton : SparkDevice? let particleConfig = ParticleConfiguration() override func viewWillAppear(animated: Bool) { if SparkCloud.sharedInstance() == nil { print("Nog instance created yet, logging in...") SparkCloud.sharedInstance().loginWithUser(particleConfig.particleUsername, password: particleConfig.particlePassword) { (error:NSError!) -> Void in if let _=error { print("Wrong credentials!") } else { print("Logged in!") } } } if myPhoton == nil { SparkCloud.sharedInstance().getDevices { (sparkDevices:[AnyObject]!, error:NSError!) -> Void in if let _=error { print("Check your internet connectivity") } else { if let devices = sparkDevices as? [SparkDevice] { for device in devices { if device.name == self.particleConfig.particleTargetDevice { self.myPhoton = device print("Device found") } } } } } } } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func operateGarageDoorButtonPressed() { if myPhoton != nil { let funcArgs = ["open"] myPhoton!.callFunction("operateDoor", withArguments: funcArgs) { (resultCode : NSNumber!, error : NSError!) -> Void in if (error == nil) { print("The door is opening") } } } else { print("Particle not yet loaded") } } }
mit
88cdc45a3bcf76800e6b4c7e13b9b477
27.85
155
0.509965
5.342593
false
true
false
false
shahmishal/swift
test/stdlib/UnsafePointerDiagnostics.swift
1
10562
// RUN: %target-typecheck-verify-swift // Test availability attributes on UnsafePointer initializers. // Assume the original source contains no UnsafeRawPointer types. func unsafePointerConversionAvailability( mrp: UnsafeMutableRawPointer, rp: UnsafeRawPointer, umpv: UnsafeMutablePointer<Void>, // expected-warning {{UnsafeMutablePointer<Void> has been replaced by UnsafeMutableRawPointer}} upv: UnsafePointer<Void>, // expected-warning {{UnsafePointer<Void> has been replaced by UnsafeRawPointer}} umpi: UnsafeMutablePointer<Int>, upi: UnsafePointer<Int>, umps: UnsafeMutablePointer<String>, ups: UnsafePointer<String>) { let omrp: UnsafeMutableRawPointer? = mrp let orp: UnsafeRawPointer? = rp let oumpv: UnsafeMutablePointer<Void> = umpv // expected-warning {{UnsafeMutablePointer<Void> has been replaced by UnsafeMutableRawPointer}} let oupv: UnsafePointer<Void>? = upv // expected-warning {{UnsafePointer<Void> has been replaced by UnsafeRawPointer}} let oumpi: UnsafeMutablePointer<Int>? = umpi let oupi: UnsafePointer<Int>? = upi let oumps: UnsafeMutablePointer<String>? = umps let oups: UnsafePointer<String>? = ups _ = UnsafeMutableRawPointer(mrp) _ = UnsafeMutableRawPointer(rp) // expected-error {{'init(_:)' has been renamed to 'init(mutating:)'}} _ = UnsafeMutableRawPointer(umpv) _ = UnsafeMutableRawPointer(upv) // expected-error {{'init(_:)' has been renamed to 'init(mutating:)'}} _ = UnsafeMutableRawPointer(umpi) _ = UnsafeMutableRawPointer(upi) // expected-error {{'init(_:)' has been renamed to 'init(mutating:)'}} _ = UnsafeMutableRawPointer(umps) _ = UnsafeMutableRawPointer(ups) // expected-error {{'init(_:)' has been renamed to 'init(mutating:)'}} _ = UnsafeMutableRawPointer(omrp) _ = UnsafeMutableRawPointer(orp) // expected-error {{'init(_:)' has been renamed to 'init(mutating:)'}} _ = UnsafeMutableRawPointer(oumpv) _ = UnsafeMutableRawPointer(oupv) // expected-error {{'init(_:)' has been renamed to 'init(mutating:)'}} _ = UnsafeMutableRawPointer(oumpi) _ = UnsafeMutableRawPointer(oupi) // expected-error {{'init(_:)' has been renamed to 'init(mutating:)'}} _ = UnsafeMutableRawPointer(oumps) _ = UnsafeMutableRawPointer(oups) // expected-error {{'init(_:)' has been renamed to 'init(mutating:)'}} // These all correctly pass with no error. _ = UnsafeRawPointer(mrp) _ = UnsafeRawPointer(rp) _ = UnsafeRawPointer(umpv) _ = UnsafeRawPointer(upv) _ = UnsafeRawPointer(umpi) _ = UnsafeRawPointer(upi) _ = UnsafeRawPointer(umps) _ = UnsafeRawPointer(ups) _ = UnsafeRawPointer(omrp) _ = UnsafeRawPointer(orp) _ = UnsafeRawPointer(oumpv) _ = UnsafeRawPointer(oupv) _ = UnsafeRawPointer(oumpi) _ = UnsafeRawPointer(oupi) _ = UnsafeRawPointer(oumps) _ = UnsafeRawPointer(oups) _ = UnsafePointer<Int>(upi) _ = UnsafePointer<Int>(oumpi) _ = UnsafePointer<Int>(oupi) _ = UnsafeMutablePointer<Int>(umpi) _ = UnsafeMutablePointer<Int>(oumpi) _ = UnsafeMutablePointer<Void>(rp) // expected-warning 4 {{UnsafeMutablePointer<Void> has been replaced by UnsafeMutableRawPointer}} expected-error {{cannot invoke initializer for type 'UnsafeMutablePointer<Void>' with an argument list of type '(UnsafeRawPointer)'}} expected-note {{overloads for 'UnsafeMutablePointer<Void>' exist with these partially matching parameter lists: (RawPointer), (UnsafeMutablePointer<Pointee>), (UnsafeMutablePointer<Pointee>?)}} _ = UnsafeMutablePointer<Void>(mrp) // expected-warning 4 {{UnsafeMutablePointer<Void> has been replaced by UnsafeMutableRawPointer}} expected-error {{cannot invoke initializer for type 'UnsafeMutablePointer<Void>' with an argument list of type '(UnsafeMutableRawPointer)'}} expected-note {{overloads for 'UnsafeMutablePointer<Void>' exist with these partially matching parameter lists: (RawPointer), (UnsafeMutablePointer<Pointee>), (UnsafeMutablePointer<Pointee>?)}} _ = UnsafeMutablePointer<Void>(umpv) // expected-warning {{UnsafeMutablePointer<Void> has been replaced by UnsafeMutableRawPointer}} _ = UnsafeMutablePointer<Void>(umpi) // expected-warning {{UnsafeMutablePointer<Void> has been replaced by UnsafeMutableRawPointer}} _ = UnsafeMutablePointer<Void>(umps) // expected-warning {{UnsafeMutablePointer<Void> has been replaced by UnsafeMutableRawPointer}} _ = UnsafePointer<Void>(rp) // expected-error {{cannot convert value of type 'UnsafeRawPointer' to expected argument type 'RawPointer'}} expected-warning 4 {{UnsafePointer<Void> has been replaced by UnsafeRawPointer}} _ = UnsafePointer<Void>(mrp) // expected-error {{cannot convert value of type 'UnsafeMutableRawPointer' to expected argument type 'RawPointer'}} expected-warning 4 {{UnsafePointer<Void> has been replaced by UnsafeRawPointer}} _ = UnsafePointer<Void>(umpv) // expected-warning {{UnsafePointer<Void> has been replaced by UnsafeRawPointer}} _ = UnsafePointer<Void>(upv) // expected-warning {{UnsafePointer<Void> has been replaced by UnsafeRawPointer}} _ = UnsafePointer<Void>(umpi) // expected-warning {{UnsafePointer<Void> has been replaced by UnsafeRawPointer}} _ = UnsafePointer<Void>(upi) // expected-warning {{UnsafePointer<Void> has been replaced by UnsafeRawPointer}} _ = UnsafePointer<Void>(umps) // expected-warning {{UnsafePointer<Void> has been replaced by UnsafeRawPointer}} _ = UnsafePointer<Void>(ups) // expected-warning {{UnsafePointer<Void> has been replaced by UnsafeRawPointer}} _ = UnsafeMutablePointer<Int>(rp) // expected-error {{cannot invoke initializer for type 'UnsafeMutablePointer<Int>' with an argument list of type '(UnsafeRawPointer)'}} expected-note {{overloads for 'UnsafeMutablePointer<Int>' exist with these partially matching parameter lists: (RawPointer), (UnsafeMutablePointer<Pointee>), (UnsafeMutablePointer<Pointee>?)}} _ = UnsafeMutablePointer<Int>(mrp) // expected-error {{cannot invoke initializer for type 'UnsafeMutablePointer<Int>' with an argument list of type '(UnsafeMutableRawPointer)'}} expected-note {{overloads for 'UnsafeMutablePointer<Int>' exist with these partially matching parameter lists: (RawPointer), (UnsafeMutablePointer<Pointee>), (UnsafeMutablePointer<Pointee>?)}} _ = UnsafeMutablePointer<Int>(orp) // expected-error {{cannot invoke initializer for type 'UnsafeMutablePointer<Int>' with an argument list of type '(UnsafeRawPointer?)'}} expected-note {{overloads for 'UnsafeMutablePointer<Int>' exist with these partially matching parameter lists: (RawPointer), (UnsafeMutablePointer<Pointee>), (UnsafeMutablePointer<Pointee>?)}} _ = UnsafeMutablePointer<Int>(omrp) // expected-error {{cannot invoke initializer for type 'UnsafeMutablePointer<Int>' with an argument list of type '(UnsafeMutableRawPointer?)'}} expected-note {{overloads for 'UnsafeMutablePointer<Int>' exist with these partially matching parameter lists: (RawPointer), (UnsafeMutablePointer<Pointee>), (UnsafeMutablePointer<Pointee>?)}} _ = UnsafePointer<Int>(rp) // expected-error {{cannot convert value of type 'UnsafeRawPointer' to expected argument type 'RawPointer'}} _ = UnsafePointer<Int>(mrp) // expected-error {{cannot convert value of type 'UnsafeMutableRawPointer' to expected argument type 'RawPointer'}} _ = UnsafePointer<Int>(orp) // expected-error {{cannot convert value of type 'UnsafeRawPointer?' to expected argument type 'RawPointer'}} _ = UnsafePointer<Int>(omrp) // expected-error {{cannot convert value of type 'UnsafeMutableRawPointer?' to expected argument type 'RawPointer'}} _ = UnsafePointer<Int>(ups) // expected-error {{cannot convert value of type 'UnsafePointer<String>' to expected argument type 'UnsafePointer<Int>'}} // expected-note@-1 {{arguments to generic parameter 'Pointee' ('String' and 'Int') are expected to be equal}} _ = UnsafeMutablePointer<Int>(umps) // expected-error {{cannot convert value of type 'UnsafeMutablePointer<String>' to expected argument type 'UnsafeMutablePointer<Int>'}} // expected-note@-1 {{arguments to generic parameter 'Pointee' ('String' and 'Int') are expected to be equal}} _ = UnsafePointer<String>(upi) // expected-error {{cannot convert value of type 'UnsafePointer<Int>' to expected argument type 'UnsafePointer<String>'}} // expected-note@-1 {{arguments to generic parameter 'Pointee' ('Int' and 'String') are expected to be equal}} _ = UnsafeMutablePointer<String>(umpi) // expected-error {{cannot convert value of type 'UnsafeMutablePointer<Int>' to expected argument type 'UnsafeMutablePointer<String>'}} // expected-note@-1 {{arguments to generic parameter 'Pointee' ('Int' and 'String') are expected to be equal}} } func unsafeRawBufferPointerConversions( mrp: UnsafeMutableRawPointer, rp: UnsafeRawPointer, mrbp: UnsafeMutableRawBufferPointer, rbp: UnsafeRawBufferPointer, mbpi: UnsafeMutableBufferPointer<Int>, bpi: UnsafeBufferPointer<Int>) { let omrp: UnsafeMutableRawPointer? = mrp let orp: UnsafeRawPointer? = rp _ = UnsafeMutableRawBufferPointer(start: mrp, count: 1) _ = UnsafeRawBufferPointer(start: mrp, count: 1) _ = UnsafeMutableRawBufferPointer(start: rp, count: 1) // expected-error {{cannot convert value of type 'UnsafeRawPointer' to expected argument type 'UnsafeMutableRawPointer?'}} _ = UnsafeRawBufferPointer(start: rp, count: 1) _ = UnsafeMutableRawBufferPointer(mrbp) _ = UnsafeRawBufferPointer(mrbp) _ = UnsafeMutableRawBufferPointer(rbp) // expected-error {{missing argument label 'mutating:' in call}} _ = UnsafeRawBufferPointer(rbp) _ = UnsafeMutableRawBufferPointer(mbpi) _ = UnsafeRawBufferPointer(mbpi) _ = UnsafeMutableRawBufferPointer(bpi) // expected-error {{cannot invoke initializer for type 'UnsafeMutableRawBufferPointer' with an argument list of type '(UnsafeBufferPointer<Int>)'}} expected-note {{overloads for 'UnsafeMutableRawBufferPointer' exist with these partially matching parameter lists: (UnsafeMutableBufferPointer<T>), (UnsafeMutableRawBufferPointer)}} _ = UnsafeRawBufferPointer(bpi) _ = UnsafeMutableRawBufferPointer(start: omrp, count: 1) _ = UnsafeRawBufferPointer(start: omrp, count: 1) _ = UnsafeMutableRawBufferPointer(start: orp, count: 1) // expected-error {{cannot convert value of type 'UnsafeRawPointer?' to expected argument type 'UnsafeMutableRawPointer?'}} _ = UnsafeRawBufferPointer(start: orp, count: 1) } struct SR9800 { func foo(_: UnsafePointer<CChar>) {} func foo(_: UnsafePointer<UInt8>) {} func ambiguityTest(buf: UnsafeMutablePointer<CChar>) { _ = foo(UnsafePointer(buf)) // this call should be unambiguoius } }
apache-2.0
900e182bfbf24046041368189de74730
76.661765
470
0.754308
4.746966
false
false
false
false
liuchuo/Swift-practice
20150612-3.playground/Contents.swift
1
748
//: Playground - noun: a place where people can play import UIKit //函数返回值 //1.无返回值 func increment(inout value : Double,amount : Double = 1.0) { value += amount } func increment1(inout value : Double,amount : Double = 1.0) ->() { value += amount } func increment2(inout value : Double,amount : Double = 1.0) ->Void { value += amount } //2.一个返回值 //3.多个返回值 1、多个参数声明为引用类型传递 2、将返回定义为元组类型 func position(dt : Double,speed : (x : Int,y : Int)) -> (x : Int,y : Int) { var posx : Int = speed.x * Int(dt) var posy : Int = speed.y * Int(dt) return (posx,posy) } let move = position(60.0, (10,-5)) println("物体位移: \(move.x),\(move.y)")
gpl-2.0
1a0852e597afbbb1fef0790c7af5bc82
22.285714
75
0.618098
2.762712
false
false
false
false
roambotics/swift
test/Sanitizers/tsan/racy_async_let_fibonacci.swift
3
1831
// RUN: %target-swiftc_driver %s -Xfrontend -disable-availability-checking -parse-as-library %import-libdispatch -target %sanitizers-target-triple -g -sanitize=thread -o %t // RUN: %target-codesign %t // RUN: env %env-TSAN_OPTIONS="abort_on_error=0" not %target-run %t 2>&1 | %swift-demangle --simplified | %FileCheck %s // REQUIRES: executable_test // REQUIRES: concurrency // REQUIRES: libdispatch // REQUIRES: tsan_runtime // rdar://76038845 // REQUIRES: concurrency_runtime // UNSUPPORTED: back_deployment_runtime // rdar://86825277 // https://github.com/apple/swift/issues/58082 // UNSUPPORTED: CPU=arm64 || CPU=arm64e // Disabled because this test is flaky rdar://76542113 // REQUIRES: rdar76542113 func fib(_ n: Int) -> Int { var first = 0 var second = 1 for _ in 0..<n { let temp = first first = second second = temp + first } return first } var racyCounter = 0 @available(SwiftStdlib 5.1, *) func asyncFib(_ n: Int) async -> Int { racyCounter += 1 if n == 0 || n == 1 { return n } async let first = await asyncFib(n-2) async let second = await asyncFib(n-1) // Sleep a random amount of time waiting on the result producing a result. await Task.sleep(UInt64.random(in: 0..<100) * 1_000_000) let result = await first + second // Sleep a random amount of time before producing a result. await Task.sleep(UInt64.random(in: 0..<100) * 1_000_000) return result } @available(SwiftStdlib 5.1, *) func runFibonacci(_ n: Int) async { let result = await asyncFib(n) print() print("Async fib = \(result), sequential fib = \(fib(n))") assert(result == fib(n)) } @available(SwiftStdlib 5.1, *) @main struct Main { static func main() async { await runFibonacci(10) } } // CHECK: ThreadSanitizer: Swift access race // CHECK: Location is global 'racyCounter'
apache-2.0
f3e8775e00df0a89391da471d9ff3486
24.430556
172
0.676133
3.323049
false
false
false
false
Piwigo/Piwigo-Mobile
fastlane/SnapshotHelper.swift
1
11671
// // SnapshotHelper.swift // Example // // Created by Felix Krause on 10/8/15. // // ----------------------------------------------------- // IMPORTANT: When modifying this file, make sure to // increment the version number at the very // bottom of the file to notify users about // the new SnapshotHelper.swift // ----------------------------------------------------- import Foundation import XCTest var deviceLanguage = "" var locale = "" func setupSnapshot(_ app: XCUIApplication, waitForAnimations: Bool = true) { Snapshot.setupSnapshot(app, waitForAnimations: waitForAnimations) } func snapshot(_ name: String, waitForLoadingIndicator: Bool) { if waitForLoadingIndicator { Snapshot.snapshot(name) } else { Snapshot.snapshot(name, timeWaitingForIdle: 0) } } /// - Parameters: /// - name: The name of the snapshot /// - timeout: Amount of seconds to wait until the network loading indicator disappears. Pass `0` if you don't want to wait. func snapshot(_ name: String, timeWaitingForIdle timeout: TimeInterval = 20) { Snapshot.snapshot(name, timeWaitingForIdle: timeout) } enum SnapshotError: Error, CustomDebugStringConvertible { case cannotFindSimulatorHomeDirectory case cannotRunOnPhysicalDevice var debugDescription: String { switch self { case .cannotFindSimulatorHomeDirectory: return "Couldn't find simulator home location. Please, check SIMULATOR_HOST_HOME env variable." case .cannotRunOnPhysicalDevice: return "Can't use Snapshot on a physical device." } } } @objcMembers open class Snapshot: NSObject { static var app: XCUIApplication? static var waitForAnimations = true static var cacheDirectory: URL? static var screenshotsDirectory: URL? { return cacheDirectory?.appendingPathComponent("screenshots", isDirectory: true) } open class func setupSnapshot(_ app: XCUIApplication, waitForAnimations: Bool = true) { Snapshot.app = app Snapshot.waitForAnimations = waitForAnimations do { let cacheDir = try getCacheDirectory() Snapshot.cacheDirectory = cacheDir setLanguage(app) setLocale(app) setLaunchArguments(app) } catch let error { NSLog(error.localizedDescription) } } class func setLanguage(_ app: XCUIApplication) { guard let cacheDirectory = self.cacheDirectory else { NSLog("CacheDirectory is not set - probably running on a physical device?") return } let path = cacheDirectory.appendingPathComponent("language.txt") do { let trimCharacterSet = CharacterSet.whitespacesAndNewlines deviceLanguage = try String(contentsOf: path, encoding: .utf8).trimmingCharacters(in: trimCharacterSet) app.launchArguments += ["-AppleLanguages", "(\(deviceLanguage))"] } catch { NSLog("Couldn't detect/set language...") } } class func setLocale(_ app: XCUIApplication) { guard let cacheDirectory = self.cacheDirectory else { NSLog("CacheDirectory is not set - probably running on a physical device?") return } let path = cacheDirectory.appendingPathComponent("locale.txt") do { let trimCharacterSet = CharacterSet.whitespacesAndNewlines locale = try String(contentsOf: path, encoding: .utf8).trimmingCharacters(in: trimCharacterSet) } catch { NSLog("Couldn't detect/set locale...") } if locale.isEmpty && deviceLanguage.isEmpty == false { locale = Locale(identifier: deviceLanguage).identifier } if locale.isEmpty == false { app.launchArguments += ["-AppleLocale", "\"\(locale)\""] } } class func setLaunchArguments(_ app: XCUIApplication) { guard let cacheDirectory = self.cacheDirectory else { NSLog("CacheDirectory is not set - probably running on a physical device?") return } let path = cacheDirectory.appendingPathComponent("snapshot-launch_arguments.txt") app.launchArguments += ["-FASTLANE_SNAPSHOT", "YES", "-ui_testing"] do { let launchArguments = try String(contentsOf: path, encoding: String.Encoding.utf8) let regex = try NSRegularExpression(pattern: "(\\\".+?\\\"|\\S+)", options: []) let matches = regex.matches(in: launchArguments, options: [], range: NSRange(location: 0, length: launchArguments.count)) let results = matches.map { result -> String in (launchArguments as NSString).substring(with: result.range) } app.launchArguments += results } catch { NSLog("Couldn't detect/set launch_arguments...") } } open class func snapshot(_ name: String, timeWaitingForIdle timeout: TimeInterval = 20) { if timeout > 0 { waitForLoadingIndicatorToDisappear(within: timeout) } NSLog("snapshot: \(name)") // more information about this, check out https://docs.fastlane.tools/actions/snapshot/#how-does-it-work if Snapshot.waitForAnimations { sleep(1) // Waiting for the animation to be finished (kind of) } #if os(OSX) guard let app = self.app else { NSLog("XCUIApplication is not set. Please call setupSnapshot(app) before snapshot().") return } app.typeKey(XCUIKeyboardKeySecondaryFn, modifierFlags: []) #else guard self.app != nil else { NSLog("XCUIApplication is not set. Please call setupSnapshot(app) before snapshot().") return } let screenshot = XCUIScreen.main.screenshot() #if os(iOS) let image = XCUIDevice.shared.orientation.isLandscape ? fixLandscapeOrientation(image: screenshot.image) : screenshot.image #else let image = screenshot.image #endif guard var simulator = ProcessInfo().environment["SIMULATOR_DEVICE_NAME"], let screenshotsDir = screenshotsDirectory else { return } do { // The simulator name contains "Clone X of " inside the screenshot file when running parallelized UI Tests on concurrent devices let regex = try NSRegularExpression(pattern: "Clone [0-9]+ of ") let range = NSRange(location: 0, length: simulator.count) simulator = regex.stringByReplacingMatches(in: simulator, range: range, withTemplate: "") let path = screenshotsDir.appendingPathComponent("\(simulator)-\(name).png") #if swift(<5.0) UIImagePNGRepresentation(image)?.write(to: path, options: .atomic) #else try image.pngData()?.write(to: path, options: .atomic) #endif } catch let error { NSLog("Problem writing screenshot: \(name) to \(screenshotsDir)/\(simulator)-\(name).png") NSLog(error.localizedDescription) } #endif } class func fixLandscapeOrientation(image: UIImage) -> UIImage { #if os(watchOS) return image #else if #available(iOS 10.0, *) { let format = UIGraphicsImageRendererFormat() format.scale = image.scale let renderer = UIGraphicsImageRenderer(size: image.size, format: format) return renderer.image { context in image.draw(in: CGRect(x: 0, y: 0, width: image.size.width, height: image.size.height)) } } else { return image } #endif } class func waitForLoadingIndicatorToDisappear(within timeout: TimeInterval) { #if os(tvOS) return #endif guard let app = self.app else { NSLog("XCUIApplication is not set. Please call setupSnapshot(app) before snapshot().") return } let networkLoadingIndicator = app.otherElements.deviceStatusBars.networkLoadingIndicators.element let networkLoadingIndicatorDisappeared = XCTNSPredicateExpectation(predicate: NSPredicate(format: "exists == false"), object: networkLoadingIndicator) _ = XCTWaiter.wait(for: [networkLoadingIndicatorDisappeared], timeout: timeout) } class func getCacheDirectory() throws -> URL { let cachePath = "Library/Caches/tools.fastlane" // on OSX config is stored in /Users/<username>/Library // and on iOS/tvOS/WatchOS it's in simulator's home dir #if os(OSX) let homeDir = URL(fileURLWithPath: NSHomeDirectory()) return homeDir.appendingPathComponent(cachePath) #elseif arch(i386) || arch(x86_64) || arch(arm64) guard let simulatorHostHome = ProcessInfo().environment["SIMULATOR_HOST_HOME"] else { throw SnapshotError.cannotFindSimulatorHomeDirectory } let homeDir = URL(fileURLWithPath: simulatorHostHome) return homeDir.appendingPathComponent(cachePath) #else throw SnapshotError.cannotRunOnPhysicalDevice #endif } } private extension XCUIElementAttributes { var isNetworkLoadingIndicator: Bool { if hasAllowListedIdentifier { return false } let hasOldLoadingIndicatorSize = frame.size == CGSize(width: 10, height: 20) let hasNewLoadingIndicatorSize = frame.size.width.isBetween(46, and: 47) && frame.size.height.isBetween(2, and: 3) return hasOldLoadingIndicatorSize || hasNewLoadingIndicatorSize } var hasAllowListedIdentifier: Bool { let allowListedIdentifiers = ["GeofenceLocationTrackingOn", "StandardLocationTrackingOn"] return allowListedIdentifiers.contains(identifier) } func isStatusBar(_ deviceWidth: CGFloat) -> Bool { if elementType == .statusBar { return true } guard frame.origin == .zero else { return false } let oldStatusBarSize = CGSize(width: deviceWidth, height: 20) let newStatusBarSize = CGSize(width: deviceWidth, height: 44) return [oldStatusBarSize, newStatusBarSize].contains(frame.size) } } private extension XCUIElementQuery { var networkLoadingIndicators: XCUIElementQuery { let isNetworkLoadingIndicator = NSPredicate { (evaluatedObject, _) in guard let element = evaluatedObject as? XCUIElementAttributes else { return false } return element.isNetworkLoadingIndicator } return self.containing(isNetworkLoadingIndicator) } var deviceStatusBars: XCUIElementQuery { guard let app = Snapshot.app else { fatalError("XCUIApplication is not set. Please call setupSnapshot(app) before snapshot().") } let deviceWidth = app.windows.firstMatch.frame.width let isStatusBar = NSPredicate { (evaluatedObject, _) in guard let element = evaluatedObject as? XCUIElementAttributes else { return false } return element.isStatusBar(deviceWidth) } return self.containing(isStatusBar) } } private extension CGFloat { func isBetween(_ numberA: CGFloat, and numberB: CGFloat) -> Bool { return numberA...numberB ~= self } } // Please don't remove the lines below // They are used to detect outdated configuration files // SnapshotHelperVersion [1.27]
mit
4090e223567804b0659ce56769a117bf
36.770227
158
0.630709
5.405743
false
false
false
false
montehurd/apps-ios-wikipedia
Wikipedia/Code/DiffHeaderCompareItemView.swift
1
6267
import UIKit class DiffHeaderCompareItemView: UIView { @IBOutlet var userStackView: UIStackView! @IBOutlet var containerStackView: UIStackView! @IBOutlet var contentView: UIView! @IBOutlet var headingLabel: UILabel! @IBOutlet var timestampLabel: UILabel! @IBOutlet var usernameLabel: UILabel! @IBOutlet var summaryLabel: UILabel! @IBOutlet var userIconImageView: UIImageView! @IBOutlet var stackViewTopPaddingConstraint: NSLayoutConstraint! let squishedBottomPadding: CGFloat = 4 let maxStackViewTopPadding: CGFloat = 14 let minStackViewTopPadding: CGFloat = 6 let maxContainerStackViewSpacing: CGFloat = 10 let minContainerStackViewSpacing: CGFloat = 4 var minHeight: CGFloat { return timestampLabel.frame.maxY + stackViewTopPaddingConstraint.constant + squishedBottomPadding } private var viewModel: DiffHeaderCompareItemViewModel? private var usernameTapGestureRecognizer: UITapGestureRecognizer? private var timestampTapGestureRecognizer: UITapGestureRecognizer? weak var delegate: DiffHeaderActionDelegate? override init(frame: CGRect) { super.init(frame: frame) commonInit() } required init?(coder: NSCoder) { super.init(coder: coder) commonInit() stackViewTopPaddingConstraint.constant = maxStackViewTopPadding containerStackView.spacing = maxContainerStackViewSpacing } override func awakeFromNib() { super.awakeFromNib() if let usernameTapGestureRecognizer = usernameTapGestureRecognizer { userStackView.addGestureRecognizer(usernameTapGestureRecognizer) } if let timestampTapGestureRecognizer = timestampTapGestureRecognizer { timestampLabel.addGestureRecognizer(timestampTapGestureRecognizer) } } func update(_ viewModel: DiffHeaderCompareItemViewModel) { headingLabel.text = viewModel.heading timestampLabel.text = viewModel.timestampString userIconImageView.image = UIImage(named: "user-edit") usernameLabel.text = viewModel.username if viewModel.isMinor, let minorImage = UIImage(named: "minor-edit") { let imageAttachment = NSTextAttachment() imageAttachment.image = minorImage let attributedText = NSMutableAttributedString(attachment: imageAttachment) attributedText.addAttributes([NSAttributedString.Key.baselineOffset: -1], range: NSRange(location: 0, length: 1)) if let summary = viewModel.summary { attributedText.append(NSAttributedString(string: " \(summary)")) } summaryLabel.attributedText = attributedText } else { summaryLabel.text = viewModel.summary } updateFonts(with: traitCollection) self.viewModel = viewModel } func squish(by percentage: CGFloat) { let topPaddingDelta = maxStackViewTopPadding - minStackViewTopPadding stackViewTopPaddingConstraint.constant = maxStackViewTopPadding - (topPaddingDelta * percentage) let spacingDelta = maxContainerStackViewSpacing - minContainerStackViewSpacing containerStackView.spacing = maxContainerStackViewSpacing - (spacingDelta * percentage) //tonitodo: shrink font size } override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) { super.traitCollectionDidChange(previousTraitCollection) updateFonts(with: traitCollection) } override func point(inside point: CGPoint, with event: UIEvent?) -> Bool { let userStackViewConvertedPoint = self.convert(point, to: userStackView) if userStackView.point(inside: userStackViewConvertedPoint, with: event) { return true } let timestampLabelConvertedPoint = self.convert(point, to: timestampLabel) if timestampLabel.point(inside: timestampLabelConvertedPoint, with: event) { return true } return false } @objc func tappedElementWithSender(_ sender: UITapGestureRecognizer) { if let username = viewModel?.username, sender == usernameTapGestureRecognizer { delegate?.tappedUsername(username: username) } else if let revisionID = viewModel?.revisionID, sender == timestampTapGestureRecognizer { delegate?.tappedRevision(revisionID: revisionID) } } } private extension DiffHeaderCompareItemView { func commonInit() { Bundle.main.loadNibNamed(DiffHeaderCompareItemView.wmf_nibName(), owner: self, options: nil) addSubview(contentView) contentView.frame = self.bounds contentView.autoresizingMask = [.flexibleHeight, .flexibleWidth] usernameTapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(tappedElementWithSender)) timestampTapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(tappedElementWithSender)) } func updateFonts(with traitCollection: UITraitCollection) { headingLabel.font = UIFont.wmf_font(DynamicTextStyle.boldFootnote, compatibleWithTraitCollection: traitCollection) timestampLabel.font = UIFont.wmf_font(DynamicTextStyle.boldFootnote, compatibleWithTraitCollection: traitCollection) usernameLabel.font = UIFont.wmf_font(DynamicTextStyle.mediumCaption1, compatibleWithTraitCollection: traitCollection) summaryLabel.font = UIFont.wmf_font(DynamicTextStyle.italicCaption1, compatibleWithTraitCollection: traitCollection) } } extension DiffHeaderCompareItemView: Themeable { func apply(theme: Theme) { backgroundColor = theme.colors.paperBackground contentView.backgroundColor = theme.colors.paperBackground headingLabel.textColor = theme.colors.secondaryText if let viewModel = viewModel { timestampLabel.textColor = viewModel.accentColor usernameLabel.textColor = viewModel.accentColor userIconImageView.tintColor = viewModel.accentColor } } }
mit
d58e4a7ce5fee09f549209d8f5a9b145
40.230263
125
0.702888
5.962892
false
false
false
false
legendecas/Rocket.Chat.iOS
Rocket.Chat.Shared/Models/Message.swift
1
2918
// // Message.swift // Rocket.Chat // // Created by Rafael K. Streit on 7/14/16. // Copyright © 2016 Rocket.Chat. All rights reserved. // import Foundation import RealmSwift import SwiftyJSON /// An enum type represents the type of a message instance /// /// - text: text message /// - textAttachment: text message with an attachment /// - image: image message /// - audio: audio message /// - video: video message /// - url: url message /// - roomNameChanged: a message that indicates a change of the name /// - userAdded: a message that indicates an add of a user by admin /// - userRemoved: a message that indicates a removal of a user by admin /// - userJoined: a message that indicates a entrance of a user /// - userLeft: a message that indicates a left of a user /// - userMuted: a message that indicates muting of a user by admin /// - userUnmuted: a message that indicates un-muting of a user by admin /// - welcome: welcome message /// - messageRemoved: a message that indicates a certain message has been removed /// - subscriptionRoleAdded: subscriptionRoleAdded /// - subscriptionRoleRemoved: subscriptionRoleRemoved /// - roomArchived: a message that indicates the room have been archived /// - roomUnarchived: a message that indicates the room have been un-archived public enum MessageType: String { case text case textAttachment case image case audio case video case url case roomNameChanged = "r" case userAdded = "au" case userRemoved = "ru" case userJoined = "uj" case userLeft = "ul" case userMuted = "user-muted" case userUnmuted = "user-unmuted" case welcome = "wm" case messageRemoved = "rm" case subscriptionRoleAdded = "subscription-role-added" case subscriptionRoleRemoved = "subscription-role-removed" case roomArchived = "room-archived" case roomUnarchived = "room-unarchived" } /// A data structure represents a message instance public class Message: BaseModel { public dynamic var subscription: Subscription! public dynamic var internalType: String = "" public dynamic var rid = "" public dynamic var createdAt: Date? public dynamic var updatedAt: Date? public dynamic var user: User? public dynamic var text = "" public dynamic var userBlocked: Bool = false public dynamic var pinned: Bool = false dynamic var alias = "" dynamic var avatar = "" dynamic var role = "" dynamic var temporary = false public var mentions = List<Mention>() public var attachments = List<Attachment>() public var urls = List<MessageURL>() public var type: MessageType { if let attachment = attachments.first { return attachment.type } if let url = urls.first { if url.isValid() { return .url } } return MessageType(rawValue: internalType) ?? .text } }
mit
d5f71254cf553462accf80cc83bb9599
29.705263
81
0.681179
4.366766
false
false
false
false
farion/eloquence
Eloquence/Core/EloConstants.swift
1
478
import Foundation public struct EloConstants { private static let PREFIX = "com.trigonmedia.eloquence." static let CONNECTION_ONLINE = PREFIX + "connectionOnline" static let CONNECTION_OFFLINE = PREFIX + "connectionOffline" static let ROSTER_CHANGED = PREFIX + "rosterChanged" static let ACTIVATE_CONTACT = PREFIX + "activateContact" static let SHOW_ACCOUNTS = PREFIX + "showAccounts" static let SHOW_PREFERENCES = PREFIX + "showPreferences" }
apache-2.0
cf0248dd7073c41b44175a4e0d234645
35.846154
64
0.73431
3.676923
false
false
false
false
3DprintFIT/octoprint-ios-client
OctoPhone/Model/Bed.swift
1
883
// // Bed.swift // OctoPhone // // Created by Josef Dolezal on 02/05/2017. // Copyright © 2017 Josef Dolezal. All rights reserved. // import Foundation import RealmSwift /// Represents current state of printing bed final class Bed: Object { // MARK: - Stored properties /// Actual temperature of bed dynamic var actualTemperature = 0.0 /// Target temperature of bed dynamic var targetTemperature = 0.0 /// Offset temperature of bed dynamic var offsetTemperature = 0.0 // MARK: - Computed properties // MARK: - Public API convenience init(actualTemperature: Double, targetTemperature: Double, offsetTemperature: Double) { self.init() self.actualTemperature = actualTemperature self.targetTemperature = targetTemperature self.offsetTemperature = offsetTemperature } // MARK: - Realm API }
mit
c7fb3b550f97eb913ffcbb6c3f1003a1
21.615385
103
0.68254
4.59375
false
false
false
false
Automattic/Automattic-Tracks-iOS
Sources/Event Logging (Swift)/TracksEventPersistenceServiceSwift.swift
1
2710
#if SWIFT_PACKAGE import AutomatticTracksModel import AutomatticTracksModelObjC #endif import CoreData /// Should eventually replace objC class `TracksEventPersistenceService`. Unfortunately /// Swift Packages do not support mixed source classes so we'll instead need to compose. /// @objc public class TracksEventPersistenceServiceSwift: NSObject { private static let incrementRetryCountBatchSize = 500 private let managedObjectContext: NSManagedObjectContext @objc public init(managedObjectContext: NSManagedObjectContext) { self.managedObjectContext = managedObjectContext super.init() } /// Increments the retry count for the specified events in batches of @objc public func incrementRetryCountForEvents(_ tracksEvents: [TracksEvent], onComplete completion: (() -> Void)?) { let uuidStrings = tracksEvents.map { event in event.uuid.uuidString } managedObjectContext.perform { for startIndex in stride(from: 0, to: uuidStrings.count, by: Self.incrementRetryCountBatchSize) { let results: [TracksEventCoreData] let count = min(uuidStrings.count - startIndex, Self.incrementRetryCountBatchSize) let uuidStringsBatch = Array(uuidStrings[startIndex ..< startIndex + count]) do { results = try self.findCoreDataEvents(uuidStrings: uuidStringsBatch) } catch { TracksLogError("Error while finding track events: \(String(describing: error))") continue } if results.count != count { TracksLogError("Not all provided events were found in the persistence layer. This signals a possible logical error in the tracking, persistence and retry-count-incrementing code. Please review.") } for event in results { event.retryCount = event.retryCount.intValue + 1 as NSNumber } self.saveManagedObjectContext() } completion?() } } func findCoreDataEvents(uuidStrings: [String]) throws -> [TracksEventCoreData] { let fetchRequest = NSFetchRequest<TracksEventCoreData>(entityName: "TracksEvent") fetchRequest.predicate = NSPredicate(format: "uuid in %@", uuidStrings) fetchRequest.returnsObjectsAsFaults = false return try fetchRequest.execute() } func saveManagedObjectContext() { do { try managedObjectContext.save() } catch { TracksLogError("Error while saving context: \(String(describing: error))") } } }
gpl-2.0
fe4385e3dc2b94bb3884d41a5b98f79c
36.123288
216
0.648339
5.669456
false
false
false
false
paterik/udacity-ios-silly-song
SillySong/UIColor.swift
1
741
// // UIColor.swift // SillySong // // Created by Patrick Paechnatz on 06.04.17. // Copyright © 2017 Patrick Paechnatz. All rights reserved. // import UIKit extension UIColor { convenience init(red: Int, green: Int, blue: Int) { assert(red >= 0 && red <= 255, "Invalid red component") assert(green >= 0 && green <= 255, "Invalid green component") assert(blue >= 0 && blue <= 255, "Invalid blue component") self.init(red: CGFloat(red) / 255.0, green: CGFloat(green) / 255.0, blue: CGFloat(blue) / 255.0, alpha: 1.0) } convenience init(netHex: Int) { self.init(red: (netHex >> 16) & 0xff, green: (netHex >> 8) & 0xff, blue: netHex & 0xff) } }
mit
37727de0eccc160aa7585e2549b9b618
27.461538
116
0.575676
3.394495
false
false
false
false