code
stringlengths
1
1.05M
repo_name
stringlengths
6
83
path
stringlengths
3
242
language
stringclasses
222 values
license
stringclasses
20 values
size
int64
1
1.05M
// Created by Cal Stephens on 1/24/22. // Copyright © 2022 Airbnb Inc. All rights reserved. import CoreGraphics // MARK: - Interpolatable /// A type that can be interpolated between two values public protocol Interpolatable: AnyInterpolatable { /// Interpolates the `self` to the given number by `amount`. /// - Parameter to: The number to interpolate to. /// - Parameter amount: The amount to interpolate, /// relative to 0.0 (self) and 1.0 (to). /// `amount` can be greater than one and less than zero, /// and interpolation should not be clamped. /// /// ``` /// let number = 5 /// let interpolated = number.interpolateTo(10, amount: 0.5) /// print(interpolated) // 7.5 /// ``` /// /// ``` /// let number = 5 /// let interpolated = number.interpolateTo(10, amount: 1.5) /// print(interpolated) // 12.5 /// ``` func interpolate(to: Self, amount: CGFloat) -> Self } // MARK: - SpatialInterpolatable /// A type that can be interpolated between two values, /// additionally using optional `spatialOutTangent` and `spatialInTangent` values. /// - If your implementation doesn't use the `spatialOutTangent` and `spatialInTangent` /// parameters, prefer implementing the simpler `Interpolatable` protocol. public protocol SpatialInterpolatable: AnyInterpolatable { /// Interpolates the `self` to the given number by `amount`. /// - Parameter to: The number to interpolate to. /// - Parameter amount: The amount to interpolate, /// relative to 0.0 (self) and 1.0 (to). /// `amount` can be greater than one and less than zero, /// and interpolation should not be clamped. func interpolate( to: Self, amount: CGFloat, spatialOutTangent: CGPoint?, spatialInTangent: CGPoint?) -> Self } // MARK: - AnyInterpolatable /// The base protocol that is implemented by both `Interpolatable` and `SpatialInterpolatable` /// Types should not directly implement this protocol. public protocol AnyInterpolatable { /// Interpolates by calling either `Interpolatable.interpolate` /// or `SpatialInterpolatable.interpolate`. /// Should not be implemented or called by consumers. func _interpolate( to: Self, amount: CGFloat, spatialOutTangent: CGPoint?, spatialInTangent: CGPoint?) -> Self } extension Interpolatable { public func _interpolate( to: Self, amount: CGFloat, spatialOutTangent _: CGPoint?, spatialInTangent _: CGPoint?) -> Self { interpolate(to: to, amount: amount) } } extension SpatialInterpolatable { /// Helper that interpolates this `SpatialInterpolatable` /// with `nil` spatial in/out tangents public func interpolate(to: Self, amount: CGFloat) -> Self { interpolate( to: to, amount: amount, spatialOutTangent: nil, spatialInTangent: nil) } public func _interpolate( to: Self, amount: CGFloat, spatialOutTangent: CGPoint?, spatialInTangent: CGPoint?) -> Self { interpolate( to: to, amount: amount, spatialOutTangent: spatialOutTangent, spatialInTangent: spatialInTangent) } } // MARK: - Double + Interpolatable extension Double: Interpolatable { } // MARK: - CGFloat + Interpolatable extension CGFloat: Interpolatable { } // MARK: - Float + Interpolatable extension Float: Interpolatable { } extension Interpolatable where Self: BinaryFloatingPoint { public func interpolate(to: Self, amount: CGFloat) -> Self { self + ((to - self) * Self(amount)) } } // MARK: - CGRect + Interpolatable extension CGRect: Interpolatable { public func interpolate(to: CGRect, amount: CGFloat) -> CGRect { CGRect( x: origin.x.interpolate(to: to.origin.x, amount: amount), y: origin.y.interpolate(to: to.origin.y, amount: amount), width: width.interpolate(to: to.width, amount: amount), height: height.interpolate(to: to.height, amount: amount)) } } // MARK: - CGSize + Interpolatable extension CGSize: Interpolatable { public func interpolate(to: CGSize, amount: CGFloat) -> CGSize { CGSize( width: width.interpolate(to: to.width, amount: amount), height: height.interpolate(to: to.height, amount: amount)) } } // MARK: - CGPoint + SpatialInterpolatable extension CGPoint: SpatialInterpolatable { public func interpolate( to: CGPoint, amount: CGFloat, spatialOutTangent: CGPoint?, spatialInTangent: CGPoint?) -> CGPoint { guard let outTan = spatialOutTangent, let inTan = spatialInTangent else { return CGPoint( x: x.interpolate(to: to.x, amount: amount), y: y.interpolate(to: to.y, amount: amount)) } let cp1 = self + outTan let cp2 = to + inTan return interpolate(to, outTangent: cp1, inTangent: cp2, amount: amount) } } // MARK: - LottieColor + Interpolatable extension LottieColor: Interpolatable { public func interpolate(to: LottieColor, amount: CGFloat) -> LottieColor { LottieColor( r: r.interpolate(to: to.r, amount: amount), g: g.interpolate(to: to.g, amount: amount), b: b.interpolate(to: to.b, amount: amount), a: a.interpolate(to: to.a, amount: amount)) } } // MARK: - LottieVector1D + Interpolatable extension LottieVector1D: Interpolatable { public func interpolate(to: LottieVector1D, amount: CGFloat) -> LottieVector1D { value.interpolate(to: to.value, amount: amount).vectorValue } } // MARK: - LottieVector2D + SpatialInterpolatable extension LottieVector2D: SpatialInterpolatable { public func interpolate( to: LottieVector2D, amount: CGFloat, spatialOutTangent: CGPoint?, spatialInTangent: CGPoint?) -> LottieVector2D { pointValue.interpolate( to: to.pointValue, amount: amount, spatialOutTangent: spatialOutTangent, spatialInTangent: spatialInTangent) .vector2dValue } } // MARK: - LottieVector3D + SpatialInterpolatable extension LottieVector3D: SpatialInterpolatable { public func interpolate( to: LottieVector3D, amount: CGFloat, spatialOutTangent: CGPoint?, spatialInTangent: CGPoint?) -> LottieVector3D { if spatialInTangent != nil || spatialOutTangent != nil { // TODO Support third dimension spatial interpolation let point = pointValue.interpolate( to: to.pointValue, amount: amount, spatialOutTangent: spatialOutTangent, spatialInTangent: spatialInTangent) return LottieVector3D( x: point.x, y: point.y, z: CGFloat(z.interpolate(to: to.z, amount: amount))) } return LottieVector3D( x: x.interpolate(to: to.x, amount: amount), y: y.interpolate(to: to.y, amount: amount), z: z.interpolate(to: to.z, amount: amount)) } } // MARK: - Array + Interpolatable, AnyInterpolatable extension Array: Interpolatable, AnyInterpolatable where Element: Interpolatable { public func interpolate(to: [Element], amount: CGFloat) -> [Element] { LottieLogger.shared.assert( count == to.count, "When interpolating Arrays, both array sound have the same element count.") return zip(self, to).map { lhs, rhs in lhs.interpolate(to: rhs, amount: amount) } } } // MARK: - Optional + Interpolatable, AnyInterpolatable extension Optional: Interpolatable, AnyInterpolatable where Wrapped: Interpolatable { public func interpolate(to: Wrapped?, amount: CGFloat) -> Wrapped? { guard let self, let to else { return nil } return self.interpolate(to: to, amount: amount) } } // MARK: - Hold /// An `Interpolatable` container that animates using "hold" keyframes. /// The keyframes do not animate, and instead always display the value from the most recent keyframe. /// This is necessary when passing non-interpolatable values to a method that requires an `Interpolatable` conformance. struct Hold<T>: Interpolatable { let value: T func interpolate(to: Hold<T>, amount: CGFloat) -> Hold<T> { if amount < 1 { return self } else { return to } } }
2201_75827989/zhi_shi_ku
uni_modules/uts-animation-view/utssdk/app-ios/lottie-ios/Public/Keyframes/Interpolatable.swift
Swift
unknown
8,066
// Created by Cal Stephens on 1/24/22. // Copyright © 2022 Airbnb Inc. All rights reserved. import CoreFoundation // MARK: - Keyframe /// A keyframe with a single value, and timing information /// about when the value should be displayed and how it /// should be interpolated. public final class Keyframe<T> { // MARK: Lifecycle /// Initialize a value-only keyframe with no time data. public init( _ value: T, spatialInTangent: LottieVector3D? = nil, spatialOutTangent: LottieVector3D? = nil) { self.value = value time = 0 isHold = true inTangent = nil outTangent = nil self.spatialInTangent = spatialInTangent self.spatialOutTangent = spatialOutTangent } /// Initialize a keyframe public init( value: T, time: AnimationFrameTime, isHold: Bool = false, inTangent: LottieVector2D? = nil, outTangent: LottieVector2D? = nil, spatialInTangent: LottieVector3D? = nil, spatialOutTangent: LottieVector3D? = nil) { self.value = value self.time = time self.isHold = isHold self.outTangent = outTangent self.inTangent = inTangent self.spatialInTangent = spatialInTangent self.spatialOutTangent = spatialOutTangent } // MARK: Public /// The value of the keyframe public let value: T /// The time in frames of the keyframe. public let time: AnimationFrameTime /// A hold keyframe freezes interpolation until the next keyframe that is not a hold. public let isHold: Bool /// The in tangent for the time interpolation curve. public let inTangent: LottieVector2D? /// The out tangent for the time interpolation curve. public let outTangent: LottieVector2D? /// The spatial in tangent of the vector. public let spatialInTangent: LottieVector3D? /// The spatial out tangent of the vector. public let spatialOutTangent: LottieVector3D? } // MARK: Equatable extension Keyframe: Equatable where T: Equatable { public static func == (lhs: Keyframe<T>, rhs: Keyframe<T>) -> Bool { lhs.value == rhs.value && lhs.time == rhs.time && lhs.isHold == rhs.isHold && lhs.inTangent == rhs.inTangent && lhs.outTangent == rhs.outTangent && lhs.spatialInTangent == rhs.spatialOutTangent && lhs.spatialOutTangent == rhs.spatialOutTangent } } // MARK: Hashable extension Keyframe: Hashable where T: Hashable { public func hash(into hasher: inout Hasher) { hasher.combine(value) hasher.combine(time) hasher.combine(isHold) hasher.combine(inTangent) hasher.combine(outTangent) hasher.combine(spatialInTangent) hasher.combine(spatialOutTangent) } } // MARK: Sendable extension Keyframe: Sendable where T: Sendable { }
2201_75827989/zhi_shi_ku
uni_modules/uts-animation-view/utssdk/app-ios/lottie-ios/Public/Keyframes/Keyframe.swift
Swift
unknown
2,715
// Created by eric_horacek on 12/9/20. // Copyright © 2020 Airbnb Inc. All rights reserved. // MARK: - LottieLogger /// A shared logger that allows consumers to intercept Lottie assertions and warning messages to pipe /// into their own logging systems. public final class LottieLogger { // MARK: Lifecycle public init( assert: @escaping Assert = { condition, message, file, line in // If we default to `Swift.assert` directly with `assert: Assert = Swift.assert`, // the call will unexpectedly not respect the -O flag and will crash in release // https://github.com/apple/swift/issues/60249 Swift.assert(condition(), message(), file: file, line: line) }, assertionFailure: @escaping AssertionFailure = { message, file, line in // If we default to `Swift.assertionFailure` directly with // `assertionFailure: AssertionFailure = Swift.assertionFailure`, // the call will unexpectedly not respect the -O flag and will crash in release // https://github.com/apple/swift/issues/60249 Swift.assertionFailure(message(), file: file, line: line) }, warn: @escaping Warn = { message, _, _ in #if DEBUG // swiftlint:disable:next no_direct_standard_out_logs print(message()) #endif }, info: @escaping Info = { message in #if DEBUG // swiftlint:disable:next no_direct_standard_out_logs print(message()) #endif }) { _assert = assert _assertionFailure = assertionFailure _warn = warn _info = info } // MARK: Public /// Logs that an assertion occurred. public typealias Assert = ( _ condition: @autoclosure () -> Bool, _ message: @autoclosure () -> String, _ fileID: StaticString, _ line: UInt) -> Void /// Logs that an assertion failure occurred. public typealias AssertionFailure = ( _ message: @autoclosure () -> String, _ fileID: StaticString, _ line: UInt) -> Void /// Logs a warning message. public typealias Warn = ( _ message: @autoclosure () -> String, _ fileID: StaticString, _ line: UInt) -> Void /// Prints a purely informational message. public typealias Info = (_ message: @autoclosure () -> String) -> Void /// The shared instance used to log Lottie assertions and warnings. /// /// Set this to a new logger instance to intercept assertions and warnings logged by Lottie. public static var shared = LottieLogger() /// Logs that an assertion occurred. public func assert( _ condition: @autoclosure () -> Bool, _ message: @autoclosure () -> String = String(), fileID: StaticString = #fileID, line: UInt = #line) { _assert(condition(), message(), fileID, line) } /// Logs that an assertion failure occurred. public func assertionFailure( _ message: @autoclosure () -> String = String(), fileID: StaticString = #fileID, line: UInt = #line) { _assertionFailure(message(), fileID, line) } /// Logs a warning message. public func warn( _ message: @autoclosure () -> String = String(), fileID: StaticString = #fileID, line: UInt = #line) { _warn(message(), fileID, line) } /// Logs a purely informational message. public func info(_ message: @autoclosure () -> String = String()) { _info(message()) } // MARK: Private private let _assert: Assert private let _assertionFailure: AssertionFailure private let _warn: Warn private let _info: Info } // MARK: - LottieLogger + printToConsole extension LottieLogger { /// A `LottieLogger` instance that always prints to the console (by calling `print`) /// instead of calling `assert` / `assertionFailure`, which halt execution in debug builds. public static var printToConsole: LottieLogger { LottieLogger( assert: { condition, message, _, _ in if !condition() { // swiftlint:disable:next no_direct_standard_out_logs print(message()) } }, assertionFailure: { message, _, _ in // swiftlint:disable:next no_direct_standard_out_logs print(message()) }) } }
2201_75827989/zhi_shi_ku
uni_modules/uts-animation-view/utssdk/app-ios/lottie-ios/Public/Logging/LottieLogger.swift
Swift
unknown
4,129
// // AnimationTime.swift // lottie-swift-iOS // // Created by Brandon Withrow on 2/6/19. // import CoreGraphics import Foundation /// Defines animation time in Frames (Seconds * Framerate). public typealias AnimationFrameTime = CGFloat /// Defines animation time by a progress from 0 (beginning of the animation) to 1 (end of the animation) public typealias AnimationProgressTime = CGFloat
2201_75827989/zhi_shi_ku
uni_modules/uts-animation-view/utssdk/app-ios/lottie-ios/Public/Primitives/AnimationTime.swift
Swift
unknown
397
// // LottieColor.swift // lottie-swift // // Created by Brandon Withrow on 2/4/19. // // MARK: - ColorFormatDenominator public enum ColorFormatDenominator: Hashable { case One case OneHundred case TwoFiftyFive var value: Double { switch self { case .One: return 1.0 case .OneHundred: return 100.0 case .TwoFiftyFive: return 255.0 } } } // MARK: - LottieColor public struct LottieColor: Hashable { public var r: Double public var g: Double public var b: Double public var a: Double public init(r: Double, g: Double, b: Double, a: Double, denominator: ColorFormatDenominator = .One) { self.r = r / denominator.value self.g = g / denominator.value self.b = b / denominator.value self.a = a / denominator.value } }
2201_75827989/zhi_shi_ku
uni_modules/uts-animation-view/utssdk/app-ios/lottie-ios/Public/Primitives/LottieColor.swift
Swift
unknown
799
// // Vectors.swift // lottie-swift // // Created by Brandon Withrow on 2/4/19. // // MARK: - LottieVector1D public struct LottieVector1D: Hashable, Sendable { public init(_ value: Double) { self.value = value } public let value: Double } // MARK: - LottieVector3D /// A three dimensional vector. /// These vectors are encoded and decoded from [Double] public struct LottieVector3D: Hashable, Sendable { public let x: Double public let y: Double public let z: Double public init(x: Double, y: Double, z: Double) { self.x = x self.y = y self.z = z } }
2201_75827989/zhi_shi_ku
uni_modules/uts-animation-view/utssdk/app-ios/lottie-ios/Public/Primitives/Vectors.swift
Swift
unknown
596
// // AnimationImageProvider.swift // Lottie_iOS // // Created by Alexandr Goncharov on 07/06/2019. // // MARK: - AnimationKeypathTextProvider /// Protocol for providing dynamic text to for a Lottie animation. public protocol AnimationKeypathTextProvider: AnyObject { /// The text to display for the given `AnimationKeypath`. /// If `nil` is returned, continues using the existing default text value. func text(for keypath: AnimationKeypath, sourceText: String) -> String? } // MARK: - AnimationKeypathTextProvider /// Legacy protocol for providing dynamic text for a Lottie animation. /// Instead prefer conforming to `AnimationKeypathTextProvider`. @available(*, deprecated, message: """ `AnimationKeypathTextProvider` has been deprecated and renamed to `LegacyAnimationTextProvider`. \ Instead, conform to `AnimationKeypathTextProvider` instead or conform to `LegacyAnimationTextProvider` explicitly. """) public typealias AnimationTextProvider = LegacyAnimationTextProvider // MARK: - LegacyAnimationTextProvider /// Legacy protocol for providing dynamic text for a Lottie animation. /// Instead prefer conforming to `AnimationKeypathTextProvider`. public protocol LegacyAnimationTextProvider: AnimationKeypathTextProvider { /// Legacy method to look up the text to display for the given keypath. /// Instead, prefer implementing `AnimationKeypathTextProvider.` /// The behavior of this method depends on the current rendering engine: /// - The Core Animation rendering engine always calls this method /// with the full keypath (e.g. `MY_LAYER.text_value`). /// - The Main Thread rendering engine always calls this method /// with the final component of the key path (e.g. just `text_value`). func textFor(keypathName: String, sourceText: String) -> String } extension LegacyAnimationTextProvider { public func text(for _: AnimationKeypath, sourceText _: String) -> String? { nil } } // MARK: - DictionaryTextProvider /// Text provider that simply map values from dictionary. /// - The dictionary keys can either be the full layer keypath string (e.g. `MY_LAYER.text_value`) /// or simply the final path component of the keypath (e.g. `text_value`). public final class DictionaryTextProvider: AnimationKeypathTextProvider, LegacyAnimationTextProvider { // MARK: Lifecycle public init(_ values: [String: String]) { self.values = values } // MARK: Public public func text(for keypath: AnimationKeypath, sourceText: String) -> String? { if let valueForFullKeypath = values[keypath.fullPath] { return valueForFullKeypath } else if let lastKeypathComponent = keypath.keys.last, let valueForLastComponent = values[lastKeypathComponent] { return valueForLastComponent } else { return sourceText } } // Never called directly by Lottie, but we continue to implement this conformance for backwards compatibility. public func textFor(keypathName: String, sourceText: String) -> String { values[keypathName] ?? sourceText } // MARK: Internal let values: [String: String] } // MARK: Equatable extension DictionaryTextProvider: Equatable { public static func ==(_ lhs: DictionaryTextProvider, _ rhs: DictionaryTextProvider) -> Bool { lhs.values == rhs.values } } // MARK: - DefaultTextProvider /// Default text provider. Uses text in the animation file public final class DefaultTextProvider: AnimationKeypathTextProvider, LegacyAnimationTextProvider { // MARK: Lifecycle public init() { } // MARK: Public public func textFor(keypathName _: String, sourceText: String) -> String { sourceText } public func text(for _: AnimationKeypath, sourceText: String) -> String { sourceText } } // MARK: Equatable extension DefaultTextProvider: Equatable { public static func ==(_: DefaultTextProvider, _: DefaultTextProvider) -> Bool { true } }
2201_75827989/zhi_shi_ku
uni_modules/uts-animation-view/utssdk/app-ios/lottie-ios/Public/TextProvider/AnimationTextProvider.swift
Swift
unknown
3,930
// // AnimationSubview.swift // lottie-swift // // Created by Brandon Withrow on 2/4/19. // #if canImport(UIKit) import UIKit /// A view that can be added to a keypath of an AnimationView public final class AnimationSubview: UIView { var viewLayer: CALayer? { layer } } #endif
2201_75827989/zhi_shi_ku
uni_modules/uts-animation-view/utssdk/app-ios/lottie-ios/Public/iOS/AnimationSubview.swift
Swift
unknown
292
// // LottieBundleImageProvider.swift // lottie-swift // // Created by Brandon Withrow on 1/25/19. // #if canImport(UIKit) import UIKit /// An `AnimationImageProvider` that provides images by name from a specific bundle. /// The BundleImageProvider is initialized with a bundle and an optional searchPath. public class BundleImageProvider: AnimationImageProvider { // MARK: Lifecycle /// Initializes an image provider with a bundle and an optional subpath. /// /// Provides images for an animation from a bundle. Additionally the provider can /// search a specific subpath for the images. /// /// - Parameter bundle: The bundle containing images for the provider. /// - Parameter searchPath: The subpath is a path within the bundle to search for image assets. /// - Parameter contentsGravity: The contents gravity to use when rendering the image. /// public init(bundle: Bundle, searchPath: String?, contentsGravity: CALayerContentsGravity = .resize) { self.bundle = bundle self.searchPath = searchPath self.contentsGravity = contentsGravity } // MARK: Public public func imageForAsset(asset: ImageAsset) -> CGImage? { if let base64Image = asset.base64Image { return base64Image } let imagePath: String? /// Try to find the image in the bundle. if let searchPath { /// Search in the provided search path for the image var directoryPath = URL(fileURLWithPath: searchPath) directoryPath.appendPathComponent(asset.directory) if let path = bundle.path(forResource: asset.name, ofType: nil, inDirectory: directoryPath.path) { /// First search for the image in the asset provided sub directory. imagePath = path } else if let path = bundle.path(forResource: asset.name, ofType: nil, inDirectory: searchPath) { /// Try finding the image in the search path. imagePath = path } else { imagePath = bundle.path(forResource: asset.name, ofType: nil) } } else { if let path = bundle.path(forResource: asset.name, ofType: nil, inDirectory: asset.directory) { /// First search for the image in the asset provided sub directory. imagePath = path } else { /// First search for the image in bundle. imagePath = bundle.path(forResource: asset.name, ofType: nil) } } if imagePath == nil { guard let image = UIImage(named: asset.name, in: bundle, compatibleWith: nil) else { LottieLogger.shared.warn("Could not find image \"\(asset.name)\" in bundle") return nil } return image.cgImage } guard let foundPath = imagePath, let image = UIImage(contentsOfFile: foundPath) else { /// No image found. LottieLogger.shared.warn("Could not find image \"\(asset.name)\" in bundle") return nil } return image.cgImage } public func contentsGravity(for _: ImageAsset) -> CALayerContentsGravity { contentsGravity } // MARK: Internal let bundle: Bundle let searchPath: String? let contentsGravity: CALayerContentsGravity } extension BundleImageProvider: Equatable { public static func ==(_ lhs: BundleImageProvider, _ rhs: BundleImageProvider) -> Bool { lhs.bundle == rhs.bundle && lhs.searchPath == rhs.searchPath } } #endif
2201_75827989/zhi_shi_ku
uni_modules/uts-animation-view/utssdk/app-ios/lottie-ios/Public/iOS/BundleImageProvider.swift
Swift
unknown
3,317
// // CompatibleAnimationKeypath.swift // Lottie_iOS // // Created by Tyler Hedrick on 3/6/19. // import Foundation #if canImport(UIKit) /// An Objective-C compatible wrapper around Lottie's AnimationKeypath @objc public final class CompatibleAnimationKeypath: NSObject { // MARK: Lifecycle /// Creates a keypath from a dot separated string. The string is separated by "." @objc public init(keypath: String) { animationKeypath = AnimationKeypath(keypath: keypath) } /// Creates a keypath from a list of strings. @objc public init(keys: [String]) { animationKeypath = AnimationKeypath(keys: keys) } // MARK: Public public let animationKeypath: AnimationKeypath } #endif
2201_75827989/zhi_shi_ku
uni_modules/uts-animation-view/utssdk/app-ios/lottie-ios/Public/iOS/Compatibility/CompatibleAnimationKeypath.swift
Swift
unknown
709
// // CompatibleAnimationView.swift // Lottie_iOS // // Created by Tyler Hedrick on 3/6/19. // import Foundation #if canImport(UIKit) import UIKit /// An Objective-C compatible wrapper around Lottie's Animation class. /// Use in tandem with CompatibleAnimationView when using Lottie in Objective-C @objc public final class CompatibleAnimation: NSObject { // MARK: Lifecycle @objc public init( name: String, subdirectory: String? = nil, bundle: Bundle = Bundle.main) { self.name = name self.subdirectory = subdirectory self.bundle = bundle super.init() } // MARK: Internal var animation: LottieAnimation? { LottieAnimation.named(name, bundle: bundle, subdirectory: subdirectory) } @objc static func named(_ name: String) -> CompatibleAnimation { CompatibleAnimation(name: name) } // MARK: Private private let name: String private let subdirectory: String? private let bundle: Bundle } /// An Objective-C compatible wrapper around Lottie's RenderingEngineOption enum. Pass in an option /// to the CompatibleAnimationView initializers to configure the rendering engine for the view. @objc public enum CompatibleRenderingEngineOption: Int { /// Uses the rendering engine specified in LottieConfiguration.shared. case shared /// Uses the library default rendering engine, coreAnimation. case defaultEngine /// Optimizes rendering performance by using the Core Animation rendering engine for animations it /// can render while falling back to the main thread renderer for all other animations. case automatic /// Only renders animations using the main thread rendering engine. case mainThread /// Only renders animations using the Core Animation rendering engine. Those animations that use /// features not yet supported on this renderer will not be rendered. case coreAnimation // MARK: Public /// Converts a CompatibleRenderingEngineOption to the corresponding LottieConfiguration for /// internal rendering engine configuration. public static func generateLottieConfiguration( _ configuration: CompatibleRenderingEngineOption) -> LottieConfiguration { switch configuration { case .shared: return LottieConfiguration.shared case .defaultEngine: return LottieConfiguration(renderingEngine: .coreAnimation) case .automatic: return LottieConfiguration(renderingEngine: .automatic) case .mainThread: return LottieConfiguration(renderingEngine: .mainThread) case .coreAnimation: return LottieConfiguration(renderingEngine: .coreAnimation) } } } /// An Objective-C compatible version of `LottieBackgroundBehavior`. @objc public enum CompatibleBackgroundBehavior: Int { /// Stop the animation and reset it to the beginning of its current play time. The completion block is called. case stop /// Pause the animation in its current state. The completion block is called. case pause /// Pause the animation and restart it when the application moves to the foreground. /// The completion block is stored and called when the animation completes. /// - This is the default when using the Main Thread rendering engine. case pauseAndRestore /// Stops the animation and sets it to the end of its current play time. The completion block is called. case forceFinish /// The animation continues playing in the background. /// - This is the default when using the Core Animation rendering engine. /// Playing an animation using the Core Animation engine doesn't come with any CPU overhead, /// so using `.continuePlaying` avoids the need to stop and then resume the animation /// (which does come with some CPU overhead). /// - This mode should not be used with the Main Thread rendering engine. case continuePlaying } /// An Objective-C compatible wrapper around Lottie's LottieAnimationView. @objc public final class CompatibleAnimationView: UIView { // MARK: Lifecycle /// Initializes a compatible AnimationView with a given compatible animation. Defaults to using /// the rendering engine specified in LottieConfiguration.shared. @objc public convenience init(compatibleAnimation: CompatibleAnimation) { self.init(compatibleAnimation: compatibleAnimation, compatibleRenderingEngineOption: .shared) } /// Initializes a compatible AnimationView with a given compatible animation and rendering engine /// configuration. @objc public init( compatibleAnimation: CompatibleAnimation, compatibleRenderingEngineOption: CompatibleRenderingEngineOption) { animationView = LottieAnimationView( animation: compatibleAnimation.animation, configuration: CompatibleRenderingEngineOption.generateLottieConfiguration(compatibleRenderingEngineOption)) self.compatibleAnimation = compatibleAnimation super.init(frame: .zero) commonInit() } /// Initializes a compatible AnimationView with the resources asynchronously loaded from a given /// URL. Defaults to using the rendering engine specified in LottieConfiguration.shared. @objc public convenience init(url: URL) { self.init(url: url, compatibleRenderingEngineOption: .shared) } /// Initializes a compatible AnimationView with the resources asynchronously loaded from a given /// URL using the given rendering engine configuration. @objc public init(url: URL, compatibleRenderingEngineOption: CompatibleRenderingEngineOption) { animationView = LottieAnimationView( url: url, closure: { _ in }, configuration: CompatibleRenderingEngineOption.generateLottieConfiguration(compatibleRenderingEngineOption)) super.init(frame: .zero) commonInit() } /// Initializes a compatible AnimationView from a given Data object specifying the Lottie /// animation. Defaults to using the rendering engine specified in LottieConfiguration.shared. @objc public convenience init(data: Data) { self.init(data: data, compatibleRenderingEngineOption: .shared) } /// Initializes a compatible AnimationView from a given Data object specifying the Lottie /// animation using the given rendering engine configuration. @objc public init(data: Data, compatibleRenderingEngineOption: CompatibleRenderingEngineOption) { if let animation = try? LottieAnimation.from(data: data) { animationView = LottieAnimationView( animation: animation, configuration: CompatibleRenderingEngineOption.generateLottieConfiguration(compatibleRenderingEngineOption)) } else { animationView = LottieAnimationView( configuration: CompatibleRenderingEngineOption.generateLottieConfiguration(compatibleRenderingEngineOption)) } super.init(frame: .zero) commonInit() } @objc public override init(frame: CGRect) { animationView = LottieAnimationView() super.init(frame: frame) commonInit() } required init?(coder: NSCoder) { animationView = LottieAnimationView() super.init(coder: coder) commonInit() } // MARK: Public @objc public var compatibleAnimation: CompatibleAnimation? { didSet { animationView.animation = compatibleAnimation?.animation } } @objc public var loopAnimationCount: CGFloat = 0 { didSet { animationView.loopMode = loopAnimationCount == -1 ? .loop : .repeat(Float(loopAnimationCount)) } } @objc public var compatibleDictionaryTextProvider: CompatibleDictionaryTextProvider? { didSet { animationView.textProvider = compatibleDictionaryTextProvider?.textProvider ?? DefaultTextProvider() } } @objc public override var contentMode: UIView.ContentMode { set { animationView.contentMode = newValue } get { animationView.contentMode } } @objc public var shouldRasterizeWhenIdle: Bool { set { animationView.shouldRasterizeWhenIdle = newValue } get { animationView.shouldRasterizeWhenIdle } } @objc public var currentProgress: CGFloat { set { animationView.currentProgress = newValue } get { animationView.currentProgress } } @objc public var duration: CGFloat { animationView.animation?.duration ?? 0.0 } @objc public var currentTime: TimeInterval { set { animationView.currentTime = newValue } get { animationView.currentTime } } @objc public var currentFrame: CGFloat { set { animationView.currentFrame = newValue } get { animationView.currentFrame } } @objc public var realtimeAnimationFrame: CGFloat { animationView.realtimeAnimationFrame } @objc public var realtimeAnimationProgress: CGFloat { animationView.realtimeAnimationProgress } @objc public var animationSpeed: CGFloat { set { animationView.animationSpeed = newValue } get { animationView.animationSpeed } } @objc public var respectAnimationFrameRate: Bool { set { animationView.respectAnimationFrameRate = newValue } get { animationView.respectAnimationFrameRate } } @objc public var isAnimationPlaying: Bool { animationView.isAnimationPlaying } @objc public var backgroundMode: CompatibleBackgroundBehavior { get { switch animationView.backgroundBehavior { case .stop: return .stop case .pause: return .pause case .pauseAndRestore: return .pauseAndRestore case .forceFinish: return .forceFinish case .continuePlaying: return .continuePlaying } } set { switch newValue { case .stop: animationView.backgroundBehavior = .stop case .pause: animationView.backgroundBehavior = .pause case .pauseAndRestore: animationView.backgroundBehavior = .pauseAndRestore case .forceFinish: animationView.backgroundBehavior = .forceFinish case .continuePlaying: animationView.backgroundBehavior = .continuePlaying } } } @objc public func play() { play(completion: nil) } @objc public func play(completion: ((Bool) -> Void)?) { animationView.play(completion: completion) } /// Note: When calling this code from Objective-C, the method signature is /// playFromProgress:toProgress:completion which drops the standard "With" naming convention. @objc public func play( fromProgress: CGFloat, toProgress: CGFloat, completion: ((Bool) -> Void)? = nil) { animationView.play( fromProgress: fromProgress, toProgress: toProgress, loopMode: nil, completion: completion) } /// Note: When calling this code from Objective-C, the method signature is /// playFromFrame:toFrame:completion which drops the standard "With" naming convention. @objc public func play( fromFrame: CGFloat, toFrame: CGFloat, completion: ((Bool) -> Void)? = nil) { animationView.play( fromFrame: fromFrame, toFrame: toFrame, loopMode: nil, completion: completion) } /// Note: When calling this code from Objective-C, the method signature is /// playFromMarker:toMarker:completion which drops the standard "With" naming convention. @objc public func play( fromMarker: String, toMarker: String, completion: ((Bool) -> Void)? = nil) { animationView.play( fromMarker: fromMarker, toMarker: toMarker, completion: completion) } @objc public func play( marker: String, completion: ((Bool) -> Void)? = nil) { animationView.play( marker: marker, completion: completion) } @objc public func stop() { animationView.stop() } @objc public func pause() { animationView.pause() } @objc public func reloadImages() { animationView.reloadImages() } @objc public func forceDisplayUpdate() { animationView.forceDisplayUpdate() } @objc public func getValue( for keypath: CompatibleAnimationKeypath, atFrame: CGFloat) -> Any? { animationView.getValue( for: keypath.animationKeypath, atFrame: atFrame) } @objc public func logHierarchyKeypaths() { animationView.logHierarchyKeypaths() } @objc public func setColorValue(_ color: UIColor, forKeypath keypath: CompatibleAnimationKeypath) { var red: CGFloat = 0 var green: CGFloat = 0 var blue: CGFloat = 0 var alpha: CGFloat = 0 let colorspace = LottieConfiguration.shared.colorSpace let convertedColor = color.cgColor.converted(to: colorspace, intent: .defaultIntent, options: nil) if let components = convertedColor?.components, components.count == 4 { red = components[0] green = components[1] blue = components[2] alpha = components[3] } else { color.getRed(&red, green: &green, blue: &blue, alpha: &alpha) } let valueProvider = ColorValueProvider(LottieColor(r: Double(red), g: Double(green), b: Double(blue), a: Double(alpha))) animationView.setValueProvider(valueProvider, keypath: keypath.animationKeypath) } @objc public func getColorValue(for keypath: CompatibleAnimationKeypath, atFrame: CGFloat) -> UIColor? { let value = animationView.getValue(for: keypath.animationKeypath, atFrame: atFrame) guard let colorValue = value as? LottieColor else { return nil; } return UIColor( red: CGFloat(colorValue.r), green: CGFloat(colorValue.g), blue: CGFloat(colorValue.b), alpha: CGFloat(colorValue.a)) } @objc public func addSubview( _ subview: AnimationSubview, forLayerAt keypath: CompatibleAnimationKeypath) { animationView.addSubview( subview, forLayerAt: keypath.animationKeypath) } @objc public func convert( rect: CGRect, toLayerAt keypath: CompatibleAnimationKeypath?) -> CGRect { animationView.convert( rect, toLayerAt: keypath?.animationKeypath) ?? .zero } @objc public func convert( point: CGPoint, toLayerAt keypath: CompatibleAnimationKeypath?) -> CGPoint { animationView.convert( point, toLayerAt: keypath?.animationKeypath) ?? .zero } @objc public func progressTime(forMarker named: String) -> CGFloat { animationView.progressTime(forMarker: named) ?? 0 } @objc public func frameTime(forMarker named: String) -> CGFloat { animationView.frameTime(forMarker: named) ?? 0 } @objc public func durationFrameTime(forMarker named: String) -> CGFloat { animationView.durationFrameTime(forMarker: named) ?? 0 } // MARK: Private private let animationView: LottieAnimationView private func commonInit() { setUpViews() } private func setUpViews() { animationView.translatesAutoresizingMaskIntoConstraints = false addSubview(animationView) animationView.topAnchor.constraint(equalTo: topAnchor).isActive = true animationView.trailingAnchor.constraint(equalTo: trailingAnchor).isActive = true animationView.leadingAnchor.constraint(equalTo: leadingAnchor).isActive = true animationView.bottomAnchor.constraint(equalTo: bottomAnchor).isActive = true } } /// An Objective-C compatible wrapper around Lottie's DictionaryTextProvider. /// Use in tandem with CompatibleAnimationView to supply text to LottieAnimationView /// when using Lottie in Objective-C. @objc public final class CompatibleDictionaryTextProvider: NSObject { // MARK: Lifecycle @objc public init(values: [String: String]) { self.values = values super.init() } // MARK: Internal var textProvider: AnimationKeypathTextProvider? { DictionaryTextProvider(values) } // MARK: Private private let values: [String: String] } #endif
2201_75827989/zhi_shi_ku
uni_modules/uts-animation-view/utssdk/app-ios/lottie-ios/Public/iOS/Compatibility/CompatibleAnimationView.swift
Swift
unknown
15,625
// // FilepathImageProvider.swift // lottie-swift // // Created by Brandon Withrow on 2/1/19. // import Foundation #if canImport(UIKit) import UIKit /// Provides an image for a lottie animation from a provided Bundle. public class FilepathImageProvider: AnimationImageProvider { // MARK: Lifecycle /// Initializes an image provider with a specific filepath. /// /// - Parameter filepath: The absolute filepath containing the images. /// - Parameter contentsGravity: The contents gravity to use when rendering the images. /// public init(filepath: String, contentsGravity: CALayerContentsGravity = .resize) { self.filepath = URL(fileURLWithPath: filepath) self.contentsGravity = contentsGravity } /// Initializes an image provider with a specific filepath. /// /// - Parameter filepath: The absolute filepath containing the images. /// - Parameter contentsGravity: The contents gravity to use when rendering the images. /// public init(filepath: URL, contentsGravity: CALayerContentsGravity = .resize) { self.filepath = filepath self.contentsGravity = contentsGravity } // MARK: Public public func imageForAsset(asset: ImageAsset) -> CGImage? { if asset.name.hasPrefix("data:"), let url = URL(string: asset.name), let data = try? Data(contentsOf: url), let image = UIImage(data: data) { return image.cgImage } let directPath = filepath.appendingPathComponent(asset.name).path if FileManager.default.fileExists(atPath: directPath) { return UIImage(contentsOfFile: directPath)?.cgImage } let pathWithDirectory = filepath.appendingPathComponent(asset.directory).appendingPathComponent(asset.name).path if FileManager.default.fileExists(atPath: pathWithDirectory) { return UIImage(contentsOfFile: pathWithDirectory)?.cgImage } LottieLogger.shared.warn("Could not find image \"\(asset.name)\" in bundle") return nil } public func contentsGravity(for _: ImageAsset) -> CALayerContentsGravity { contentsGravity } // MARK: Internal let filepath: URL let contentsGravity: CALayerContentsGravity } extension FilepathImageProvider: Equatable { public static func ==(_ lhs: FilepathImageProvider, _ rhs: FilepathImageProvider) -> Bool { lhs.filepath == rhs.filepath } } #endif
2201_75827989/zhi_shi_ku
uni_modules/uts-animation-view/utssdk/app-ios/lottie-ios/Public/iOS/FilepathImageProvider.swift
Swift
unknown
2,341
// // LottieAnimationViewBase.swift // lottie-swift-iOS // // Created by Brandon Withrow on 2/6/19. // #if canImport(UIKit) import UIKit /// The base view for `LottieAnimationView` on iOS, tvOS, watchOS, and macCatalyst. /// /// Enables the `LottieAnimationView` implementation to be shared across platforms. open class LottieAnimationViewBase: UIView { // MARK: Public public override var contentMode: UIView.ContentMode { didSet { setNeedsLayout() } } public override func didMoveToWindow() { super.didMoveToWindow() animationMovedToWindow() } public override func layoutSubviews() { super.layoutSubviews() layoutAnimation() } // MARK: Internal var viewLayer: CALayer? { layer } var screenScale: CGFloat { #if os(iOS) || os(tvOS) if #available(iOS 13.0, tvOS 13.0, *) { return max(UITraitCollection.current.displayScale, 1) } else { return UIScreen.main.scale } #else // if os(visionOS) // We intentionally don't check `#if os(visionOS)`, because that emits // a warning when building on Xcode 14 and earlier. 1.0 #endif } func layoutAnimation() { // Implemented by subclasses. } func animationMovedToWindow() { // Implemented by subclasses. } func commonInit() { contentMode = .scaleAspectFit clipsToBounds = true NotificationCenter.default.addObserver( self, selector: #selector(animationWillEnterForeground), name: UIApplication.willEnterForegroundNotification, object: nil) NotificationCenter.default.addObserver( self, selector: #selector(animationWillMoveToBackground), name: UIApplication.didEnterBackgroundNotification, object: nil) } @objc func animationWillMoveToBackground() { // Implemented by subclasses. } @objc func animationWillEnterForeground() { // Implemented by subclasses. } } #endif
2201_75827989/zhi_shi_ku
uni_modules/uts-animation-view/utssdk/app-ios/lottie-ios/Public/iOS/LottieAnimationViewBase.swift
Swift
unknown
1,934
// // UIColorExtension.swift // lottie-swift // // Created by Brandon Withrow on 2/4/19. // #if canImport(UIKit) import UIKit extension UIColor { public var lottieColorValue: LottieColor { var r: CGFloat = 0, g: CGFloat = 0, b: CGFloat = 0, a: CGFloat = 0 getRed(&r, green: &g, blue: &b, alpha: &a) return LottieColor(r: Double(r), g: Double(g), b: Double(b), a: Double(a)) } } #endif
2201_75827989/zhi_shi_ku
uni_modules/uts-animation-view/utssdk/app-ios/lottie-ios/Public/iOS/UIColorExtension.swift
Swift
unknown
408
// // AnimationSubview.swift // lottie-swift-iOS // // Created by Brandon Withrow on 2/5/19. // #if os(macOS) import AppKit /// A view that can be added to a keypath of an AnimationView public final class AnimationSubview: NSView { var viewLayer: CALayer? { layer } } #endif
2201_75827989/zhi_shi_ku
uni_modules/uts-animation-view/utssdk/app-ios/lottie-ios/Public/macOS/AnimationSubview.macOS.swift
Swift
unknown
290
// // LottieBundleImageProvider.swift // lottie-swift // // Created by Brandon Withrow on 1/25/19. // #if os(macOS) import AppKit /// Provides an image for a lottie animation from a provided Bundle. public class BundleImageProvider: AnimationImageProvider { // MARK: Lifecycle /// Initializes an image provider with a bundle and an optional subpath. /// /// Provides images for an animation from a bundle. Additionally the provider can /// search a specific subpath for the images. /// /// - Parameter bundle: The bundle containing images for the provider. /// - Parameter searchPath: The subpath is a path within the bundle to search for image assets. /// - Parameter contentsGravity: The contents gravity to use when rendering the image. /// public init(bundle: Bundle, searchPath: String?, contentsGravity: CALayerContentsGravity = .resize) { self.bundle = bundle self.searchPath = searchPath self.contentsGravity = contentsGravity } // MARK: Public public func imageForAsset(asset: ImageAsset) -> CGImage? { if let base64Image = asset.base64Image { return base64Image } let imagePath: String? /// Try to find the image in the bundle. if let searchPath { /// Search in the provided search path for the image var directoryPath = URL(fileURLWithPath: searchPath) directoryPath.appendPathComponent(asset.directory) if let path = bundle.path(forResource: asset.name, ofType: nil, inDirectory: directoryPath.path) { /// First search for the image in the asset provided sub directory. imagePath = path } else if let path = bundle.path(forResource: asset.name, ofType: nil, inDirectory: searchPath) { /// Try finding the image in the search path. imagePath = path } else { imagePath = bundle.path(forResource: asset.name, ofType: nil) } } else { if let path = bundle.path(forResource: asset.name, ofType: nil, inDirectory: asset.directory) { /// First search for the image in the asset provided sub directory. imagePath = path } else { /// First search for the image in bundle. imagePath = bundle.path(forResource: asset.name, ofType: nil) } } guard let foundPath = imagePath, let image = NSImage(contentsOfFile: foundPath) else { /// No image found. LottieLogger.shared.warn("Could not find image \"\(asset.name)\" in bundle") return nil } return image.lottie_CGImage } public func contentsGravity(for _: ImageAsset) -> CALayerContentsGravity { contentsGravity } // MARK: Internal let bundle: Bundle let searchPath: String? let contentsGravity: CALayerContentsGravity } extension BundleImageProvider: Equatable { public static func ==(_ lhs: BundleImageProvider, _ rhs: BundleImageProvider) -> Bool { lhs.bundle == rhs.bundle && lhs.searchPath == rhs.searchPath } } #endif
2201_75827989/zhi_shi_ku
uni_modules/uts-animation-view/utssdk/app-ios/lottie-ios/Public/macOS/BundleImageProvider.macOS.swift
Swift
unknown
2,955
// // FilepathImageProvider.swift // lottie-swift // // Created by Brandon Withrow on 2/1/19. // #if os(macOS) import AppKit /// An `AnimationImageProvider` that provides images by name from a specific filepath. public class FilepathImageProvider: AnimationImageProvider { // MARK: Lifecycle /// Initializes an image provider with a specific filepath. /// /// - Parameter filepath: The absolute filepath containing the images. /// - Parameter contentsGravity: The contents gravity to use when rendering the images. /// public init(filepath: String, contentsGravity: CALayerContentsGravity = .resize) { self.filepath = URL(fileURLWithPath: filepath) self.contentsGravity = contentsGravity } /// Initializes an image provider with a specific filepath. /// /// - Parameter filepath: The absolute filepath containing the images. /// - Parameter contentsGravity: The contents gravity to use when rendering the images. /// public init(filepath: URL, contentsGravity: CALayerContentsGravity = .resize) { self.filepath = filepath self.contentsGravity = contentsGravity } // MARK: Public public func imageForAsset(asset: ImageAsset) -> CGImage? { if asset.name.hasPrefix("data:"), let url = URL(string: asset.name), let data = try? Data(contentsOf: url), let image = NSImage(data: data) { return image.lottie_CGImage } let directPath = filepath.appendingPathComponent(asset.name).path if FileManager.default.fileExists(atPath: directPath) { return NSImage(contentsOfFile: directPath)?.lottie_CGImage } let pathWithDirectory = filepath.appendingPathComponent(asset.directory).appendingPathComponent(asset.name).path if FileManager.default.fileExists(atPath: pathWithDirectory) { return NSImage(contentsOfFile: pathWithDirectory)?.lottie_CGImage } LottieLogger.shared.warn("Could not find image \"\(asset.name)\" in bundle") return nil } public func contentsGravity(for _: ImageAsset) -> CALayerContentsGravity { contentsGravity } // MARK: Internal let filepath: URL let contentsGravity: CALayerContentsGravity } extension FilepathImageProvider: Equatable { public static func ==(_ lhs: FilepathImageProvider, _ rhs: FilepathImageProvider) -> Bool { lhs.filepath == rhs.filepath } } extension NSImage { @nonobjc var lottie_CGImage: CGImage? { guard let imageData = tiffRepresentation else { return nil } guard let sourceData = CGImageSourceCreateWithData(imageData as CFData, nil) else { return nil } return CGImageSourceCreateImageAtIndex(sourceData, 0, nil) } } #endif
2201_75827989/zhi_shi_ku
uni_modules/uts-animation-view/utssdk/app-ios/lottie-ios/Public/macOS/FilepathImageProvider.macOS.swift
Swift
unknown
2,656
// // LottieAnimationViewBase.swift // lottie-swift-iOS // // Created by Brandon Withrow on 2/6/19. // #if os(macOS) import AppKit public enum LottieContentMode: Int { case scaleToFill case scaleAspectFit case scaleAspectFill case redraw case center case top case bottom case left case right case topLeft case topRight case bottomLeft case bottomRight } /// The base view for `LottieAnimationView` on macOs. /// /// Enables the `LottieAnimationView` implementation to be shared across platforms. open class LottieAnimationViewBase: NSView { // MARK: Public public override var wantsUpdateLayer: Bool { true } public override var isFlipped: Bool { true } public var contentMode: LottieContentMode = .scaleAspectFit { didSet { setNeedsLayout() } } public override func viewDidMoveToWindow() { super.viewDidMoveToWindow() animationMovedToWindow() } public override func layout() { super.layout() CATransaction.begin() CATransaction.setDisableActions(true) layoutAnimation() CATransaction.commit() } // MARK: Internal var screenScale: CGFloat { NSApp.mainWindow?.backingScaleFactor ?? 1 } var viewLayer: CALayer? { layer } func layoutAnimation() { // Implemented by subclasses. } func animationMovedToWindow() { // Implemented by subclasses. } func commonInit() { wantsLayer = true } func setNeedsLayout() { needsLayout = true } func layoutIfNeeded() { // Implemented by subclasses. } @objc func animationWillMoveToBackground() { // Implemented by subclasses. } @objc func animationWillEnterForeground() { // Implemented by subclasses. } } #endif
2201_75827989/zhi_shi_ku
uni_modules/uts-animation-view/utssdk/app-ios/lottie-ios/Public/macOS/LottieAnimationViewBase.macOS.swift
Swift
unknown
1,742
export function getBatteryInfo(options) { return my.getBatteryInfo(options) } export function getBatteryInfoSync(options) { return my.getBatteryInfoSync(options) }
2201_75827989/zhi_shi_ku
uni_modules/uts-getbatteryinfo/utssdk/mp-alipay/index.js
JavaScript
unknown
172
export function getBatteryInfo(options) { return swan.getBatteryInfo(options) } export function getBatteryInfoSync(options) { return swan.getBatteryInfoSync(options) }
2201_75827989/zhi_shi_ku
uni_modules/uts-getbatteryinfo/utssdk/mp-baidu/index.js
JavaScript
unknown
176
export function getBatteryInfo(options) { return qq.getBatteryInfo(options) } export function getBatteryInfoSync(options) { return qq.getBatteryInfoSync(options) }
2201_75827989/zhi_shi_ku
uni_modules/uts-getbatteryinfo/utssdk/mp-qq/index.js
JavaScript
unknown
172
export function getBatteryInfo(options) { return wx.getBatteryInfo(options) } export function getBatteryInfoSync(options) { return wx.getBatteryInfoSync(options) }
2201_75827989/zhi_shi_ku
uni_modules/uts-getbatteryinfo/utssdk/mp-weixin/index.js
JavaScript
unknown
172
export function getBatteryInfo(options) { if (navigator.getBattery) { navigator.getBattery().then(battery => { const res = { errCode: 0, errSubject: "uni-getBatteryInfo", errMsg: 'getBatteryInfo:ok', level: battery.level * 100, isCharging: battery.charging } options.success && options.success(res) options.complete && options.complete(res) }) } else { const res = { errCode: 1002, errSubject: "uni-getBatteryInfo", errMsg: 'getBatteryInfo:fail navigator.getBattery is unsupported' } options.fail && options.fail(res) options.complete && options.complete(res) } }
2201_75827989/zhi_shi_ku
uni_modules/uts-getbatteryinfo/utssdk/web/index.js
JavaScript
unknown
746
<template> <view > <slot></slot> </view> </template> <script lang="uts"> import LinearLayout from 'android.widget.LinearLayout' import Context from 'android.content.Context' import View from 'android.view.View' /** * 自定义android布局组件,可以实现监听显示状态等复杂的功能 */ class CustomLinearLayout extends LinearLayout{ constructor(context: Context) { super(context) } override onWindowVisibilityChanged(visibility:kotlin.Int){ if (visibility == View.VISIBLE){ console.log("可见状态",visibility) }else if(visibility == INVISIBLE || visibility == GONE){ console.log("不可见状态",visibility) } } } //原生提供以下属性或方法的实现 export default { name: "uts-hello-container", NVLoad(): LinearLayout { let contentLayout = new CustomLinearLayout($androidContext!) contentLayout.orientation = LinearLayout.VERTICAL; return contentLayout } } </script>
2201_75827989/zhi_shi_ku
uni_modules/uts-hello-component/utssdk/app-android/container.vue
Vue
unknown
1,051
<template> <view > </view> </template> <script lang="uts"> import TextUtils from 'android.text.TextUtils' import Button from 'android.widget.Button' import LinearLayout from 'android.widget.LinearLayout' import View from 'android.view.View' class ButtonClickListenr implements View.OnClickListener { override onClick(v ? : View) { console.log(v) } } //原生提供以下属性或方法的实现 export default { /** * 组件名称,也就是开发者使用的标签 */ name: "uts-hello-view", /** * 组件涉及的事件声明,只有声明过的事件,才能被正常发送 */ emits: ['buttonClick'], /** * 属性声明,组件的使用者会传递这些属性值到组件 */ props: { /** * 字符串类型 属性:buttonText 需要设置默认值 */ "buttonText": { type: String, default: "点击触发" } }, /** * 组件内部变量声明 */ data() { return {} }, /** * 属性变化监听器实现 */ watch: { "buttonText": { /** * 这里监听属性变化,并进行组件内部更新 */ handler(newButtonText: string) { if (this.$el != null) { let button = this.$el!.findViewWithTag("centerButton") as Button if (!TextUtils.isEmpty(newButtonText)) { button.setText(newButtonText) } } }, immediate: false //创建时是否通过此方法更新属性,默认值为false }, }, /** * 规则:如果没有配置expose,则methods中的方法均对外暴露,如果配置了expose,则以expose的配置为准向外暴露 * ['publicMethod'] 含义为:只有 `publicMethod` 在实例上可用 */ expose: ['doSth'], methods: { /** * 对外公开的组件方法 */ doSth(paramA: string) { // 这是组件的自定义方法 console.log("paramA",paramA) }, /** * 内部使用的组件方法 */ privateMethod() { } }, /** * 组件被创建,组件第一个生命周期, * 在内存中被占用的时候被调用,开发者可以在这里执行一些需要提前执行的初始化逻辑 * [可选实现] */ created() { }, /** * 对应平台的view载体即将被创建,对应前端beforeMount * [可选实现] */ NVBeforeLoad() { }, /** * 创建原生View,必须定义返回值类型 * 开发者需要重点实现这个函数,声明原生组件被创建出来的过程,以及最终生成的原生组件类型 * (Android需要明确知道View类型,需特殊校验) * todo 补充IOS平台限制 * [必须实现] */ NVLoad(): LinearLayout { //必须实现 let contentLayout = new LinearLayout(this.$androidContext) let button = new Button(this.$androidContext) button.setText("点击触发"); button.setTag("centerButton"); contentLayout.addView(button, new LinearLayout.LayoutParams(500, 500)); button.setOnClickListener(new ButtonClickListenr()) return contentLayout }, /** * 原生View已创建 * [可选实现] */ NVLoaded() { // 组件内可以调用 UTSAndroid 内置方法 console.log("UTSAndroid.devicePX2px(1080) : ",UTSAndroid.devicePX2px(1080)) console.log("UTSAndroid.rpx2px(1080) : ",UTSAndroid.rpx2px(1080)) // console.log("UTSAndroid.appJSBundleUrl() : ",UTSAndroid.appJSBundleUrl()) }, /** * 原生View布局完成 * [可选实现] */ NVLayouted() { }, /** * 原生View将释放 * [可选实现] */ NVBeforeUnload() {}, /** * 原生View已释放,这里可以做释放View之后的操作 * [可选实现] */ NVUnloaded() { }, /** * 组件销毁 * [可选实现] */ unmounted() {}, /** * 自定组件布局尺寸 * [可选实现] */ NVMeasure(size: UTSSize,mode:UTSMeasureMode): UTSSize { size.width = 120.0.toFloat() size.height = 800.0.toFloat() return size } } </script> <style> </style>
2201_75827989/zhi_shi_ku
uni_modules/uts-hello-component/utssdk/app-android/index.vue
Vue
unknown
3,989
<template> <view> <slot></slot> </view> </template> <script lang="uts"> import { UIView } from 'UIKit' //原生提供以下属性或方法的实现 export default { name: "uts-hello-container", NVLoad(): UIView { let view = new UIView() return view } } </script>
2201_75827989/zhi_shi_ku
uni_modules/uts-hello-component/utssdk/app-ios/container.vue
Vue
unknown
307
<template> <view class="defaultStyles"> </view> </template> <script lang="uts"> import { UIButton, UIControl } from "UIKit" // 定义按钮点击后触发回调的类 class ButtonClickListsner { // 按钮点击回调方法 @objc buttonClick() { console.log("按钮被点击") } } //原生提供以下属性或方法的实现 export default { name: "uts-hello-view", emits: ['buttonClick'], props: { "buttonText": { type: String, default: "点击触发" } }, watch: { "buttonText": { /** * 这里监听属性变化,并进行组件内部更新 */ handler(newButtonText: string, oldButtonText) { this.$el.setTitle(newButtonText, for = UIControl.State.normal) }, immediate: false //创建时是否通过此方法更新属性,默认值为false }, }, data() { return { buttonClickListsner : new ButtonClickListsner() } }, expose: ['doSth'], methods: { /** * 对外公开的组件方法 */ doSth(paramA: string) { // 这是组件的自定义方法 console.log("paramA") } }, /** * 创建原生View,必须定义返回值类型 */ NVLoad(): UIButton { //必须实现 let button = new UIButton() button.setTitle(this.buttonText, for = UIControl.State.normal) const method = Selector("buttonClick") button.addTarget(this.buttonClickListsner, action = method, for = UIControl.Event.touchUpInside) return button } } </script>
2201_75827989/zhi_shi_ku
uni_modules/uts-hello-component/utssdk/app-ios/index.vue
Vue
unknown
1,487
package uts.sdk.modules.utsNativepage class NativeLib { /** * A native method that is implemented by the 'nativelib' native library, * which is packaged with this application. */ external fun stringFromJNI(): String companion object { // Used to load the 'nativelib' library on application startup. init { System.loadLibrary("nativelib") } } }
2201_75827989/zhi_shi_ku
uni_modules/uts-nativepage/utssdk/app-android/NativeLib.kt
Kotlin
unknown
415
package uts.sdk.modules.utsSyntaxcase; import io.dcloud.uts.console; public class JavaUser { public String name; public int age; public JavaUser(String name, int age) { this.name = name; this.age = age; } public String toString() { String ret = "Name: " + name + ", Age: " + age; console.log(ret); return ret; } }
2201_75827989/zhi_shi_ku
uni_modules/uts-syntaxcase/utssdk/app-android/JavaUser.java
Java
unknown
389
package uts.sdk.modules.utsSyntaxcase import android.app.ActivityManager import android.content.Context.ACTIVITY_SERVICE import android.os.Build import io.dcloud.uts.UTSAndroid import io.dcloud.uts.setInterval import io.dcloud.uts.clearInterval import io.dcloud.uts.console object NativeCode { fun getPhoneInfo():String{ val ret = "${Build.BOARD}-${Build.USER}" console.log("PhoneInfo",ret) return ret } fun finishActivity(){ UTSAndroid.getUniActivity()?.finish() } fun getJavaUser():JavaUser{ return JavaUser("张三",12) } /** * 记录上一次的任务id */ private var lastTaskId = -1 fun kotlinCallbackUTS(callback: (String) -> Unit){ if(lastTaskId != -1){ // 避免重复开启 clearInterval(lastTaskId) } lastTaskId = setInterval({ val activityManager = UTSAndroid.getUniActivity()?.getSystemService(ACTIVITY_SERVICE) as ActivityManager val memoryInfo = ActivityManager.MemoryInfo() activityManager.getMemoryInfo(memoryInfo) val availMem = memoryInfo.availMem / 1024 / 1024 val totalMem = memoryInfo.totalMem / 1024 / 1024 callback("设备内存:$totalMem MB,可用内存:$availMem MB") },1000,2000).toInt() } fun kotlinStopMemListenTest(){ if(lastTaskId != -1){ // 避免重复开启 clearInterval(lastTaskId) } } }
2201_75827989/zhi_shi_ku
uni_modules/uts-syntaxcase/utssdk/app-android/kotlinCode.kt
Kotlin
unknown
1,512
import DCloudUTSFoundation class ReadFile { public static func readFile( _ path: String, _ completionHandler: ((ArrayBuffer?, NSNumber) -> Void)? = nil ) { if FileManager.default.fileExists(atPath: path) == false { completionHandler?(nil, 1) return } let fileUrl = URL(fileURLWithPath: path) do { let fileData = try Data(contentsOf: fileUrl) let result = ArrayBuffer.fromData(fileData) if result == nil { completionHandler?(nil, 2) return } completionHandler?(result, 0) } catch { completionHandler?(nil, 1) } } }
2201_75827989/zhi_shi_ku
uni_modules/uts-syntaxcase/utssdk/app-ios/readFile.swift
Swift
unknown
668
// // TencentLBS.h // TencentLBS // // Created by mirantslu on 16/4/19. // Copyright © 2016年 Tencent. All rights reserved. // #import <UIKit/UIKit.h> //! Project version number for TencentLBS. FOUNDATION_EXPORT double TencentLBSVersionNumber; //! Project version string for TencentLBS. FOUNDATION_EXPORT const unsigned char TencentLBSVersionString[]; // In this header, you should import all the public headers of your framework using statements like #import <TencentLBS/PublicHeader.h> #import <TencentLBS/TencentLBSLocation.h> #import <TencentLBS/TencentLBSLocationManager.h> #import <TencentLBS/TencentLBSLocationUtils.h>
2201_75827989/zhi_shi_ku
uni_modules/uts-tencentgeolocation/utssdk/app-ios/Frameworks/TencentLBS.framework/Headers/TencentLBS.h
Objective-C
unknown
637
// // TencentLBSLocation.h // TencentLBS // // Created by mirantslu on 16/4/19. // Copyright © 2016年 Tencent. All rights reserved. // #import <Foundation/Foundation.h> #import <CoreLocation/CoreLocation.h> NS_ASSUME_NONNULL_BEGIN #define TENCENTLBS_DEBUG 0 typedef NS_ENUM(NSInteger, TencentLBSDRProvider) { TencentLBSDRProviderError = -2, //!< 错误,可能未开启dr TencentLBSDRProviderUnkown = -1, //!< 定位结果来源未知 TencentLBSDRProviderFusion = 0, //!< 定位结果来源融合的结果 TencentLBSDRProviderGPS = 1, //!< 定位结果来源GPS TencentLBSDRProviderNetWork = 2, //!< 定位结果来源网络 }; @interface TencentLBSPoi : NSObject<NSSecureCoding, NSCopying> @property (nonatomic, copy) NSString *uid; //!< 当前POI的uid @property (nonatomic, copy) NSString *name; //!< 当前POI的名称 @property (nonatomic, copy) NSString *address; //!< 当前POI的地址 @property (nonatomic, copy) NSString *catalog; //!< 当前POI的类别 @property (nonatomic, assign) double longitude; //!< 当前POI的经度 @property (nonatomic, assign) double latitude; //!< 当前POI的纬度 @property (nonatomic, assign) double distance; //!< 当前POI与当前位置的距离 @end @interface TencentLBSLocation : NSObject<NSSecureCoding, NSCopying> /** * 返回当前位置的CLLocation信息 */ @property (nonatomic, strong) CLLocation *location; /** * 返回当前位置的行政区划, 0-表示中国大陆、港、澳, 1-表示其他 */ @property (nonatomic, assign) NSInteger areaStat; /** * 返回室内定位楼宇Id */ @property (nonatomic, copy, nullable) NSString *buildingId; /** * 返回室内定位楼层 */ @property (nonatomic, copy, nullable) NSString *buildingFloor; /** * 返回室内定位类型,0表示普通定位结果,1表示蓝牙室内定位结果 */ @property (nonatomic, assign) NSInteger indoorLocationType; /** * */ @property (nonatomic, assign) TencentLBSDRProvider drProvider; /** * 返回当前位置的名称, * 仅当TencentLBSRequestLevel为TencentLBSRequestLevelName或TencentLBSRequestLevelAdminName或TencentLBSRequestLevelPoi有返回值,否则为空 */ @property (nonatomic, copy, nullable) NSString *name; /** * 返回当前位置的地址 * 仅当TencentLBSRequestLevel为TencentLBSRequestLevelName或TencentLBSRequestLevelAdminName有返回值,否则为空 */ @property (nonatomic, copy, nullable) NSString *address; /** * 返回国家编码,例如中国为156 * <b>注意:该接口涉及到WebService API,请参考https://lbs.qq.com/service/webService/webServiceGuide/webServiceOverview中的配额限制说明, * 并将申请的有效key通过TencentLBSLocationManager的- (void)setDataWithValue: forKey:方法设置,其中key为固定值@"ReGeoCodingnKey",例如[tencentLocationManager setDataWithValue:@"您申请的key(务必正确)" forKey:@"ReGeoCodingnKey"];,否则将返回默认值0</b> */ @property (nonatomic, assign) NSInteger nationCode; /** * 返回当前位置的城市编码 * 仅当TencentLBSRequestLevel为TencentLBSRequestLevelAdminName或TencentLBSRequestLevelPoi有返回值,否则为空 */ @property (nonatomic, copy, nullable) NSString *code; /** * 返回当前位置的国家 * 仅当TencentLBSRequestLevel为TencentLBSRequestLevelAdminName或TencentLBSRequestLevelPoi有返回值,否则为空 */ @property (nonatomic, copy, nullable) NSString *nation; /** * 返回当前位置的省份 * 仅当TencentLBSRequestLevel为TencentLBSRequestLevelAdminName或TencentLBSRequestLevelPoi有返回值,否则为空 */ @property (nonatomic, copy, nullable) NSString *province; /** * 返回当前位置的城市固话编码. * 仅当TencentLBSRequestLevel为TencentLBSRequestLevelAdminName或TencentLBSRequestLevelPoi有返回值,否则为空 */ @property (nonatomic, copy, nullable) NSString *cityPhoneCode; /** * 返回当前位置的城市 * 仅当TencentLBSRequestLevel为TencentLBSRequestLevelAdminName或TencentLBSRequestLevelPoi有返回值,否则为空 */ @property (nonatomic, copy, nullable) NSString *city; /** * 返回当前位置的区县 * 仅当TencentLBSRequestLevel为TencentLBSRequestLevelAdminName或TencentLBSRequestLevelPoi有返回值,否则为空 */ @property (nonatomic, copy, nullable) NSString *district; /** * 返回当前位置的乡镇 * 仅当TencentLBSRequestLevel为TencentLBSRequestLevelAdminName或TencentLBSRequestLevelPoi有返回值,否则为空 */ @property (nonatomic, copy, nullable) NSString *town; /** * 返回当前位置的村 * 仅当TencentLBSRequestLevel为TencentLBSRequestLevelAdminName或TencentLBSRequestLevelPoi有返回值,否则为空 */ @property (nonatomic, copy, nullable) NSString *village; /** * 返回当前位置的街道 * 仅当TencentLBSRequestLevel为TencentLBSRequestLevelAdminName或TencentLBSRequestLevelPoi有返回值,否则为空 */ @property (nonatomic, copy, nullable) NSString *street; /** * 返回当前位置的街道编码 * 仅当TencentLBSRequestLevel为TencentLBSRequestLevelAdminName或TencentLBSRequestLevelPoi有返回值,否则为空 */ @property (nonatomic, copy, nullable) NSString *street_no; /** * 返回当前位置周围的POI * 仅当TencentLBSRequestLevel为TencentLBSRequestLevelPoi有返回值,否则为空 */ @property (nonatomic, strong, nullable) NSArray<TencentLBSPoi*> *poiList; /** * 返回两个位置之间的横向距离 * @param location */ - (double)distanceFromLocation:(const TencentLBSLocation *)location; // 测试使用 #if TENCENTLBS_DEBUG @property (nonatomic, copy, nullable) NSString *halleyTime; #endif @end NS_ASSUME_NONNULL_END
2201_75827989/zhi_shi_ku
uni_modules/uts-tencentgeolocation/utssdk/app-ios/Frameworks/TencentLBS.framework/Headers/TencentLBSLocation.h
Objective-C
unknown
5,796
// // TencentLBSLocationManager.h // TencentLBS // // Created by mirantslu on 16/4/19. // Copyright © 2016年 Tencent. All rights reserved. // #import <Foundation/Foundation.h> #import <CoreLocation/CoreLocation.h> #import "TencentLBSLocation.h" NS_ASSUME_NONNULL_BEGIN typedef NS_ENUM(NSUInteger, TencentLBSRequestLevel) { TencentLBSRequestLevelGeo = 0, TencentLBSRequestLevelName = 1, TencentLBSRequestLevelAdminName = 3, TencentLBSRequestLevelPoi = 4, }; typedef NS_ENUM(NSUInteger, TencentLBSLocationCoordinateType) { TencentLBSLocationCoordinateTypeGCJ02 = 0, //!< 火星坐标,即国测局坐标 TencentLBSLocationCoordinateTypeWGS84 = 1, //!< 地球坐标,注:如果是海外,无论设置的是火星坐标还是地球坐标,返回的都是地球坐标 }; typedef NS_ENUM(NSUInteger, TencentLBSLocationError) { TencentLBSLocationErrorUnknown = 0, //!< 错误码,表示目前位置未知,但是会一直尝试获取 TencentLBSLocationErrorDenied = 1, //!< 错误码,表示定位权限被禁止 TencentLBSLocationErrorNetwork = 2, //!< 错误码,表示网络错误 TencentLBSLocationErrorHeadingFailure = 3, //!< 错误码,表示朝向无法确认 TencentLBSLocationErrorOther = 4, //!< 错误码,表示未知错误 }; typedef NS_ENUM(NSInteger, TencentLBSDRStartCode) { TencentLBSDRStartCodeSuccess = 0, //!< 启动成功 TencentLBSDRStartCodeNotSupport = -1, //!< 传感器有缺失或没有GPS芯片 TencentLBSDRStartCodeHasStarted = -2, //!< 已经启动 TencentLBSDRStartCodeSensorFailed = -3, //!< 传感器启动失败 TencentLBSDRStartCodeGpsFailed = -4, //!< GPS启动失败 TencentLBSDRStartCodePermissionFailed = -5, //!< 没有位置权限 TencentLBSDRStartCodeUnkown = -6, //!< 未知 }; typedef NS_ENUM(NSInteger, TencentLBSDRStartMotionType) { TencentLBSDRStartMotionTypeWalk = 2, //!< 步行 TencentLBSDRStartMotionTypeBike = 3, //!< 骑行 }; typedef NS_ENUM(NSInteger, TencentLBSAccuracyAuthorization) { // This application has the user's permission to receive accurate location information. TencentLBSAccuracyAuthorizationFullAccuracy, // The user has chosen to grant this application access to location information with reduced accuracy. // Region monitoring and beacon ranging are not available to the application. Other CoreLocation APIs // are available with reduced accuracy. // Location estimates will have a horizontalAccuracy on the order of about 5km. To achieve the // reduction in accuracy, CoreLocation will snap location estimates to a nearby point which represents // the region the device is in. Furthermore, CoreLocation will reduce the rate at which location // estimates are produced. Applications should be prepared to receive locations that are up to 20 // minutes old. TencentLBSAccuracyAuthorizationReducedAccuracy, }; /** * TencentLBSLocatingCompletionBlock 单次定位返回Block * * @param location 位置信息 * @param error 错误信息 参考 TencentLBSLocationError */ typedef void (^TencentLBSLocatingCompletionBlock)(TencentLBSLocation * _Nullable location, NSError * _Nullable error); @protocol TencentLBSLocationManagerDelegate; @interface TencentLBSLocationManager : NSObject /** * 当前位置管理器定位精度的授权状态 */ @property(nonatomic, readonly)TencentLBSAccuracyAuthorization accuracyAuthorization; /** * 当前位置管理器定位权限的授权状态 */ @property(nonatomic, readonly)CLAuthorizationStatus authorizationStatus; /** * API Key, 在使用定位SDK服务之前需要先绑定key。 */ @property (nonatomic, copy) NSString* apiKey; /** * 实现了 TencentLBSLocationManagerDelegate 协议的类指针。 */ @property (nonatomic, weak) id<TencentLBSLocationManagerDelegate> delegate; /** * 设定定位的最小更新距离。默认为 kCLDistanceFilterNone。 */ @property (nonatomic, assign) CLLocationDistance distanceFilter; /** * 设定定位精度。默认为 kCLLocationAccuracyBest 。 */ @property (nonatomic, assign) CLLocationAccuracy desiredAccuracy; /** * 指定定位是否会被系统自动暂停。默认为 YES 。 */ @property (nonatomic, assign) BOOL pausesLocationUpdatesAutomatically; /** * 是否允许后台定位。默认为 NO。 * iOS 9.0 以上用户需要设置该选项并且在info.list里面Background Modes 中的 Location updates 处于选中状态才可以使用后台定位权限。iOS 9.0之前可以直接申请总是使用的权限来获得后台定位。 * * 设置为 YES 的时候必须保证 Background Modes 中的 Location updates 处于选中状态,否则会抛出异常。 */ @property (nonatomic, assign) BOOL allowsBackgroundLocationUpdates; /** * 用户的活动类型 * * 设置用户的活动类型。默认值为 CLActivityTypeOther */ @property (nonatomic, assign) CLActivityType activityType; /** * 设置当朝向改变时,每隔多少度调用一次 * 只有当设备方向的改变值超过该属性值时才激发delegate的方法。 */ @property(nonatomic, assign) CLLocationDegrees headingFilter; /** * 设置设备当前的朝向 */ @property(nonatomic, assign) CLDeviceOrientation headingOrientation; /** * 连续定位的逆地理信息请求的Level。默认为TencentLBSRequestLevelGeo */ @property (nonatomic, assign) TencentLBSRequestLevel requestLevel; /** * 返回的TencentLBSLocation的location字段的坐标类型。默认为TencentLBSLocationCoordinateTypeGCJ02。 * * 在一次定位过程中,只允许设置一次,不允许重复设置 */ @property (nonatomic, assign) TencentLBSLocationCoordinateType coordinateType; /** * 指定POI的更新间隔。 默认是10s */ @property(nonatomic, assign) NSInteger poiUpdateInterval; #pragma mark - /** * accuracyAuthorization * * Discussion: * Return the current TencentLBSAccuracyAuthorization of the calling application. */ + (TencentLBSAccuracyAuthorization)accuracyAuthorization; /** * 设置用户是否同意隐私协议政策 * <p>调用其他接口前必须首先调用此接口进行用户是否同意隐私政策的设置,传入YES后才能正常使用定位功能,否则TencentLBSLocationManager初始化不成功,返回nil,定位功能均无法使用</p> * @param isAgree 是否同意隐私政策 */ + (void)setUserAgreePrivacy:(BOOL) isAgree; /** * 获取用户是否同意隐私政策协议 * <p>设置用户隐私后,可通过该接口判断用户隐私状态</p> * @return isAgreePrivacy 是否同意隐私政策 */ + (BOOL)getUserAgreePrivacy; #pragma mark - - (void)requestWhenInUseAuthorization; - (void)requestAlwaysAuthorization; /** * 当前属于模糊定位状态时,通过该接口请求暂时的完全定位精度的权限 * @param purposeKey 需要在info.plist中配置NSLocationTemporaryUsageDescriptionDictionary key值和对应的申请该权限的描述理由 * @param completion 在弹框让用户选择后的用户的反馈,如果用户授予该权限,block中的参数为nil,如果未授予,block中的参数将为PurposeKey对于的key的描述(如PurposeKey=TemporaryPurposKey_1) */ - (void)requestTemporaryFullAccuracyAuthorizationWithPurposeKey:(NSString *)purposeKey completion:(void (^)(NSError *))completion; /** * 当前属于模糊定位状态时,通过该接口请求暂时的完全定位精度的权限 * @param purposeKey 需要在info.plist中配置NSLocationTemporaryUsageDescriptionDictionary key值和对应的申请该权限的描述理由 */ - (void)requestTemporaryFullAccuracyAuthorizationWithPurposeKey:(NSString *)purposeKey; #pragma mark - /** * 获取定位SDK的版本 */ +(NSString *)getLBSSDKVersion; /** * 获取定位SDK的构建日期 */ +(NSString *)getLBSSDKbuild; #pragma mark - /** * 向SDK内部设置数据,以满足定制的需求 * @param value * @param key */ - (void)setDataWithValue:(NSString *)value forKey:(NSString *)key; /** * 单次定位 * * 该方法为下面方法的一层封装。 * level默认是TencentLBSRequestLevelPoi * timeout默认是10s */ - (BOOL)requestLocationWithCompletionBlock:(TencentLBSLocatingCompletionBlock)completionBlock; /** * 单次定位 * * 注意:不能连续调用该接口,需在上一次返回之后才能再次发起调用。该接口兼容iOS 7.0及以上,因iOS 9.0系统提供单次定位能力,故在9.0以上会调用系统单次定位接口,9.0之前SDK完成封装。可以通过调用cancelRequestLocation来取消。 * * @param level 可以根据此参数来对应的获取POI信息 * @param timeout 表示获取POI的超时时间。 * @param completionBlock 单次定位完成后的Block */ - (BOOL)requestLocationWithRequestLevel:(TencentLBSRequestLevel)level locationTimeout:(NSTimeInterval)timeout completionBlock:(TencentLBSLocatingCompletionBlock)completionBlock; /** * 取消单次定位 **/ - (void)cancelRequestLocation; /** * 开始连续定位 */ - (void)startUpdatingLocation; /** * 停止连续定位 */ - (void)stopUpdatingLocation; /** * 开启更新定位朝向 */ - (void)startUpdatingHeading; /** * 结束更新定位朝向 */ - (void)stopUpdatingHeading; /** * 停止展示定位朝向校准提示 */ - (void)dismissHeadingCalibrationDisplay; #pragma mark - PDR 对外接口 /** * 主动获取DR实时融合位置,调用startDrEngine:成功后才可能有值,业务可根据自己的频率主动获取 * @return DR融合后的定位结果 */ -(TencentLBSLocation *)getPosition; /** * 启动DR引擎。引擎会自动获取传感器和GPS数据,并进行位置计算。 * 启动后DR引擎会主动开启CLLocationManager startUpdatingLocation。 * * 注意:请确保调用之前已获取位置权限(使用期间或者始终允许) * * @param type 运动类型 目前支持,参考TencentLBSDRStartMotionType * @return 返回码,参考TencentLBSDRStartCode */ -(TencentLBSDRStartCode)startDrEngine:(TencentLBSDRStartMotionType)type; /** * 停止DR引擎。内部有极短时间延迟,若在此期间调用TencentLBSLocationManager startDrEngine:可能导致启动不成功。 */ -(void)terminateDrEngine; /** * 是否支持DR引擎 * @return */ -(BOOL)isSupport; #pragma mark - test used // 测试使用 #if TENCENTLBS_DEBUG + (void)upLoadData; + (NSData *)getLocationLog; + (void)newLocationLog; #endif @end #pragma mark - TencentLBSLocationManagerDelegate /** * TencentLBSLocationManagerDelegate * 定义了发生错误时的错误回调方法,连续定位的回调方法等。 */ @protocol TencentLBSLocationManagerDelegate <NSObject> @optional /** * 当定位发生错误时,会调用代理的此方法 * * @param manager 定位 TencentLBSLocationManager 类 * @param error 返回的错误,参考 TencentLBSLocationError */ - (void)tencentLBSLocationManager:(TencentLBSLocationManager *)manager didFailWithError:(NSError *)error; /** * 连续定位回调函数 * * @param manager 定位 TencentLBSLocationManager 类 * @param location 定位结果 */ - (void)tencentLBSLocationManager:(TencentLBSLocationManager *)manager didUpdateLocation:(TencentLBSLocation *)location; /** * 定位权限状态改变时回调函数 * @deprecated 在iOS 14及以上废弃,由tencentLBSDidChangeAuthorization:代替 * @param manager 定位 TencentLBSLocationManager 类 * @param status 定位权限状态 */ - (void)tencentLBSLocationManager:(TencentLBSLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status; /** * 定位权限状态改变时回调函数 * @param manager 定位 TencentLBSLocationManager 类,由此访问authorizationStatus,accuracyAuthorization */ - (void)tencentLBSDidChangeAuthorization:(TencentLBSLocationManager *)manager; /** * 定位朝向改变时回调函数 * * @param manager 定位 TencentLBSLocationManager 类 * @param newHeading 新的定位朝向 */ - (void)tencentLBSLocationManager:(TencentLBSLocationManager *)manager didUpdateHeading:(CLHeading *)newHeading; /** * 是否展示定位朝向校准提示的回调函数 * * @param manager 定位 TencentLBSLocationManager 类 */ - (BOOL)tencentLBSLocationManagerShouldDisplayHeadingCalibration:(TencentLBSLocationManager *)manager; /** * 只是内部调试使用,外部不应实现该接口 */ - (void)tencentLBSLocationManager:(TencentLBSLocationManager *)manager didThrowLocation:(TencentLBSLocation *)location; @end NS_ASSUME_NONNULL_END
2201_75827989/zhi_shi_ku
uni_modules/uts-tencentgeolocation/utssdk/app-ios/Frameworks/TencentLBS.framework/Headers/TencentLBSLocationManager.h
Objective-C
unknown
12,978
// // TencentLBSLocationUtils.h // TencentLBS // // Created by mirantslu on 16/8/11. // Copyright © 2016年 Tencent. All rights reserved. // #import <Foundation/Foundation.h> #import <CoreLocation/CoreLocation.h> @class TencentLBSLocation; NS_ASSUME_NONNULL_BEGIN @interface TencentLBSLocationUtils : NSObject /** * 计算两个坐标点的距离 */ + (double)distanceBetweenTwoCoordinate2D:(const CLLocationCoordinate2D *)coordinate coordinateTwo:(const CLLocationCoordinate2D *)coordinate2; /** * 计算两个location的距离 */ + (double)distanceBetweenTwoCLLocations:(const CLLocation *)location locationTwo:(const CLLocation *)location2; /** * 计算两个TencentLBSLocation的距离 */ + (double)distanceBetweenTwoTencentLBSLocations:(const TencentLBSLocation *)location locationTwo:(const TencentLBSLocation *)location2; /** * 判断经纬度是否在国内 * */ + (BOOL) isInRegionWithLatitude:(double)latitude longitude:(double)longitude; /** * wgs84坐标转成gcj02坐标 */ + (CLLocationCoordinate2D)WGS84TOGCJ02:(CLLocationCoordinate2D)coordinate; @end @interface TencentLBSServiceManager : NSObject /** * 设置ID,如QQ号,微信号或是其他的登录账号,可用在发布前联调使用 */ @property (atomic, copy) NSString *deviceID; + (instancetype)sharedInsance; @end NS_ASSUME_NONNULL_END
2201_75827989/zhi_shi_ku
uni_modules/uts-tencentgeolocation/utssdk/app-ios/Frameworks/TencentLBS.framework/Headers/TencentLBSLocationUtils.h
Objective-C
unknown
1,357
package uts.sdk.modules.utsTests import android.os.Build import io.dcloud.uts.UTSAndroid object NativeCode { fun getNativeStr():String{ return "android-code" } }
2201_75827989/zhi_shi_ku
uni_modules/uts-tests/utssdk/app-android/kotlinCode.kt
Kotlin
unknown
186
import Foundation class NativeCode { static func getNativeStr() -> String { return "iOS-code" } }
2201_75827989/zhi_shi_ku
uni_modules/uts-tests/utssdk/app-ios/SwiftCode.swift
Swift
unknown
115
package uts.sdk.modules.utsTestsHybrid import io.dcloud.uts.* object TestNumber{ fun testAll() { testToFixed() testIsFinite() testIsInteger() testIsNaN() testToPrecision() testToString() testValueOf() testToInt() testFrom() } @Suppress("DEPRECATION","IMPLICIT_BOXING_IN_IDENTITY_EQUALS") fun testToFixed() { // #TEST Number.toFixed fun financial(x: Number): String { return x.toFixed(2) } console.log(financial(123.456)) // expected output: "123.46" console.log(financial(0.004)) // expected output: "0.00" // #END } fun testIsFinite() { // #TEST Number.isFinite console.log(isFinite(1000)) //expected output: true console.log(isFinite(910)) //expected output: true console.log(isFinite(0)) //expected output: false // #END } fun testIsInteger() { // #TEST Number.isInteger console.log(UTSNumber.isInteger(12)) //expected output: true console.log(UTSNumber.isInteger(12.01)) //expected output: false console.log(UTSNumber.isInteger(-213123112.01)) //expected output: false console.log(UTSNumber.isInteger(-213123112)) //expected output: true // #END } fun testIsNaN() { // #TEST Number.isNaN console.log(isNaN(0)) //expected output: false var aj2 = JSON.parse("{\"a\":1}") as UTSJSONObject var aNumber = aj2["a"] as Number console.log(isNaN(aNumber)) //expected output: false console.log(UTSNumber.isNaN(aNumber)) //expected output: false console.log(UTSNumber.isNaN(11)) //expected output: false console.log(UTSNumber.isNaN(null)) //expected output: false console.log(UTSNumber.isNaN((1 as Number) / 0)) //expected output: false // #END } fun testToPrecision() { // #TEST Number.toPrecision console.log(123.456.toPrecision(4)) //expected output: "123.5" console.log(0.004.toPrecision(4)) //expected output: "0.004000" // #END } fun testToString() { // #TEST Number.toString console.log(10.toString(10)) //expected output: "10" console.log(17.toString(10)) //expected output: "17" console.log(17.2.toString(10)) //expected output: "17.2" console.log(6.toString(2)) //expected output: "110" console.log(254.toString(16)) //expected output: "fe" console.log((-10).toString(2)) //expected output: "-1010" console.log(10.22.toString(8)) //expected output: "12.16050753412172704" console.log((-10.22).toString(8)) //expected output: "-12.16050753412172704" console.log(123456789987654.toString(16)) //expected output: "7048861cc146" console.log((-0xff).toString(2)) //expected output: "-11111111" // #END } fun testValueOf() { // #TEST Number.valueOf console.log(10.valueOf()) //expected output: 10 console.log((-10.2).valueOf()) //expected output: -10.2 console.log(0xf.valueOf()) //expected output: 15 // #END } fun testToInt() { // #TEST Number.toInt var a: Number = 12 console.log(a.toInt()) //expected output: 12 var b: Number = 2147483648 console.log(b.toInt()) //expected output: -2147483648 // #END } fun testFrom() { // #TEST Number.toInt var a: Int = 12 var b = UTSNumber.from(a) console.log(b) //expected output: 12 // #END } }
2201_75827989/zhi_shi_ku
uni_modules/uts-tests-hybrid/utssdk/app-android/TestNumber.kt
Kotlin
unknown
3,924
package uts.sdk.modules.utsTestsHybrid import io.dcloud.uts.* object TestUTSJSONObject{ fun testKeys() { // #TEST UTSJSONObject.keys var obj: UTSJSONObject = object : UTSJSONObject() { var name = "zhangsan" var age: Number = 11 } var ret1 = UTSJSONObject.keys(obj).length console.log(ret1) //2 // #END } fun testAssign() { // #TEST UTSJSONObject.assign var target: UTSJSONObject = object : UTSJSONObject() { var a: Number = 1 var b: Number = 2 } var source: UTSJSONObject = object : UTSJSONObject() { var b: Number = 4 var c: Number = 5 } // 得到一个UTSJSONObject对象 var returnedTarget = UTSJSONObject.assign(target, source) console.log(returnedTarget.toMap().count()) //3 // #END // #TEST UTSJSONObject.assign var target1: UTSJSONObject = object : UTSJSONObject() { var a: Number = 1 var b: Number = 2 } var source1: UTSJSONObject = object : UTSJSONObject() { var b: Number = 4 var c: Number = 5 } // 得到一个UTSJSONObject对象 var returned = UTSJSONObject.assign<UTSJSONObject>(target1, source1) console.log(returned) // {"a": 1, "b": 4, "c": 5} // #END } fun testGetNumber() { // #TEST UTSJSONObject.getNumber var test: UTSJSONObject = object : UTSJSONObject(UTSSourceMapPosition("test", "pages/index/index.uvue", 48, 8)) { var qq: UTSArray<Number> = utsArrayOf( 11, 22 ) } console.log(test.getNumber("qq[2]")) // null console.log(test.getNumber("qq[2]")) // 999 // #END } fun testGetJSON() { // #TEST UTSJSONObject.getJSON var obj: UTSJSONObject = object : UTSJSONObject() { var cars = utsArrayOf( object : UTSJSONObject() { var name = "car1" var value: Number = 100 } ) } var firstCar = obj.getJSON("cars[0]") console.log(firstCar!!["value"]) // 100 // #END } fun testGetArray() { // #TEST UTSJSONObject.getArray var obj: UTSJSONObject = object : UTSJSONObject() { var cars = utsArrayOf( object : UTSJSONObject() { var name = "car1" var value: Number = 100 } ) } var cars: UTSArray<UTSJSONObject>? = obj.getArray<UTSJSONObject>("cars") cars!![0].set("value", 20) console.log(cars[0]["value"]) // 20 // #END // #TEST UTSJSONObject.getArray_1 //这个方法用来获取指定元素类型的数组 var obj1 = JSON.parseObject("{\"name\":\"tom\",\"tag\":[\"student\",\"user\"]}") // 这里得到是 Array<*> var noGenericArray = obj1!!.getArray("tag") console.log(noGenericArray) // 这里得到是 Array<string>, 注意:要手动指定返回值类型,以便Swift进行泛型推断 var genericArray = obj1.getArray<String>("tag") console.log(genericArray) //["student", "user"] // #END } fun testGetString() { // #TEST UTSJSONObject.getString val utsObj: UTSJSONObject = UTSJSONObject() run { var i: Number = 0 while(i < 100){ utsObj.set("" + i, "" + i) i++ } } console.log("--start--") var startTime = Date.now() run { var i: Number = 0 while(i < 10000){ utsObj.getString("0") i++ } } var spendTime = Date.now() - startTime console.log(spendTime < 800) // true // #END } @Suppress("UNUSED_VALUE","ASSIGNED_BUT_NEVER_ACCESSED_VARIABLE","UNUSED_VARIABLE") fun testSample() { // #TEST UTSJSONObject.sample_create,UTSJSONObject.get,UTSJSONObject.set var person: UTSJSONObject = object : UTSJSONObject() { var name = "Tom" var printName = fun(){ console.log(name) } } //返回指定键对应的值,如果对象中不存在此键则返回 null。 var name: String = person["name"] as String //get 方法可以简化为使用下标运算符 `[]` 访问 name = person["name"] as String //增加或更新指定键对应的值。 person["name"] = "Tom1" //set 方法可以简化为使用下标运算符 `[]` 赋值 person["name"] = "Tom2" // #END // #TEST UTSJSONObject.sample_create1 // 写法1 推荐 var person1: UTSJSONObject = JSON.parseObject("{\"name\":\"Tom\"}")!! // 写法2 推荐 val person2: UTSJSONObject = JSON.parse<UTSJSONObject>("{\"name\":\"Tom\"}")!! // 写法3 如果 as 转换的实际类型不匹配 会导致 crash,建议先通过 `instanceof` 判断类型再进行as转换。 val parseRet3 = JSON.parse("{\"name\":\"Tom\"}") if (parseRet3 is UTSJSONObject) { person = parseRet3 } // #END // #TEST UTSJSONObject.toMap val person0 = JSON.parseObject("{\"name\":\"Tom\"}")!! person0.toMap().forEach(fun(value, key){ console.log(key) console.log(value) }) // #END } fun testConvert() { // #TEST UTSJSONObject.convert open class User ( @JsonNotNull open var name: String, @JsonNotNull open var age: Number, ) : UTSObject() { } var jsonObj: UTSJSONObject = object : UTSJSONObject() { var name = "张三" var age: Number = 12 } // UTSJSONObject => 自定义type var userA = JSON.parse<User>(JSON.stringify(jsonObj))!! console.log(userA.name) // 自定义type => UTSJSONObject var utsJsonA = JSON.parseObject(JSON.stringify(userA))!! console.log(utsJsonA) // #END } fun testAll(){ testKeys() testAssign() testGetNumber() testGetJSON() testGetArray() testGetString() testSample() testConvert() } }
2201_75827989/zhi_shi_ku
uni_modules/uts-tests-hybrid/utssdk/app-android/TestUTSJSONObject.kt
Kotlin
unknown
6,640
import Foundation import DCloudUTSFoundation class TestNumber { static func testAll() { testToFixed() testIsFinite() testIsInteger() testIsNaN() testToPrecision() testToString() testValueOf() testToInt() testFrom() } static func testToFixed() { // #TEST Number.toFixed let financial = { (x: NSNumber) in return x.toFixed(2) } console.log(financial(NSNumber(value: 123.456))) // expected output: "123.46" console.log(financial(NSNumber(value: 0.004))); // expected output: "0.00" let num: NSNumber = 3.1415926 console.log(num.toFixed(2)) //expected output: "3.14" // #END } static func testIsFinite() { // #TEST Number.isFinite console.log(NSNumber.isFinite(1000 / 1)) //expected output: true console.log(NSNumber.isFinite(910)) //expected output: true console.log(NSNumber.isFinite(Double.infinity)) //expected output: false // #END } static func testIsInteger() { // #TEST Number.isInteger console.log(NSNumber.isInteger(12)) //expected output: true console.log(NSNumber.isInteger(12.01)) //expected output: false console.log(NSNumber.isInteger(-213123112.01)) //expected output: false console.log(NSNumber.isInteger(-213123112)) //expected output: true // #END } static func testIsNaN() { // #TEST Number.isNaN console.log(isNaN(0)) //expected output: false console.log(NSNumber.isNaN(0)) // expected output: false let obj: UTSJSONObject? = JSON.parseObject("{\"a\":1}") let aNumber = obj?.getNumber("a") ?? 0 console.log(NSNumber.isNaN(aNumber)) //expected output: false console.log(NSNumber.isNaN(11)) //expected output: false console.log(NSNumber.isNaN( 1 / 0)) //expected output: false // #END } static func testToPrecision() { // #TEST Number.toPrecision console.log(123.456.toPrecision(4)) //expected output: "123.5" console.log((0.004).toPrecision(4)) //expected output: "0.004000" // #END } static func testToString() { // #TEST Number.toString console.log(10.toString()) //expected output: "10" console.log(17.2.toString()) //expected output: "17.2" console.log(6.toString(2)) //expected output: "110" console.log(254.toString(16)) //expected output: "fe" console.log((-10).toString(2)) //expected output: "-1010" console.log(10.22.toString(8)) //expected output: "12.16050753412172704" console.log((-10.22).toString(8)) //expected output: "-12.16050753412172704" console.log(123456789987654.toString(16)) //expected output: "7048861cc146" console.log((-0xff).toString(2)) //expected output: "-11111111" // #END } static func testValueOf() { // #TEST Number.valueOf console.log(10.valueOf()) //expected output: 10 console.log((-10.2).valueOf()) //expected output: -10.2 console.log(0xf.valueOf()) //expected output: 15 // #END } static func testToInt() { // #TEST Number.toInt let a: NSNumber = 12 console.log(a.toInt()) //expected output: 12 let b: NSNumber = 2147483648 console.log(b.toInt()) //expected output: -2147483648 // #END } static func testFrom() { // #TEST Number.toInt let a: Int = 12 let b = NSNumber.from(a) console.log(b) //expected output: 12 // #END } }
2201_75827989/zhi_shi_ku
uni_modules/uts-tests-hybrid/utssdk/app-ios/testNumber.swift
Swift
unknown
3,971
import Foundation import DCloudUTSFoundation class TestUTSJSONObject { static func testKeys() { // #TEST UTSJSONObject.keys let obj = UTSJSONObject(dictionary: [ "name": "zhangsan", "age": 11 ]) let ret1 = UTSJSONObject.keys(obj).length console.log(ret1) //2 // #END } static func testAssign() { // #TEST UTSJSONObject.assign let target = UTSJSONObject(dictionary: [ "a": 1, "b": 2 ]); let source = UTSJSONObject(dictionary: [ "b": 4, "c": 5 ]) // 得到一个UTSJSONObject对象 let returnedTarget = UTSJSONObject.assign(target, source); console.log(returnedTarget.toMap().count) //3 // #END // #TEST UTSJSONObject.assign let target1 = UTSJSONObject(dictionary: [ "a": 1, "b": 2 ]); let source1 = UTSJSONObject(dictionary: [ "b": 4, "c": 5 ]) // 得到一个UTSJSONObject对象 let ret = UTSJSONObject.assign(target1, source1, type: UTSJSONObject.self); console.log(ret) // {"a": 1, "b": 4, "c": 5} // #END } static func testGetNumber() { // #TEST UTSJSONObject.getNumber let obj = UTSJSONObject(dictionary: [ "qq": [11, 22] ]) console.log(obj.getNumber("obj[2]")) // null console.log(obj.getNumber("obj[2]", 999)) // 999 // #END } static func testGetJSON() { // #TEST UTSJSONObject.getJSON let obj = UTSJSONObject(dictionary: [ "cars": [ UTSJSONObject(dictionary: [ "name": "car1", "value": 100 ]) ] ]) let firstCar = obj.getJSON("cars[0]") console.log(firstCar!["value"]) // 100 // #END } static func testGetArray() { // #TEST UTSJSONObject.getArray let obj = UTSJSONObject(dictionary: [ "cars": [ UTSJSONObject(dictionary: [ "name": "car1", "value": 100 ]) ] ]) let cars: [UTSJSONObject]? = obj.getArray("cars") cars![0].set("value", 20) console.log(cars![0]["value"]) // 20 // #END // #TEST UTSJSONObject.getArray_1 //这个方法用来获取指定元素类型的数组 let obj1 = JSON.parseObject("{\"name\":\"tom\",\"tag\":[\"student\",\"user\"]}") // 这里得到是 Array<*> let noGenericArray = obj1!.getArray("tag") console.log(noGenericArray) // 这里得到是 Array<string>, 注意:要手动指定返回值类型,以便Swift进行泛型推断 let genericArray: [String]? = obj1!.getArray("tag") console.log(genericArray) //["student", "user"] // #END } static func testGetString() { // #TEST UTSJSONObject.getString let obj = UTSJSONObject() var i = 0 while i < 100 { obj.set("\(i)", "\(i)") i++ } let startTime = Date.now() var j = 0 while j < 10000 { obj.getString("0") j++ } let spendTime = Date.now() - startTime console.log(spendTime < 800) // true // #END } static func testSample() { // #TEST UTSJSONObject.sample_create,UTSJSONObject.get,UTSJSONObject.set var person: UTSJSONObject = UTSJSONObject([ "name": "Tom", "printName": {() -> Void in} ]) //返回指定键对应的值,如果对象中不存在此键则返回 null。 var name: String? = person["name"] as? String //get 方法可以简化为使用下标运算符 `[]` 访问 name = person["name"] as? String //增加或更新指定键对应的值。 person.set("name", "Tom1") //set 方法可以简化为使用下标运算符 `[]` 赋值 person["name"] = "Tom2" // #END // #TEST UTSJSONObject.sample_create1 // 写法1 推荐 var person1: UTSJSONObject = JSON.parseObject("{\"name\":\"Tom\"}")! // 写法2 推荐 let person2: UTSJSONObject = JSON.parse("{\"name\":\"Tom\"}", UTSJSONObject.self)! // 写法3 如果 as 转换的实际类型不匹配 会导致 crash,建议先通过 `instanceof` 判断类型再进行as转换。 let parseRet3 = JSON.parse("{\"name\":\"Tom\"}") if parseRet3 is UTSJSONObject { person = parseRet3 as! UTSJSONObject } // #END // #TEST UTSJSONObject.toMap person1 = JSON.parseObject("{\"name\":\"Tom\"}")! person1.toMap().forEach { value, key in console.log(key, value) } // #END } static func testConvert() { // #TEST UTSJSONObject.convert //自定义class 如果需要使用JSON.stringify 或者 JSON.parse处理,则需要实现 Codable 协议 //通常 uts 代码中 Class 的Codable 协议的实现由编译器自动实现,因此,这类代码不建议在混编代码中使用,除非你能很熟练的使用Codable协议 class User : Codable { var name: String var age: NSNumber public init(_ obj: UTSJSONObject) { self.name = obj["name"] as! String self.age = obj["age"] as! NSNumber } enum CodingKeys: String, CodingKey { case name; case age } required public init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) self.name = try container.decode(String.self, forKey: .name, decoder) self.age = try container.decode(NSNumber.self, forKey: .age, decoder) } func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) try container.encode(name, forKey: .name, encoder) try container.encode(age, forKey: .age, encoder) } } let jsonObj = UTSJSONObject([ "name": "张三", "age": 12 as NSNumber ]) let userA = JSON.parse(JSON.stringify(jsonObj)!, User.self) console.log(userA?.name) let utsJsonA = JSON.parseObject(JSON.stringify(userA)!) console.log(utsJsonA) // #END } static func testAll() { testKeys() testAssign() testGetNumber() testGetJSON() testGetArray() testGetString() testSample() testConvert() } }
2201_75827989/zhi_shi_ku
uni_modules/uts-tests-hybrid/utssdk/app-ios/testUTSJSONObject.swift
Swift
unknown
7,026
// // ToastSwiftFramework.h // ToastSwiftFramework // // Created by DCloud on 2022/11/25. // #import <Foundation/Foundation.h> //! Project version number for ToastSwiftFramework. FOUNDATION_EXPORT double ToastSwiftFrameworkVersionNumber; //! Project version string for ToastSwiftFramework. FOUNDATION_EXPORT const unsigned char ToastSwiftFrameworkVersionString[]; // In this header, you should import all the public headers of your framework using statements like #import <ToastSwiftFramework/PublicHeader.h>
2201_75827989/zhi_shi_ku
uni_modules/uts-toast/utssdk/app-ios/Frameworks/ToastSwiftFramework.framework/Headers/ToastSwiftFramework.h
Objective-C
unknown
518
const STORAGE_KEY = 'user_background_setting' const DEFAULT_BG = { type: 'color', value: '#ffffff' } export const getBackgroundSetting = () => { try { const val = uni.getStorageSync(STORAGE_KEY) if (val) { return typeof val === 'string' ? JSON.parse(val) : val } } catch (e) {} return DEFAULT_BG } export const setBackgroundSetting = (setting) => { const data = { ...DEFAULT_BG, ...setting, } const val = data.value || '' if (!data.type) { data.type = isImage(val) ? 'image' : 'color' } uni.setStorageSync(STORAGE_KEY, JSON.stringify(data)) return data } export const getBackgroundStyle = () => { const setting = getBackgroundSetting() const val = setting.value || DEFAULT_BG.value if (setting.type === 'image' || isImage(val)) { return { backgroundImage: `url(${val})`, backgroundSize: 'cover', backgroundPosition: 'center', backgroundRepeat: 'no-repeat', backgroundColor: '#ffffff', } } // 默认颜色 / 渐变 return { background: val, } } export const applyGlobalBackground = () => { const style = getBackgroundStyle() if (typeof document !== 'undefined') { const el = document.body || document.documentElement if (style.backgroundImage) { el.style.backgroundImage = style.backgroundImage el.style.backgroundSize = style.backgroundSize el.style.backgroundRepeat = style.backgroundRepeat el.style.backgroundPosition = style.backgroundPosition el.style.backgroundColor = style.backgroundColor || '#ffffff' } else { el.style.background = style.background || '#ffffff' el.style.backgroundImage = '' } } return style } export default { getBackgroundSetting, setBackgroundSetting, getBackgroundStyle, applyGlobalBackground, } function isImage(val) { if (!val) return false return /^https?:\/\//.test(val) || val.startsWith('data:') || val.startsWith('file:') || val.startsWith('/') || val.startsWith('blob:') || val.includes('tmp/') || val.includes('temp/') }
2201_75827989/zhi_shi_ku
utils/theme.js
JavaScript
unknown
2,073
from flask import Flask, render_template, jsonify, request, send_file import json import os from datetime import datetime, timedelta import pandas as pd from transformers import pipeline import jieba import jieba.analyse from collections import Counter import random app = Flask(__name__) # 初始化情感分析模型 sentiment_analyzer = pipeline( "sentiment-analysis", model="IDEA-CCNL/Erlangshen-Micro-2.6M", tokenizer="IDEA-CCNL/Erlangshen-Micro-2.6M" ) # 模拟微博热搜数据 def get_hot_topics(): """获取模拟的微博热搜数据""" topics = [ {"rank": 1, "title": "双十一购物节", "heat": "爆", "url": "#"}, {"rank": 2, "title": "新能源汽车销量创新高", "heat": "沸", "url": "#"}, {"rank": 3, "title": "考研报名开始", "heat": "热", "url": "#"}, {"rank": 4, "title": "冬季流感预防", "heat": "新", "url": "#"}, {"rank": 5, "title": "AI技术发展", "heat": "热", "url": "#"}, {"rank": 6, "title": "环保新政策", "heat": "新", "url": "#"}, {"rank": 7, "title": "教育改革方案", "heat": "沸", "url": "#"}, {"rank": 8, "title": "健康饮食趋势", "heat": "热", "url": "#"}, {"rank": 9, "title": "远程办公模式", "heat": "新", "url": "#"}, {"rank": 10, "title": "数字人民币试点", "heat": "热", "url": "#"} ] return topics # 模拟评论数据 def generate_comments(topic, count=50): """生成模拟评论数据""" positive_comments = [ "太棒了!支持这个话题", "说得很有道理,点赞", "这个政策真的很好,为民着想", "期待已久,终于来了", "非常有意义,支持!" ] neutral_comments = [ "了解一下情况", "看看后续发展", "这个要看具体实施", "保持关注", "理性看待" ] negative_comments = [ "不太看好这个", "感觉没什么用", "又要割韭菜了", "形式主义罢了", "不抱太大希望" ] comments = [] for i in range(count): sentiment_type = random.choice(['positive', 'neutral', 'negative']) if sentiment_type == 'positive': text = random.choice(positive_comments) elif sentiment_type == 'neutral': text = random.choice(neutral_comments) else: text = random.choice(negative_comments) comments.append({ 'id': i + 1, 'text': text, 'user': f'用户{i+1}', 'time': (datetime.now() - timedelta(hours=random.randint(1, 24))).strftime('%Y-%m-%d %H:%M'), 'likes': random.randint(0, 100), 'sentiment': sentiment_type }) return comments @app.route('/') def index(): """首页""" topics = get_hot_topics() return render_template('index.html', topics=topics) @app.route('/api/topics') def api_topics(): """获取热搜话题API""" topics = get_hot_topics() return jsonify(topics) @app.route('/api/analysis/<topic>') def api_analysis(topic): """获取话题分析数据""" # 获取评论 comments = generate_comments(topic, 100) # 情感分析 sentiments = {'positive': 0, 'neutral': 0, 'negative': 0} for comment in comments: sentiments[comment['sentiment']] += 1 # 关键词提取 all_text = ' '.join([c['text'] for c in comments]) keywords = jieba.analyse.extract_tags(all_text, topK=10, withWeight=True) keywords = [{'word': k[0], 'weight': k[1]} for k in keywords] # 时间分布 time_dist = {} for comment in comments: hour = comment['time'].split(' ')[1].split(':')[0] time_dist[hour] = time_dist.get(hour, 0) + 1 return jsonify({ 'topic': topic, 'sentiments': sentiments, 'keywords': keywords, 'time_distribution': time_dist, 'total_comments': len(comments) }) @app.route('/api/export/<topic>') def api_export(topic): """导出分析结果""" comments = generate_comments(topic, 100) # 创建DataFrame df = pd.DataFrame(comments) # 保存为CSV filename = f'data/{topic}_analysis_{datetime.now().strftime("%Y%m%d_%H%M%S")}.csv' df.to_csv(filename, index=False, encoding='utf-8-sig') return send_file(filename, as_attachment=True) if __name__ == '__main__': # 确保数据目录存在 os.makedirs('data', exist_ok=True) app.run(debug=True, host='0.0.0.0', port=5000)
2301_79702837/01
app.py
Python
unknown
4,604
""" 微博热搜评论语义分析系统 - Flask版本 """ import os import json from datetime import datetime, timedelta from typing import List, Dict, Any import sqlite3 from pathlib import Path from flask import Flask, request, jsonify from flask_cors import CORS import torch from transformers import AutoTokenizer, AutoModelForSequenceClassification import numpy as np # 初始化Flask应用 app = Flask(__name__) CORS(app) # 配置 app.config['DATABASE'] = 'data/weibo_analysis.db' # 初始化数据库 def init_database(): """初始化SQLite数据库""" db_path = Path(app.config['DATABASE']) db_path.parent.mkdir(exist_ok=True) conn = sqlite3.connect(db_path) cursor = conn.cursor() # 创建热搜话题表 cursor.execute(''' CREATE TABLE IF NOT EXISTS hot_topics ( id TEXT PRIMARY KEY, title TEXT NOT NULL, description TEXT, hot INTEGER DEFAULT 0, comment_count INTEGER DEFAULT 0, create_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP ) ''') # 创建评论表 cursor.execute(''' CREATE TABLE IF NOT EXISTS comments ( id TEXT PRIMARY KEY, topic_id TEXT NOT NULL, text TEXT NOT NULL, sentiment REAL DEFAULT 0, keywords TEXT, create_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP, FOREIGN KEY (topic_id) REFERENCES hot_topics (id) ) ''') conn.commit() conn.close() # 情感分析模型 class SentimentAnalyzer: def __init__(self): self.model_name = "hfl/chinese-bert-wwm" self.tokenizer = None self.model = None self.load_model() def load_model(self): """加载预训练的情感分析模型""" try: self.tokenizer = AutoTokenizer.from_pretrained(self.model_name) self.model = AutoModelForSequenceClassification.from_pretrained( self.model_name, num_labels=3 ) self.model.eval() print("情感分析模型加载成功") except Exception as e: print(f"模型加载失败: {e}") self.model = None def predict_sentiment(self, text: str) -> float: """预测文本情感得分 (-1到1之间)""" if not self.model: # 简单的规则基线 positive_words = ['好', '棒', '赞', '喜欢', '支持', '优秀', '厉害', '不错'] negative_words = ['差', '坏', '烂', '讨厌', '反对', '垃圾', '失望', '不好'] score = 0 for word in positive_words: if word in text: score += 0.2 for word in negative_words: if word in text: score -= 0.2 return max(-1, min(1, score)) # 使用BERT模型预测 inputs = self.tokenizer( text, return_tensors="pt", truncation=True, max_length=512, padding=True ) with torch.no_grad(): outputs = self.model(**inputs) predictions = torch.softmax(outputs.logits, dim=-1) # 将三分类转换为连续值 sentiment_score = predictions[0][2].item() - predictions[0][0].item() return sentiment_score # 关键词提取 def extract_keywords(text: str, top_k: int = 10) -> List[str]: """简单的关键词提取""" import jieba import re # 分词 words = jieba.cut(text) # 过滤停用词 stop_words = {'的', '了', '在', '是', '我', '有', '和', '就', '不', '人', '都', '一', '个', '上', '也', '很', '到', '说', '要', '去', '你', '会', '着', '没有', '看', '好', '自己', '这'} word_freq = {} for word in words: if len(word) > 1 and word not in stop_words and re.match(r'^[\u4e00-\u9fa5]+$', word): word_freq[word] = word_freq.get(word, 0) + 1 # 返回前top_k个关键词 sorted_words = sorted(word_freq.items(), key=lambda x: x[1], reverse=True) return [word for word, freq in sorted_words[:top_k]] # 初始化 init_database() analyzer = SentimentAnalyzer() # 模拟数据生成 def generate_mock_data(): """生成模拟数据用于演示""" conn = sqlite3.connect(app.config['DATABASE']) cursor = conn.cursor() # 检查是否已有数据 cursor.execute("SELECT COUNT(*) FROM hot_topics") if cursor.fetchone()[0] > 0: conn.close() return # 模拟热搜话题 mock_topics = [ { "id": "topic_001", "title": "双十一购物节", "description": "2024年双十一购物节火热进行中", "hot": 8765432, "comment_count": 15420 }, { "id": "topic_002", "title": "新能源汽车销量创新高", "description": "10月新能源汽车销量同比增长35%", "hot": 6543210, "comment_count": 8932 }, { "id": "topic_003", "title": "冬季旅游推荐", "description": "国内热门冬季旅游目的地盘点", "hot": 5432109, "comment_count": 5678 }, { "id": "topic_004", "title": "人工智能新进展", "description": "国产大模型技术取得重大突破", "hot": 4321098, "comment_count": 12456 }, { "id": "topic_005", "title": "健康饮食趋势", "description": "轻食主义成为新潮流", "hot": 3210987, "comment_count": 3421 }, { "id": "topic_006", "title": "电影票房破纪录", "description": "国庆档电影总票房创历史新高", "hot": 2109876, "comment_count": 7890 } ] # 插入话题数据 for topic in mock_topics: cursor.execute(''' INSERT OR IGNORE INTO hot_topics (id, title, description, hot, comment_count) VALUES (?, ?, ?, ?, ?) ''', (topic["id"], topic["title"], topic["description"], topic["hot"], topic["comment_count"])) # 生成评论数据 mock_comments = [ "这个购物节真的太棒了,优惠力度很大!", "感觉价格并没有便宜多少,有点失望", "新能源汽车确实不错,环保又省钱", "充电还是不太方便,希望基础设施能跟上", "哈尔滨的雪景太美了,值得一去", "人太多了,体验不太好", "AI技术发展真快,期待更多应用", "担心AI会取代人类工作", "轻食真的很健康,已经坚持一个月了", "还是喜欢重口味,轻食太清淡了" ] for topic_id in [t["id"] for t in mock_topics]: for i in range(50): # 每个话题50条评论 text = mock_comments[i % len(mock_comments)] sentiment = analyzer.predict_sentiment(text) keywords = json.dumps(extract_keywords(text)) cursor.execute(''' INSERT INTO comments (id, topic_id, text, sentiment, keywords) VALUES (?, ?, ?, ?, ?) ''', (f"comment_{topic_id}_{i}", topic_id, text, sentiment, keywords)) conn.commit() conn.close() # 生成模拟数据 generate_mock_data() # API路由 @app.route('/api/hot-topics', methods=['GET']) def get_hot_topics(): """获取实时热搜榜单""" conn = sqlite3.connect(app.config['DATABASE']) conn.row_factory = sqlite3.Row cursor = conn.cursor() cursor.execute(''' SELECT * FROM hot_topics ORDER BY hot DESC LIMIT 50 ''') topics = [] for row in cursor.fetchall(): topics.append({ "id": row["id"], "title": row["title"], "description": row["description"], "hot": row["hot"], "comment_count": row["comment_count"], "create_time": row["create_time"] }) conn.close() return jsonify(topics) @app.route('/api/analysis/<topic_id>', methods=['GET']) def get_analysis(topic_id): """获取话题的情感分析结果""" time_range = request.args.get('time_range', '24h') conn = sqlite3.connect(app.config['DATABASE']) conn.row_factory = sqlite3.Row cursor = conn.cursor() # 检查话题是否存在 cursor.execute("SELECT * FROM hot_topics WHERE id = ?", (topic_id,)) if not cursor.fetchone(): return jsonify({"error": "话题不存在"}), 404 # 获取评论数据 cursor.execute(''' SELECT * FROM comments WHERE topic_id = ? ORDER BY create_time DESC ''', (topic_id,)) comments = [] sentiment_scores = [] sentiment_distribution = {"positive": 0, "neutral": 0, "negative": 0} for row in cursor.fetchall(): sentiment = row["sentiment"] comments.append({ "id": row["id"], "text": row["text"], "sentiment": sentiment, "create_time": row["create_time"] }) sentiment_scores.append(sentiment) # 统计情感分布 if sentiment > 0.1: sentiment_distribution["positive"] += 1 elif sentiment < -0.1: sentiment_distribution["negative"] += 1 else: sentiment_distribution["neutral"] += 1 # 计算关键词权重 keyword_weights = {} for comment in comments: keywords = json.loads(comment.get("keywords", "[]")) for keyword in keywords: keyword_weights[keyword] = keyword_weights.get(keyword, 0) + 1 keywords = [ {"word": word, "weight": count / len(comments) if comments else 0} for word, count in keyword_weights.items() ] keywords.sort(key=lambda x: x["weight"], reverse=True) # 生成情感趋势数据 trend_labels = [f"{i:02d}:00" for i in range(24)] base_sentiment = sum(sentiment_scores) / len(sentiment_scores) if sentiment_scores else 0 trend_values = [base_sentiment + (np.random.randn() * 0.1) for _ in range(24)] conn.close() return jsonify({ "total_comments": len(comments), "avg_sentiment": sum(sentiment_scores) / len(sentiment_scores) if sentiment_scores else 0, "sentiment_distribution": sentiment_distribution, "sentiment_trend": {"labels": trend_labels, "values": trend_values}, "keywords": keywords[:20], "comments": comments[:10] }) @app.route('/api/export/<topic_id>', methods=['GET']) def export_data(topic_id): """导出分析数据""" return jsonify({"message": "导出功能开发中"}) @app.route('/health', methods=['GET']) def health_check(): return jsonify({"status": "healthy", "timestamp": datetime.now().isoformat()}) if __name__ == '__main__': app.run(debug=True, host='0.0.0.0', port=5000)
2301_79702837/01
backend/app.py
Python
unknown
11,225
""" 微博热搜评论语义分析系统 - 后端主程序 FastAPI + PyTorch + Transformers """ import os import asyncio from datetime import datetime, timedelta from typing import List, Dict, Any import json import sqlite3 from pathlib import Path from fastapi import FastAPI, HTTPException, Query from fastapi.middleware.cors import CORSMiddleware from pydantic import BaseModel import torch from transformers import AutoTokenizer, AutoModelForSequenceClassification import uvicorn # 初始化FastAPI应用 app = FastAPI( title="微博热搜评论语义分析系统", description="基于深度学习的微博热搜评论情感分析API", version="1.0.0" ) # 配置CORS app.add_middleware( CORSMiddleware, allow_origins=["*"], allow_credentials=True, allow_methods=["*"], allow_headers=["*"], ) # 数据模型 class HotTopic(BaseModel): id: str title: str description: str hot: int comment_count: int create_time: datetime class Comment(BaseModel): id: str text: str sentiment: float create_time: datetime class AnalysisResult(BaseModel): total_comments: int avg_sentiment: float sentiment_distribution: Dict[str, int] sentiment_trend: Dict[str, List] keywords: List[Dict[str, Any]] comments: List[Comment] # 初始化数据库 def init_database(): """初始化SQLite数据库""" db_path = Path("data/weibo_analysis.db") db_path.parent.mkdir(exist_ok=True) conn = sqlite3.connect(db_path) cursor = conn.cursor() # 创建热搜话题表 cursor.execute(''' CREATE TABLE IF NOT EXISTS hot_topics ( id TEXT PRIMARY KEY, title TEXT NOT NULL, description TEXT, hot INTEGER DEFAULT 0, comment_count INTEGER DEFAULT 0, create_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP ) ''') # 创建评论表 cursor.execute(''' CREATE TABLE IF NOT EXISTS comments ( id TEXT PRIMARY KEY, topic_id TEXT NOT NULL, text TEXT NOT NULL, sentiment REAL DEFAULT 0, keywords TEXT, create_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP, FOREIGN KEY (topic_id) REFERENCES hot_topics (id) ) ''') conn.commit() conn.close() # 情感分析模型 class SentimentAnalyzer: def __init__(self): self.model_name = "hfl/chinese-bert-wwm" self.tokenizer = None self.model = None self.load_model() def load_model(self): """加载预训练的情感分析模型""" try: self.tokenizer = AutoTokenizer.from_pretrained(self.model_name) self.model = AutoModelForSequenceClassification.from_pretrained( self.model_name, num_labels=3 # 正面、中性、负面 ) self.model.eval() print("情感分析模型加载成功") except Exception as e: print(f"模型加载失败: {e}") # 使用简单的规则作为备选 self.model = None def predict_sentiment(self, text: str) -> float: """预测文本情感得分 (-1到1之间)""" if not self.model: # 简单的规则基线 positive_words = ['好', '棒', '赞', '喜欢', '支持', '优秀', '厉害'] negative_words = ['差', '坏', '烂', '讨厌', '反对', '垃圾', '失望'] score = 0 for word in positive_words: if word in text: score += 0.2 for word in negative_words: if word in text: score -= 0.2 return max(-1, min(1, score)) # 使用BERT模型预测 inputs = self.tokenizer( text, return_tensors="pt", truncation=True, max_length=512, padding=True ) with torch.no_grad(): outputs = self.model(**inputs) predictions = torch.softmax(outputs.logits, dim=-1) # 将三分类转换为连续值 sentiment_score = predictions[0][2].item() - predictions[0][0].item() return sentiment_score # 关键词提取 def extract_keywords(text: str, top_k: int = 10) -> List[str]: """简单的关键词提取""" # 这里使用TF-IDF或TextRank算法 # 为演示目的,使用简单的词频统计 import jieba import re # 分词 words = jieba.cut(text) # 过滤停用词 stop_words = {'的', '了', '在', '是', '我', '有', '和', '就', '不', '人', '都', '一', '个', '上', '也', '很', '到', '说', '要', '去', '你', '会', '着', '没有', '看', '好', '自己', '这'} word_freq = {} for word in words: if len(word) > 1 and word not in stop_words and re.match(r'^[\u4e00-\u9fa5]+$', word): word_freq[word] = word_freq.get(word, 0) + 1 # 返回前top_k个关键词 sorted_words = sorted(word_freq.items(), key=lambda x: x[1], reverse=True) return [word for word, freq in sorted_words[:top_k]] # 初始化 init_database() analyzer = SentimentAnalyzer() # 模拟数据生成 def generate_mock_data(): """生成模拟数据用于演示""" conn = sqlite3.connect("data/weibo_analysis.db") cursor = conn.cursor() # 检查是否已有数据 cursor.execute("SELECT COUNT(*) FROM hot_topics") if cursor.fetchone()[0] > 0: conn.close() return # 模拟热搜话题 mock_topics = [ { "id": "topic_001", "title": "双十一购物节", "description": "2024年双十一购物节火热进行中", "hot": 8765432, "comment_count": 15420 }, { "id": "topic_002", "title": "新能源汽车销量创新高", "description": "10月新能源汽车销量同比增长35%", "hot": 6543210, "comment_count": 8932 }, { "id": "topic_003", "title": "冬季旅游推荐", "description": "国内热门冬季旅游目的地盘点", "hot": 5432109, "comment_count": 5678 }, { "id": "topic_004", "title": "人工智能新进展", "description": "国产大模型技术取得重大突破", "hot": 4321098, "comment_count": 12456 }, { "id": "topic_005", "title": "健康饮食趋势", "description": "轻食主义成为新潮流", "hot": 3210987, "comment_count": 3421 }, { "id": "topic_006", "title": "电影票房破纪录", "description": "国庆档电影总票房创历史新高", "hot": 2109876, "comment_count": 7890 } ] # 插入话题数据 for topic in mock_topics: cursor.execute(''' INSERT OR IGNORE INTO hot_topics (id, title, description, hot, comment_count) VALUES (?, ?, ?, ?, ?) ''', (topic["id"], topic["title"], topic["description"], topic["hot"], topic["comment_count"])) # 生成评论数据 mock_comments = [ "这个购物节真的太棒了,优惠力度很大!", "感觉价格并没有便宜多少,有点失望", "新能源汽车确实不错,环保又省钱", "充电还是不太方便,希望基础设施能跟上", "哈尔滨的雪景太美了,值得一去", "人太多了,体验不太好", "AI技术发展真快,期待更多应用", "担心AI会取代人类工作", "轻食真的很健康,已经坚持一个月了", "还是喜欢重口味,轻食太清淡了" ] for topic_id in [t["id"] for t in mock_topics]: for i in range(50): # 每个话题50条评论 text = mock_comments[i % len(mock_comments)] sentiment = analyzer.predict_sentiment(text) keywords = json.dumps(extract_keywords(text)) cursor.execute(''' INSERT INTO comments (id, topic_id, text, sentiment, keywords) VALUES (?, ?, ?, ?, ?) ''', (f"comment_{topic_id}_{i}", topic_id, text, sentiment, keywords)) conn.commit() conn.close() # 生成模拟数据 generate_mock_data() # API路由 @app.get("/api/hot-topics", response_model=List[HotTopic]) async def get_hot_topics(): """获取实时热搜榜单""" conn = sqlite3.connect("data/weibo_analysis.db") conn.row_factory = sqlite3.Row cursor = conn.cursor() cursor.execute(''' SELECT * FROM hot_topics ORDER BY hot DESC LIMIT 50 ''') topics = [] for row in cursor.fetchall(): topics.append(HotTopic( id=row["id"], title=row["title"], description=row["description"], hot=row["hot"], comment_count=row["comment_count"], create_time=datetime.fromisoformat(row["create_time"]) )) conn.close() return topics @app.get("/api/analysis/{topic_id}", response_model=AnalysisResult) async def get_analysis( topic_id: str, time_range: str = Query("24h", regex="^(1h|24h|7d)$") ): """获取话题的情感分析结果""" conn = sqlite3.connect("data/weibo_analysis.db") conn.row_factory = sqlite3.Row cursor = conn.cursor() # 检查话题是否存在 cursor.execute("SELECT * FROM hot_topics WHERE id = ?", (topic_id,)) if not cursor.fetchone(): raise HTTPException(status_code=404, detail="话题不存在") # 获取评论数据 time_filter = { "1h": timedelta(hours=1), "24h": timedelta(days=1), "7d": timedelta(days=7) }[time_range] cursor.execute(''' SELECT * FROM comments WHERE topic_id = ? ORDER BY create_time DESC ''', (topic_id,)) comments = [] sentiment_scores = [] sentiment_distribution = {"positive": 0, "neutral": 0, "negative": 0} for row in cursor.fetchall(): sentiment = row["sentiment"] comments.append(Comment( id=row["id"], text=row["text"], sentiment=sentiment, create_time=datetime.fromisoformat(row["create_time"]) )) sentiment_scores.append(sentiment) # 统计情感分布 if sentiment > 0.1: sentiment_distribution["positive"] += 1 elif sentiment < -0.1: sentiment_distribution["negative"] += 1 else: sentiment_distribution["neutral"] += 1 # 计算关键词权重 keyword_weights = {} for comment in comments: keywords = json.loads(cursor.execute( "SELECT keywords FROM comments WHERE id = ?", (comment.id,) ).fetchone()["keywords"] or "[]") for keyword in keywords: keyword_weights[keyword] = keyword_weights.get(keyword, 0) + 1 keywords = [ {"word": word, "weight": count / len(comments) if comments else 0} for word, count in keyword_weights.items() ] keywords.sort(key=lambda x: x["weight"], reverse=True) # 生成情感趋势数据 trend_labels = [] trend_values = [] # 模拟时间序列数据 for i in range(24): trend_labels.append(f"{i:02d}:00") # 添加一些随机波动 base_sentiment = sum(sentiment_scores) / len(sentiment_scores) if sentiment_scores else 0 trend_values.append(base_sentiment + (torch.randn(1).item() * 0.1)) conn.close() return AnalysisResult( total_comments=len(comments), avg_sentiment=sum(sentiment_scores) / len(sentiment_scores) if sentiment_scores else 0, sentiment_distribution=sentiment_distribution, sentiment_trend={"labels": trend_labels, "values": trend_values}, keywords=keywords[:20], comments=comments[:10] ) @app.get("/api/export/{topic_id}") async def export_data(topic_id: str): """导出分析数据""" # 实现数据导出功能 return {"message": "导出功能开发中"} # 健康检查 @app.get("/health") async def health_check(): return {"status": "healthy", "timestamp": datetime.now()} if __name__ == "__main__": uvicorn.run( "main:app", host="0.0.0.0", port=8000, reload=True )
2301_79702837/01
backend/main.py
Python
unknown
12,711
#!/usr/bin/env python3 """ 微博热搜评论语义分析系统 - 启动脚本 """ import os import sys from pathlib import Path # 添加当前目录到Python路径 sys.path.insert(0, str(Path(__file__).parent)) # 启动Flask应用 if __name__ == '__main__': from app import app # 确保数据目录存在 os.makedirs('data', exist_ok=True) print("🚀 启动微博热搜评论语义分析系统...") print("📡 后端服务运行在: http://localhost:5000") print("📊 前端界面请打开: index.html")
2301_79702837/01
backend/run.py
Python
unknown
545
<!DOCTYPE html> <html lang="zh-CN"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>微博热搜评论语义分析系统</title> <!-- Bootstrap 5.3 CSS --> <link href="https://cdn.bootcdn.net/ajax/libs/bootstrap/5.3.2/css/bootstrap.min.css" rel="stylesheet"> <!-- Font Awesome --> <link href="https://cdn.bootcdn.net/ajax/libs/font-awesome/6.4.0/css/all.min.css" rel="stylesheet"> <!-- Custom CSS --> <style> body { background-color: #f8f9fa; font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Microsoft YaHei', sans-serif; } .hot-topic-card { transition: transform 0.3s ease, box-shadow 0.3s ease; cursor: pointer; border: none; border-radius: 12px; overflow: hidden; } .hot-topic-card:hover { transform: translateY(-5px); box-shadow: 0 8px 25px rgba(0,0,0,0.15); } .topic-rank { font-size: 1.5rem; font-weight: bold; color: #ff4757; } .sentiment-positive { color: #2ed573; } .sentiment-neutral { color: #ffa502; } .sentiment-negative { color: #ff4757; } .chart-container { position: relative; height: 300px; margin: 20px 0; } .keyword-cloud { display: flex; flex-wrap: wrap; gap: 10px; padding: 20px; background: white; border-radius: 12px; box-shadow: 0 2px 10px rgba(0,0,0,0.1); } .keyword-tag { padding: 5px 15px; border-radius: 20px; font-size: 14px; font-weight: 500; } .loading-spinner { display: none; text-align: center; padding: 40px; } .navbar-brand { font-weight: bold; font-size: 1.5rem; } .time-filter { margin-bottom: 20px; } .search-box { margin-bottom: 20px; } @media (max-width: 768px) { .chart-container { height: 250px; } } </style> </head> <body> <!-- 导航栏 --> <nav class="navbar navbar-expand-lg navbar-dark bg-primary"> <div class="container"> <a class="navbar-brand" href="#"> <i class="fab fa-weibo me-2"></i> 微博热搜评论语义分析 </a> <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarNav"> <ul class="navbar-nav ms-auto"> <li class="nav-item"> <a class="nav-link active" href="#hot-topics">热搜榜单</a> </li> <li class="nav-item"> <a class="nav-link" href="#analysis">情感分析</a> </li> <li class="nav-item"> <a class="nav-link" href="#export">导出数据</a> </li> </ul> </div> </div> </nav> <!-- 主要内容 --> <div class="container mt-4"> <!-- 热搜榜单 --> <section id="hot-topics"> <h2 class="mb-4"> <i class="fas fa-fire text-danger me-2"></i> 实时热搜榜单 </h2> <div class="loading-spinner" id="loading-topics"> <div class="spinner-border text-primary" role="status"> <span class="visually-hidden">加载中...</span> </div> </div> <div class="row" id="topics-container"> <!-- 热搜话题卡片将动态加载 --> </div> </section> <!-- 情感分析详情 --> <section id="analysis" class="mt-5" style="display: none;"> <div class="d-flex justify-content-between align-items-center mb-4"> <h2> <i class="fas fa-chart-line me-2"></i> <span id="analysis-title">情感分析详情</span> </h2> <button class="btn btn-outline-secondary" onclick="hideAnalysis()"> <i class="fas fa-arrow-left me-2"></i>返回榜单 </button> </div> <!-- 时间筛选 --> <div class="time-filter"> <div class="btn-group" role="group"> <input type="radio" class="btn-check" name="timeRange" id="time1h" value="1h" checked> <label class="btn btn-outline-primary" for="time1h">近1小时</label> <input type="radio" class="btn-check" name="timeRange" id="time24h" value="24h"> <label class="btn btn-outline-primary" for="time24h">近24小时</label> <input type="radio" class="btn-check" name="timeRange" id="time7d" value="7d"> <label class="btn btn-outline-primary" for="time7d">近7天</label> </div> </div> <!-- 搜索框 --> <div class="search-box"> <div class="input-group"> <input type="text" class="form-control" id="keyword-search" placeholder="搜索关键词..."> <button class="btn btn-primary" type="button" onclick="searchComments()"> <i class="fas fa-search"></i> </button> </div> </div> <!-- 统计卡片 --> <div class="row mb-4"> <div class="col-md-4"> <div class="card text-center"> <div class="card-body"> <h5 class="card-title">总评论数</h5> <h3 class="text-primary" id="total-comments">0</h3> </div> </div> </div> <div class="col-md-4"> <div class="card text-center"> <div class="card-body"> <h5 class="card-title">平均情感得分</h5> <h3 class="text-info" id="avg-sentiment">0.0</h3> </div> </div> </div> <div class="col-md-4"> <div class="card text-center"> <div class="card-body"> <h5 class="card-title">热门关键词</h5> <h3 class="text-warning" id="top-keywords">0</h3> </div> </div> </div> </div> <!-- 图表区域 --> <div class="row"> <div class="col-lg-6"> <div class="card"> <div class="card-header"> <h5 class="mb-0">情感分布</h5> </div> <div class="card-body"> <div class="chart-container"> <canvas id="sentiment-chart"></canvas> </div> </div> </div> </div> <div class="col-lg-6"> <div class="card"> <div class="card-header"> <h5 class="mb-0">情感趋势</h5> </div> <div class="card-body"> <div class="chart-container"> <canvas id="trend-chart"></canvas> </div> </div> </div> </div> </div> <!-- 关键词云 --> <div class="row mt-4"> <div class="col-12"> <div class="card"> <div class="card-header"> <h5 class="mb-0">关键词云</h5> </div> <div class="card-body"> <div id="keyword-cloud" class="keyword-cloud"> <!-- 关键词将动态加载 --> </div> </div> </div> </div> </div> <!-- 评论列表 --> <div class="row mt-4"> <div class="col-12"> <div class="card"> <div class="card-header"> <h5 class="mb-0">评论列表</h5> </div> <div class="card-body"> <div id="comments-list"> <!-- 评论将动态加载 --> </div> </div> </div> </div> </div> </section> </div> <!-- Bootstrap JS --> <script src="https://cdn.bootcdn.net/ajax/libs/bootstrap/5.3.2/js/bootstrap.bundle.min.js"></script> <!-- Chart.js --> <script src="https://cdn.bootcdn.net/ajax/libs/Chart.js/4.4.0/chart.min.js"></script> <!-- Axios --> <script src="https://cdn.bootcdn.net/ajax/libs/axios/1.6.7/axios.min.js"></script> <!-- 自定义JS --> <script> // API基础URL const API_BASE = 'http://localhost:8000/api'; // 全局变量 let currentTopic = null; let sentimentChart = null; let trendChart = null; // 页面加载完成后初始化 document.addEventListener('DOMContentLoaded', function() { loadHotTopics(); // 监听时间范围变化 document.querySelectorAll('input[name="timeRange"]').forEach(radio => { radio.addEventListener('change', function() { if (currentTopic) { loadAnalysisData(currentTopic); } }); }); }); // 加载热搜榜单 async function loadHotTopics() { const loading = document.getElementById('loading-topics'); const container = document.getElementById('topics-container'); loading.style.display = 'block'; try { const response = await axios.get(`${API_BASE}/hot-topics`); const topics = response.data; container.innerHTML = ''; topics.forEach((topic, index) => { const card = createTopicCard(topic, index + 1); container.appendChild(card); }); } catch (error) { console.error('加载热搜榜单失败:', error); container.innerHTML = '<div class="col-12 text-center text-danger">加载失败,请稍后重试</div>'; } finally { loading.style.display = 'none'; } } // 创建话题卡片 function createTopicCard(topic, rank) { const col = document.createElement('div'); col.className = 'col-lg-4 col-md-6 mb-4'; col.innerHTML = ` <div class="card hot-topic-card" onclick="showAnalysis('${topic.id}', '${topic.title}')"> <div class="card-body"> <div class="d-flex justify-content-between align-items-start mb-2"> <span class="topic-rank">#${rank}</span> <span class="badge bg-danger">${topic.hot}</span> </div> <h5 class="card-title">${topic.title}</h5> <p class="card-text text-muted">${topic.description || ''}</p> <div class="d-flex justify-content-between align-items-center"> <small class="text-muted">${topic.comment_count || 0} 条评论</small> <small class="text-muted">${new Date(topic.create_time).toLocaleString()}</small> </div> </div> </div> `; return col; } // 显示情感分析详情 function showAnalysis(topicId, topicTitle) { currentTopic = topicId; document.getElementById('analysis-title').textContent = topicTitle; document.getElementById('hot-topics').style.display = 'none'; document.getElementById('analysis').style.display = 'block'; loadAnalysisData(topicId); } // 隐藏分析详情,返回榜单 function hideAnalysis() { document.getElementById('hot-topics').style.display = 'block'; document.getElementById('analysis').style.display = 'none'; currentTopic = null; } // 加载分析数据 async function loadAnalysisData(topicId) { const timeRange = document.querySelector('input[name="timeRange"]:checked').value; try { const response = await axios.get(`${API_BASE}/analysis/${topicId}`, { params: { time_range: timeRange } }); const data = response.data; updateStatistics(data); updateCharts(data); updateKeywordCloud(data.keywords); updateCommentsList(data.comments); } catch (error) { console.error('加载分析数据失败:', error); } } // 更新统计数据 function updateStatistics(data) { document.getElementById('total-comments').textContent = data.total_comments; document.getElementById('avg-sentiment').textContent = data.avg_sentiment.toFixed(2); document.getElementById('top-keywords').textContent = data.keywords.length; } // 更新图表 function updateCharts(data) { updateSentimentChart(data.sentiment_distribution); updateTrendChart(data.sentiment_trend); } // 更新情感分布饼图 function updateSentimentChart(distribution) { const ctx = document.getElementById('sentiment-chart').getContext('2d'); if (sentimentChart) { sentimentChart.destroy(); } sentimentChart = new Chart(ctx, { type: 'pie', data: { labels: ['正面', '中性', '负面'], datasets: [{ data: [distribution.positive, distribution.neutral, distribution.negative], backgroundColor: ['#2ed573', '#ffa502', '#ff4757'] }] }, options: { responsive: true, maintainAspectRatio: false, plugins: { legend: { position: 'bottom' } } } }); } // 更新情感趋势折线图 function updateTrendChart(trend) { const ctx = document.getElementById('trend-chart').getContext('2d'); if (trendChart) { trendChart.destroy(); } trendChart = new Chart(ctx, { type: 'line', data: { labels: trend.labels, datasets: [{ label: '情感得分', data: trend.values, borderColor: '#3498db', backgroundColor: 'rgba(52, 152, 219, 0.1)', tension: 0.4 }] }, options: { responsive: true, maintainAspectRatio: false, scales: { y: { beginAtZero: true, max: 1 } } } }); } // 更新关键词云 function updateKeywordCloud(keywords) { const container = document.getElementById('keyword-cloud'); container.innerHTML = ''; keywords.slice(0, 20).forEach(keyword => { const tag = document.createElement('span'); tag.className = 'keyword-tag'; tag.style.backgroundColor = `hsl(${Math.random() * 60 + 200}, 70%, 85%)`; tag.style.fontSize = `${Math.min(14 + keyword.weight * 8, 24)}px`; tag.textContent = keyword.word; container.appendChild(tag); }); } // 更新评论列表 function updateCommentsList(comments) { const container = document.getElementById('comments-list'); container.innerHTML = ''; comments.slice(0, 10).forEach(comment => { const item = document.createElement('div'); item.className = 'border-bottom py-3'; const sentimentClass = comment.sentiment > 0.5 ? 'sentiment-positive' : comment.sentiment < -0.5 ? 'sentiment-negative' : 'sentiment-neutral'; item.innerHTML = ` <div class="d-flex justify-content-between align-items-start"> <div> <p class="mb-1">${comment.text}</p> <small class="text-muted">${new Date(comment.create_time).toLocaleString()}</small> </div> <span class="${sentimentClass}"> <i class="fas fa-${comment.sentiment > 0 ? 'smile' : comment.sentiment < 0 ? 'frown' : 'meh'}"></i> ${comment.sentiment.toFixed(2)} </span> </div> `; container.appendChild(item); }); } // 搜索评论 function searchComments() { const keyword = document.getElementById('keyword-search').value.trim(); if (!keyword || !currentTopic) return; // 实现搜索逻辑 loadAnalysisData(currentTopic); } // 导出数据 function exportData() { if (!currentTopic) return; // 实现导出逻辑 window.open(`${API_BASE}/export/${currentTopic}`); } </script
2301_79702837/01
index.html
HTML
unknown
19,501
<!DOCTYPE html> <html lang="zh-CN"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>微博热搜评论语义分析系统</title> <!-- Bootstrap CSS --> <link href="https://cdn.bootcdn.net/ajax/libs/bootstrap/5.3.2/css/bootstrap.min.css" rel="stylesheet"> <!-- Font Awesome --> <link href="https://cdn.bootcdn.net/ajax/libs/font-awesome/6.4.0/css/all.min.css" rel="stylesheet"> <!-- Chart.js --> <script src="https://cdn.bootcdn.net/ajax/libs/Chart.js/4.4.0/chart.min.js"></script> <!-- WordCloud --> <script src="https://cdn.bootcdn.net/ajax/libs/wordcloud2.js/1.2.2/wordcloud2.min.js"></script> <style> body { background-color: #f8f9fa; font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif; } .topic-card { transition: transform 0.2s; cursor: pointer; } .topic-card:hover { transform: translateY(-2px); box-shadow: 0 4px 8px rgba(0,0,0,0.1); } .hot-rank { font-size: 1.2em; font-weight: bold; } .heat-badge { font-size: 0.8em; padding: 0.25em 0.5em; } .analysis-section { display: none; } .loading { display: none; } .keyword-cloud { height: 300px; border: 1px solid #dee2e6; border-radius: 0.375rem; position: relative; } </style> </head> <body> <nav class="navbar navbar-dark bg-primary"> <div class="container-fluid"> <span class="navbar-brand mb-0 h1"> <i class="fas fa-fire"></i> 微博热搜评论语义分析系统 </span> </div> </nav> <div class="container-fluid mt-4"> <div class="row"> <!-- 热搜榜单 --> <div class="col-md-4"> <div class="card"> <div class="card-header"> <h5 class="mb-0"> <i class="fas fa-list-ol"></i> 实时热搜榜 </h5> </div> <div class="card-body"> <div id="hot-topics"> {% for topic in topics %} <div class="card mb-2 topic-card" data-topic="{{ topic.title }}"> <div class="card-body py-2"> <div class="d-flex justify-content-between align-items-center"> <div> <span class="hot-rank text-primary">{{ topic.rank }}</span> <span class="ms-2">{{ topic.title }}</span> </div> <span class="badge bg-danger heat-badge">{{ topic.heat }}</span> </div> </div> </div> {% endfor %} </div> </div> </div> </div> <!-- 分析结果 --> <div class="col-md-8"> <div id="initial-message" class="text-center py-5"> <i class="fas fa-chart-line fa-3x text-muted mb-3"></i> <h4 class="text-muted">点击左侧热搜话题查看分析结果</h4> </div> <div id="analysis-content" class="analysis-section"> <!-- 加载动画 --> <div id="loading" class="text-center py-5 loading"> <div class="spinner-border text-primary" role="status"> <span class="visually-hidden">Loading...</span> </div> <p class="mt-2">正在分析评论数据...</p> </div> <!-- 分析结果 --> <div id="results"> <div class="card mb-4"> <div class="card-header d-flex justify-content-between align-items-center"> <h5 class="mb-0"> <i class="fas fa-chart-pie"></i> 情感分析结果 <span id="topic-title" class="text-primary"></span> </h5> <button id="export-btn" class="btn btn-outline-primary btn-sm"> <i class="fas fa-download"></i> 导出数据 </button> </div> <div class="card-body"> <div class="row"> <div class="col-md-6"> <canvas id="sentiment-chart"></canvas> </div> <div class="col-md-6"> <div class="row text-center"> <div class="col-4"> <div class="text-success"> <h3 id="positive-count">0</h3> <small>正面</small> </div> </div> <div class="col-4"> <div class="text-warning"> <h3 id="neutral-count">0</h3> <small>中性</small> </div> </div> <div class="col-4"> <div class="text-danger"> <h3 id="negative-count">0</h3> <small>负面</small> </div> </div> </div> </div> </div> </div> </div> <div class="row"> <div class="col-md-6"> <div class="card mb-4"> <div class="card-header"> <h5 class="mb-0"> <i class="fas fa-cloud"></i> 关键词云 </h5> </div> <div class="card-body"> <div id="keyword-cloud" class="keyword-cloud"></div> </div> </div> </div> <div class="col-md-6"> <div class="card mb-4"> <div class="card-header"> <h5 class="mb-0"> <i class="fas fa-chart-line"></i> 时间分布 </h5> </div> <div class="card-body"> <canvas id="time-chart"></canvas> </div> </div> </div> </div> </div> </div> </div> </div> </div> <!-- Bootstrap JS --> <script src="https://cdn.bootcdn.net/ajax/libs/bootstrap/5.3.2/js/bootstrap.bundle.min.js"></script> <script> let sentimentChart = null; let timeChart = null; // 点击话题事件 document.querySelectorAll('.topic-card').forEach(card => { card.addEventListener('click', function() { const topic = this.dataset.topic; loadAnalysis(topic); }); }); // 加载分析数据 async function loadAnalysis(topic) { // 显示加载动画 document.getElementById('initial-message').style.display = 'none'; document.getElementById('analysis-content').style.display = 'block'; document.getElementById('loading').style.display = 'block'; document.getElementById('results').style.display = 'none'; try { const response = await fetch(`/api/analysis/${encodeURIComponent(topic)}`); const data = await response.json(); // 更新UI document.getElementById('topic-title').textContent = ` - ${data.topic}`; updateSentimentChart(data.sentiments); updateKeywordCloud(data.keywords); updateTimeChart(data.time_distribution); // 更新计数 document.getElementById('positive-count').textContent = data.sentiments.positive; document.getElementById('neutral-count').textContent = data.sentiments.neutral; document.getElementById('negative-count').textContent = data.sentiments.negative; // 设置导出按钮 document.getElementById('export-btn').onclick = () => { window.location.href = `/api/export/${encodeURIComponent(topic)}`; }; } catch (error) { console.error('Error loading analysis:', error); alert('加载数据失败,请重试'); } finally { document.getElementById('loading').style.display = 'none'; document.getElementById('results').style.display = 'block'; } } // 更新情感分析图表 function updateSentimentChart(sentiments) { const ctx = document.getElementById('sentiment-chart').getContext('2d'); if (sentimentChart) { sentimentChart.destroy(); } sentimentChart = new Chart(ctx, { type: 'doughnut', data: { labels: ['正面', '中性', '负面'], datasets: [{ data: [sentiments.positive, sentiments.neutral, sentiments.negative], backgroundColor: ['#28a745', '#ffc107', '#dc3545'], borderWidth: 0 }] }, options: { responsive: true, maintainAspectRatio: true, plugins: { legend: { position: 'bottom' } } } }); } // 更新关键词云 function updateKeywordCloud(keywords) { const container = document.getElementById('keyword-cloud'); container.innerHTML = ''; const wordList = keywords.map(k => [k.word, k.weight * 100]); WordCloud(container, { list: wordList, gridSize: 16, weightFactor: 10, fontFamily: 'Times, serif', color: function(word, weight) { const colors = ['#007bff', '#28a745', '#ffc107', '#dc3545', '#6f42c1']; return colors[Math.floor(Math.random() * colors.length)]; }, rotateRatio: 0.5, rotationSteps: 2, backgroundColor: '#ffffff' }); } // 更新时间分布图表 function updateTimeChart(timeData) { const ctx = document.getElementById('time-chart').getContext('2d'); if (timeChart) { timeChart.destroy(); } const hours = Object.keys(timeData).sort(); const counts = hours.map(h => timeData[h]); timeChart = new Chart(ctx, { type: 'line', data: { labels: hours.map(h => `${h}:00`), datasets: [{ label: '评论数量', data: counts, borderColor: '#007bff', backgroundColor: 'rgba(0, 123, 255, 0.1)', tension: 0.4, fill: true }] }, options: { responsive: true, maintainAspectRatio: true, plugins: { legend: { display: false } }, scales: { y: { beginAtZero: true } } } }); } </script> </body> </html>
2301_79702837/01
templates/index.html
HTML
unknown
13,777
import warnings warnings.filterwarnings('ignore') import matplotlib matplotlib.use('Qt5Agg') import numpy as np import matplotlib.pyplot as plt X = np.random.randn(100,1) y = 5 + 4*X +np.random.randn(100,1) X_b = np.c_[np.ones((100,1)),X] a = np.linalg.inv(X_b.T.dot(X_b)).dot(X_b.T).dot(y) print(a) # 实际应用 x_new = np.array([[0],[2] ]) x_new = np.c_[np.ones((2,1)),x_new] print(x_new) y_predict = x_new.dot(a) print(y_predict) plt.plot(x_new,y_predict) plt.plot(X,y,'b.') plt.axis([0,1,0,15]) plt.show() # 实际应用 from sklearn.linear_model import LinearRegression X1 = 2*np.random.rand(100,1) X2 = 2*np.random.rand(100,1) X = np.c_[X1,X2] y = 4 + 3*X1 + 5+X2 +np.random.randn(100,1) reg = LinearRegression() reg.fit(X,y) print(reg.intercept_,reg.coef_) X_new = np.array([[0,0], [2,1], [2,4]]) y_prediction = reg.predict(X_new) # 绘图 plt.plot(X_new[:,0],y_prediction,'r-') plt.plot(X1,y,'b.') plt.axis([0,2,0,25]) plt.show()
2301_79790887/myself
000线性回归复现.py
Python
unknown
1,042
import warnings warnings.filterwarnings('ignore') import matplotlib matplotlib.use('Qt5Agg') import numpy as np import matplotlib.pyplot as plt # 全量梯度下降 X=np.random.rand(100,1) y = 4 + 5*X + np.random.randn(100,1) X_new = np.c_[np.ones((100,1)),X] # 学习率 learning_rate = 0.001 # 迭代次数 n_iterations = 1000 # 初始化 theat = np.random.randn(2,1) for i in range(n_iterations): #求梯度 gradients = X_new.T.dot(X_new.dot(theat)-y) theat = theat + learning_rate * gradients print(theat) # 随机梯度下降 X=2*np.random.randn(100,1) y = 4+3*X+np.random.randn(100,1) X_b = np.c_[np.ones((100,1)),X] # 轮次 n_epoch = 1000 theat = np.random.randn(2,1) m = 100 learning_rate = 0.001 for epoch in range(n_epoch): for j in range(m): random_index = np.random.randint(m) xi = X_b[random_index:random_index+1] yi = y[random_index:random_index+1] gradients = xi.T.dot(xi.dot(theat)-yi) theat = theat - learning_rate * gradients print(theat) # 小批量梯度下降 X=2*np.random.randn(100,1) y = 4+3*X +np.random.randn(100,1) X_b = np.c_[np.ones((100,1)),X] learning_rate = 0.01 n_epochs = 10000 m=100 batch_size=10 num_batches=int(m/batch_size) theta = np.random.randn(2,1) for i in range(n_epochs): for j in range(num_batches): random_index = np.random.randint(m) x_batch = X_b[random_index:random_index+batch_size] y_batch = y[random_index:random_index+batch_size] gradient = x_batch.T.dot(x_batch.dot(theta)-y_batch) theta = theta - learning_rate * gradient print(theta)
2301_79790887/myself
001三种梯度下降算法复现.py
Python
unknown
1,670
package com.example.chat.client; import com.example.chat.common.Message; import com.example.chat.common.MessageType; import lombok.extern.slf4j.Slf4j; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.net.Socket; import java.util.Date; import java.util.List; import java.util.Map; import java.util.Optional; /** * 聊天客户端 */ @Slf4j public class ChatClient { private static final String DEFAULT_HOST = "localhost"; private static final int DEFAULT_PORT = 8888; private final ClientState state; private final MessageHandler messageHandler; private final CommandHandler commandHandler; private final MessageDisplay display; public ChatClient(String host, int port) { this.state = new ClientState(host, port); this.messageHandler = new MessageHandler(state); this.commandHandler = new CommandHandler(state, messageHandler); this.display = new MessageDisplay(); } public ChatClient() { this(DEFAULT_HOST, DEFAULT_PORT); } /** * 启动客户端 */ public void start() { display.displayInfo("\n=== 聊天客户端启动 ===\n* 服务器地址: " + state.getHost() + "\n* 端口: " + state.getPort() + "\n* 按 Ctrl+C 退出程序\n===================\n"); try { display.displayInfo(String.format("正在连接到服务器 %s:%d...", state.getHost(), state.getPort())); initializeConnection() .flatMap(this::handleLogin) .ifPresent(success -> { if (success) { startMessageReceiver(); processUserInput(); } }); } catch (IOException e) { log.error("连接服务器失败: {}", e.getMessage()); } finally { state.close(); } } /** * 初始化连接 */ private Optional<Boolean> initializeConnection() throws IOException { Socket socket = new Socket(state.getHost(), state.getPort()); state.setSocket(socket); state.setOutput(new ObjectOutputStream(socket.getOutputStream())); state.setInput(new ObjectInputStream(socket.getInputStream())); state.setRunning(true); display.displayInfo("已成功连接到服务器"); return Optional.of(true); } /** * 处理登录 */ private Optional<Boolean> handleLogin(boolean connected) { try { while (true) { // 修改为无限循环,直到成功登录或发生异常 display.displayInfo("请输入您的用户名:"); String input = state.getScanner().nextLine().trim(); if (!validateUsername(input)) { continue; } messageHandler.sendMessage(Message.createLoginRequest(input)); while (state.isRunning()) { Message response = (Message) state.getInput().readObject(); if (handleLoginResponse(response, input)) { return Optional.of(true); } if (response.getType() == MessageType.LOGIN_FAILURE_USERNAME_TAKEN) { break; // 用户名被占用,跳出内层循环重新输入 } } state.setRunning(true); // 重置运行状态,允许重新尝试 } } catch (IOException | ClassNotFoundException e) { log.error("登录过程中发生错误: {}", e.getMessage()); display.displayError("连接异常,请重试..."); } return Optional.of(false); } /** * 验证用户名 */ private boolean validateUsername(String username) { if (username.isEmpty()) { display.displayError("用户名不能为空,请重新输入!"); return false; } if (!username.matches("^[a-zA-Z0-9_]+$")) { display.displayError("用户名只能包含大小写字母、数字和下划线,请重新输入!"); return false; } return true; } /** * 处理登录响应 */ @SuppressWarnings("unchecked") private boolean handleLoginResponse(Message response, String username) { switch (response.getType()) { case LOGIN_SUCCESS: state.setUsername(username); display.displayInfo("登录成功!"); // 显示在线用户列表和可用聊天室 Map<String, Object> loginData = (Map<String, Object>) response.getData(); Optional.ofNullable(loginData.get("users")) .map(users -> (List<String>) users) .filter(users -> !users.isEmpty()) .ifPresent(users -> display.displayInfo("当前在线用户:" + String.join(", ", users))); Optional.ofNullable(loginData.get("rooms")) .map(rooms -> (List<String>) rooms) .filter(rooms -> !rooms.isEmpty()) .ifPresent(rooms -> display.displayInfo("当前可用聊天室:" + String.join(", ", rooms))); return true; case LOGIN_FAILURE_USERNAME_TAKEN: display.display(response, null); state.setRunning(false); // 中断内部循环 return false; case ERROR_MESSAGE: display.display(response, null); return true; case USER_JOINED_NOTIFICATION: case USER_LEFT_NOTIFICATION: display.display(response, username); return false; default: log.warn("登录过程中收到意外的消息类型:{}", response.getType()); return false; } } /** * 启动消息接收线程 */ private void startMessageReceiver() { Thread messageReceiver = new Thread(() -> { try { while (state.isRunning()) { Message message = (Message) state.getInput().readObject(); messageHandler.handleMessage(message); } } catch (IOException e) { if (state.isRunning()) { log.error("接收消息失败: {}", e.getMessage()); } } catch (ClassNotFoundException e) { log.error("消息类型转换错误: {}", e.getMessage()); } }); messageReceiver.setDaemon(true); messageReceiver.start(); } /** * 处理用户输入 */ private void processUserInput() { display.displayHelp(); while (state.isRunning()) { String input = state.getScanner().nextLine().trim(); if (!input.isEmpty()) { commandHandler.handleInput(input); } } } /** * 启动客户端的主方法 */ public static void main(String[] args) { String host = DEFAULT_HOST; int port = DEFAULT_PORT; if (args.length >= 1) { host = args[0]; } if (args.length >= 2) { try { port = Integer.parseInt(args[1]); } catch (NumberFormatException e) { System.err.println("端口参数无效,使用默认端口: " + DEFAULT_PORT); } } ChatClient client = new ChatClient(host, port); // 添加关闭钩子,确保在Ctrl+C时正确退出 Runtime.getRuntime().addShutdownHook(new Thread(() -> { if (client.state.isRunning()) { try { // 发送登出消息 client.messageHandler.sendMessage(Message.builder() .type(MessageType.LOGOUT_REQUEST) .sender(client.state.getUsername()) .timestamp(new Date()) .build()); // 等待服务器响应 Thread.sleep(100); } catch (Exception e) { // 忽略关闭过程中的异常 } finally { client.state.close(); } } })); client.start(); } }
2301_79174397/Socket_Chat
src/main/java/com/example/chat/client/ChatClient.java
Java
mit
8,536
package com.example.chat.client; import lombok.Data; import lombok.RequiredArgsConstructor; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.net.Socket; import java.util.Optional; import java.util.Scanner; import java.util.concurrent.atomic.AtomicBoolean; /** * 客户端状态类,封装所有可变状态 */ @RequiredArgsConstructor @Data public class ClientState { private final String host; private final int port; private final Scanner scanner = new Scanner(System.in); private Socket socket; private ObjectInputStream input; private ObjectOutputStream output; private volatile String username; private volatile Optional<String> currentRoom = Optional.empty(); private final AtomicBoolean running = new AtomicBoolean(false); public boolean isRunning() { return running.get(); } public void setRunning(boolean value) { running.set(value); } public void close() { setRunning(false); try { if (input != null) input.close(); if (output != null) output.close(); if (socket != null) socket.close(); scanner.close(); } catch (Exception e) { // 忽略关闭异常 } } }
2301_79174397/Socket_Chat
src/main/java/com/example/chat/client/ClientState.java
Java
mit
1,331
package com.example.chat.client; import com.example.chat.common.Message; import com.example.chat.common.MessageType; import java.io.IOException; import java.util.HashMap; import java.util.Map; import java.util.function.BiFunction; import java.util.function.Function; import java.util.function.Supplier; import java.util.Arrays; import java.util.Optional; /** * 命令处理器,使用函数式方式处理不同的命令 */ public class CommandHandler { private final ClientState state; private final MessageHandler messageHandler; private final MessageDisplay display; private final Map<String, BiFunction<String[], ClientState, Boolean>> commands; public CommandHandler(ClientState state, MessageHandler messageHandler) { this.state = state; this.messageHandler = messageHandler; this.display = new MessageDisplay(); this.commands = new HashMap<>(); initializeCommands(); } private void initializeCommands() { commands.put("/passwd", this::handlePasswdCommand); commands.put("/clear", this::handleClearCommand); commands.put("/help", this::handleHelpCommand); commands.put("/exit", this::handleExitCommand); commands.put("/list", this::handleListCommand); commands.put("/rooms", this::handleRoomsCommand); commands.put("/create-room", this::handleCreateRoomCommand); commands.put("/join", this::handleJoinCommand); commands.put("/leave", this::handleLeaveCommand); commands.put("/room-info", this::handleRoomInfoCommand); commands.put("/pm", this::handlePmCommand); } /** * 处理修改密码命令 */ private boolean handlePasswdCommand(String[] args, ClientState state) { if (args.length < 2) { display.displayHint("修改房间密码格式:/passwd room-name <new-password>"); return false; } try { String roomName = args[1]; String newPassword = args.length > 2 ? args[2] : ""; if (newPassword != null && !newPassword.isEmpty() && !isValidName(newPassword)) { display.displayError("密码只能包含大小写字母、数字和下划线!"); return false; } messageHandler.sendMessage(Message.createChangePasswordRequest(roomName, state.getUsername(), newPassword)); return true; } catch (IOException e) { display.displayError("修改密码失败: " + e.getMessage()); return false; } } /** * 处理清屏命令 */ private boolean handleClearCommand(String[] args, ClientState state) { // 使用ANSI转义序列清屏 System.out.print("\033[H\033[2J"); System.out.flush(); return true; } /** * 处理帮助命令 */ private boolean handleHelpCommand(String[] args, ClientState state) { display.displayHelp(); return true; } /** * 处理退出命令 */ private boolean handleExitCommand(String[] args, ClientState state) { try { messageHandler.sendMessage(Message.builder() .type(MessageType.LOGOUT_REQUEST) .sender(state.getUsername()) .build()); return true; } catch (IOException e) { display.displayError("发送退出请求失败: " + e.getMessage()); return false; } } /** * 处理用户列表命令 */ private boolean handleListCommand(String[] args, ClientState state) { try { messageHandler.sendMessage(Message.createUserListRequest(state.getUsername())); return true; } catch (IOException e) { display.displayError("获取用户列表失败: " + e.getMessage()); return false; } } /** * 处理聊天室列表命令 */ private boolean handleRoomsCommand(String[] args, ClientState state) { try { messageHandler.sendMessage(Message.createListRoomsRequest(state.getUsername())); return true; } catch (IOException e) { display.displayError("获取聊天室列表失败: " + e.getMessage()); return false; } } /** * 处理创建聊天室命令 */ private boolean handleCreateRoomCommand(String[] args, ClientState state) { if (args.length < 2) { display.displayHint("创建聊天室格式:/create-room room-name <password>"); return false; } String password = args.length > 2 ? args[2] : ""; return handleCreateRoom(args[1], password); } /** * 处理加入聊天室命令 */ private boolean handleJoinCommand(String[] args, ClientState state) { if (args.length < 2) { display.displayHint("加入聊天室格式:/join room-name <password>"); return false; } String password = args.length > 2 ? args[2] : ""; return handleJoinRoom(args[1], password); } /** * 处理离开聊天室命令 */ private boolean handleLeaveCommand(String[] args, ClientState state) { return state.getCurrentRoom() .map(this::handleLeaveRoom) .orElseGet(() -> { display.displayError("您当前不在任何聊天室中"); return false; }); } /** * 处理房间信息命令 */ private boolean handleRoomInfoCommand(String[] args, ClientState state) { return state.getCurrentRoom() .map(room -> { try { messageHandler.sendMessage(Message.createRoomInfoRequest(state.getUsername(), room)); return true; } catch (IOException e) { display.displayError("获取房间信息失败: " + e.getMessage()); return false; } }) .orElseGet(() -> { display.displayError("您当前不在任何聊天室中"); return false; }); } /** * 处理私聊命令 */ private boolean handlePmCommand(String[] args, ClientState state) { if (args.length < 3) { display.displayHint("私聊格式:/pm <用户名> <消息>"); return false; } return handlePrivateMessage(args); } /** * 处理用户输入 */ public void handleInput(String input) { if (input.isEmpty()) { return; } // 清除用户输入的命令行 System.out.print("\033[1A"); // 光标上移一行 System.out.print("\033[2K"); // 清除整行 if (input.startsWith("/")) { String[] args = input.split(" "); String command = args[0]; commands.getOrDefault(command, (cmdArgs, state) -> { display.displayError("无效的命令。使用 /help 查看可用命令。"); return false; }).apply(args, state); } else { // 非命令消息发送到当前聊天室 state.getCurrentRoom() .map(room -> { try { messageHandler.sendMessage(Message.createRoomMessage(input, state.getUsername(), room)); return true; } catch (IOException e) { display.displayError("发送消息失败: " + e.getMessage()); return false; } }) .orElseGet(() -> { display.displayHint("请先加入一个聊天室再发送消息(使用 /join <房间名>)"); return false; }); } } private boolean handleCreateRoom(String roomName, String password) { if (!isValidName(roomName)) { display.displayError("房间名只能包含大小写字母、数字和下划线!"); return false; } if (roomName.equals(state.getCurrentRoom().orElse(null))) { display.displayError("您已经在该聊天室中!"); return false; } if (password != null && !password.isEmpty() && !isValidName(password)) { display.displayError("密码只能包含大小写字母、数字和下划线!"); return false; } // 如果已经在某个聊天室中,则先离开当前聊天室 state.getCurrentRoom().ifPresent(currentRoom -> { handleLeaveRoom(currentRoom); }); try { messageHandler.sendMessage(Message.createCreateRoomRequest(roomName, state.getUsername(), password)); return true; } catch (IOException e) { display.displayError("创建聊天室失败: " + e.getMessage()); return false; } } private boolean handleJoinRoom(String roomName, String password) { if (!isValidName(roomName)) { display.displayError("房间名只能包含大小写字母、数字和下划线!"); return false; } if (roomName.equals(state.getCurrentRoom().orElse(null))) { display.displayError("您已经在该聊天室中!"); return false; } // 如果已经在某个聊天室中,则先离开当前聊天室 state.getCurrentRoom().ifPresent(currentRoom -> { handleLeaveRoom(currentRoom); }); try { messageHandler.sendMessage(Message.createJoinRoomRequest(roomName, state.getUsername(), password)); return true; } catch (IOException e) { display.displayError("加入聊天室失败: " + e.getMessage()); return false; } } private boolean handleLeaveRoom(String roomName) { try { messageHandler.sendMessage(Message.createLeaveRoomRequest(roomName, state.getUsername())); return true; } catch (IOException e) { display.displayError("离开聊天室失败: " + e.getMessage()); return false; } } private boolean handlePrivateMessage(String[] args) { String targetUser = args[1]; String content = String.join(" ", Arrays.copyOfRange(args, 2, args.length)); // 检查是否试图给自己发送私聊消息 if (targetUser.equals(state.getUsername())) { display.displayError("不能向自己发送私聊消息"); return false; } try { messageHandler.sendMessage(Message.createPrivateMessage(content, state.getUsername(), targetUser)); return true; } catch (IOException e) { display.displayError("发送私聊消息失败: " + e.getMessage()); return false; } } /** * 验证名称格式(用户名或房间名) * 只允许使用大小写字母、数字和下划线 */ private boolean isValidName(String name) { return name != null && !name.isEmpty() && name.matches("^[a-zA-Z0-9_]+$"); } }
2301_79174397/Socket_Chat
src/main/java/com/example/chat/client/CommandHandler.java
Java
mit
11,413
package com.example.chat.client; import com.example.chat.common.Message; import com.example.chat.common.MessageType; /** * 消息显示器,负责格式化并显示各种类型的消息 */ public class MessageDisplay { /** * 显示消息 */ public void display(Message message, String currentUser) { System.out.println(MessageFormatter.formatMessage(message, currentUser)); } /** * 显示错误消息(红色) */ public void displayError(String content) { Message message = Message.builder() .type(MessageType.LOCAL_ERROR) .content(content) .build(); display(message, null); } /** * 显示提示消息(青色) */ public void displayHint(String content) { Message message = Message.builder() .type(MessageType.LOCAL_HINT) .content(content) .build(); display(message, null); } /** * 显示普通信息(蓝色) */ public void displayInfo(String content) { Message message = Message.builder() .type(MessageType.LOCAL_INFO) .content(content) .build(); display(message, null); } /** * 显示帮助信息 */ public void displayHelp() { StringBuilder help = new StringBuilder() .append("\n=== 聊天室命令说明 ===\n") .append("/help - 显示此帮助信息\n") .append("/clear - 清除屏幕\n") .append("/exit - 退出聊天室\n") .append("/list - 查看在线用户\n") .append("/rooms - 查看可用聊天室\n") .append("/create-room room-name <密码> - 创建新聊天室(密码可选)\n") .append("/join room-name <密码> - 加入聊天室(密码可选)\n") .append("/passwd room-name <新密码> - 修改房间密码(仅房主可用,空密码则取消密码)\n") .append("/leave - 离开当前聊天室\n") .append("/room-info - 显示当前房间信息和成员列表\n") .append("/pm <用户名> <消息> - 发送私聊消息\n") .append("直接输入消息 - 在当前聊天室发言\n") .append("==================\n"); displayInfo(help.toString()); } }
2301_79174397/Socket_Chat
src/main/java/com/example/chat/client/MessageDisplay.java
Java
mit
2,678
package com.example.chat.client; import com.example.chat.common.Message; import java.util.List; import java.util.Map; /** * 消息格式化工具类,负责消息的颜色和格式处理 */ public class MessageFormatter { // ANSI 颜色代码 private static final String ANSI_RESET = "\u001B[0m"; private static final String ANSI_GRAY = "\u001B[90m"; // 时间戳 private static final String ANSI_RED = "\u001B[31m"; // 错误消息 private static final String ANSI_GREEN = "\u001B[32m"; // 系统消息 private static final String ANSI_YELLOW = "\u001B[33m"; // 接收的私聊 private static final String ANSI_BLUE = "\u001B[34m"; // 聊天室消息 private static final String ANSI_MAGENTA = "\u001B[35m"; // 用户名 private static final String ANSI_CYAN = "\u001B[36m"; // 发出的私聊 /** * 格式化时间戳(右对齐到行末) */ private static String formatTimestamp(java.util.Date timestamp) { if (timestamp == null) { timestamp = new java.util.Date(); } String timeStr = String.format("%s[%s]%s", ANSI_GRAY, new java.text.SimpleDateFormat("HH:mm:ss").format(timestamp), ANSI_RESET); // 保存当前光标位置,移动到行末前10个字符的位置,打印时间戳,然后恢复光标位置 return String.format("\033[s\033[80G%s\033[u", timeStr); } /** * 格式化消息用于显示 * * @param message 要格式化的消息 * @param currentUsername 当前用户名(用于判断消息的发送/接收状态) * @return 格式化后的消息字符串 */ public static String formatMessage(Message message, String currentUsername) { if (message == null) { return ""; } switch (message.getType()) { // 本地消息类型 case LOCAL_ERROR: return String.format("%s[错误] %s%s%s", ANSI_RED, message.getContent(), ANSI_RESET, formatTimestamp(message.getTimestamp())); case LOCAL_HINT: return String.format("%s[提示] %s%s%s", ANSI_CYAN, message.getContent(), ANSI_RESET, formatTimestamp(message.getTimestamp())); case LOCAL_INFO: return String.format("%s[信息] %s%s%s", ANSI_BLUE, message.getContent(), ANSI_RESET, formatTimestamp(message.getTimestamp())); // 聊天室消息 case ROOM_MESSAGE_BROADCAST: return String.format("%s[%s%s%s] %s%s%s: %s%s%s", ANSI_BLUE, ANSI_CYAN, message.getRoomName(), ANSI_BLUE, ANSI_MAGENTA, message.getSender(), ANSI_BLUE, message.getContent(), ANSI_RESET, formatTimestamp(message.getTimestamp())); // 私聊消息 case PRIVATE_MESSAGE_DELIVERY: String color = message.getSender().equals(currentUsername) ? ANSI_CYAN : ANSI_YELLOW; return String.format("%s[私聊] %s%s%s: %s%s%s", color, ANSI_MAGENTA, message.getSender(), color, message.getContent(), ANSI_RESET, formatTimestamp(message.getTimestamp())); // 聊天室操作结果 case CREATE_ROOM_SUCCESS: case JOIN_ROOM_SUCCESS: case LEAVE_ROOM_SUCCESS: return String.format("%s[系统] %s%s%s", ANSI_GREEN, message.getContent(), ANSI_RESET, formatTimestamp(message.getTimestamp())); case CREATE_ROOM_FAILURE: case JOIN_ROOM_FAILURE: return String.format("%s[错误] %s%s%s", ANSI_RED, message.getContent(), ANSI_RESET, formatTimestamp(message.getTimestamp())); // 聊天室状态变更通知 case USER_JOINED_ROOM_NOTIFICATION: case USER_LEFT_ROOM_NOTIFICATION: return String.format("%s[%s%s%s] %s%s%s", ANSI_GREEN, ANSI_CYAN, message.getRoomName(), ANSI_GREEN, message.getContent(), ANSI_RESET, formatTimestamp(message.getTimestamp())); case ROOM_DESTROYED_NOTIFICATION: return String.format("%s[系统] %s%s%s", ANSI_RED, message.getContent(), ANSI_RESET, formatTimestamp(message.getTimestamp())); // 用户列表 case USER_LIST_RESPONSE: @SuppressWarnings("unchecked") java.util.List<String> users = (java.util.List<String>) message.getData(); String coloredUsers = users.stream() .map(user -> ANSI_MAGENTA + user + ANSI_GREEN) .collect(java.util.stream.Collectors.joining(", ")); return String.format("%s当前在线用户:%s%s%s", ANSI_GREEN, coloredUsers, ANSI_RESET, formatTimestamp(message.getTimestamp())); // 聊天室列表 case LIST_ROOMS_RESPONSE: @SuppressWarnings("unchecked") java.util.List<String> rooms = (java.util.List<String>) message.getData(); if (rooms.isEmpty()) { return String.format("%s当前没有可用的聊天室%s%s", ANSI_GREEN, ANSI_RESET, formatTimestamp(message.getTimestamp())); } String coloredRooms = rooms.stream() .map(room -> ANSI_CYAN + room + ANSI_GREEN) .collect(java.util.stream.Collectors.joining(", ")); return String.format("%s可用聊天室:%s%s%s", ANSI_GREEN, coloredRooms, ANSI_RESET, formatTimestamp(message.getTimestamp())); // 房间信息响应 case ROOM_INFO_RESPONSE: @SuppressWarnings("unchecked") Map<String, Object> roomInfo = (Map<String, Object>) message.getData(); String roomName = (String) roomInfo.get("name"); @SuppressWarnings("unchecked") List<String> members = (List<String>) roomInfo.get("members"); String coloredMembers = members.stream() .map(member -> ANSI_MAGENTA + member + ANSI_GREEN) .collect(java.util.stream.Collectors.joining(", ")); String creator = (String) roomInfo.get("creator"); long creationTime = (Long) roomInfo.get("creationTime"); String timeStr = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss") .format(new java.util.Date(creationTime)); return String.format("%s房间: %s%s%s\n创建者: %s%s%s\n创建时间: %s\n成员: %s%s", ANSI_GREEN, ANSI_CYAN, roomName, ANSI_GREEN, ANSI_MAGENTA, creator, ANSI_GREEN, timeStr, coloredMembers, ANSI_RESET); // 用户状态通知 case USER_JOINED_NOTIFICATION: case USER_LEFT_NOTIFICATION: case SERVER_SHUTDOWN_NOTIFICATION: case LOGOUT_CONFIRMATION: return String.format("%s[系统] %s%s", ANSI_GREEN, message.getContent(), ANSI_RESET); // 错误消息 case ERROR_MESSAGE: case LOGIN_FAILURE_USERNAME_TAKEN: return String.format("%s[错误] %s%s%s", ANSI_RED, message.getContent(), ANSI_RESET, formatTimestamp(message.getTimestamp())); default: return String.format("%s[系统] %s%s%s", ANSI_BLUE, message.getContent(), ANSI_RESET, formatTimestamp(message.getTimestamp())); } } }
2301_79174397/Socket_Chat
src/main/java/com/example/chat/client/MessageFormatter.java
Java
mit
8,229
package com.example.chat.client; import com.example.chat.common.Message; import com.example.chat.common.MessageType; import java.util.List; import java.io.IOException; import java.util.Optional; import java.util.HashMap; import java.util.Map; import java.util.function.BiConsumer; /** * 消息处理器,使用函数式方式处理不同类型的消息 */ public class MessageHandler { private final ClientState state; private final Map<MessageType, BiConsumer<Message, ClientState>> handlers; private final MessageDisplay display; public MessageHandler(ClientState state) { this.state = state; this.handlers = new HashMap<>(); this.display = new MessageDisplay(); initializeHandlers(); } private void initializeHandlers() { // 注册各种消息类型的处理器 handlers.put(MessageType.ROOM_HISTORY_RESPONSE, (message, state) -> { display.displayInfo("=== 历史消息 ==="); @SuppressWarnings("unchecked") List<Message> history = (List<Message>) message.getData(); history.forEach(msg -> display.display(msg, state.getUsername())); display.displayInfo("=== 历史消息结束 ==="); }); handlers.put(MessageType.JOIN_ROOM_SUCCESS, (message, state) -> { state.setCurrentRoom(Optional.ofNullable(message.getRoomName())); display.display(message, state.getUsername()); }); handlers.put(MessageType.LEAVE_ROOM_SUCCESS, (message, state) -> { state.setCurrentRoom(Optional.empty()); display.display(message, state.getUsername()); }); handlers.put(MessageType.ROOM_INFO_RESPONSE, (message, state) -> display.display(message, state.getUsername())); handlers.put(MessageType.LIST_ROOMS_RESPONSE, (message, state) -> display.display(message, state.getUsername())); handlers.put(MessageType.USER_LIST_RESPONSE, (message, state) -> display.display(message, state.getUsername())); handlers.put(MessageType.LOGOUT_CONFIRMATION, (message, state) -> { display.display(message, state.getUsername()); state.close(); }); handlers.put(MessageType.SERVER_SHUTDOWN_NOTIFICATION, (message, state) -> { display.display(message, state.getUsername()); state.close(); }); } /** * 处理接收到的消息 */ public void handleMessage(Message message) { handlers.getOrDefault(message.getType(), (msg, state) -> display.display(msg, state.getUsername())) .accept(message, state); } /** * 发送消息到服务器 */ public void sendMessage(Message message) throws IOException { synchronized (state) { state.getOutput().writeObject(message); state.getOutput().flush(); } } }
2301_79174397/Socket_Chat
src/main/java/com/example/chat/client/MessageHandler.java
Java
mit
2,934
package com.example.chat.common; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; import lombok.NoArgsConstructor; import java.io.Serializable; import java.util.Date; /** * 消息类,用于客户端和服务器之间的所有通信 * 实现 Serializable 接口以支持网络传输 */ @Data @Builder @NoArgsConstructor @AllArgsConstructor public class Message implements Serializable { private static final long serialVersionUID = 3L; // 更新版本号,因为添加了新字段 private MessageType type; // 消息类型 private String content; // 消息内容 private String sender; // 发送者用户名 private String receiver; // 接收者用户名(仅用于私聊) private String roomName; // 聊天室名称(用于聊天室相关消息) private Object data; // 附加数据(如用户列表、聊天室列表、房间密码等) @Builder.Default private Date timestamp = new Date(); // 消息时间戳 /** * 创建一个系统消息(如错误消息、通知等) */ public static Message createSystemMessage(MessageType type, String content) { return Message.builder() .type(type) .content(content) .sender("SERVER") .timestamp(new Date()) .build(); } /** * 创建一个私聊消息 */ public static Message createPrivateMessage(String content, String sender, String receiver) { return Message.builder() .type(MessageType.PRIVATE_MESSAGE_REQUEST) .content(content) .sender(sender) .receiver(receiver) .timestamp(new Date()) .build(); } /** * 创建一个聊天室消息 */ public static Message createRoomMessage(String content, String sender, String roomName) { return Message.builder() .type(MessageType.ROOM_MESSAGE_REQUEST) .content(content) .sender(sender) .roomName(roomName) .timestamp(new Date()) .build(); } /** * 创建一个创建聊天室的请求消息 */ public static Message createCreateRoomRequest(String roomName, String username, String password) { return Message.builder() .type(MessageType.CREATE_ROOM_REQUEST) .sender(username) .roomName(roomName) .data(password) // 使用data字段存储密码 .timestamp(new Date()) .build(); } /** * 创建一个加入聊天室的请求消息 */ public static Message createJoinRoomRequest(String roomName, String username, String password) { return Message.builder() .type(MessageType.JOIN_ROOM_REQUEST) .sender(username) .roomName(roomName) .data(password) // 使用data字段存储密码 .timestamp(new Date()) .build(); } /** * 创建一个离开聊天室的请求消息 */ public static Message createLeaveRoomRequest(String roomName, String username) { return Message.builder() .type(MessageType.LEAVE_ROOM_REQUEST) .sender(username) .roomName(roomName) .timestamp(new Date()) .build(); } /** * 创建一个登录请求消息 */ public static Message createLoginRequest(String username) { return Message.builder() .type(MessageType.LOGIN_REQUEST) .sender(username) .timestamp(new Date()) .build(); } /** * 创建一个请求用户列表的消息 */ public static Message createUserListRequest(String username) { return Message.builder() .type(MessageType.USER_LIST_REQUEST) .sender(username) .timestamp(new Date()) .build(); } /** * 创建一个请求聊天室列表的消息 */ public static Message createListRoomsRequest(String username) { return Message.builder() .type(MessageType.LIST_ROOMS_REQUEST) .sender(username) .timestamp(new Date()) .build(); } /** * 创建一个请求房间信息的消息 */ public static Message createRoomInfoRequest(String username, String roomName) { return Message.builder() .type(MessageType.ROOM_INFO_REQUEST) .sender(username) .roomName(roomName) .timestamp(new Date()) .build(); } /** * 创建一个修改房间密码的请求消息 */ public static Message createChangePasswordRequest(String roomName, String username, String newPassword) { return Message.builder() .type(MessageType.CHANGE_ROOM_PASSWORD_REQUEST) .sender(username) .roomName(roomName) .data(newPassword) // 使用data字段存储新密码 .timestamp(new Date()) .build(); } }
2301_79174397/Socket_Chat
src/main/java/com/example/chat/common/Message.java
Java
mit
5,297
package com.example.chat.common; /** * 定义所有可能的消息类型 */ public enum MessageType { // 登录相关 LOGIN_REQUEST, // C->S: 客户端请求登录,sender=欲使用的昵称 LOGIN_SUCCESS, // S->C: 服务器通知登录成功 LOGIN_FAILURE_USERNAME_TAKEN, // S->C: 服务器通知登录失败,昵称已被占用 // 私聊消息相关 PRIVATE_MESSAGE_REQUEST, // C->S: 客户端发送私聊消息请求 PRIVATE_MESSAGE_DELIVERY, // S->C: 服务器向目标客户端投递私聊消息 // 用户管理相关 USER_LIST_REQUEST, // C->S: 客户端请求在线用户列表 USER_LIST_RESPONSE, // S->C: 服务器响应用户列表请求 USER_JOINED_NOTIFICATION, // S->C: 服务器通知有新用户加入 USER_LEFT_NOTIFICATION, // S->C: 服务器通知有用户离开 // 登出相关 LOGOUT_REQUEST, // C->S: 客户端请求登出 LOGOUT_CONFIRMATION, // S->C: 服务器确认登出 // 错误和系统消息 ERROR_MESSAGE, // S->C: 服务器发送错误信息 SERVER_SHUTDOWN_NOTIFICATION, // S->C: 服务器通知即将关闭 // 聊天室相关消息类型 CREATE_ROOM_REQUEST, // C->S: 客户端请求创建聊天室 CREATE_ROOM_SUCCESS, // S->C: 服务器通知聊天室创建成功 CREATE_ROOM_FAILURE, // S->C: 服务器通知聊天室创建失败(如名称已存在) JOIN_ROOM_REQUEST, // C->S: 客户端请求加入聊天室 JOIN_ROOM_SUCCESS, // S->C: 服务器通知成功加入聊天室 JOIN_ROOM_FAILURE, // S->C: 服务器通知加入聊天室失败(如房间不存在) LEAVE_ROOM_REQUEST, // C->S: 客户端请求离开聊天室 LEAVE_ROOM_SUCCESS, // S->C: 服务器通知成功离开聊天室 ROOM_MESSAGE_REQUEST, // C->S: 客户端发送聊天室消息请求 ROOM_MESSAGE_BROADCAST, // S->C: 服务器广播聊天室消息给所有房间成员 LIST_ROOMS_REQUEST, // C->S: 客户端请求获取可用聊天室列表 LIST_ROOMS_RESPONSE, // S->C: 服务器响应聊天室列表 // 聊天室状态变更通知 USER_JOINED_ROOM_NOTIFICATION, // S->C: 服务器通知房间内有新用户加入 USER_LEFT_ROOM_NOTIFICATION, // S->C: 服务器通知房间内有用户离开 ROOM_DESTROYED_NOTIFICATION, // S->C: 服务器通知聊天室已被销毁(当房间空了之后) // 房间信息相关 ROOM_INFO_REQUEST, // C->S: 客户端请求获取当前房间信息 ROOM_INFO_RESPONSE, // S->C: 服务器响应房间信息 ROOM_HISTORY_RESPONSE, // S->C: 服务器发送房间历史消息 // 房间密码相关 CHANGE_ROOM_PASSWORD_REQUEST, // C->S: 房主请求修改房间密码 CHANGE_ROOM_PASSWORD_SUCCESS, // S->C: 服务器通知修改密码成功 CHANGE_ROOM_PASSWORD_FAILURE, // S->C: 服务器通知修改密码失败(如非房主) // 本地消息类型(客户端内部使用) LOCAL_ERROR, // 本地错误提示(红色) LOCAL_HINT, // 本地操作提示(青色) LOCAL_INFO // 本地普通提示(蓝色) }
2301_79174397/Socket_Chat
src/main/java/com/example/chat/common/MessageType.java
Java
mit
3,072
package com.example.chat.server; import lombok.Getter; import java.util.Set; import java.util.List; import java.util.ArrayList; import java.util.Collections; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.atomic.AtomicInteger; import com.example.chat.common.Message; /** * 表示一个聊天室 * 该类负责管理单个聊天室的状态,包括成员列表和基本属性 * 设计为线程安全的,因为会被多个 ClientHandler 并发访问 */ @Getter public class ChatRoom { private final String name; // 聊天室名称(唯一标识) private final String creator; // 创建者用户名 private final long creationTime; // 创建时间 private String password; // 房间密码,如果为null或空字符串表示无密码 private final Set<String> members; // 当前成员列表(用户名) private final AtomicInteger memberCount; // 成员计数器,避免频繁计算size private final List<Message> messageHistory; // 聊天记录 private static final int MAX_HISTORY_SIZE = 100; // 最大历史消息数量 /** * 创建一个新的聊天室 * * @param name 聊天室名称 * @param creator 创建者用户名 */ public ChatRoom(String name, String creator, String password) { this.name = name; this.creator = creator; this.password = password; this.creationTime = System.currentTimeMillis(); // 使用 ConcurrentHashMap 的 newKeySet 来创建线程安全的 Set this.members = ConcurrentHashMap.newKeySet(); this.memberCount = new AtomicInteger(0); this.messageHistory = Collections.synchronizedList(new ArrayList<>()); } /** * 添加成员到聊天室 * 返回true如果添加成功,false如果用户已在房间中 */ public boolean addMember(String username) { if (username == null || username.isEmpty()) { return false; } if (members.add(username)) { memberCount.incrementAndGet(); return true; } return false; } /** * 从聊天室移除成员 * 返回true如果移除成功,false如果用户不在房间中 */ public boolean removeMember(String username) { if (username == null || username.isEmpty()) { return false; } if (members.remove(username)) { memberCount.decrementAndGet(); return true; } return false; } /** * 判断用户是否在聊天室中 */ public boolean hasMember(String username) { return username != null && !username.isEmpty() && members.contains(username); } /** * 获取聊天室当前成员数 * 使用原子计数器,避免频繁计算size */ public int getMemberCount() { return memberCount.get(); } /** * 检查聊天室是否为空 */ public boolean isEmpty() { return memberCount.get() == 0; } /** * 获取所有成员的用户名集合的不可变副本 */ public Set<String> getMembers() { return Set.copyOf(members); } /** * 验证密码是否正确 * 如果房间没有密码(password为null或空字符串),则始终返回true */ public synchronized boolean validatePassword(String inputPassword) { if (password == null || password.isEmpty()) { return true; } return password.equals(inputPassword); } /** * 修改房间密码 * 只有房主可以修改密码 * * @param username 请求修改密码的用户 * @param newPassword 新密码 * @return true 如果修改成功,false 如果用户不是房主 */ public synchronized boolean changePassword(String username, String newPassword) { if (!isCreator(username)) { return false; } if (newPassword != null && !newPassword.matches("^[a-zA-Z0-9_]*$")) { return false; } this.password = newPassword; return true; } /** * 检查用户是否是房主 */ public boolean isCreator(String username) { return username != null && username.equals(creator); } /** * 添加一条消息到历史记录 * 如果历史记录超过最大容量,将移除最旧的消息 */ public synchronized void addMessage(Message message) { if (messageHistory.size() >= MAX_HISTORY_SIZE) { messageHistory.remove(0); // 移除最旧的消息 } messageHistory.add(message); } /** * 获取最近的n条消息历史 * 如果n大于历史记录数量,则返回所有历史记录 */ public List<Message> getRecentMessages(int n) { synchronized (messageHistory) { int start = Math.max(0, messageHistory.size() - n); return new ArrayList<>(messageHistory.subList(start, messageHistory.size())); } } }
2301_79174397/Socket_Chat
src/main/java/com/example/chat/server/ChatRoom.java
Java
mit
5,056
package com.example.chat.server; import com.example.chat.common.Message; import com.example.chat.common.MessageType; import lombok.extern.slf4j.Slf4j; import java.io.IOException; import java.net.ServerSocket; import java.net.Socket; import java.util.concurrent.CompletableFuture; import java.util.concurrent.atomic.AtomicReference; /** * 聊天服务器主类 */ @Slf4j public class ChatServer { private static final int DEFAULT_PORT = 8888; private final ServerState state; private final ServerMessageProcessor messageProcessor; private final AtomicReference<CompletableFuture<Void>> shutdownFuture = new AtomicReference<>(); public ChatServer(int port) { this.state = new ServerState(port); this.messageProcessor = new ServerMessageProcessor(state); } public ChatServer() { this(DEFAULT_PORT); } /** * 启动服务器 */ public void start() { try { ServerSocket serverSocket = new ServerSocket(state.getPort()); state.setServerSocket(serverSocket); state.setRunning(true); log.info("聊天服务器启动成功,正在监听端口: {}", state.getPort()); log.info("按 Ctrl+C 可以安全关闭服务器"); System.out.println("\n=== 聊天服务器已启动 ==="); System.out.println("* 监听端口: " + state.getPort()); System.out.println("* 按 Ctrl+C 关闭服务器"); System.out.println("=====================\n"); // 创建优雅关闭的Future shutdownFuture.set(new CompletableFuture<>()); while (state.isRunning()) { try { Socket clientSocket = serverSocket.accept(); if (!state.isRunning()) { clientSocket.close(); break; } System.out.println("新的客户端连接:" + clientSocket.getRemoteSocketAddress()); // 为新客户端创建一个处理器并在线程池中执行 ClientHandler clientHandler = new ClientHandler(clientSocket, state, messageProcessor); state.getExecutorService().execute(clientHandler); } catch (IOException e) { if (state.isRunning()) { log.error("接受客户端连接时发生错误: {}", e.getMessage()); } } } } catch (IOException e) { log.error("服务器启动失败: {}", e.getMessage()); } finally { shutdown(); } } /** * 关闭服务器 */ public void shutdown() { CompletableFuture<Void> future = shutdownFuture.get(); if (future != null && !future.isDone()) { try { log.info("开始服务器关闭流程..."); // 先设置状态为不运行,阻止新的连接 state.setRunning(false); // 通知所有客户端服务器关闭 log.info("通知所有客户端服务器即将关闭..."); state.getOnlineUsers().values().forEach(handler -> handler.sendMessage(Message.createSystemMessage( MessageType.SERVER_SHUTDOWN_NOTIFICATION, "服务器即将关闭..."))); // 等待消息发送完成 Thread.sleep(100); // 关闭服务器套接字 if (state.getServerSocket() != null && !state.getServerSocket().isClosed()) { log.info("关闭服务器套接字..."); state.getServerSocket().close(); } // 关闭服务器状态(这会关闭所有客户端连接和线程池) state.shutdown(); log.info("服务器关闭完成"); future.complete(null); } catch (Exception e) { future.completeExceptionally(e); log.error("服务器关闭过程中发生错误: {}", e.getMessage()); } } } /** * 启动服务器的主方法 */ public static void main(String[] args) { int port = DEFAULT_PORT; if (args.length > 0) { try { port = Integer.parseInt(args[0]); } catch (NumberFormatException e) { System.err.println("端口参数无效,使用默认端口: " + DEFAULT_PORT); } } ChatServer server = new ChatServer(port); // 添加关闭钩子,确保在Ctrl+C时正确关闭服务器 Runtime.getRuntime().addShutdownHook(new Thread(() -> { System.out.println("\n正在关闭服务器..."); server.shutdown(); try { // 等待关闭完成 CompletableFuture<Void> future = server.shutdownFuture.get(); if (future != null) { future.get(); } } catch (Exception e) { System.err.println("等待服务器关闭时发生错误: " + e.getMessage()); } })); server.start(); } }
2301_79174397/Socket_Chat
src/main/java/com/example/chat/server/ChatServer.java
Java
mit
5,272
package com.example.chat.server; import com.example.chat.common.Message; import com.example.chat.common.MessageType; import lombok.extern.slf4j.Slf4j; import java.io.EOFException; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.net.Socket; import java.net.SocketException; import java.util.HashMap; import java.util.Map; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.locks.ReentrantLock; /** * 处理单个客户端连接的处理器 */ @Slf4j public class ClientHandler implements Runnable { private final Socket clientSocket; private final ServerState serverState; private final ServerMessageProcessor messageProcessor; private final ReentrantLock sendLock = new ReentrantLock(); private ObjectInputStream input; private ObjectOutputStream output; private String username; private final AtomicBoolean running = new AtomicBoolean(false); public ClientHandler(Socket clientSocket, ServerState serverState, ServerMessageProcessor messageProcessor) { this.clientSocket = clientSocket; this.serverState = serverState; this.messageProcessor = messageProcessor; } @Override public void run() { try { if (initializeStreams()) { if (handleLogin()) { processMessages(); } } } catch (Exception e) { if (running.get()) { log.error("客户端连接异常: {}", e.getMessage()); } } finally { close(); } } /** * 初始化输入输出流 */ private boolean initializeStreams() { try { output = new ObjectOutputStream(clientSocket.getOutputStream()); input = new ObjectInputStream(clientSocket.getInputStream()); running.set(true); return true; } catch (IOException e) { log.error("初始化流失败: {}", e.getMessage()); return false; } } /** * 处理客户端登录 */ private boolean handleLogin() throws IOException, ClassNotFoundException { while (running.get()) { Message loginMessage = (Message) input.readObject(); if (loginMessage.getType() != MessageType.LOGIN_REQUEST) { sendMessage(Message.createSystemMessage( MessageType.ERROR_MESSAGE, "请先登录!")); continue; } String requestedUsername = loginMessage.getSender(); if (!isValidName(requestedUsername)) { sendMessage(Message.createSystemMessage( MessageType.ERROR_MESSAGE, "用户名只能包含大小写字母、数字和下划线")); continue; } if (serverState.addUser(requestedUsername, this)) { username = requestedUsername; // 发送登录成功消息,包含当前在线用户列表和可用聊天室列表 Map<String, Object> loginData = new HashMap<>(); loginData.put("users", serverState.getOnlineUserList()); loginData.put("rooms", serverState.getChatRoomList()); sendMessage(Message.builder() .type(MessageType.LOGIN_SUCCESS) .content("登录成功!") .data(loginData) .sender("SERVER") .build()); return true; } else { sendMessage(Message.createSystemMessage( MessageType.LOGIN_FAILURE_USERNAME_TAKEN, "用户名 '" + requestedUsername + "' 已被占用,请选择其他用户名")); } } return false; } /** * 处理消息循环 */ private void processMessages() { try { while (running.get()) { Message message = (Message) input.readObject(); messageProcessor.processMessage(message, this); } } catch (EOFException | SocketException e) { if (running.get()) { // 客户端正常断开连接,不需要记录错误 log.debug("客户端断开连接: {}", clientSocket.getRemoteSocketAddress()); } } catch (IOException e) { if (running.get() && e.getMessage() != null) { log.error("接收消息失败: {}", e.getMessage()); } } catch (ClassNotFoundException e) { if (running.get()) { log.error("消息类型转换错误: {}", e.getMessage()); } } } /** * 发送消息给客户端 * 使用ReentrantLock确保消息发送的原子性和顺序性 */ public void sendMessage(Message message) { sendLock.lock(); try { if (running.get() && output != null) { output.writeObject(message); output.flush(); } } catch (IOException e) { if (running.get() && e.getMessage() != null) { log.error("发送消息失败: {}", e.getMessage()); } close(); } finally { sendLock.unlock(); } } /** * 关闭客户端连接 */ public void close() { if (running.compareAndSet(true, false)) { if (username != null) { serverState.removeUser(username); } try { if (input != null) { try { input.close(); } catch (IOException ignored) { // 忽略关闭流时的异常 } input = null; } if (output != null) { try { output.close(); } catch (IOException ignored) { // 忽略关闭流时的异常 } output = null; } if (!clientSocket.isClosed()) { try { clientSocket.close(); } catch (IOException ignored) { // 忽略关闭套接字时的异常 } } } catch (Exception e) { if (e.getMessage() != null) { log.error("关闭客户端连接时发生错误: {}", e.getMessage()); } } } } /** * 获取用户名 */ public String getUsername() { return username; } /** * 验证名称格式(用户名或房间名) * 只允许使用大小写字母、数字和下划线 */ private boolean isValidName(String name) { return name != null && name.matches("^[a-zA-Z0-9_]+$"); } }
2301_79174397/Socket_Chat
src/main/java/com/example/chat/server/ClientHandler.java
Java
mit
7,116
package com.example.chat.server; import com.example.chat.common.Message; import com.example.chat.common.MessageType; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.ArrayList; import java.util.function.BiConsumer; import java.util.stream.Collectors; /** * 服务器消息处理器,使用函数式方式处理不同类型的消息 */ @Slf4j @RequiredArgsConstructor public class ServerMessageProcessor { private final ServerState serverState; private final Map<MessageType, BiConsumer<Message, ClientHandler>> handlers; public ServerMessageProcessor(ServerState serverState) { this.serverState = serverState; this.handlers = new HashMap<>(); initializeHandlers(); } private void initializeHandlers() { handlers.put(MessageType.PRIVATE_MESSAGE_REQUEST, this::handlePrivateMessage); handlers.put(MessageType.USER_LIST_REQUEST, this::handleUserListRequest); handlers.put(MessageType.CREATE_ROOM_REQUEST, this::handleCreateRoom); handlers.put(MessageType.JOIN_ROOM_REQUEST, this::handleJoinRoom); handlers.put(MessageType.LEAVE_ROOM_REQUEST, this::handleLeaveRoom); handlers.put(MessageType.ROOM_MESSAGE_REQUEST, this::handleRoomMessage); handlers.put(MessageType.LIST_ROOMS_REQUEST, this::handleListRoomsRequest); handlers.put(MessageType.ROOM_INFO_REQUEST, this::handleRoomInfoRequest); handlers.put(MessageType.LOGOUT_REQUEST, this::handleLogout); handlers.put(MessageType.CHANGE_ROOM_PASSWORD_REQUEST, this::handleChangePassword); } /** * 处理消息 */ public void processMessage(Message message, ClientHandler handler) { handlers.getOrDefault(message.getType(), (msg, h) -> log.warn("收到未知类型的消息: {}", msg.getType())).accept(message, handler); } /** * 处理私聊消息 */ private void handlePrivateMessage(Message message, ClientHandler sender) { Optional<ClientHandler> targetHandler = serverState.getClientHandler(message.getReceiver()); Optional<ClientHandler> senderHandler = serverState.getClientHandler(message.getSender()); Message deliveryMessage = Message.builder() .type(MessageType.PRIVATE_MESSAGE_DELIVERY) .content(message.getContent()) .sender(message.getSender()) .receiver(message.getReceiver()) .timestamp(message.getTimestamp()) .build(); targetHandler.ifPresentOrElse( handler -> { handler.sendMessage(deliveryMessage); senderHandler.ifPresent(sh -> sh.sendMessage(deliveryMessage)); }, () -> senderHandler.ifPresent(sh -> sh.sendMessage(Message.createSystemMessage( MessageType.ERROR_MESSAGE, "用户 " + message.getReceiver() + " 不存在或已离线")))); } /** * 处理用户列表请求 */ private void handleUserListRequest(Message message, ClientHandler handler) { List<String> userList = serverState.getOnlineUserList(); handler.sendMessage(Message.builder() .type(MessageType.USER_LIST_RESPONSE) .data(userList) .sender("SERVER") .build()); } /** * 处理创建聊天室请求 */ private void handleCreateRoom(Message message, ClientHandler handler) { String roomName = message.getRoomName(); String username = message.getSender(); String password = (String) message.getData(); if (!isValidName(roomName)) { handler.sendMessage(Message.createSystemMessage( MessageType.ERROR_MESSAGE, "房间名只能包含大小写字母、数字和下划线")); return; } if (password != null && !password.isEmpty() && !isValidName(password)) { handler.sendMessage(Message.createSystemMessage( MessageType.ERROR_MESSAGE, "密码只能包含大小写字母、数字和下划线")); return; } ChatRoom newRoom = new ChatRoom(roomName, username, password); if (serverState.addChatRoom(roomName, newRoom)) { broadcastSystemMessage(Message.createSystemMessage( MessageType.CREATE_ROOM_SUCCESS, "新的聊天室 '" + roomName + "' 已创建")); // 创建者自动加入房间 handleJoinRoom(message, handler); } else { handler.sendMessage(Message.createSystemMessage( MessageType.CREATE_ROOM_FAILURE, "创建聊天室失败:名称 '" + roomName + "' 已被使用")); } } /** * 处理加入聊天室请求 */ private void handleJoinRoom(Message message, ClientHandler handler) { String roomName = message.getRoomName(); String username = message.getSender(); String password = (String) message.getData(); if (!isValidName(roomName)) { handler.sendMessage(Message.createSystemMessage( MessageType.ERROR_MESSAGE, "房间名只能包含大小写字母、数字和下划线")); return; } serverState.getChatRoom(roomName).ifPresentOrElse( room -> { if (!room.validatePassword(password)) { handler.sendMessage(Message.createSystemMessage( MessageType.JOIN_ROOM_FAILURE, "加入聊天室失败:密码错误")); return; } if (room.addMember(username)) { // 通知房间内所有成员有新用户加入 broadcastToRoom(roomName, Message.builder() .type(MessageType.USER_JOINED_ROOM_NOTIFICATION) .content("用户 " + username + " 加入了聊天室") .roomName(roomName) .sender("SERVER") .build()); // 发送加入成功消息 handler.sendMessage(Message.builder() .type(MessageType.JOIN_ROOM_SUCCESS) .content("成功加入聊天室 '" + roomName + "'") .roomName(roomName) .sender("SERVER") .build()); // 发送历史消息 List<Message> history = room.getRecentMessages(15); if (!history.isEmpty()) { handler.sendMessage(Message.builder() .type(MessageType.ROOM_HISTORY_RESPONSE) .roomName(roomName) .sender("SERVER") .data(history) .build()); } } else { handler.sendMessage(Message.createSystemMessage( MessageType.JOIN_ROOM_FAILURE, "加入聊天室失败:您已在房间中")); } }, () -> handler.sendMessage(Message.createSystemMessage( MessageType.JOIN_ROOM_FAILURE, "加入聊天室失败:聊天室 '" + roomName + "' 不存在"))); } /** * 处理离开聊天室请求 */ private void handleLeaveRoom(Message message, ClientHandler handler) { String roomName = message.getRoomName(); String username = message.getSender(); serverState.getChatRoom(roomName).ifPresent(room -> { if (room.removeMember(username)) { // 通知房间内的其他成员 broadcastToRoom(roomName, Message.builder() .type(MessageType.USER_LEFT_ROOM_NOTIFICATION) .content("用户 " + username + " 离开了聊天室") .roomName(roomName) .sender("SERVER") .build()); handler.sendMessage(Message.createSystemMessage( MessageType.LEAVE_ROOM_SUCCESS, "已离开聊天室 '" + roomName + "'")); // 如果房间空了,就删除这个房间 if (room.isEmpty()) { serverState.removeChatRoom(roomName); broadcastSystemMessage(Message.createSystemMessage( MessageType.ROOM_DESTROYED_NOTIFICATION, "聊天室 '" + roomName + "' 已被销毁(没有活跃用户)")); } } }); } /** * 处理聊天室消息 */ private void handleRoomMessage(Message message, ClientHandler handler) { String roomName = message.getRoomName(); String username = message.getSender(); if (roomName == null) { handler.sendMessage(Message.createSystemMessage( MessageType.ERROR_MESSAGE, "消息缺少聊天室名称")); return; } serverState.getChatRoom(roomName).ifPresentOrElse( room -> { if (!room.hasMember(username)) { handler.sendMessage(Message.createSystemMessage( MessageType.ERROR_MESSAGE, "您不是聊天室 '" + roomName + "' 的成员")); return; } Message broadcastMessage = Message.builder() .type(MessageType.ROOM_MESSAGE_BROADCAST) .content(message.getContent()) .sender(username) .roomName(roomName) .timestamp(message.getTimestamp()) .build(); // 保存消息到房间历史记录 room.addMessage(broadcastMessage); broadcastToRoom(roomName, broadcastMessage); }, () -> handler.sendMessage(Message.createSystemMessage( MessageType.ERROR_MESSAGE, "聊天室 '" + roomName + "' 不存在"))); } /** * 处理列出聊天室请求 */ private void handleListRoomsRequest(Message message, ClientHandler handler) { List<String> roomList = serverState.getChatRoomList(); handler.sendMessage(Message.builder() .type(MessageType.LIST_ROOMS_RESPONSE) .data(roomList) .build()); } /** * 处理房间信息请求 */ private void handleRoomInfoRequest(Message message, ClientHandler handler) { String roomName = message.getRoomName(); if (roomName == null) { handler.sendMessage(Message.createSystemMessage( MessageType.ERROR_MESSAGE, "请求房间信息失败:聊天室名称不能为空")); return; } serverState.getChatRoom(roomName).ifPresentOrElse( room -> { Map<String, Object> roomInfo = new HashMap<>(); roomInfo.put("name", room.getName()); roomInfo.put("creator", room.getCreator()); roomInfo.put("creationTime", room.getCreationTime()); roomInfo.put("members", new ArrayList<>(room.getMembers())); handler.sendMessage(Message.builder() .type(MessageType.ROOM_INFO_RESPONSE) .data(roomInfo) .roomName(roomName) .build()); }, () -> handler.sendMessage(Message.createSystemMessage( MessageType.ERROR_MESSAGE, "请求房间信息失败:聊天室 '" + roomName + "' 不存在"))); } /** * 处理登出请求 */ private void handleLogout(Message message, ClientHandler handler) { String username = message.getSender(); // 获取用户所在的所有房间 List<String> userRooms = serverState.getChatRooms().entrySet().stream() .filter(entry -> entry.getValue().hasMember(username)) .map(Map.Entry::getKey) .collect(Collectors.toList()); // 让用户离开所有房间 userRooms.forEach(roomName -> handleLeaveRoom(Message.builder() .type(MessageType.LEAVE_ROOM_REQUEST) .sender(username) .roomName(roomName) .build(), handler)); // 发送登出确认消息 handler.sendMessage(Message.createSystemMessage( MessageType.LOGOUT_CONFIRMATION, "您已成功登出")); // 关闭连接 handler.close(); } /** * 向所有在线用户广播系统消息 */ private void broadcastSystemMessage(Message message) { serverState.getOnlineUsers().values() .forEach(handler -> handler.sendMessage(message)); } /** * 在聊天室内广播消息 */ private void broadcastToRoom(String roomName, Message message) { serverState.getChatRoom(roomName).ifPresent(room -> room.getMembers().stream() .map(username -> serverState.getClientHandler(username)) .filter(Optional::isPresent) .map(Optional::get) .forEach(handler -> handler.sendMessage(message))); } /** * 验证名称格式(用户名或房间名) * 只允许使用大小写字母、数字和下划线 */ private boolean isValidName(String name) { return name != null && !name.isEmpty() && name.matches("^[a-zA-Z0-9_]+$"); } /** * 处理修改房间密码请求 */ private void handleChangePassword(Message message, ClientHandler handler) { String roomName = message.getRoomName(); String username = message.getSender(); String newPassword = (String) message.getData(); if (newPassword != null && !newPassword.isEmpty() && !isValidName(newPassword)) { handler.sendMessage(Message.createSystemMessage( MessageType.CHANGE_ROOM_PASSWORD_FAILURE, "密码只能包含大小写字母、数字和下划线")); return; } serverState.getChatRoom(roomName).ifPresentOrElse( room -> { if (!room.isCreator(username)) { handler.sendMessage(Message.createSystemMessage( MessageType.CHANGE_ROOM_PASSWORD_FAILURE, "修改密码失败:只有房主可以修改密码")); return; } if (room.changePassword(username, newPassword)) { handler.sendMessage(Message.createSystemMessage( MessageType.CHANGE_ROOM_PASSWORD_SUCCESS, "房间密码修改成功")); } else { handler.sendMessage(Message.createSystemMessage( MessageType.CHANGE_ROOM_PASSWORD_FAILURE, "修改密码失败:密码格式错误")); } }, () -> handler.sendMessage(Message.createSystemMessage( MessageType.CHANGE_ROOM_PASSWORD_FAILURE, "修改密码失败:聊天室 '" + roomName + "' 不存在"))); } }
2301_79174397/Socket_Chat
src/main/java/com/example/chat/server/ServerMessageProcessor.java
Java
mit
16,394
package com.example.chat.server; import java.net.ServerSocket; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.atomic.AtomicBoolean; import lombok.Getter; import lombok.Setter; /** * 服务器状态类,使用不可变数据和函数式方法管理服务器状态 */ @Getter public class ServerState { private final int port; private final ConcurrentHashMap<String, ClientHandler> onlineUsers; private final ConcurrentHashMap<String, ChatRoom> chatRooms; private final ExecutorService executorService; @Setter private ServerSocket serverSocket; private final AtomicBoolean running; public ServerState(int port) { this.port = port; this.onlineUsers = new ConcurrentHashMap<>(); this.chatRooms = new ConcurrentHashMap<>(); this.executorService = Executors.newCachedThreadPool(); this.running = new AtomicBoolean(false); } public boolean isRunning() { return running.get(); } public void setRunning(boolean value) { running.set(value); } /** * 获取在线用户列表 */ public List<String> getOnlineUserList() { return List.copyOf(onlineUsers.keySet()); } /** * 获取聊天室列表 */ public List<String> getChatRoomList() { return List.copyOf(chatRooms.keySet()); } /** * 添加在线用户 */ public boolean addUser(String username, ClientHandler handler) { if (username == null || handler == null) { return false; } return onlineUsers.putIfAbsent(username, handler) == null; } /** * 移除在线用户并获取其处理器 */ public Optional<ClientHandler> removeUser(String username) { if (username == null) { return Optional.empty(); } return Optional.ofNullable(onlineUsers.remove(username)); } /** * 获取用户处理器 */ public Optional<ClientHandler> getClientHandler(String username) { if (username == null) { return Optional.empty(); } return Optional.ofNullable(onlineUsers.get(username)); } /** * 获取聊天室 */ public Optional<ChatRoom> getChatRoom(String roomName) { if (roomName == null) { return Optional.empty(); } return Optional.ofNullable(chatRooms.get(roomName)); } /** * 添加聊天室 */ public boolean addChatRoom(String roomName, ChatRoom room) { if (roomName == null || room == null) { return false; } return chatRooms.putIfAbsent(roomName, room) == null; } /** * 移除聊天室 */ public Optional<ChatRoom> removeChatRoom(String roomName) { if (roomName == null) { return Optional.empty(); } return Optional.ofNullable(chatRooms.remove(roomName)); } /** * 获取聊天室信息 */ public Optional<Map<String, Object>> getRoomInfo(String roomName) { return getChatRoom(roomName).map(room -> Map.of( "name", room.getName(), "creator", room.getCreator(), "creationTime", room.getCreationTime(), "members", room.getMembers())); } /** * 获取所有聊天室的不可变视图 */ public Map<String, ChatRoom> getChatRooms() { return Map.copyOf(chatRooms); } /** * 获取所有在线用户的不可变视图 */ public Map<String, ClientHandler> getOnlineUsers() { return Map.copyOf(onlineUsers); } /** * 关闭服务器状态 */ public void shutdown() { if (running.compareAndSet(true, false)) { onlineUsers.values().forEach(ClientHandler::close); onlineUsers.clear(); chatRooms.clear(); executorService.shutdown(); } } }
2301_79174397/Socket_Chat
src/main/java/com/example/chat/server/ServerState.java
Java
mit
4,114
//! //! hifmt-macros //! To parse format strings, `parse`/`unescape` from `ufmt` are reused here. //! //! 实现过程参考了UFMT的实现,重用了其部分代码,parse/unescape,涉及到格式化字符串的解析 //! extern crate proc_macro; use core::mem; use proc_macro::TokenStream; use proc_macro2::Span; use quote::quote; use std::borrow::Cow; use syn::{ parse::{self, Parse, ParseStream}, parse_macro_input, punctuated::Punctuated, spanned::Spanned, Expr, LitStr, Token, }; #[proc_macro] pub fn print(input: TokenStream) -> TokenStream { cprintf(input, false, 1, false) } #[proc_macro] pub fn cprint(input: TokenStream) -> TokenStream { cprintf(input, false, 1, false) } #[proc_macro] pub fn println(input: TokenStream) -> TokenStream { cprintf(input, true, 1, false) } #[proc_macro] pub fn cprintln(input: TokenStream) -> TokenStream { cprintf(input, true, 1, false) } #[proc_macro] pub fn eprint(input: TokenStream) -> TokenStream { cprintf(input, false, 2, false) } #[proc_macro] pub fn ceprint(input: TokenStream) -> TokenStream { cprintf(input, false, 2, false) } #[proc_macro] pub fn eprintln(input: TokenStream) -> TokenStream { cprintf(input, true, 2, false) } #[proc_macro] pub fn ceprintln(input: TokenStream) -> TokenStream { cprintf(input, true, 2, false) } #[proc_macro] pub fn csprint(input: TokenStream) -> TokenStream { csnprintf(input, true, false) } #[proc_macro] pub fn sprint(input: TokenStream) -> TokenStream { csnprintf(input, true, false) } #[proc_macro] pub fn cbprint(input: TokenStream) -> TokenStream { csnprintf(input, false, false) } #[proc_macro] pub fn bprint(input: TokenStream) -> TokenStream { csnprintf(input, false, false) } #[proc_macro] pub fn nolibc_print(input: TokenStream) -> TokenStream { cprintf(input, false, 1, true) } #[proc_macro] pub fn nolibc_cprint(input: TokenStream) -> TokenStream { cprintf(input, false, 1, true) } #[proc_macro] pub fn nolibc_println(input: TokenStream) -> TokenStream { cprintf(input, true, 1, true) } #[proc_macro] pub fn nolibc_cprintln(input: TokenStream) -> TokenStream { cprintf(input, true, 1, true) } #[proc_macro] pub fn nolibc_eprint(input: TokenStream) -> TokenStream { cprintf(input, false, 2, true) } #[proc_macro] pub fn nolibc_ceprint(input: TokenStream) -> TokenStream { cprintf(input, false, 2, true) } #[proc_macro] pub fn nolibc_eprintln(input: TokenStream) -> TokenStream { cprintf(input, true, 2, true) } #[proc_macro] pub fn nolibc_ceprintln(input: TokenStream) -> TokenStream { cprintf(input, true, 2, true) } #[proc_macro] pub fn nolibc_csprint(input: TokenStream) -> TokenStream { csnprintf(input, true, true) } #[proc_macro] pub fn nolibc_sprint(input: TokenStream) -> TokenStream { csnprintf(input, true, true) } #[proc_macro] pub fn nolibc_cbprint(input: TokenStream) -> TokenStream { csnprintf(input, false, true) } #[proc_macro] pub fn nolibc_bprint(input: TokenStream) -> TokenStream { csnprintf(input, false, true) } fn csnprintf(input: TokenStream, is_str: bool, nolibc: bool) -> TokenStream { let input = parse_macro_input!(input as BufInput); let mut buf_format = input.input.format.value(); buf_format.push('\0'); let buf = &input.buf; let ident = hifmt_ident(0, buf.span()); let mut buf_vars = vec![]; let mut buf_args = vec![]; if is_str { buf_vars.push(quote!(let #ident: &mut str = #buf;)); buf_args.push(quote!(#ident.as_bytes_mut().as_mut_ptr())); } else { buf_vars.push(quote!(let #ident: &mut [u8] = #buf;)); buf_args.push(quote!(#ident.as_mut_ptr())); } buf_args.push(quote!(#ident.len() as usize)); cformat( &buf_format, &input.input, |test_vars, vars, args, format, pieces, idents| { if !nolibc { (quote!{{ #(#test_vars)* #(#buf_vars)* #(#vars)* unsafe { snprintf( #(#buf_args),*, #format.as_bytes().as_ptr(), #(#args),*) }}}).into() } else { nolibc_cformat( input.input.format.span(), quote! {#(#test_vars)* #(#buf_vars)* #(#vars)*}, pieces, idents, |formatter| { quote! { let mut #formatter = unsafe { ::hifmt::BufFormatter::new(#(#buf_args),*) }; } }, ) } }, ) } fn cprintf(input: TokenStream, ln: bool, fd: i32, nolibc: bool) -> TokenStream { let input = parse_macro_input!(input as Input); let mut format = input.format.value(); if ln { format.push_str("\n\0"); } else { format.push('\0'); } cformat( &format, &input, |test_vars, vars, args, format, pieces, idents| { if !nolibc { (quote! { { #(#test_vars)* #(#vars)* unsafe { dprintf( #fd, #format.as_bytes().as_ptr(), #(#args),*) } } }).into() } else { nolibc_cformat( input.format.span(), quote! {#(#test_vars)* #(#vars)*}, pieces, idents, |formatter| { quote! {let mut #formatter = _hifmt_Formatter::new(#fd);} }, ) } }, ) } fn nolibc_cformat<F>( span: Span, pre_tokens: proc_macro2::TokenStream, pieces: &[Piece], idents: &[syn::Ident], make_formatter: F, ) -> TokenStream where F: FnOnce(&syn::Ident) -> proc_macro2::TokenStream, { let formatter = hifmt_ident(pieces.len() + 1, span); let size = hifmt_ident(pieces.len() + 2, span); let mut tokens = vec![]; tokens.push(pre_tokens); tokens.push(make_formatter(&formatter)); tokens.push(quote! { let mut #size = 0_usize; }); tokens.push(quote! { use ::hifmt::Formatter; }); let mut ident_iter = idents.iter(); for piece in pieces { if let Piece::Literal(literal) = piece { let literal = if !literal.as_bytes().ends_with(b"\0") { literal } else { &literal[..literal.len() - 1] }; if !literal.is_empty() { tokens.push(quote! { #size += #formatter.write_buf(#literal.as_bytes()); }); } continue; } let ident = ident_iter.next().unwrap(); match piece { Piece::Str => tokens.push(quote! { #size += #formatter.write_buf(#ident.as_bytes()); }), Piece::Bytes | Piece::Char => { tokens.push(quote! { #size += #formatter.write_buf(#ident); }) } Piece::Pointer => tokens.push(quote! { #size += #formatter.write_ptr(#ident); }), Piece::CStr => { tokens.push(quote! { #size += unsafe { #formatter.write_cstr(#ident) }; }) } Piece::Double => tokens.push(quote! { #size += #formatter.write_f64(#ident); }), Piece::Signed => tokens.push(quote! { #size += #formatter.write_i64(#ident); }), Piece::Unsigned => { tokens.push(quote! { #size += #formatter.write_u64(#ident as u64); }) } Piece::Hex => tokens.push(quote! { #size += #formatter.write_hex(#ident as u64); }), Piece::CChar => tokens.push(quote! { #size += #formatter.write_buf(&[#ident as u8]); }), _ => unreachable!(), } } (quote! {{ #(#tokens)* #size as i32 }}) .into() } fn hifmt_ident(idx: usize, span: Span) -> syn::Ident { let name = format!("_hifmt_{}", idx); syn::Ident::new(&name, span) } fn cformat<F>(format: &str, input: &Input, f: F) -> TokenStream where F: Fn( &[proc_macro2::TokenStream], &[proc_macro2::TokenStream], &[proc_macro2::TokenStream], &str, &[Piece], &[syn::Ident], ) -> TokenStream, { let pieces = match parse(format, input.format.span()) { Err(e) => return e.to_compile_error().into(), Ok(pieces) => pieces, }; let argc: usize = input.args.len(); let required_argc: usize = pieces.iter().filter(|piece| !piece.is_literal()).count(); if argc != required_argc { return parse::Error::new( input.format.span(), format!( "format string required {} arguments but {} were supplied", required_argc, argc ), ) .to_compile_error() .into(); } let literal = gen_literal(&pieces); let mut args = vec![]; let mut vars = vec![]; let mut test_vars = vec![]; let mut idents = vec![]; let mut i: usize = 0; for piece in pieces.iter() { if matches!(piece, Piece::Literal(_)) { continue; } let arg = &input.args[i]; i += 1; let ident = hifmt_ident(i, arg.span()); idents.push(ident.clone()); match piece { Piece::Literal(_) => {} Piece::Str | Piece::Bytes => { args.push(quote!(#ident.len() as i32)); if matches!(piece, Piece::Str) { test_vars.push(quote!({ let #ident: &str = #arg; })); vars.push(quote!(let #ident: &str = #arg;)); args.push(quote!(#ident.as_bytes().as_ptr())); } else { test_vars.push(quote!({ let #ident: &[u8] = #arg; })); vars.push(quote!(let #ident: &[u8] = #arg;)); args.push(quote!(#ident.as_ptr())); } } Piece::Char => { test_vars.push(quote!({ let #ident = (#arg) as i64; })); vars.push(quote!( let mut #ident = [0_u8; 4]; let #ident = ::hifmt::encode_utf8(#arg, &mut #ident); )); args.push(quote!(#ident.len() as i32)); args.push(quote!(#ident.as_ptr())); } Piece::CChar => { test_vars.push(quote!({ let #ident = (#arg) as i32; })); vars.push(quote!(let #ident = (#arg) as i32;)); args.push(quote!(#ident)); } Piece::CStr | Piece::Pointer => { test_vars.push(quote!({ let #ident = (#arg) as *const _ as *const u8; })); vars.push(quote!(let #ident = (#arg) as *const _ as *const u8;)); args.push(quote!(#ident)); } Piece::Double => { test_vars.push(quote!({ let #ident = (#arg) as f64; })); vars.push(quote!(let #ident = (#arg) as f64;)); args.push(quote!(#ident)); } _ => { test_vars.push(quote!({ let #ident = (#arg) as i64; })); vars.push(quote!(let #ident = (#arg) as i64;)); args.push(quote!(#ident)); } } } f(&test_vars, &vars, &args, &literal, &pieces, &idents) } fn gen_literal(pieces: &[Piece]) -> String { let mut buf = String::new(); pieces.iter().all(|piece| { match piece { Piece::Literal(s) => buf.push_str(s), Piece::CStr => buf.push_str("%s"), Piece::Pointer => buf.push_str("%p"), Piece::Str => buf.push_str("%.*s"), Piece::Bytes => buf.push_str("%.*s"), Piece::Signed => buf.push_str("%lld"), Piece::Unsigned => buf.push_str("%llu"), Piece::Hex => buf.push_str("%llx"), Piece::Char => buf.push_str("%.*s"), Piece::CChar => buf.push_str("%c"), Piece::Double => buf.push_str("%e"), } true }); buf } struct Input { format: LitStr, _comma: Option<Token![,]>, args: Punctuated<Expr, Token![,]>, } impl Parse for Input { fn parse(input: ParseStream) -> parse::Result<Self> { let format = input.parse()?; if input.is_empty() { Ok(Input { format, _comma: None, args: Punctuated::new(), }) } else { Ok(Input { format, _comma: input.parse()?, args: Punctuated::parse_terminated(input)?, }) } } } struct BufInput { buf: Expr, input: Input, } impl Parse for BufInput { fn parse(input: ParseStream) -> parse::Result<Self> { let buf = input.parse()?; let _: Option<Token![,]> = input.parse()?; let input = Input::parse(input)?; Ok(BufInput { buf, input }) } } enum Piece<'a> { Literal(Cow<'a, str>), CStr, Pointer, CChar, Char, Str, Bytes, Hex, Unsigned, Signed, Double, } impl Piece<'_> { fn is_literal(&self) -> bool { matches!(self, Piece::Literal(_)) } } fn parse(mut format: &str, span: Span) -> parse::Result<Vec<Piece>> { let mut pieces = vec![]; let mut buf = String::new(); loop { let mut parts = format.splitn(2, '{'); match (parts.next(), parts.next()) { (None, None) => break, (Some(s), None) => { if buf.is_empty() { if !s.is_empty() { pieces.push(Piece::Literal(unescape(s, span)?)); } } else { buf.push_str(&unescape(s, span)?); pieces.push(Piece::Literal(Cow::Owned(buf))); } break; } (head, Some(tail)) => { const CSTR: &str = ":cs}"; const POINTER: &str = ":p}"; const STR: &str = ":rs}"; const BYTES: &str = ":rb}"; const HEX: &str = ":x}"; const SIGNED: &str = ":d}"; const UNSIGNED: &str = ":u}"; const DOUBLE: &str = ":e}"; const CCHAR: &str = ":cc}"; const CHAR: &str = ":rc}"; const ESCAPE_BRACE: &str = "{"; let head = head.unwrap_or(""); if tail.starts_with(CSTR) || tail.starts_with(POINTER) || tail.starts_with(STR) || tail.starts_with(BYTES) || tail.starts_with(HEX) || tail.starts_with(SIGNED) || tail.starts_with(UNSIGNED) || tail.starts_with(DOUBLE) || tail.starts_with(CCHAR) || tail.starts_with(CHAR) { if buf.is_empty() { if !head.is_empty() { pieces.push(Piece::Literal(unescape(head, span)?)); } } else { buf.push_str(&unescape(head, span)?); pieces.push(Piece::Literal(Cow::Owned(mem::take(&mut buf)))); } if let Some(tail_tail) = tail.strip_prefix(CSTR) { pieces.push(Piece::CStr); format = tail_tail; } else if let Some(tail_tail) = tail.strip_prefix(POINTER) { pieces.push(Piece::Pointer); format = tail_tail; } else if let Some(tail_tail) = tail.strip_prefix(STR) { pieces.push(Piece::Str); format = tail_tail; } else if let Some(tail_tail) = tail.strip_prefix(BYTES) { pieces.push(Piece::Bytes); format = tail_tail; } else if let Some(tail_tail) = tail.strip_prefix(HEX) { pieces.push(Piece::Hex); format = tail_tail; } else if let Some(tail_tail) = tail.strip_prefix(SIGNED) { pieces.push(Piece::Signed); format = tail_tail; } else if let Some(tail_tail) = tail.strip_prefix(UNSIGNED) { pieces.push(Piece::Unsigned); format = tail_tail; } else if let Some(tail_tail) = tail.strip_prefix(CCHAR) { pieces.push(Piece::CChar); format = tail_tail; } else if let Some(tail_tail) = tail.strip_prefix(CHAR) { pieces.push(Piece::Char); format = tail_tail; } else if let Some(tail_tail) = tail.strip_prefix(DOUBLE) { pieces.push(Piece::Double); format = tail_tail; } } else if let Some(tail_tail) = tail.strip_prefix(ESCAPE_BRACE) { buf.push_str(&unescape(head, span)?); buf.push('{'); format = tail_tail; } else { return Err(parse::Error::new(span, "invalid format string: expected {:d}, {:u}, {:x}, {:e}, {:p}, {:cs}, {:rs}, {:rb} {:cc} {:rc} {{")); } } } } Ok(pieces) } fn unescape(mut format: &str, span: Span) -> parse::Result<Cow<str>> { if format.contains('}') { let mut buf = String::new(); while format.contains('}') { const ERR: &str = "invalid format string: unmatched right brace"; let mut parts = format.splitn(2, '}'); match (parts.next(), parts.next()) { (Some(head), Some(tail)) => { const ESCAPE_BRACE: &str = "}"; if let Some(tail_tail) = tail.strip_prefix(ESCAPE_BRACE) { buf.push_str(head); buf.push('}'); format = tail_tail; } else { return Err(parse::Error::new(span, ERR)); } } _ => unreachable!(), } } buf.push_str(format); Ok(buf.into()) } else { Ok(Cow::Borrowed(format)) } }
2301_79799776/hifmt
macros/src/lib.rs
Rust
apache-2.0
18,374
#[link(name = "c")] extern "C" { fn dprintf(fd: i32, format: *const u8, ...) -> i32; #[cfg(not(feature = "nolibc"))] fn snprintf(buf: *mut u8, len: usize, format: *const u8, ...) -> i32; } #[cfg(feature = "nolibc")] fn write_buf(buf: &[u8]) -> usize { unsafe { dprintf(1, b"%.*s\0".as_ptr(), buf.len() as i32, buf.as_ptr()) as usize } } #[cfg(feature = "nolibc")] hifmt::make_nolibc_formatter!(write_buf); fn main() { let s = vec![b'\0'; 100]; let s = &mut String::from_utf8(s).unwrap(); hifmt::sprint!(s, "sprint({:rs})", "hello snprintf"); let b = &mut [0_u8; 100]; hifmt::bprint!(b, "bprint({:rs})", "hello snprintf"); hifmt::println!( "d = {:d} u = {:u} x = {:x} e = {:e} p = {:p} cstr = {:cs} str = {:rs} bytes = {:rb} char = {:rc}", 100, 200, 300, 400.0, b, b, s, b, '中' ); }
2301_79799776/hifmt
src/example.rs
Rust
apache-2.0
914
//! hifmt - Format output without Rust code segment in binary //! //! # Design objective: //! 1. The print output depends on the API of C //! 2. Eliminate the dependency on Display/Debug trait. //! //! # Examples //! //! ```rust //! #[link(name = "c")] //! extern "C" { //! fn dprintf(fd: i32, format: *const u8, ...) -> i32; //! #[cfg(not(feature = "nolibc"))] //! fn snprintf(buf: *mut u8, size: usize, format: *const u8, ...) -> i32; //! } //! //! #[cfg(feature = "nolibc")] //! fn write_buf(buf: &[u8]) -> usize { //! unsafe { dprintf(1, b"%.*s\0".as_ptr(), buf.len() as i32, buf.as_ptr()) as usize } //! } //! #[cfg(feature = "nolibc")] //! hifmt::make_nolibc_formatter!(write_buf); //! //! hifmt::println!("hello world"); //! hifmt::println!("signed decimal {:d}", -1); //! hifmt::println!("unsigned decimal {:u}", -1); //! hifmt::println!("hexadecimal {:x}", -1); //! hifmt::println!("pointer {:p}", &1); //! hifmt::println!("float {:e}", -1.0); //! hifmt::println!("rust &str {:rs}", "hello world"); //! hifmt::println!("rust &[u8] {:rb}", b"hello world"); //! hifmt::println!("rust char {:rc}", '中'); //! hifmt::println!("c str {:cs}", b"hello world\0"); //! hifmt::println!("c char {:cc}", b'0'); //! //! let mut buf = [0_u8; 100]; //! hifmt::bprint!(&mut buf, "snprintf rust string {:rs}", "hello world"); //! hifmt::println!("c str {:cs}", &buf); //! //! //test_retn_length //! let s = "hello world"; //! let len = hifmt::bprint!(&mut [], "{:rs}", s); //! assert_eq!(len as usize, s.len()); //! let len = hifmt::print!("{:rs}", s); //! assert_eq!(len as usize, s.len()); //! //! //! // test_fat_pointer //! let mut buf = [0_u8; 100]; //! let s = "hello"; //! let n = s as *const _ as *const u8 as usize; //! hifmt::bprint!(&mut buf[0..], "{:p} {:p}", s, s); //! let s = format!("0x{:x} 0x{:x}\0", n, n); //! assert_eq!(s.as_bytes(), &buf[0..s.len()]); //! ``` //! //#![no_std] #[cfg(not(feature = "nolibc"))] mod libc; #[cfg(not(feature = "nolibc"))] pub use libc::*; #[cfg(feature = "nolibc")] mod nolibc; #[cfg(feature = "nolibc")] pub use nolibc::*; #[inline(never)] pub fn encode_utf8(c: char, buf: &mut [u8; 4]) -> &[u8] { let mut u = c as u32; if u <= 0x7F { buf[3] = u as u8; return &buf[3..]; } buf[3] = (u as u8 & 0x3F) | 0x80; u >>= 6; if u <= 0x1F { buf[2] = (u | 0xC0) as u8; return &buf[2..]; } buf[2] = (u as u8 & 0x3F) | 0x80; u >>= 6; if u <= 0xF { buf[1] = (u | 0xE0) as u8; return &buf[1..]; } buf[1] = (u as u8 & 0x3F) | 0x80; u >>= 6; buf[0] = (u | 0xF0) as u8; buf }
2301_79799776/hifmt
src/lib.rs
Rust
apache-2.0
2,631
pub use hifmt_macros::{ bprint, cbprint, ceprint, ceprintln, cprint, cprintln, csprint, eprint, eprintln, print, println, sprint, };
2301_79799776/hifmt
src/libc.rs
Rust
apache-2.0
141
/// feature = "nolibc" /// 用户必须提供一个字符串输出函数: fn(&[u8]) -> usize /// 这里将此输出函数适配到`hifmt::Formatter`用户`hifmt::print`系列, 适用于无多线程并发输出场景. #[macro_export] macro_rules! make_nolibc_formatter { ($printf: ident) => { #[allow(non_camel_case_types)] struct _hifmt_Formatter; impl $crate::Formatter for _hifmt_Formatter { fn new(_: i32) -> Self { _hifmt_Formatter } fn write_buf(&mut self, buf: &[u8]) -> usize { $printf(buf) } } }; } /// feature = "nolibc" /// 用户实现支持hifmt::Formater的类型用于`hifmt::print`系列. /// 如果打印输出有多线程同步需求,应该完整实现`Formatter`接口并接口`nolibc_formatter`使用. #[macro_export] macro_rules! nolibc_formatter { ($formatter: path) => { #[allow(non_camel_case_types)] type _hifmt_Formatter = $formatter; }; } pub trait Formatter { /// fd = 1 代表标准输出端口 /// fd = 2 代表错误输出端口 /// 每次`print`系列宏对应一次`Formatter::new`接口, 会对应多次的`write_***`系列接口. /// 可以在这里实现多线程同步机制,避免多线程输出时信息混杂在一起. fn new(fd: i32) -> Self where Self: Sized; fn write_buf(&mut self, buf: &[u8]) -> usize; fn write_u64(&mut self, val: u64) -> usize { self.write_buf(unsafe { u64_buf(val, &mut [0_u8; 24]) }) } fn write_i64(&mut self, val: i64) -> usize { self.write_buf(i64_buf(val, &mut [0_u8; 24])) } fn write_hex(&mut self, val: u64) -> usize { self.write_buf(hex_buf(val, &mut [0_u8; 24])) } fn write_ptr(&mut self, val: *const u8) -> usize { self.write_buf(ptr_buf(val, &mut [0_u8; 24])) } fn write_f64(&mut self, val: f64) -> usize { self.write_buf(f64_buf(val, &mut [0_u8; 24])) } /// # Safety /// 调用者保证是一个空指针或者有效的c字符串 #[inline(never)] unsafe fn write_cstr(&mut self, val: *const u8) -> usize { if val.is_null() { self.write_buf(b"null") } else { let mut p = val; while p.read() != 0 { p = p.add(1); } self.write_buf(core::slice::from_raw_parts( val, p.offset_from(val) as usize, )) } } } #[inline(never)] fn i64_buf(val: i64, buf: &mut [u8; 24]) -> &[u8] { let mut len = unsafe { u64_buf(val.abs() as u64, buf).len() }; if val < 0 { buf[buf.len() - len - 1] = b'-'; len += 1; } &buf[buf.len() - len..] } #[inline(never)] fn ptr_buf(val: *const u8, buf: &mut [u8; 24]) -> &[u8] { let mut len = hex_buf(val as u64, buf).len(); buf[buf.len() - len - 1] = b'x'; buf[buf.len() - len - 2] = b'0'; len += 2; &buf[buf.len() - len..] } // # Safety 输入保证buf空间足够 #[inline(never)] unsafe fn u64_buf(mut val: u64, buf: &mut [u8]) -> &[u8] { let mut pos = buf.len(); loop { pos -= 1; let n = val % 10; buf[pos] = b'0' + (n as u8); val /= 10; if val == 0 { break; } } &buf[pos..] } #[inline(never)] fn hex_buf(mut val: u64, buf: &mut [u8; 24]) -> &[u8] { let mut pos = buf.len(); loop { pos -= 1; let n = val & 0xF; if n < 10 { buf[pos] = b'0' + (n as u8); } else { buf[pos] = b'a' + (n as u8 - 10); } val >>= 4; if val == 0 { break; } } &buf[pos..] } /// f64::log10/powf依赖std,无法使用. 这里输出的是(+/-)(1/0).dddddd*2^(+/-)d, /// 是2的指数,而非10的指数 #[inline(never)] fn f64_buf(val: f64, buf: &mut [u8; 24]) -> &[u8] { if val.is_nan() { return b"nan"; }; if val.is_infinite() { if val.is_sign_negative() { return b"-inf"; } return b"info"; } let (sign, denormal, fract, exp) = f64_decode(val); let mut len = unsafe { u64_buf(exp.abs() as u64, buf).len() }; len += 1; if exp < 0 { buf[buf.len() - len] = b'-'; } else { buf[buf.len() - len] = b'+'; } for b in b"^2*" { len += 1; buf[buf.len() - len] = *b; } let end = buf.len() - len; let d6 = (fract * 1_000_000.0) as u64; let len6 = unsafe { u64_buf(d6, &mut buf[..end]).len() }; len += len6; for _ in len6..6 { len += 1; buf[buf.len() - len] = b'0'; } len += 1; buf[buf.len() - len] = b'.'; len += 1; if denormal { buf[buf.len() - len] = b'0'; } else { buf[buf.len() - len] = b'1'; } if sign { len += 1; buf[buf.len() - len] = b'-'; } &buf[buf.len() - len..] } // return (sign, denormal, fract, exp) fn f64_decode(val: f64) -> (bool, bool, f64, i64) { let bits = val.to_bits(); let s = bits >> 63; let e = (bits >> 52) & 0x7FF; let mut m = bits & ((0x01 << 52) - 1); let mut exp = e as i64 - 1023; if e == 0 { if m == 0 { return (true, true, 0.0, 0); } let h = hi_bit_1(m) as i64; exp = -(1022 + 52 - h); m <<= 52 - h; } let mut fract = 0.0f64; let mut n = 0.5f64; m <<= 12; while m > 0 { if (m & (0x01 << 63)) > 0 { fract += n; } m <<= 1; n /= 2.0; } (s > 0, e == 0, fract, exp) } fn hi_bit_1(mut n: u64) -> u64 { if n == 0 { return 0; } let mut b = 1; let mut m = n & 0xFFFF_FFFF_0000_0000; if m > 0 { n = m; b += 32; } m = n & 0xFFFF_0000_FFFF_0000; if m > 0 { n = m; b += 16; } m = n & 0xFF00_FF00_FF00_FF00; if m > 0 { n = m; b += 8; } m = n & 0xF0F0_F0F0_F0F0_F0F0; if m > 0 { n = m; b += 4; } m = n & 0xCCCC_CCCC_CCCC_CCCC; if m > 0 { n = m; b += 2; } m = n & 0xAAAA_AAAA_AAAA_AAAA; if m > 0 { b += 1; } b } pub struct BufFormatter<'a> { buf: &'a mut [u8], pos: usize, } impl BufFormatter<'_> { /// # Safety /// 调用者保证buf指针有效,长度至少为len pub unsafe fn new(buf: *mut u8, len: usize) -> Self { Self { buf: core::slice::from_raw_parts_mut(buf, len), pos: 0, } } } impl Formatter for BufFormatter<'_> { fn write_buf(&mut self, buf: &[u8]) -> usize { let len = buf.len().min(self.buf.len() - self.pos); self.buf[self.pos..self.pos + len].copy_from_slice(&buf[..len]); self.pos += len; buf.len() } fn new(_fd: i32) -> Self { Self { buf: &mut [], pos: 0, } } } pub use hifmt_macros::nolibc_bprint as bprint; pub use hifmt_macros::nolibc_cbprint as cbprint; pub use hifmt_macros::nolibc_ceprint as ceprint; pub use hifmt_macros::nolibc_ceprintln as ceprintln; pub use hifmt_macros::nolibc_cprint as cprint; pub use hifmt_macros::nolibc_cprintln as cprintln; pub use hifmt_macros::nolibc_csprint as csprint; pub use hifmt_macros::nolibc_eprint as eprint; pub use hifmt_macros::nolibc_eprintln as eprintln; pub use hifmt_macros::nolibc_print as print; pub use hifmt_macros::nolibc_println as println; pub use hifmt_macros::nolibc_sprint as sprint; #[cfg(test)] mod test { use super::*; extern crate std; use std::*; fn datas() -> &'static [f64] { &[ -2.25123f64, 7.534678f64, -2.2578888e-5f64, 7.5000789e10f64, -7.534000123e200f64, 10.300099911e256, 10.3000789e-100, -0.0, f64::MIN, f64::MAX, ] } #[test] fn test_f64() { let f = 1.5f64; let (sign, denormal, fract, exp) = f64_decode(f); assert_eq!(fract, 0.5f64); assert_eq!(exp, 0); assert_eq!(sign, false); assert_eq!(denormal, false); let mut buf = [0_u8; 24]; for f in datas() { let s = f64_buf(*f, &mut buf); let s = core::str::from_utf8(s).unwrap(); let (sign, denormal, fract, exp) = f64_decode(*f); let mut nf = if denormal { fract } else { 1.0 + fract }; nf = nf * 2_f64.powf(exp as f64); if sign { nf = -nf; } std::println!("{f}, {nf} {s}"); assert_eq!(*f, nf); } } }
2301_79799776/hifmt
src/nolibc.rs
Rust
apache-2.0
8,695
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <link rel="stylesheet" href="./main.css"> </head> <body> <h1>Coffee Order</h1> <ul id="orders"> <!-- <li class="order" id="1"> <p> Name: <span class="name">John</span> <input type="text" class="name nonedit"> </p> <p> Drink: <span class="drink">Coffee</span> <input type="text" class="drink nonedit"> </p> <button data-id="1" class="delete-order">Delete</button> <button class="edit-order">Edit</button> <button class="save-edit nonedit">Save</button> <button class="cancel-edit nonedit">Cancel</button> </li> <li class="order" id="2"> <p> Name: <span class="name">Emily</span> <input type="text" class="name nonedit"> </p> <p> Drink: <span class="drink">Mocha</span> <input type="text" class="drink nonedit"> </p> <button data-id="2" class="delete-order">Delete</button> <button class="edit-order">Edit</button> <button class="save-edit nonedit">Save</button> <button class="cancel-edit nonedit">Cancel</button> </li> --> </ul> <h4>Add a Coffee Order</h4> <p>name: <input type="text" id="name"></p> <p>drink: <input type="text" id="drink"></p> <button id="add-order">Add!</button> <script src="./jquery-3.5.1.js"></script> <script src="./script.js"></script> </body> </html>
2301_79534346/JIT-Cangjie-examples
songqvlv/CoffeeOrder/src/public/index.html
HTML
apache-2.0
1,811
* { padding: 0; margin: 10px; } #orders { list-style-type: none; margin: 0; } #orders .order { background-color: #c4c4c4; padding: 5px; } #orders .nonedit { display: none; } #orders .edit { display: none; } button { padding: 5px 10px; }
2301_79534346/JIT-Cangjie-examples
songqvlv/CoffeeOrder/src/public/main.css
CSS
apache-2.0
277
$(function () { let $name = $('#name') let $drink = $('#drink') let $orders = $('#orders') function addOrder(order) { $orders.append(`<li class="order" id="${order.id}"> <p> Name: <span class="name">${order.name}</span> <input type="text" class="name nonedit"> </p> <p> Drink: <span class="drink">${order.drink}</span> <input type="text" class="drink nonedit"> </p> <!--<button data-id="${order.id}" class="delete-order">Delete</button> <button data-id="${order.id}" class="edit-order">Edit</button> <button data-id="${order.id}" class="save-edit nonedit">Save</button> <button data-id="${order.id}" class="cancel-edit nonedit">Cancel</button>--> </li>`) } $.ajax({ url: '/orders', type: 'GET', dataType: 'json', success: function (data) { console.log(data) //let orders = JSON.parse(data)这里的data已经是js对象了,而且是个对象数组 $.each(data, function (index, order) { addOrder(order) }) }, error: function () { alert('error in GET') } }) $('#add-order').on('click', function () { if($name.val() === '' || $drink.val() === ''){ alert('Please input name and drink') return } $.ajax({ url: '/orders', type: 'POST', dataType: 'json', //服务器返回的数据类型 contentType: 'application/json', //发送的数据类型 data: JSON.stringify({ name: $name.val(), drink: $drink.val() }), success: function (data) { console.log(data) addOrder(data) }, error: function () { alert('error in POST') } }) //清空输入框 $name.val('') $drink.val('') }) /* $orders.delegate('.delete-order', 'click', function () { $li = $(this).closest('.order') $.ajax({ url: `/orders/${$li.attr('id')}`, type: 'DELETE', success: function () { $li.slideUp(300, function () { $li.remove() // 从DOM中移除元素,slideUp()不会移除而是添加了display:none }) }, error: function () { alert('error in DELETE') } }) }) $orders.delegate('.edit-order', 'click', function () { $li = $(this).closest('.order') $li.find('input.name').val($li.find('span.name').text()) $li.find('input.drink').val($li.find('span.drink').text()) $li.find('span,.edit-order').addClass('edit') $li.find('.nonedit').removeClass('nonedit') }) $orders.delegate('.cancel-edit', 'click', function () { $li = $(this).closest('.order') $li.find('span,.edit-order').removeClass('edit') $li.find('input,.save-edit,.cancel-edit').addClass('nonedit') }) $orders.delegate('.save-edit', 'click', function () { $li = $(this).closest('.order') $.ajax({ url: `/orders/${$li.attr('id')}`, type: 'PUT', dataType: 'json', contentType: 'application/json', data: JSON.stringify({ name: $li.find('input.name').val(), drink: $li.find('input.drink').val() }), success: function () { $li.find('span.name').text($li.find('input.name').val()) $li.find('span.drink').text($li.find('input.drink').val()) $li.find('span,.edit-order').removeClass('edit') $li.find('input,.save-edit,.cancel-edit').addClass('nonedit') }, error: function () { alert('error in PUT') } }) })*/ })
2301_79534346/JIT-Cangjie-examples
songqvlv/CoffeeOrder/src/public/script.js
JavaScript
apache-2.0
4,073
""" ASGI config for hunan_web project. It exposes the ASGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/4.0/howto/deployment/asgi/ """ import os from django.core.asgi import get_asgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'hunan_web.settings') application = get_asgi_application()
2301_78696cqk/Django_pyecharts_scrapy
scenery_spider_web-main/hunan_web/asgi.py
Python
unknown
396
"""hunan_web URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/4.0/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.urls import include, path 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) """ from django.contrib import admin from django.urls import path from mainapp import views urlpatterns = [ path('admin/', admin.site.urls), path('index/', views.index), path('', views.login), path('login/', views.login), path('register/', views.register), path('page/', views.page), # path('china_map/', views.china_map), # path('pie_goods_weight/', views.pie_goods_weight), # path('pie_goods_count/', views.pie_goods_count), ]
2301_78696cqk/Django_pyecharts_scrapy
scenery_spider_web-main/hunan_web/urls.py
Python
unknown
1,097
""" WSGI config for hunan_web project. It exposes the WSGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/4.0/howto/deployment/wsgi/ """ import os from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'hunan_web.settings') application = get_wsgi_application()
2301_78696cqk/Django_pyecharts_scrapy
scenery_spider_web-main/hunan_web/wsgi.py
Python
unknown
396
import pymysql pymysql.install_as_MySQLdb()
2301_78696cqk/Django_pyecharts_scrapy
scenery_spider_web-main/mainapp/__init__.py
Python
unknown
45
from django.contrib import admin # Register your models here.
2301_78696cqk/Django_pyecharts_scrapy
scenery_spider_web-main/mainapp/admin.py
Python
unknown
63
from django.apps import AppConfig class MainappConfig(AppConfig): default_auto_field = 'django.db.models.BigAutoField' name = 'mainapp'
2301_78696cqk/Django_pyecharts_scrapy
scenery_spider_web-main/mainapp/apps.py
Python
unknown
146
from django.shortcuts import render, redirect from django.utils.deprecation import MiddlewareMixin class UserAuth(MiddlewareMixin): def process_request(self, request): # print(request.path_info) if request.path_info in ["/login/", "/register/", "/login.html", "/", '/img/code/', '/index/login.html']: return user_info = request.session.get("user_info") if user_info: return return redirect("/login")
2301_78696cqk/Django_pyecharts_scrapy
scenery_spider_web-main/mainapp/middleware/auth.py
Python
unknown
471
from django.db import models # Create your models here. class Userinfo(models.Model): id = models.BigAutoField(primary_key=True) username = models.CharField(max_length=32) password = models.CharField(max_length=64) class Evaluate(models.Model): eid = models.AutoField(primary_key=True) content = models.TextField(blank=True, null=True) send_time = models.DateField(blank=True, null=True) user_name = models.CharField(max_length=32, blank=True, null=True) score = models.IntegerField(blank=True, null=True) scenery_name = models.CharField(max_length=32, blank=True, null=True) class Scenery(models.Model): sid = models.AutoField(primary_key=True) city = models.CharField(max_length=64, blank=True, null=True) people_percent = models.CharField(max_length=32, blank=True, null=True) play_time = models.CharField(max_length=64, blank=True, null=True) rank = models.IntegerField(blank=True, null=True) scenery_name = models.CharField(max_length=64, blank=True, null=True) score = models.FloatField(blank=True, null=True) evaluates = models.ManyToManyField(Evaluate) class xian_poi(models.Model): name = models.CharField(max_length=255) lng = models.DecimalField(max_digits=10, decimal_places=6) lat = models.DecimalField(max_digits=10, decimal_places=6) address = models.TextField() province = models.CharField(max_length=100) city = models.CharField(max_length=100) area = models.CharField(max_length=100) # 区县字段 street_id = models.CharField(max_length=100, blank=True, null=True) telephone = models.CharField(max_length=100, blank=True, null=True) detail = models.IntegerField() uid = models.CharField(max_length=100) tag = models.TextField(blank=True, null=True) type = models.CharField(max_length=100) overall_rating = models.FloatField(blank=True, null=True) comment_num = models.IntegerField(blank=True, null=True) query_category = models.CharField(max_length=50) poi_category = models.CharField(max_length=50) created_at = models.DateTimeField()
2301_78696cqk/Django_pyecharts_scrapy
scenery_spider_web-main/mainapp/models.py
Python
unknown
2,106
*{ margin: 0; padding: 0; font-family: PingFangSC-Light, 微软雅黑; } body,html{ width: 100%; height: auto; color:#333; /* overflow: hidden;*/ background: url('../img/true.png') no-repeat; background-size: 100% 100%; } /*各浏览器显示不同,去掉蓝色边框*/ fieldset, img, input, button { border: none; padding: 0; margin: 0; outline-style: none; } img { border: 0; vertical-align: middle; } ul, li { list-style: none; } a { text-decoration: none; cursor: pointer; } /*清除浮动*/ .clear-both:before, .clear-both:after { display: table; content: ""; -webkit-box-sizing: border-box; -moz-box-sizing: border-box; box-sizing: border-box; clear: both; } .clearfix { *zoom: 1; /*IE/7/6*/ } .fl{ float: left; } .fr{ float: right; } /*header开始*/ .header{ width: 100%; height: 80px; padding:0 20px; min-width: 1366px; } .bg_header{ width: 100%; height: 80px; background: url(../img/title.png) no-repeat; background-size: 100% 100%; } .header>.header_logo{ padding:18px 10px 10px 0px; } .header>.header_logo>a{ display: block; } .header>.header_logo>a>img{ width:260px; } .header>.header_nav{ margin-left: 20px; } .header>.header_nav>ul>li{ float: left; margin-right: 6px; position: relative; } .header>.header_nav>ul>li>a{ display: block; height: 80px; padding:0 10px 0 30px; line-height: 80px; color:#fff; } .header>.header_nav>ul>li>a:hover{ border-bottom: 4px solid #4b8df8; } .header>.header_nav>ul>li>img{ float: left; position: absolute; top: 33px; left:10px; } .header>.header_nav>ul>li>a.nav_current{ border-bottom: 4px solid #4b8df8; } .header>.header_myself{ width: 90px; text-align: center; } .header>.header_myself>p{ color:#fff; font-size: 13px; margin-top: 15px; } .header>.header_myself>a{ color:#fff; font-size: 13px; } /*content 开始*/ .content{ margin: 20px; width: calc(100% - 40px); min-width: 1366px; } .content>.content_title{ width: 100%; height: 35px; line-height: 35px; background-color: #4b8df8; box-sizing: border-box; margin-bottom: 20px; } .content>.content_title>p{ color:#fff; font-size: 16px; font-weight: 600; } .content>.content_title>img{ margin: 10px 10px 0px 10px; } .content>.content_main{ min-width: 1366px; } .content>.content_main>.content_search>div{ margin-right: 25px; } .content>.content_main>.content_search>div>label{ width: 80px; text-align: right; } .content>.content_main>.content_search>div>select, .content>.content_main>.content_search>div>input { width: 200px; } .content>.content_main>.content_table{ margin-top: 30px; } .content>.content_main>.content_table>table{ margin-top: 15px; } .content>.content_main>.content_table>table th:nth-child(1), .content>.content_main>.content_table>table td:nth-child(1){ width: 50px; text-align: center; } .content>.content_main>.content_page>span { font-size: 12.8px; margin-top: 7px; } .content>.content_main>.content_page>select{ width: 70px; margin-right: 10px; } /*content 结束*/
2301_78696cqk/Django_pyecharts_scrapy
scenery_spider_web-main/mainapp/static/css/base.css
CSS
unknown
3,243
.datepicker { display: none; position: absolute; padding: 4px; margin-top: 1px; direction: ltr; } .datepicker.dropdown-menu { position: absolute; top: 100%; left: 0; z-index: 1000; float: left; display: none; min-width: 160px; list-style: none; background-color: #fff; border: 1px solid rgba(0, 0, 0, 0.2); -webkit-border-radius: 5px; -moz-border-radius: 5px; border-radius: 5px; -webkit-box-shadow: 0 5px 10px rgba(0, 0, 0, 0.2); -moz-box-shadow: 0 5px 10px rgba(0, 0, 0, 0.2); box-shadow: 0 5px 10px rgba(0, 0, 0, 0.2); -webkit-background-clip: padding-box; -moz-background-clip: padding; background-clip: padding-box; *border-right-width: 2px; *border-bottom-width: 2px; color: #333; font-size: 13px; line-height: 18px; } .datepicker.dropdown-menu th { padding: 4px 5px; } .datepicker.dropdown-menu td { padding: 4px 5px; } .datepicker table { border: 0; margin: 0; width: auto; } .datepicker table tr td span { display: block; width: 23%; height: 54px; line-height: 54px; float: left; margin: 1%; cursor: pointer; } .datepicker td { text-align: center; width: 20px; height: 20px; border: 0; font-size: 12px; padding: 4px 8px; background: #fff; cursor: pointer; } .datepicker td.active.day, .datepicker td.active.year { background: #2ba6cb; } .datepicker td.old, .datepicker td.new { color: #999; } .datepicker td span.active { background: #2ba6cb; } .datepicker td.day.disabled { color: #eee; } .datepicker th { text-align: center; width: 20px; height: 20px; border: 0; font-size: 12px; padding: 4px 8px; background: #fff; cursor: pointer; } .datepicker th.active.day, .datepicker th.active.year { background: #2ba6cb; } .datepicker th.date-switch { width: 145px; } .datepicker th span.active { background: #2ba6cb; } .datepicker .cw { font-size: 10px; width: 12px; padding: 0 2px 0 5px; vertical-align: middle; } .datepicker.days div.datepicker-days { display: block; } .datepicker.months div.datepicker-months { display: block; } .datepicker.years div.datepicker-years { display: block; } .datepicker thead tr:first-child th { cursor: pointer; } .datepicker thead tr:first-child th.cw { cursor: default; background-color: transparent; } .datepicker tfoot tr:first-child th { cursor: pointer; } .datepicker-inline { width: 220px; } .datepicker-rtl { direction: rtl; } .datepicker-rtl table tr td span { float: right; } .datepicker-dropdown { top: 0; left: 0; } .datepicker-dropdown:before { content: ''; display: inline-block; border-left: 7px solid transparent; border-right: 7px solid transparent; border-bottom: 7px solid #ccc; border-bottom-color: 1px solid rgba(0, 0, 0, 0.2); position: absolute; top: -7px; left: 6px; } .datepicker-dropdown:after { content: ''; display: inline-block; border-left: 6px solid transparent; border-right: 6px solid transparent; border-bottom: 6px solid #fff; position: absolute; top: -6px; left: 7px; } .datepicker > div, .datepicker-dropdown::before, .datepicker-dropdown::after { display: none; } .datepicker-close { position: absolute; top: -30px; right: 0; width: 15px; height: 30px; padding: 0; display: none; } .table-striped .datepicker table tr td, .table-striped .datepicker table tr th { background-color: transparent; }
2301_78696cqk/Django_pyecharts_scrapy
scenery_spider_web-main/mainapp/static/css/datepicker.css
CSS
unknown
3,672
.data_content{ /*overflow-x: hidden;*/ min-width: 1366px; padding-top: 20px; padding-bottom: 20px; } .data_content .data_time{ width: 480px; height: 35px; background-color: #2C58A6; line-height: 35px; color: #fff; font-size: 12.8px; position: relative; margin-bottom: 25px; margin-left: 20px; text-align: center; } .data_content .data_time img{ position: absolute; top: 8px; left: 15px; } .data_content .data_info{ width: calc(100% - 40px); margin-bottom: 40px; height: 110px; margin-left: 20px; } .data_content .data_info .info_1{ width: 40%; height: 110px; } .data_content .data_info .info_1>.text_1{ width: calc(100% - 25px); background-color: #034c6a; height: 110px; } .data_content .data_info .info_2{ width: 31%; height: 110px; } .data_content .data_info .info_2>.text_2{ width: calc(100% - 25px); background-color: #034c6a; height: 110px; } .data_content .data_info .info_3{ width: 29%; height: 110px; } .data_content .data_info .info_3>.text_3{ width:100%; background-color: #034c6a; height: 110px; } .data_content .data_info>div.info_1>.text_1>div{ width: 33.333%; position: relative; } .data_content .data_info>div.info_2>div>div, .data_content .data_info>div.info_3>div>div{ width: 50%; position: relative; } .data_content .data_info img{ position: absolute; top: 35px; left: 15px; } .data_content .data_info>div>div>div>div{ margin-left:65px; margin-top: 23px; } .data_content .data_info>div.info_2>div>div>div{ margin-left: 70px; margin-top: 23px; } .data_content .data_info p:nth-child(1){ color:#fff; font-size: 12.8px; } .data_content .data_info p:nth-child(2){ font-weight: 600; font-size: 28px; color:#ffff43; } .data_content .data_info>div.info_2 p:nth-child(2){ font-weight: 600; font-size: 28px; color:#25f3e6; } .data_content .data_info>div.info_3 p:nth-child(2){ font-weight: 600; font-size: 28px; color:#ff4e4e; } .data_content .data_main{ width: calc(100% - 40px); margin-bottom: 40px; height: 615px; margin-left: 20px; } .data_content .data_main .main_left{ width: 24%; } .data_content .data_main .main_left>div{ width: 100%; height: 280px; box-sizing: border-box; border: 1px solid #2C58A6; position: relative; box-shadow: 0 0 10px #2C58A6; } .data_content .data_main .main_left div.left_1{ /*background: url("../img/chart_1.png") no-repeat center;*/ } .data_content .data_main .main_left div.left_2{ /*background: url("../img/chart_2.png") no-repeat center;*/ } .data_content .data_main .main_left div:nth-child(1){ margin-bottom: 50px; } .data_content .data_main .main_left div .main_title{ width: 180px; height: 35px; line-height: 33px; background-color: #2C58A6; border-radius: 18px; position: absolute; top: -17px; left:50%; margin-left: -90px; color:#fff; font-size: 18px; font-weight: 600; box-sizing: border-box; padding-left: 45px; z-index: 1000; } .data_content .data_main .main_left div .main_title img{ position: absolute; top: 8px; left: 20px; } .data_content .data_main .main_center{ width: 52%; height: 610px; } .data_content .data_main .main_center .center_text{ width: calc(100% - 50px); height: 610px; margin-left: 25px; margin-right: 25px; box-sizing: border-box; border: 1px solid #2C58A6; box-shadow: 0px 0px 6px #2C58A6; position: relative; } .l_t_line{ width: 5px; height: 24px; left: -3px; top: -3px; } .t_l_line{ height: 5px; width: 26px; left: -3px; top: -3px; } .t_line_box { position: absolute; width: 100%; height: 100%; } .t_line_box i{ background-color: #4788fb; box-shadow: 0px 0px 10px #4788fb; position: absolute; } .t_r_line{ height: 5px; width: 26px; right: -3px; top: -3px; } .r_t_line{ width: 5px; height: 24px; right: -3px; top: -3px; } .l_b_line{ width: 5px; height: 24px; left: -3px; bottom: -3px; } .b_l_line{ height: 5px; width: 26px; left: -3px; bottom: -3px; } .r_b_line{ width: 5px; height: 24px; right: -3px; bottom: -3px; } .b_r_line{ height: 5px; width: 26px; right: -3px; bottom: -3px; } .data_content .data_main .main_center .main_title{ display: flex; justify-content: center; width: 200px; height: 35px; line-height: 33px; background-color: #2C58A6; border-radius: 18px; position: absolute; top: -17px; left:50%; margin-left: -90px; color:#fff; font-size: 18px; font-weight: 600; box-sizing: border-box; padding-left: 45px; z-index: 1000; } .data_content .data_main .main_center .main_title img{ position: absolute; top: 8px; left: 20px; } .data_content .data_main .main_right{ width: 24%; } .data_content .data_main .main_right>div{ width: 100%; height: 280px; box-sizing: border-box; border: 1px solid #2C58A6; position: relative; box-shadow: 0 0 10px #2C58A6; } .data_content .data_main .main_right div.right_1 .choice{ position: absolute; top: 25px; right: 30px; z-index: 1000; } .data_content .data_main .main_right div.right_1 .choice label{ color:#fff; } .data_content .data_main .main_right div.right_2{ /*background: url("../img/chart_4.png") no-repeat center;*/ } .data_content .data_main .main_right div.right_2 .chart_text { width: 18%; color:#fff; text-align: center; margin-top: 12px; } .data_content .data_main .main_right div.right_2 .chart_text p{ margin-top: 21px; } .data_content .data_main .main_right div.right_2 .chart_text p img{ margin-right: 5px; margin-top: -4px; } .data_content .data_main .main_right div.right_2 .chart_text p:nth-child(1){ font-size: 14px; font-weight: 600; } .data_content .data_main .main_right div.right_2 .text_sum{ text-align: center; color:#ffff43; font-weight: 600; } .data_content .data_main .main_right div.right_2 .text_sum div:nth-child(2){ font-size: 18px; font-weight: 600; } .data_content .data_main .main_right div:nth-child(1){ margin-bottom: 50px; } .data_content .data_main .main_right div .main_title{ width: 180px; height: 35px; line-height: 33px; background-color: #2C58A6; border-radius: 18px; position: absolute; top: -17px; left:50%; margin-left: -90px; color:#fff; font-size: 18px; font-weight: 600; box-sizing: border-box; padding-left: 45px; } .data_content .data_main .main_right div .main_title img{ position: absolute; top: 8px; left: 20px; } .data_content .data_bottom{ width: calc(100% - 40px); height: 280px; margin-left: 20px; } .data_content .data_bottom div{ } .data_content .data_bottom .bottom_1{ width: 24%; height: 280px; position: relative; box-sizing: border-box; border: 1px solid #2C58A6; box-shadow: 0 0 10px #2C58A6; } .data_content .data_bottom .bottom_center{ width: 52%; height: 280px; } .data_content .data_bottom .bottom_2{ width: calc(100% - 45px); height: 280px; position: relative; box-sizing: border-box; border: 1px solid #2C58A6; margin-left: 25px; box-shadow: 0 0 10px #2C58A6; } .data_content .data_bottom .bottom_3{ width: calc(50% - 40px); height: 280px; position: relative; box-sizing: border-box; border: 1px solid #2C58A6; margin-left:25px; box-shadow: 0 0 10px #2C58A6; } .data_content .data_bottom .bottom_4{ width: 24%; height: 280px; position: relative; box-sizing: border-box; border: 1px solid #2C58A6; box-shadow: 0 0 10px #2C58A6; } .data_content .data_bottom div .main_title{ width: 220px; height: 35px; line-height: 33px; background-color: #2C58A6; border-radius: 18px; position: absolute; top: -17px; left:50%; margin-left: -110px; color:#fff; font-size: 18px; font-weight: 600; box-sizing: border-box; padding-left: 45px; } .data_content .data_bottom div .main_title img{ position: absolute; top: 8px; left: 20px; } .table_div{ height: 278px; overflow-y: scroll; overflow-x: scroll; } .main_table tr{ height: 42px; } div#chart_1,div#chart_3 { overflow-y: scroll; height: 250px !important; } div#chart_1::-webkit-scrollbar, div#chart_3::-webkit-scrollbar{ background-color: #002c51; border-radius: 50px; } div#chart_1::-webkit-scrollbar-thumb, div#chart_3::-webkit-scrollbar-thumb{ background-color: #003f76; border-radius: 50px; } .main_table{ width: 100%; margin-top: 25px; } .main_table table{ width: 100%; } .main_table thead tr{ height: 42px; } .main_table th{ font-size: 12px; font-weight: 600; color:#61d2f7; text-align: center; } .main_table th:nth-child(1){ } .main_table th:nth-child(2){ } .main_table td{ color:#fff; font-size: 10px; text-align: center; } .main_table tbody tr:nth-child(odd){ background-color: #072951; box-shadow:-10px 0px 15px #2C58A6 inset, /*左边阴影*/ 10px 0px 15px #2C58A6 inset; /*右边阴影*/ } .t_btn8,.t_btn2,.t_btn3{ position: relative; z-index: 100; cursor: pointer; }
2301_78696cqk/Django_pyecharts_scrapy
scenery_spider_web-main/mainapp/static/css/index.css
CSS
unknown
9,449
html,body{ width: 100%; height: 100%; background: url('../img/true.png') no-repeat; } .data_content{ /*overflow-x: hidden;*/ min-width: 1366px; background-size: 100% 100%; padding-top: 20px; padding-bottom: 20px; height: 91.8%; } .data_content .data_time{ width: 130px; height: 35px; background-color: #04425f; line-height: 35px; color:#fff; font-size: 12.8px; position: relative; padding-left: 45px; margin-bottom: 25px; margin-left: 20px; } .data_content .data_time img{ position: absolute; top: 8px; left: 15px; } .l_t_line{ width: 5px; height: 24px; left: -3px; top: -3px; } .t_l_line{ height: 5px; width: 26px; left: -3px; top: -3px; } .t_line_box { position: absolute; width: 100%; height: 100%; } .t_line_box i{ background-color: #4788fb; box-shadow: 0px 0px 10px #4788fb; position: absolute; } .t_r_line{ height: 5px; width: 26px; right: -3px; top: -3px; } .t_title { width: 100%; height: 100%; text-align: center; font-size: 2.5em; line-height: 80px; color: #fff; } .r_t_line{ width: 5px; height: 24px; right: -3px; top: -3px; } .l_b_line{ width: 5px; height: 24px; left: -3px; bottom: -3px; } .b_l_line{ height: 5px; width: 26px; left: -3px; bottom: -3px; } .r_b_line{ width: 5px; height: 24px; right: -3px; bottom: -3px; } .b_r_line{ height: 5px; width: 26px; right: -3px; bottom: -3px; } .data_content .data_info{ width: calc(100% - 40px); margin-bottom: 40px; height: 110px; margin-left: 20px; } .data_content .data_info .info_1{ width: 40%; height: 110px; } .data_content .data_info .info_1>.text_1{ width: calc(100% - 25px); background-color: #034c6a; height: 110px; } .data_content .data_info .info_2{ width: 31%; height: 110px; } .data_content .data_info .info_2>.text_2{ width: calc(100% - 25px); background-color: #034c6a; height: 110px; } .data_content .data_info .info_3{ width: 29%; height: 110px; } .data_content .data_info .info_3>.text_3{ width:100%; background-color: #034c6a; height: 110px; } .data_content .data_info>div.info_1>.text_1>div{ width: 33.333%; position: relative; } .data_content .data_info>div.info_2>div>div, .data_content .data_info>div.info_3>div>div{ width: 50%; position: relative; } .data_content .data_info img{ position: absolute; top: 35px; left: 15px; } .data_content .data_info>div>div>div>div{ margin-left:65px; margin-top: 23px; } .data_content .data_info>div.info_2>div>div>div{ margin-left: 70px; margin-top: 23px; } .data_content .data_info p:nth-child(1){ color:#fff; font-size: 12.8px; } .data_content .data_info p:nth-child(2){ font-weight: 600; font-size: 28px; color:#ffff43; } .data_content .data_info>div.info_2 p:nth-child(2){ font-weight: 600; font-size: 28px; color:#25f3e6; } .data_content .data_info>div.info_3 p:nth-child(2){ font-weight: 600; font-size: 28px; color:#ff4e4e; } .data_content .data_main{ width: calc(100% - 40px); margin-bottom: 40px; height: 774px; margin-left: 20px; margin-top: 20px; } .data_content .data_main .main_left{ width: 24%; } .data_content .data_main .main_left>div{ width: 100%; height: 780px; position: relative; } .data_content .data_main .main_left div.left_1{ /*background: url("../img/chart_1.png") no-repeat center;*/ } .data_content .data_main .main_left div.left_2{ /*background: url("../img/chart_2.png") no-repeat center;*/ } .data_content .data_main .main_left div .main_title{ width: 180px; height: 35px; line-height: 33px; background-color: #034c6a; border-radius: 18px; position: absolute; top: -17px; left:50%; margin-left: -90px; color:#fff; font-size: 18px; font-weight: 600; box-sizing: border-box; padding-left: 45px; z-index: 1000; } .data_content .data_main .main_left div .main_title img{ position: absolute; top: 8px; left: 20px; } .data_content .data_main .main_center{ width: 76%; height: 796px; } .data_content .data_main .main_center .center_text{ width: calc(100% - 50px); height: 780px; margin-left: 25px; margin-right: 25px; box-sizing: border-box; border: 1px solid #2C58A6; border-radius: 2px; position: relative; } .data_content .data_main .main_center .main_title{ width: 180px; height: 35px; line-height: 33px; background-color: #2C58A6; border-radius: 2px; position: absolute; top: -17px; left: 50%; margin-left: -90px; color: #fff; font-size: 18px; font-weight: 600; box-sizing: border-box; z-index: 1000; text-align: center; } .data_content .data_main .main_center .main_title img{ position: absolute; top: 8px; left: 20px; } .data_content .data_main .main_right{ width: 24%; } .data_content .data_main .main_right>div{ width: 100%; height: 280px; box-sizing: border-box; border: 1px solid #034c6a; box-shadow:-10px 0px 15px #034c6a inset, /*左边阴影*/ 0px -10px 15px #034c6a inset, /*上边阴影*/ 10px 0px 15px #034c6a inset, /*右边阴影*/ 0px 10px 15px #034c6a inset; position: relative; } .data_content .data_main .main_right div.right_1 .choice{ position: absolute; top: 25px; right: 30px; z-index: 1000; } .data_content .data_main .main_right div.right_1 .choice label{ color:#fff; } .data_content .data_main .main_right div.right_2{ /*background: url("../img/chart_4.png") no-repeat center;*/ } .data_content .data_main .main_right div.right_2 .chart_text { width: 18%; color:#fff; text-align: center; margin-top: 12px; } .data_content .data_main .main_right div.right_2 .chart_text p{ margin-top: 21px; } .data_content .data_main .main_right div.right_2 .chart_text p img{ margin-right: 5px; margin-top: -4px; } .data_content .data_main .main_right div.right_2 .chart_text p:nth-child(1){ font-size: 14px; font-weight: 600; } .data_content .data_main .main_right div.right_2 .text_sum{ text-align: center; color:#ffff43; font-weight: 600; } .data_content .data_main .main_right div.right_2 .text_sum div:nth-child(2){ font-size: 18px; font-weight: 600; } .data_content .data_main .main_right div:nth-child(1){ margin-bottom: 50px; } .data_content .data_main .main_right div .main_title{ width: 180px; height: 35px; line-height: 33px; background-color: #034c6a; border-radius: 18px; position: absolute; top: -17px; left:50%; margin-left: -90px; color:#fff; font-size: 18px; font-weight: 600; box-sizing: border-box; padding-left: 45px; } .data_content .data_main .main_right div .main_title img{ position: absolute; top: 8px; left: 20px; } .data_content .data_bottom{ width: calc(100% - 40px); height: 280px; margin-left: 20px; } .data_content .data_bottom div{ } .data_content .data_bottom .bottom_1{ width: 24%; height: 280px; box-shadow:-10px 0px 15px #034c6a inset, /*左边阴影*/ 0px -10px 15px #034c6a inset, /*上边阴影*/ 10px 0px 15px #034c6a inset, /*右边阴影*/ 0px 10px 15px #034c6a inset; position: relative; box-sizing: border-box; border: 1px solid #034c6a; /*background: url("../img/chart_5.png") no-repeat;*/ } .data_content .data_bottom .bottom_center{ width: 52%; height: 280px; } .data_content .data_bottom .bottom_2{ width: calc(50% - 35px); height: 280px; box-shadow:-10px 0px 15px #034c6a inset, /*左边阴影*/ 0px -10px 15px #034c6a inset, /*上边阴影*/ 10px 0px 15px #034c6a inset, /*右边阴影*/ 0px 10px 15px #034c6a inset; position: relative; box-sizing: border-box; border: 1px solid #034c6a; margin-left: 25px; /*background: url("../img/chart_6.png") no-repeat;*/ } .data_content .data_bottom .bottom_3{ width: calc(50% - 40px); height: 280px; box-shadow:-10px 0px 15px #034c6a inset, /*左边阴影*/ 0px -10px 15px #034c6a inset, /*上边阴影*/ 10px 0px 15px #034c6a inset, /*右边阴影*/ 0px 10px 15px #034c6a inset; position: relative; box-sizing: border-box; border: 1px solid #034c6a; /*background: url("../img/chart_7.png") no-repeat;*/ margin-left:25px; } .data_content .data_bottom .bottom_4{ width: 24%; height: 280px; box-shadow:-10px 0px 15px #034c6a inset, /*左边阴影*/ 0px -10px 15px #034c6a inset, /*上边阴影*/ 10px 0px 15px #034c6a inset, /*右边阴影*/ 0px 10px 15px #034c6a inset; position: relative; box-sizing: border-box; border: 1px solid #034c6a; /*background: url("../img/chart_8.png") no-repeat;*/ } .data_content .data_bottom div .main_title{ width: 220px; height: 35px; line-height: 33px; background-color: #034c6a; border-radius: 18px; position: absolute; top: -17px; left:50%; margin-left: -110px; color:#fff; font-size: 18px; font-weight: 600; box-sizing: border-box; padding-left: 45px; } .data_content .data_bottom div .main_title img{ position: absolute; top: 8px; left: 20px; } .data_content .data_bottom div .main_table tr{ height: 42px; } .data_content .data_bottom div .main_table{ width: 100%; margin-top: 25px; } .data_content .data_bottom div .main_table table{ width: 100%; } .data_content .data_bottom div .main_table thead tr{ height: 42px; } .data_content .data_bottom div .main_table th{ font-size: 14px; font-weight: 600; color:#61d2f7; text-align: center; } .data_content .data_bottom div .main_table th:nth-child(1){ width: 30%; } .data_content .data_bottom div .main_table th:nth-child(2){ width: 35%; } .data_content .data_bottom div .main_table th:nth-child(2){ width: 35%; } .data_content .data_bottom div .main_table td{ color:#fff; font-size: 12.8px; text-align: center; } .data_content .data_bottom div .main_table tbody tr:nth-child(1), .data_content .data_bottom div .main_table tbody tr:nth-child(3), .data_content .data_bottom div .main_table tbody tr:nth-child(5){ background-color: #072951; box-shadow:-10px 0px 15px #034c6a inset, /*左边阴影*/ 10px 0px 15px #034c6a inset; /*右边阴影*/ /*0px 10px 15px #034c6a inset;*/ }
2301_78696cqk/Django_pyecharts_scrapy
scenery_spider_web-main/mainapp/static/css/style.css
CSS
unknown
10,622
$(function () { echart_map(); //echart_1湖南各市货运量 function echart_1() { // 基于准备好的dom,初始化echarts实例 var myChart = echarts.init(document.getElementById('chart_1')); myChart.clear(); option = { tooltip: { trigger: 'item', formatter: "{a} <br/>{b} : {c}万元" }, legend: { x: 'center', y: '15%', data: ['长沙', '株洲', '湘潭', '衡阳', '邵阳', '岳阳', '常德', '张家界', '益阳', '郴州', '永州', '娄底', '怀化', '湘西'], icon: 'circle', textStyle: { color: '#fff', } }, calculable: true, series: [{ name: '', type: 'pie', //起始角度,支持范围[0, 360] startAngle: 0, //饼图的半径,数组的第一项是内半径,第二项是外半径 radius: [41, 280.75], //支持设置成百分比,设置成百分比时第一项是相对于容器宽度,第二项是相对于容器高度 center: ['50%', '40%'], //是否展示成南丁格尔图,通过半径区分数据大小。可选择两种模式: // 'radius' 面积展现数据的百分比,半径展现数据的大小。 // 'area' 所有扇区面积相同,仅通过半径展现数据大小 roseType: 'area', //是否启用防止标签重叠策略,默认开启,圆环图这个例子中需要强制所有标签放在中心位置,可以将该值设为 false。 avoidLabelOverlap: false, label: { normal: { show: true, formatter: '{c}万元' }, emphasis: { show: true } }, labelLine: { normal: { show: true, length2: 1, }, emphasis: { show: true } }, data: [{ value: 900.58, name: '怀化', itemStyle: { normal: { color: '#f845f1' } } }, { value: 1100.58, name: '永州', itemStyle: { normal: { color: '#ad46f3' } } }, { value: 1200.58, name: '张家界', itemStyle: { normal: { color: '#5045f6' } } }, { value: 1300.58, name: '邵阳', itemStyle: { normal: { color: '#4777f5' } } }, { value: 1400.58, name: '常德', itemStyle: { normal: { color: '#44aff0' } } }, { value: 1500.58, name: '岳阳', itemStyle: { normal: { color: '#45dbf7' } } }, { value: 1500.58, name: '湘潭', itemStyle: { normal: { color: '#f6d54a' } } }, { value: 1600.58, name: '株洲', itemStyle: { normal: { color: '#f69846' } } }, { value: 1800, name: '长沙', itemStyle: { normal: { color: '#ff4343' } } }, { value: 0, name: "", itemStyle: { normal: { color: '#transparent' } }, label: { show: false }, labelLine: { show: false } }, { value: 0, name: "", itemStyle: { normal: { color: 'transparent' } }, label: { show: false }, labelLine: { show: false } }, { value: 0, name: "", itemStyle: { normal: { color: 'transparent' } }, label: { show: false }, labelLine: { show: false } }, { value: 0, name: "", itemStyle: { normal: { color: 'transparent' } }, label: { show: false }, labelLine: { show: false } }, { value: 0, name: "", itemStyle: { normal: { color: 'transparent' } }, label: { show: false }, labelLine: { show: false } }, { value: 0, name: "", itemStyle: { normal: { color: 'transparent' } }, label: { show: false }, labelLine: { show: false } }, { value: 0, name: "", itemStyle: { normal: { color: 'transparent' } }, label: { show: false }, labelLine: { show: false } }, { value: 0, name: "", itemStyle: { normal: { color: 'transparent' } }, label: { show: false }, labelLine: { show: false } }, { value: 0, name: "", itemStyle: { normal: { color: 'transparent' } }, label: { show: false }, labelLine: { show: false } } ] }] }; // 使用刚指定的配置项和数据显示图表。 myChart.setOption(option); window.addEventListener("resize", function () { myChart.resize(); }); } //echart_0湖南省飞机场 function echart_0() { // 基于准备好的dom,初始化echarts实例 var myChart = echarts.init(document.getElementById('chart_0')); function showProvince() { var geoCoordMap = { '长沙黄花国际机场': [113.226512,28.192929], '张家界荷花机场': [110.454598,29.107223], '常德桃花源机场': [111.651508,28.921516], '永州零陵机场': [111.622869,26.340994], '怀化芷江机场': [109.714784,27.44615], }; var data = [{ name: '长沙黄花国际机场', value: 100 }, { name: '张家界荷花机场', value: 100 }, { name: '常德桃花源机场', value: 100 }, { name: '永州零陵机场', value: 100 }, { name: '怀化芷江机场', value: 100 } ]; var max = 480, min = 9; // todo var maxSize4Pin = 100, minSize4Pin = 20; var convertData = function (data) { var res = []; for (var i = 0; i < data.length; i++) { var geoCoord = geoCoordMap[data[i].name]; if (geoCoord) { res.push({ name: data[i].name, value: geoCoord.concat(data[i].value) }); } } return res; }; myChart.setOption(option = { title: { top: 20, text: '', subtext: '', x: 'center', textStyle: { color: '#ccc' } }, legend: { orient: 'vertical', y: 'bottom', x: 'right', data: ['pm2.5'], textStyle: { color: '#fff' } }, visualMap: { show: false, min: 0, max: 500, left: 'left', top: 'bottom', text: ['高', '低'], // 文本,默认为数值文本 calculable: true, seriesIndex: [1], inRange: { } }, geo: { show: true, map:'hunan', mapType: 'hunan', label: { normal: { }, //鼠标移入后查看效果 emphasis: { textStyle: { color: '#fff' } } }, //鼠标缩放和平移 roam: true, itemStyle: { normal: { // color: '#ddd', borderColor: 'rgba(147, 235, 248, 1)', borderWidth: 1, areaColor: { type: 'radial', x: 0.5, y: 0.5, r: 0.8, colorStops: [{ offset: 0, color: 'rgba(175,238,238, 0)' // 0% 处的颜色 }, { offset: 1, color: 'rgba( 47,79,79, .2)' // 100% 处的颜色 }], globalCoord: false // 缺省为 false }, shadowColor: 'rgba(128, 217, 248, 1)', shadowOffsetX: -2, shadowOffsetY: 2, shadowBlur: 10 }, emphasis: { areaColor: '#389BB7', borderWidth: 0 } } }, series: [{ name: 'light', type: 'map', coordinateSystem: 'geo', data: convertData(data), itemStyle: { normal: { color: '#F4E925' } } }, { name: '点', type: 'scatter', coordinateSystem: 'geo', symbol: 'pin', symbolSize: function(val) { var a = (maxSize4Pin - minSize4Pin) / (max - min); var b = minSize4Pin - a * min; b = maxSize4Pin - a * max; return a * val[2] + b; }, label: { normal: { // show: true, // textStyle: { // color: '#fff', // fontSize: 9, // } } }, itemStyle: { normal: { color: '#F62157', //标志颜色 } }, zlevel: 6, data: convertData(data), }, { name: 'light', type: 'map', mapType: 'hunan', geoIndex: 0, aspectScale: 0.75, //长宽比 showLegendSymbol: false, // 存在legend时显示 label: { normal: { show: false }, emphasis: { show: false, textStyle: { color: '#fff' } } }, roam: true, itemStyle: { normal: { areaColor: '#031525', borderColor: '#FFFFFF', }, emphasis: { areaColor: '#2B91B7' } }, animation: false, data: data }, { name: ' ', type: 'effectScatter', coordinateSystem: 'geo', data: convertData(data.sort(function (a, b) { return b.value - a.value; }).slice(0, 5)), symbolSize: function (val) { return val[2] / 10; }, showEffectOn: 'render', rippleEffect: { brushType: 'stroke' }, hoverAnimation: true, label: { normal: { formatter: '{b}', position: 'right', show: true } }, itemStyle: { normal: { color: '#05C3F9', shadowBlur: 10, shadowColor: '#05C3F9' } }, zlevel: 1 }, ] }); } showProvince(); // 使用刚指定的配置项和数据显示图表。 // myChart.setOption(option); window.addEventListener("resize", function () { myChart.resize(); }); } //echart_2湖南省高速公路 function echart_2() { // 基于准备好的dom,初始化echarts实例 var myChart = echarts.init(document.getElementById('chart_2')); myChart.setOption({ series: [{ type: 'map', mapType: 'hunan' }] }); var geoCoordMap = { '怀化': [109.999867,27.518949], '吉首': [109.741528,28.332629], '张家界': [110.491722,29.112001], '常德': [111.701486,29.076683], '益阳': [112.348741,28.544124], '岳阳': [113.126486,29.382401], '长沙': [113.019455,28.200103], '株洲': [113.163141,27.8418], '湘潭': [112.91977,27.882141], '邵阳': [111.467859,27.21915], '娄底': [112.012438,27.745506], '衡阳': [112.63809,26.895225], '永州': [111.577632,26.460144], '郴州': [113.039396,25.81497] }; var goData = [ [{ name: '张家界' }, { id: 1, name: '常德', value: 86 }], [{ name: '吉首' }, { id: 1, name: '常德', value: 86 }], [{ name: '常德' }, { id: 1, name: '益阳', value: 70 }], [{ name: '益阳' }, { id: 1, name: '长沙', value: 95 }], [{ name: '长沙' }, { id: 1, name: '岳阳', value: 70 }], [{ name: '长沙' }, { id: 1, name: '湘潭', value: 80 }], [{ name: '长沙' }, { id: 1, name: '株洲', value: 80 }], [{ name: '长沙' }, { id: 1, name: '衡阳', value: 80 }], [{ name: '衡阳' }, { id: 1, name: '郴州', value: 70 }], [{ name: '衡阳' }, { id: 1, name: '永州', value: 70 }], [{ name: '湘潭' }, { id: 1, name: '娄底', value: 60 }], [{ name: '娄底' }, { id: 1, name: '邵阳', value: 75 }], [{ name: '邵阳' }, { id: 1, name: '怀化', value: 75 }], ]; //值控制圆点大小 var backData = [ [{ name: '常德' }, { id: 1, name: '张家界', value: 80 }], [{ name: '常德' }, { id: 1, name: '吉首', value: 66 }], [{ name: '益阳' }, { id: 1, name: '常德', value: 86 }], [{ name: '长沙' }, { id: 1, name: '益阳', value: 70 }], [{ name: '岳阳' }, { id: 1, name: '长沙', value: 95 }], [{ name: '湘潭' }, { id: 1, name: '长沙', value: 95 }], [{ name: '株洲' }, { id: 1, name: '长沙', value: 95 }], [{ name: '衡阳' }, { id: 1, name: '长沙', value: 95 }], [{ name: '郴州' }, { id: 1, name: '衡阳', value: 80 }], [{ name: '永州' }, { id: 1, name: '衡阳', value: 80 }], [{ name: '娄底' }, { id: 1, name: '湘潭', value: 80 }], [{ name: '邵阳' }, { id: 1, name: '娄底', value: 60 }], [{ name: '怀化' }, { id: 1, name: '邵阳', value: 75 }], ]; var planePath = 'path://M1705.06,1318.313v-89.254l-319.9-221.799l0.073-208.063c0.521-84.662-26.629-121.796-63.961-121.491c-37.332-0.305-64.482,36.829-63.961,121.491l0.073,208.063l-319.9,221.799v89.254l330.343-157.288l12.238,241.308l-134.449,92.931l0.531,42.034l175.125-42.917l175.125,42.917l0.531-42.034l-134.449-92.931l12.238-241.308L1705.06,1318.313z'; var arcAngle = function(data) { var j, k; for (var i = 0; i < data.length; i++) { var dataItem = data[i]; if (dataItem[1].id == 1) { j = 0.2; return j; } else if (dataItem[1].id == 2) { k = -0.2; return k; } } } var convertData = function(data) { var res = []; for (var i = 0; i < data.length; i++) { var dataItem = data[i]; var fromCoord = geoCoordMap[dataItem[0].name]; var toCoord = geoCoordMap[dataItem[1].name]; if (dataItem[1].id == 1) { if (fromCoord && toCoord) { res.push([{ coord: fromCoord, }, { coord: toCoord, value: dataItem[1].value //线条颜色 }]); } } else if (dataItem[1].id == 2) { if (fromCoord && toCoord) { res.push([{ coord: fromCoord, }, { coord: toCoord }]); } } } return res; }; var color = ['#fff', '#FF1493', '#0000FF']; var series = []; [ ['1', goData], ['2', backData] ].forEach(function(item, i) { series.push({ name: item[0], type: 'lines', zlevel: 2, symbol: ['arrow', 'arrow'], //线特效配置 effect: { show: true, period: 6, trailLength: 0.1, symbol: 'arrow', //标记类型 symbolSize: 5 }, lineStyle: { normal: { width: 1, opacity: 0.4, curveness: arcAngle(item[1]), //弧线角度 color: '#fff' } }, edgeLabel: { normal: { show: true, textStyle: { fontSize: 14 }, formatter: function(params) { var txt = ''; if (params.data.speed !== undefined) { txt = params.data.speed; } return txt; }, } }, data: convertData(item[1]) }, { type: 'effectScatter', coordinateSystem: 'geo', zlevel: 2, //波纹效果 rippleEffect: { period: 2, brushType: 'stroke', scale: 3 }, label: { normal: { show: true, color: '#fff', position: 'right', formatter: '{b}' } }, //终点形象 symbol: 'circle', //圆点大小 symbolSize: function(val) { return val[2] / 8; }, itemStyle: { normal: { show: true } }, data: item[1].map(function(dataItem) { return { name: dataItem[1].name, value: geoCoordMap[dataItem[1].name].concat([dataItem[1].value]) }; }) }); }); option = { title: { text: '', subtext: '', left: 'center', textStyle: { color: '#fff' } }, tooltip: { trigger: 'item', formatter: '{b}' }, //线颜色及飞行轨道颜色 visualMap: { show: false, min: 0, max: 100, color: ['#31A031','#31A031'] }, //地图相关设置 geo: { map: 'hunan', //视角缩放比例 zoom: 1, //显示文本样式 label: { normal: { show: false, textStyle: { color: '#fff' } }, emphasis: { textStyle: { color: '#fff' } } }, //鼠标缩放和平移 roam: true, itemStyle: { normal: { // color: '#ddd', borderColor: 'rgba(147, 235, 248, 1)', borderWidth: 1, areaColor: { type: 'radial', x: 0.5, y: 0.5, r: 0.8, colorStops: [{ offset: 0, color: 'rgba(175,238,238, 0)' // 0% 处的颜色 }, { offset: 1, color: 'rgba( 47,79,79, .2)' // 100% 处的颜色 }], globalCoord: false // 缺省为 false }, shadowColor: 'rgba(128, 217, 248, 1)', // shadowColor: 'rgba(255, 255, 255, 1)', shadowOffsetX: -2, shadowOffsetY: 2, shadowBlur: 10 }, emphasis: { areaColor: '#389BB7', borderWidth: 0 } } }, series: series }; myChart.setOption(option); } // echart_map中国地图 function echart_map() { // 基于准备好的dom,初始化echarts实例 var myChart = echarts.init(document.getElementById('chart_map')); var mapName = 'china' var data = [] var toolTipData = []; /*获取地图数据*/ myChart.showLoading(); var mapFeatures = echarts.getMap(mapName).geoJson.features; myChart.hideLoading(); var geoCoordMap = { '福州': [119.4543, 25.9222], '长春': [125.8154, 44.2584], '重庆': [107.7539, 30.1904], '西安': [109.1162, 34.2004], '成都': [103.9526, 30.7617], '常州': [119.4543, 31.5582], '北京': [116.4551, 40.2539], '北海': [109.314, 21.6211], '海口': [110.3893, 19.8516], '长沙': [113.019455,28.200103], '上海': [121.40, 31.73], '内蒙古': [106.82, 39.67] }; var GZData = [ [{ name: '长沙' }, { name: '福州', value: 95 }], [{ name: '长沙' }, { name: '长春', value: 80 }], [{ name: '长沙' }, { name: '重庆', value: 70 }], [{ name: '长沙' }, { name: '西安', value: 60 }], [{ name: '长沙' }, { name: '成都', value: 50 }], [{ name: '长沙' }, { name: '常州', value: 40 }], [{ name: '长沙' }, { name: '北京', value: 30 }], [{ name: '长沙' }, { name: '北海', value: 20 }], [{ name: '长沙' }, { name: '海口', value: 10 }], [{ name: '长沙' }, { name: '上海', value: 80 }], [{ name: '长沙' }, { name: '内蒙古', value: 80 }] ]; var convertData = function (data) { var res = []; for (var i = 0; i < data.length; i++) { var dataItem = data[i]; var fromCoord = geoCoordMap[dataItem[0].name]; var toCoord = geoCoordMap[dataItem[1].name]; if (fromCoord && toCoord) { res.push({ fromName: dataItem[0].name, toName: dataItem[1].name, coords: [fromCoord, toCoord] }); } } return res; }; var color = ['#c5f80e']; var series = []; [ ['石家庄', GZData] ].forEach(function (item, i) { series.push({ name: item[0], type: 'lines', zlevel: 2, symbol: ['none', 'arrow'], symbolSize: 10, effect: { show: true, period: 6, trailLength: 0, symbol: 'arrow', symbolSize: 5 }, lineStyle: { normal: { color: color[i], width: 1, opacity: 0.6, curveness: 0.2 } }, data: convertData(item[1]) }, { name: item[0], type: 'effectScatter', coordinateSystem: 'geo', zlevel: 2, rippleEffect: { brushType: 'stroke' }, label: { normal: { show: true, position: 'right', formatter: '{b}' } }, symbolSize: function (val) { return val[2] / 8; }, itemStyle: { normal: { color: color[i] } }, data: item[1].map(function (dataItem) { return { name: dataItem[1].name, value: geoCoordMap[dataItem[1].name].concat([dataItem[1].value]) }; }) }); }); option = { tooltip: { trigger: 'item' }, geo: { map: 'china', label: { emphasis: { show: false } }, roam: true, itemStyle: { normal: { // color: '#ddd', borderColor: 'rgba(147, 235, 248, 1)', borderWidth: 1, areaColor: { type: 'radial', x: 0.5, y: 0.5, r: 0.8, colorStops: [{ offset: 0, color: 'rgba(175,238,238, 0)' // 0% 处的颜色 }, { offset: 1, color: 'rgba( 47,79,79, .1)' // 100% 处的颜色 }], globalCoord: false // 缺省为 false }, shadowColor: 'rgba(128, 217, 248, 1)', // shadowColor: 'rgba(255, 255, 255, 1)', shadowOffsetX: -2, shadowOffsetY: 2, shadowBlur: 10 }, emphasis: { areaColor: '#389BB7', borderWidth: 0 } } }, series: series }; // 使用刚指定的配置项和数据显示图表。 myChart.setOption(option); window.addEventListener("resize", function () { myChart.resize(); }); } //echart_3交通就业人员 function echart_3() { var myChart = echarts.init(document.getElementById('chart_3')); myChart.clear(); option = { title: { text: '' }, tooltip: { trigger: 'axis' }, legend: { data:['铁路运输业','公路运输业','水上运输业','航空运输业','管道运输业','装卸搬运和其他运输服务业','等外公路公路里程'], textStyle:{ color: '#fff' }, top: '4%' }, grid: { left: '3%', right: '4%', bottom: '3%', containLabel: true }, toolbox: { orient: 'vertical', right: '1%', top: '2%', iconStyle: { color: '#FFEA51', borderColor: '#FFA74D', borderWidth: 1, }, feature: { saveAsImage: {}, magicType: { show: true, type: ['line','bar','stack','tiled'] } } }, xAxis: { type: 'category', boundaryGap: false, data: ['2014年','2015年','2016年','2017年','2018年'], splitLine: { show: false }, axisLine: { lineStyle: { color: '#fff' } } }, yAxis: { name: '人', type: 'value', splitLine: { show: false }, axisLine: { lineStyle: { color: '#fff' } } }, color: ['#FF4949','#FFA74D','#FFEA51','#4BF0FF','#44AFF0','#4E82FF','#584BFF','#BE4DFF','#F845F1'], series: [ { name:'铁路运输业', type:'line', data:[57197, 51533, 57000, 58150, 55748] }, { name:'公路运输业', type:'line', data:[148054, 150198, 144943, 138157, 114234] }, { name:'水上运输业', type:'line', data:[27100, 25568, 25734, 24393, 23851] }, { name:'航空运输业', type:'line', data:[1795, 3306, 4151, 5538, 4766] }, { name:'管道运输业', type:'line', data:[1586,567,647,1235,1186] }, { name:'装卸搬运和其他运输服务业', type:'line', data:[4448, 11742, 12706, 10666, 10902] } ] }; myChart.setOption(option); } //中国铁路 function echart_4() { // 基于准备好的dom,初始化echarts图表 var myChart = echarts2.init(document.getElementById('chart_4')); var effect = { show: true, scaleSize: 1, period: 30, // 运动周期,无单位,值越大越慢 color: '#fff', shadowColor: 'rgba(220,220,220,0.4)', shadowBlur: 5 }; function itemStyle(idx) { return { normal: { color: '#fff', borderWidth: 1, borderColor: ['rgba(30,144,255,1)', 'lime'][idx], lineStyle: { //shadowColor : ['rgba(30,144,255,1)','lime'][idx], //默认透明 //shadowBlur: 10, //shadowOffsetX: 0, //shadowOffsetY: 0, type: 'solid' } } } }; option = { color: ['rgba(30,144,255,1)', 'lime'], title: { text: '', subtext: '', sublink: '', x: 'center', textStyle: { color: '#fff' } }, tooltip: { trigger: 'item', formatter: '{b}' }, legend: { orient: 'vertical', x: '2%', y: '3%', selectedMode: 'single', data: ['八纵通道', '八横通道'], textStyle: { color: '#fff' } }, toolbox: { show: true, orient: 'vertical', x: 'right', y: 'center', padding: [0 ,30, 0 ,0], feature: { mark: { show: true }, dataView: { show: true, readOnly: false }, restore: { show: true }, saveAsImage: { show: true } } }, series: [{ name: '八纵通道', type: 'map', roam: true, hoverable: false, mapType: 'china', itemStyle: { normal: { borderColor: 'rgba(100,149,237,1)', borderWidth: 0.5, areaStyle: { color: '#1b1b1b' } } }, data: [], markLine: { symbol: ['circle', 'circle'], symbolSize: 1, effect: effect, itemStyle: itemStyle(0), smooth: true, data: [ [{ name: '北京' }, { name: '哈尔滨' }], [{ name: '哈尔滨' }, { name: '满洲里' }], [{ name: '沈阳' }, { name: '大连' }], [{ name: '大连' }, { name: '烟台' }], [{ name: '烟台' }, { name: '青岛' }], [{ name: '青岛' }, { name: '淮安' }], [{ name: '淮安' }, { name: '上海' }], [{ name: '上海' }, { name: '杭州' }], [{ name: '杭州' }, { name: '宁波' }], [{ name: '宁波' }, { name: '温州' }], [{ name: '温州' }, { name: '福州' }], [{ name: '福州' }, { name: '厦门' }], [{ name: '厦门' }, { name: '广州' }], [{ name: '广州' }, { name: '湛江' }], [{ name: '北京' }, { name: '天津' }], [{ name: '天津' }, { name: '济南' }], [{ name: '济南' }, { name: '南京' }], [{ name: '南京' }, { name: '上海' }], [{ name: '北京' }, { name: '南昌' }], [{ name: '南昌' }, { name: '深圳' }], [{ name: '深圳' }, { name: '九龙红磡' }], [{ name: '北京' }, { name: '郑州' }], [{ name: '郑州' }, { name: '武汉' }], [{ name: '武汉' }, { name: '广州' }], [{ name: '大同' }, { name: '太原' }], [{ name: '太原' }, { name: '焦作' }], [{ name: '焦作' }, { name: '洛阳' }], [{ name: '洛阳' }, { name: '柳州' }], [{ name: '柳州' }, { name: '湛江' }], [{ name: '包头' }, { name: '西安' }], [{ name: '西安' }, { name: '重庆' }], [{ name: '重庆' }, { name: '贵阳' }], [{ name: '贵阳' }, { name: '柳州' }], [{ name: '柳州' }, { name: '南宁' }], [{ name: '兰州' }, { name: '成都' }], [{ name: '成都' }, { name: '昆明' }] ] } }, { name: '八横通道', type: 'map', mapType: 'china', itedmStyle: { normal: { borderColor: 'rgba(100,149,237,1)', borderWidth: 0.5, areaStyle: { color: '#1b1b1b' } } }, data: [], markLine: { symbol: ['circle', 'circle'], symbolSize: 1, effect: effect, itemStyle: itemStyle(1), smooth: true, data: [ [{ name: '北京' }, { name: '兰州' }], [{ name: '兰州' }, { name: '拉萨' }], [{ name: '大同' }, { name: '秦皇岛' }], [{ name: '神木' }, { name: '黄骅' }], [{ name: '太原' }, { name: '德州' }], [{ name: '德州' }, { name: '龙口' }], [{ name: '龙口' }, { name: '烟台' }], [{ name: '太原' }, { name: '德州' }], [{ name: '德州' }, { name: '济南' }], [{ name: '济南' }, { name: '青岛' }], [{ name: '长治' }, { name: '邯郸' }], [{ name: '邯郸' }, { name: '济南' }], [{ name: '济南' }, { name: '青岛' }], [{ name: '瓦塘' }, { name: '临汾' }], [{ name: '临汾' }, { name: '长治' }], [{ name: '长治' }, { name: '汤阴' }], [{ name: '汤阴' }, { name: '台前' }], [{ name: '台前' }, { name: '兖州' }], [{ name: '兖州' }, { name: '日照' }], [{ name: '侯马' }, { name: '月山' }], [{ name: '月山' }, { name: '新乡' }], [{ name: '新乡' }, { name: '兖州' }], [{ name: '兖州' }, { name: '日照' }], [{ name: '连云港' }, { name: '郑州' }], [{ name: '郑州' }, { name: '兰州' }], [{ name: '兰州' }, { name: '乌鲁木齐' }], [{ name: '乌鲁木齐' }, { name: '阿拉山口' }], [{ name: '西安' }, { name: '南阳' }], [{ name: '南阳' }, { name: '信阳' }], [{ name: '信阳' }, { name: '合肥' }], [{ name: '合肥' }, { name: '南京' }], [{ name: '南京' }, { name: '启东' }], [{ name: '重庆' }, { name: '武汉' }], [{ name: '武汉' }, { name: '九江' }], [{ name: '九江' }, { name: '铜陵' }], [{ name: '铜陵' }, { name: '南京' }], [{ name: '南京' }, { name: '上海' }], [{ name: '上海' }, { name: '怀化' }], [{ name: '怀化' }, { name: '重庆' }], [{ name: '重庆' }, { name: '成都' }], [{ name: '成都' }, { name: '贵阳' }], [{ name: '贵阳' }, { name: '昆明' }], [{ name: '昆明' }, { name: '南宁' }], [{ name: '南宁' }, { name: '黎塘' }], [{ name: '黎塘' }, { name: '湛江' }] ] }, geoCoord: { '阿拉山口': [82.5757, 45.1706], '包头': [109.8403, 40.6574], '北京': [116.4075, 39.9040], '成都': [104.0665, 30.5723], '大连': [121.6147, 38.9140], '大同': [113.3001, 40.0768], '德州': [116.3575, 37.4341], '福州': [119.2965, 26.0745], '广州': [113.2644, 23.1292], '贵阳': [106.6302, 26.6477], '哈尔滨': [126.5363, 45.8023], '邯郸': [114.5391, 36.6256], '杭州': [120.1551, 30.2741], '合肥': [117.2272, 31.8206], '侯马': [111.3720, 35.6191], '怀化': [109.9985, 27.5550], '淮安': [119.0153, 33.6104], '黄骅': [117.3300, 38.3714], '济南': [117.1205, 36.6510], '焦作': [113.2418, 35.2159], '九江': [116.0019, 29.7051], '九龙红磡': [114.1870, 22.3076], '昆明': [102.8329, 24.8801], '拉萨': [91.1409, 29.6456], '兰州': [103.8343, 36.0611], '黎塘': [109.1363, 23.2066], '连云港': [119.2216, 34.5967], '临汾': [111.5190, 36.0880], '柳州': [109.4160, 24.3255], '龙口': [120.4778, 37.6461], '洛阳': [112.4540, 34.6197], '满洲里': [117.3787, 49.5978], '南昌': [115.8581, 28.6832], '南京': [118.7969, 32.0603], '南宁': [108.3661, 22.8172], '南阳': [112.5283, 32.9908], '宁波': [121.5440, 29.8683], '启东': [121.6574, 31.8082], '秦皇岛': [119.6005, 39.9354], '青岛': [120.3826, 36.0671], '日照': [119.5269, 35.4164], '厦门': [118.0894, 24.4798], '上海': [121.4737, 31.2304], '深圳': [114.0579, 22.5431], '神木': [110.4871, 38.8610], '沈阳': [123.4315, 41.8057], '台前': [115.8717, 35.9701], '太原': [112.5489, 37.8706], '汤阴': [114.3572, 35.9218], '天津': [117.2010, 39.0842], '铜陵': [117.8121, 30.9454], '瓦塘': [109.7600, 23.3161], '温州': [120.6994, 27.9943], '乌鲁木齐': [87.6168, 43.8256], '武汉': [114.3054, 30.5931], '西安': [108.9402, 34.3416], '新乡': [113.9268, 35.3030], '信阳': [114.0913, 32.1470], '烟台': [121.4479, 37.4638], '兖州': [116.7838, 35.5531], '月山': [113.0550, 35.2104], '湛江': [110.3594, 21.2707], '长治': [113.1163, 36.1954], '郑州': [113.6254, 34.7466], '重庆': [106.5516, 29.5630] } } ] }; // 为echarts对象加载数据 myChart.setOption(option); } //湖南省高铁 function echart_6() { // 基于准备好的dom,初始化echarts实例 var myChart = echarts.init(document.getElementById('chart_6')); //加载地图 myChart.setOption({ series: [{ type: 'map', mapType: 'hunan' }] }); var geoCoordMap = { '怀化站': [109.999867,27.518949], '吉首站': [109.741528,28.332629], '张家界站': [110.491722,29.112001], '常德站': [111.701486,29.076683], '益阳站': [112.348741,28.544124], '岳阳站': [113.126486,29.382401], '长沙站': [113.019455,28.200103], '株洲站': [113.163141,27.8418], '湘潭站': [112.91977,27.882141], '邵阳站': [111.467859,27.21915], '娄底站': [112.012438,27.745506], '衡阳站': [112.63809,26.895225], '永州站': [111.577632,26.460144], '郴州站': [113.039396,25.81497] }; var goData = [ [{ name: '怀化站' }, { id: 1, name: '吉首站', value: 60 }], [{ name: '吉首站' }, { id: 1, name: '张家界站', value: 70 }], [{ name: '张家界站' }, { id: 1, name: '常德站', value: 77 }], [{ name: '常德站' }, { id: 1, name: '岳阳站', value: 70 }], [{ name: '常德站' }, { id: 1, name: '益阳站', value: 65 }], [{ name: '常德站' }, { id: 1, name: '邵阳站', value: 80 }], [{ name: '益阳站' }, { id: 1, name: '长沙站', value: 95 }], [{ name: '益阳站' }, { id: 1, name: '娄底站', value: 72 }], [{ name: '长沙站' }, { id: 1, name: '株洲站', value: 80 }], [{ name: '长沙站' }, { id: 1, name: '湘潭站', value: 90 }], [{ name: '长沙站' }, { id: 1, name: '衡阳站', value: 88 }], [{ name: '湘潭站' }, { id: 1, name: '娄底站', value: 72 }], [{ name: '娄底站' }, { id: 1, name: '怀化站', value: 80 }], [{ name: '邵阳站' }, { id: 1, name: '永州站', value: 74 }], [{ name: '衡阳站' }, { id: 1, name: '邵阳站', value: 80 }], [{ name: '衡阳站' }, { id: 1, name: '永州站', value: 74 }], [{ name: '衡阳站' }, { id: 1, name: '郴州站', value: 70 }], ]; //值控制圆点大小 var backData = [ [{ name: '吉首站' }, { id: 2, name: '怀化站', value: 80 }], [{ name: '常德站' }, { id: 1, name: '张家界站', value: 70 }], [{ name: '岳阳站' }, { id: 1, name: '常德站', value: 77 }], [{ name: '益阳站' }, { id: 1, name: '常德站', value: 77 }], [{ name: '邵阳站' }, { id: 1, name: '常德站', value: 77 }], [{ name: '长沙站' }, { id: 1, name: '益阳站', value: 65 }], [{ name: '娄底站' }, { id: 1, name: '益阳站', value: 65 }], [{ name: '株洲站' }, { id: 1, name: '长沙站', value: 95 }], [{ name: '湘潭站' }, { id: 1, name: '长沙站', value: 95 }], [{ name: '衡阳站' }, { id: 1, name: '长沙站', value: 95 }], [{ name: '娄底站' }, { id: 1, name: '湘潭站', value: 90 }], [{ name: '怀化站' }, { id: 1, name: '娄底站', value: 72 }], [{ name: '永州站' }, { id: 1, name: '邵阳站', value: 80 }], [{ name: '邵阳站' }, { id: 1, name: '衡阳站', value: 88 }], [{ name: '永州站' }, { id: 1, name: '衡阳站', value: 88 }], [{ name: '郴州站' }, { id: 1, name: '衡阳站', value: 88 }], ]; var arcAngle = function(data) { var j, k; for (var i = 0; i < data.length; i++) { var dataItem = data[i]; if (dataItem[1].id == 1) { j = 0.2; return j; } else if (dataItem[1].id == 2) { k = -0.2; return k; } } } var convertData = function(data) { var res = []; for (var i = 0; i < data.length; i++) { var dataItem = data[i]; var fromCoord = geoCoordMap[dataItem[0].name]; var toCoord = geoCoordMap[dataItem[1].name]; if (dataItem[1].id == 1) { if (fromCoord && toCoord) { res.push([{ coord: fromCoord, }, { coord: toCoord, value: dataItem[1].value //线条颜色 }]); } } else if (dataItem[1].id == 2) { if (fromCoord && toCoord) { res.push([{ coord: fromCoord, }, { coord: toCoord }]); } } } return res; }; var color = ['#fff', '#FF1493', '#00FF00']; var series = []; [ ['1', goData], ['2', backData] ].forEach(function(item, i) { series.push({ name: item[0], type: 'lines', zlevel: 2, symbol: ['arrow', 'arrow'], //线特效配置 effect: { show: true, period: 6, trailLength: 0.1, symbol: 'arrow', //标记类型 symbolSize: 5 }, lineStyle: { normal: { width: 1, opacity: 0.4, curveness: arcAngle(item[1]), //弧线角度 color: '#fff' } }, data: convertData(item[1]) }, { type: 'effectScatter', coordinateSystem: 'geo', zlevel: 2, //波纹效果 rippleEffect: { period: 2, brushType: 'stroke', scale: 3 }, label: { normal: { show: true, color: '#fff', position: 'right', formatter: '{b}' } }, //终点形象 symbol: 'circle', //圆点大小 symbolSize: function(val) { return val[2] / 8; }, itemStyle: { normal: { show: true } }, data: item[1].map(function(dataItem) { return { name: dataItem[1].name, value: geoCoordMap[dataItem[1].name].concat([dataItem[1].value]) }; }) }); }); option = { title: { text: '', subtext: '', left: 'center', textStyle: { color: '#fff' } }, tooltip: { trigger: 'item', formatter: "{b}" }, //线颜色及飞行轨道颜色 visualMap: { show: false, min: 0, max: 100, color: ['#fff'] }, //地图相关设置 geo: { map: 'hunan', //视角缩放比例 zoom: 1, //显示文本样式 label: { normal: { show: false, textStyle: { color: '#fff' } }, emphasis: { textStyle: { color: '#fff' } } }, //鼠标缩放和平移 roam: true, itemStyle: { normal: { // color: '#ddd', borderColor: 'rgba(147, 235, 248, 1)', borderWidth: 1, areaColor: { type: 'radial', x: 0.5, y: 0.5, r: 0.8, colorStops: [{ offset: 0, color: 'rgba(175,238,238, 0)' // 0% 处的颜色 }, { offset: 1, color: 'rgba( 47,79,79, .2)' // 100% 处的颜色 }], globalCoord: false // 缺省为 false }, shadowColor: 'rgba(128, 217, 248, 1)', shadowOffsetX: -2, shadowOffsetY: 2, shadowBlur: 10 }, emphasis: { areaColor: '#389BB7', borderWidth: 0 } } }, series: series }; myChart.setOption(option); } //湖南总货运量 function echart_7() { var myChart = echarts.init(document.getElementById('chart_7')); myChart.clear(); option = { title: { text: '' }, tooltip: { trigger: 'axis' }, legend: { data:['货运量','铁路货运量','国家铁路货运量','地方铁路货运量','合资铁路货运量','公路货运量','水运货运量'], textStyle:{ color: '#fff' }, top: '4%' }, grid: { left: '3%', right: '4%', bottom: '3%', containLabel: true }, toolbox: { orient: 'vertical', right: '1%', top: '2%', iconStyle: { color: '#FFEA51', borderColor: '#FFA74D', borderWidth: 1, }, feature: { saveAsImage: {}, magicType: { show: true, type: ['line','bar','stack','tiled'] } } }, xAxis: { type: 'category', boundaryGap: false, data: ['2012年','2013年','2014年','2015年','2016年'], splitLine: { show: false }, axisLine: { lineStyle: { color: '#fff' } } }, yAxis: { name: '单位(万吨)', type: 'value', splitLine: { show: false }, axisLine: { lineStyle: { color: '#fff' } } }, color: ['#FF4949','#FFA74D','#FFEA51','#4BF0FF','#44AFF0','#4E82FF','#584BFF','#BE4DFF','#F845F1'], series: [ { name:'货运量', type:'line', data:[219130, 198009, 209946, 198024, 210586] }, { name:'铁路货运量', type:'line', data:[21010, 22469, 20619, 17843, 16313] }, { name:'国家铁路货运量', type:'line', data:[17866, 19354, 17589, 17709, 18589] }, { name:'地方铁路货运量', type:'line', data:[3034, 2845, 2712, 2790, 2812] }, { name:'合资铁路货运量', type:'line', data:[111, 271, 318, 327, 349] }, { name:'公路货运量', type:'line', data:[195530, 172492, 185286,175637,189822] }, { name:'水运货运量', type:'line', data:[2590, 3048, 4041,4544,4451] } ] }; myChart.setOption(option); } //湖南货物周转量 function echart_8() { var myChart = echarts.init(document.getElementById('chart_8')); myChart.clear(); option = { title: { text: '' }, tooltip: { trigger: 'axis' }, legend: { data:['铁路货物周转量','国家铁路货物周转量','地方铁路货物周转量','合资铁路货物周转量','公路货物周转量','水运货物周转量'], textStyle:{ color: '#fff' }, top: '4%' }, grid: { left: '3%', right: '4%', bottom: '3%', containLabel: true }, toolbox: { orient: 'vertical', right: '1%', top: '2%', iconStyle: { color: '#FFEA51', borderColor: '#FFA74D', borderWidth: 1, }, feature: { saveAsImage: {}, magicType: { show: true, type: ['line','bar','stack','tiled'] } } }, color: ['#FF4949','#FFA74D','#FFEA51','#4BF0FF','#44AFF0','#4E82FF','#584BFF','#BE4DFF','#F845F1'], xAxis: { type: 'category', boundaryGap: false, data: ['2014年','2015年','2016年','2017年','2018年'], splitLine: { show: false }, axisLine: { lineStyle: { color: '#fff' } } }, yAxis: { name: '亿吨公里', type: 'value', splitLine: { show: false }, axisLine: { lineStyle: { color: '#fff' } } }, series: [ { name:'铁路货物周转量', type:'line', data:[3961.88, 4233.63, 4183.14, 3633.01, 3704.47] }, { name:'国家铁路货物周转量', type:'line', data:[3374.76, 3364.76, 3274.76, 3371.82, 3259.87] }, { name:'地方铁路货物周转量', type:'line', data:[14.77, 15.17, 13.17, 14.56, 15.84] }, { name:'合资铁路货物周转量', type:'line', data:[686.17,847.26,895.22,865.28,886.72] }, { name:'公路货物周转量', type:'line', data:[6133.47, 6577.89, 7019.56,6821.48,7294.59] }, { name:'水运货物周转量', type:'line', data:[509.60, 862.54, 1481.77,1552.79,1333.62] } ] }; myChart.setOption(option); } //湖南运输线长度 function echart_9() { var myChart = echarts.init(document.getElementById('chart_9')); myChart.clear(); option = { title: { text: '' }, tooltip: { trigger: 'axis' }, legend: { data:['铁路营业里程','公路里程','等级公路里程','高速等级公路里程','一级等级公路里程','二级等级公路里程','等外公路公路里程'], textStyle:{ color: '#fff' }, top: '4%' }, grid: { left: '3%', right: '4%', bottom: '3%', containLabel: true }, toolbox: { orient: 'vertical', right: '1%', top: '2%', iconStyle: { color: '#FFEA51', borderColor: '#FFA74D', borderWidth: 1, }, feature: { saveAsImage: {}, magicType: { show: true, type: ['line','bar','stack','tiled'] } } }, xAxis: { type: 'category', boundaryGap: false, data: ['2014年','2015年','2016年','2017年','2018年'], splitLine: { show: false }, axisLine: { lineStyle: { color: '#fff' } } }, yAxis: { name: '万公里', type: 'value', splitLine: { show: false }, axisLine: { lineStyle: { color: '#fff' } } }, color: ['#FF4949','#FFA74D','#FFEA51','#4BF0FF','#44AFF0','#4E82FF','#584BFF','#BE4DFF','#F845F1'], series: [ { name:'铁路营业里程', type:'line', data:[0.56, 0.63, 0.63, 0.70, 0.70] }, { name:'公路里程', type:'line', data:[16.30, 17.45, 17.92, 18.46, 18.84] }, { name:'等级公路里程', type:'line', data:[15.54, 16.77, 17.29, 17.86, 18.26] }, { name:'高速等级公路里程', type:'line', data:[0.51, 0.56, 0.59, 0.63, 0.65] }, { name:'一级等级公路里程', type:'line', data:[0.47,0.48,0.51,0.54,0.56] }, { name:'二级等级公路里程', type:'line', data:[1.76, 1.85, 1.93, 1.97, 1.99] }, { name:'等外公路公路里程', type:'line', data:[0.76, 0.68, 0.63, 0.60, 0.58] } ] }; myChart.setOption(option); } //湖南省快递业务量 function echart_10(){ var myChart = echarts.init(document.getElementById('chart_10')); myChart.clear(); option = { tooltip: { trigger: 'item', formatter: "{a} <br/>{b}: {c} ({d}%)" }, legend: { orient: 'vertical', x: 'left', top: '2%', left: '1%', textStyle: { color: '#fff' }, data:[ '国际','省外','省内', ] }, color: ['#FF4949','#FFA74D','#4BF0FF','#44AFF0','#4E82FF','#584BFF','#BE4DFF','#F845F1','#4BF0FF','#44AFF0'], series: [ { name:'业务量(万件)', type:'pie', selectedMode: 'single', radius: [0, '15%'], center: ['28%','28%'], label: { normal: { position: 'inner' } }, labelLine: { normal: { show: false } }, data:[ {value:90392.39, name:'2018年业务量(90392.39万件)'}, ] }, { name:'业务量(万件)', type:'pie', radius: ['20%', '30%'], center: ['28%','28%'], label: { normal: { formatter: '{a|{a}}{abg|}\n{hr|}\n {b|{b}:}{c} {per|{d}%} ', backgroundColor: '#eee', borderColor: '#aaa', borderWidth: 1, borderRadius: 4, rich: { a: { color: '#999', lineHeight: 22, align: 'center' }, hr: { borderColor: '#aaa', width: '100%', borderWidth: 0.5, height: 0 }, b: { fontSize: 16, lineHeight: 33 }, per: { color: '#eee', backgroundColor: '#334455', padding: [2, 4], borderRadius: 2 } } } }, data:[ {value:464.43, name:'国际'}, {value:68575.6, name:'省外'}, {value:21352.36, name:'省内'}, ] }, { name:'业务量(万件)', type:'pie', selectedMode: 'single', radius: [0, '15%'], center: ['70%','28%'], label: { normal: { position: 'inner' } }, labelLine: { normal: { show: false } }, data:[ {value:54911.94, name:'2017年业务量(54911.94万件)'}, ] }, { name:'业务量(万件)', type:'pie', radius: ['20%', '30%'], center: ['70%','28%'], label: { normal: { formatter: '{a|{a}}{abg|}\n{hr|}\n {b|{b}:}{c} {per|{d}%} ', backgroundColor: '#eee', borderColor: '#aaa', borderWidth: 1, borderRadius: 4, rich: { a: { color: '#999', lineHeight: 22, align: 'center' }, hr: { borderColor: '#aaa', width: '100%', borderWidth: 0.5, height: 0 }, b: { fontSize: 16, lineHeight: 33 }, per: { color: '#eee', backgroundColor: '#334455', padding: [2, 4], borderRadius: 2 } } } }, data:[ {value:278.5, name:'国际'}, {value:37111.03, name:'省外'}, {value:17522.41, name:'省内'}, ] }, { name:'业务量(万件)', type:'pie', selectedMode: 'single', radius: [0, '15%'], center: ['28%','70%'], label: { normal: { position: 'inner' } }, labelLine: { normal: { show: false } }, data:[ {value:34019.15, name:'2016年业务量(34019.15万件)'}, ] }, { name:'业务量(万件)', type:'pie', radius: ['20%', '30%'], center: ['28%','70%'], label: { normal: { formatter: '{a|{a}}{abg|}\n{hr|}\n {b|{b}:}{c} {per|{d}%} ', backgroundColor: '#eee', borderColor: '#aaa', borderWidth: 1, borderRadius: 4, rich: { a: { color: '#999', lineHeight: 22, align: 'center' }, hr: { borderColor: '#aaa', width: '100%', borderWidth: 0.5, height: 0 }, b: { fontSize: 16, lineHeight: 33 }, per: { color: '#eee', backgroundColor: '#334455', padding: [2, 4], borderRadius: 2 } } } }, data:[ {value:163.72, name:'国际'}, {value:26841.29, name:'省外'}, {value:7014.14, name:'省内'}, ] }, { name:'业务量(万件)', type:'pie', selectedMode: 'single', radius: [0, '15%'], center: ['70%','70%'], label: { normal: { position: 'inner' } }, labelLine: { normal: { show: false } }, data:[ {value:20755.74, name:'2015年业务量(20755.74万件)'}, ] }, { name:'业务量(万件)', type:'pie', radius: ['20%', '30%'], center: ['70%','70%'], label: { normal: { formatter: '{a|{a}}{abg|}\n{hr|}\n {b|{b}:}{c} {per|{d}%} ', backgroundColor: '#eee', borderColor: '#aaa', borderWidth: 1, borderRadius: 4, rich: { a: { color: '#999', lineHeight: 22, align: 'center' }, hr: { borderColor: '#aaa', width: '100%', borderWidth: 0.5, height: 0 }, b: { fontSize: 16, lineHeight: 33 }, per: { color: '#eee', backgroundColor: '#334455', padding: [2, 4], borderRadius: 2 } } } }, data:[ {value:129.65, name:'国际'}, {value:18072.54, name:'省外'}, {value:2553.55, name:'省内'}, ] }, ] }; myChart.setOption(option); } //湖南省公路营运 function echart_11(){ var myChart = echarts.init(document.getElementById('chart_11')); myChart.clear(); option = { tooltip: { trigger: 'item', formatter: "{a} <br/>{b}: {c} ({d}%)" }, legend: { x: 'left', top: '2%', left: '1%', textStyle: { color: '#fff' }, data:['公路营运载客','公路营运载货'] }, color: ['#FF4949','#FFA74D','#4BF0FF','#44AFF0','#4E82FF','#584BFF','#BE4DFF','#F845F1'], series: [ { name:'公路营运', type:'pie', selectedMode: 'single', radius: [0, '15%'], center: ['28%','28%'], label: { normal: { position: 'inner' } }, labelLine: { normal: { show: false } }, data:[ {value:145.18, name:'2018年公路营运拥有量(145.18万辆)'}, ] }, { name:'汽车拥有量(万辆)', type:'pie', radius: ['20%', '30%'], center: ['28%','28%'], label: { normal: { formatter: '{a|{a}}{abg|}\n{hr|}\n {b|{b}:}{c} {per|{d}%} ', backgroundColor: '#eee', borderColor: '#aaa', borderWidth: 1, borderRadius: 4, position: 'outside', rich: { a: { color: '#999', lineHeight: 22, align: 'center' }, hr: { borderColor: '#aaa', width: '100%', borderWidth: 0.5, height: 0 }, b: { fontSize: 16, lineHeight: 33 }, per: { color: '#eee', backgroundColor: '#334455', padding: [2, 4], borderRadius: 2 } } } }, data:[ {value:142.65, name:'公路营运载客'}, {value:2.53, name:'公路营运载货'}, ] }, { name:'公路营运', type:'pie', selectedMode: 'single', radius: [0, '15%'], center: ['70%','28%'], label: { normal: { position: 'inner' } }, labelLine: { normal: { show: false } }, data:[ {value:142.47, name:'2017年公路营运拥有量(142.47万辆)'} ] }, { name:'汽车拥有量(万辆)', type:'pie', radius: ['20%', '30%'], center: ['70%','28%'], label: { normal: { formatter: '{a|{a}}{abg|}\n{hr|}\n {b|{b}:}{c} {per|{d}%} ', backgroundColor: '#eee', borderColor: '#aaa', borderWidth: 1, borderRadius: 4, position: 'outside', rich: { a: { color: '#999', lineHeight: 22, align: 'center' }, hr: { borderColor: '#aaa', width: '100%', borderWidth: 0.5, height: 0 }, b: { fontSize: 16, lineHeight: 33 }, per: { color: '#eee', backgroundColor: '#334455', padding: [2, 4], borderRadius: 2 } } } }, data:[ {value:139.95, name:'公路营运载客'}, {value:2.52, name:'公路营运载货'}, // {value:137.96, name:'2014年公路营运载客汽车拥有量(万辆)'}, // {value:2.65, name:'2014年公路营运载货汽车拥有量(万辆)'}, // {value:131.48, name:'2013年公路营运载客汽车拥有量(万辆)'}, // {value:2.97, name:'2013年公路营运载货汽车拥有量(万辆)'} ] }, { name:'公路营运', type:'pie', selectedMode: 'single', radius: [0, '15%'], center: ['28%','70%'], label: { normal: { position: 'inner' } }, labelLine: { normal: { show: false } }, data:[ {value:140.61, name:'2016年公路营运拥有量(140.61万辆)'}, // {value:142.47, name:'2015年公路营运拥有量(142.47万辆)'}, // {value:140.61, name:'2014年公路营运拥有量(140.61万辆)'}, // {value:134.45, name:'2013年公路营运拥有量(134.45万辆)'}, ] }, { name:'汽车拥有量(万辆)', type:'pie', radius: ['20%', '30%'], center: ['28%','70%'], label: { normal: { formatter: '{a|{a}}{abg|}\n{hr|}\n {b|{b}:}{c} {per|{d}%} ', backgroundColor: '#eee', borderColor: '#aaa', borderWidth: 1, borderRadius: 4, position: 'outside', rich: { a: { color: '#999', lineHeight: 22, align: 'center' }, hr: { borderColor: '#aaa', width: '100%', borderWidth: 0.5, height: 0 }, b: { fontSize: 16, lineHeight: 33 }, per: { color: '#eee', backgroundColor: '#334455', padding: [2, 4], borderRadius: 2 } } } }, data:[ {value:137.96, name:'公路营运载客'}, {value:2.65, name:'公路营运载货'}, // {value:137.96, name:'2014年公路营运载客汽车拥有量(万辆)'}, // {value:2.65, name:'2014年公路营运载货汽车拥有量(万辆)'}, // {value:131.48, name:'2013年公路营运载客汽车拥有量(万辆)'}, // {value:2.97, name:'2013年公路营运载货汽车拥有量(万辆)'} ] }, { name:'公路营运', type:'pie', selectedMode: 'single', radius: [0, '15%'], center: ['70%','70%'], label: { normal: { position: 'inner' } }, labelLine: { normal: { show: false } }, data:[ {value:134.45, name:'2015年公路营运拥有量(134.45万辆)'}, ] }, { name:'汽车拥有量(万辆)', type:'pie', radius: ['20%', '30%'], center: ['70%','70%'], label: { normal: { formatter: '{a|{a}}{abg|}\n{hr|}\n {b|{b}:}{c} {per|{d}%} ', backgroundColor: '#eee', borderColor: '#aaa', borderWidth: 1, borderRadius: 4, position: 'outside', rich: { a: { color: '#999', lineHeight: 22, align: 'center' }, hr: { borderColor: '#aaa', width: '100%', borderWidth: 0.5, height: 0 }, b: { fontSize: 16, lineHeight: 33 }, per: { color: '#eee', backgroundColor: '#334455', padding: [2, 4], borderRadius: 2 } } } }, data:[ {value:131.48, name:'公路营运载客'}, {value:2.97, name:'公路营运载货'}, // {value:137.96, name:'2014年公路营运载客汽车拥有量(万辆)'}, // {value:2.65, name:'2014年公路营运载货汽车拥有量(万辆)'}, // {value:131.48, name:'2013年公路营运载客汽车拥有量(万辆)'}, // {value:2.97, name:'2013年公路营运载货汽车拥有量(万辆)'} ] } ] }; myChart.setOption(option); } //湖南省城市公共交通 function echart_12() { var myChart = echarts.init(document.getElementById('chart_12')); myChart.clear(); option = { title: { text: '' }, tooltip: { trigger: 'axis' }, legend: { data:['公共交通运营数','运营线路总长度','公共交通客运总量'], textStyle:{ color: '#fff' }, top: '4%' }, grid: { left: '3%', right: '4%', bottom: '3%', containLabel: true }, toolbox: { orient: 'vertical', right: '1%', top: '2%', iconStyle: { color: '#FFEA51', borderColor: '#FFA74D', borderWidth: 1, }, feature: { saveAsImage: {}, magicType: { show: true, type: ['line','bar','stack','tiled'] } } }, xAxis: { type: 'category', boundaryGap: false, data: ['2014年','2015年','2016年','2017年','2018年'], splitLine: { show: false }, axisLine: { lineStyle: { color: '#fff' } } }, yAxis: { name: '万公里', type: 'value', splitLine: { show: false }, axisLine: { lineStyle: { color: '#fff' } } }, color: ['#FF4949','#FFA74D','#FFEA51','#4BF0FF','#44AFF0','#4E82FF','#584BFF','#BE4DFF','#F845F1'], series: [ { name:'公共交通运营数', type:'line', data:[16493,17498, 15977, 18927, 21479] }, { name:'运营线路总长度', type:'line', data:[18812, 19647, 20305, 22940, 26077] }, { name:'公共交通客运总量', type:'line', data:[203954, 202727, 205342, 187208, 186048] }, ] }; myChart.setOption(option); } //湖南省地图 function echart_13(){ // 基于准备好的dom,初始化echarts实例 var myChart = echarts.init(document.getElementById('chart_13')); function showProvince() { myChart.setOption(option = { // backgroundColor: '#ffffff', visualMap: { show: false, min: 0, max: 100, left: 'left', top: 'bottom', text: ['高', '低'], // 文本,默认为数值文本 calculable: true, inRange: { color: ['yellow', 'lightskyblue', 'orangered'] } }, series: [{ type: 'map', mapType: 'hunan', roam: true, label: { normal: { show: true }, emphasis: { textStyle: { color: '#fff' } } }, itemStyle: { normal: { borderColor: '#389BB7', areaColor: '#fff', }, emphasis: { areaColor: '#389BB7', borderWidth: 0 } }, animation: false, data: [{ name: '长沙市', value: 100 }, { name: '株洲市', value: 96 }, { name: '湘潭市', value: 98 }, { name: '衡阳市', value: 80 }, { name: '邵阳市', value: 88 }, { name: '岳阳市', value: 79 }, { name: '常德市', value: 77, }, { name: '张家界市', value: 33 }, { name: '益阳市', value: 69, }, { name: '郴州市', value: 66 }, { name: '永州市', value: 22 },{ name: '娄底市', value: 51 },{ name: '湘西土家族苗族自治州', value: 44 },{ name: '怀化市', value: 9 }] }] }); } var currentIdx = 0; showProvince(); // 使用刚指定的配置项和数据显示图表。 window.addEventListener("resize", function () { myChart.resize(); }); } //GPS function echart_14(){ var myChart = echarts.init(document.getElementById('chart_14')); var data = [ {name: '海门', value: 9, address:'二道区东环域路2038号', typeName:'联运', area:'0.18', service:'东北地区'}, {name: '鄂尔多斯', value: 12, address:'二道区东环域路2038号', typeName:'联运', area:'0.18', service:'东北地区'}, {name: '招远', value: 12, address:'二道区东环域路2038号', typeName:'联运', area:'0.18', service:'东北地区'}, {name: '舟山', value: 12, address:'二道区东环域路2038号', typeName:'联运', area:'0.18', service:'东北地区'}, {name: '齐齐哈尔', value: 14, address:'二道区东环域路2038号', typeName:'联运', area:'0.18', service:'东北地区'}, {name: '盐城', value: 15, address:'二道区东环域路2038号', typeName:'联运', area:'0.18', service:'东北地区'}, {name: '赤峰', value: 16, address:'二道区东环域路2038号', typeName:'联运', area:'0.18', service:'东北地区'}, {name: '青岛', value: 18, address:'二道区东环域路2038号', typeName:'联运', area:'0.18', service:'东北地区'}, {name: '乳山', value: 18, address:'二道区东环域路2038号', typeName:'联运', area:'0.18', service:'东北地区'}, {name: '金昌', value: 19, address:'二道区东环域路2038号', typeName:'联运', area:'0.18', service:'东北地区'}, {name: '泉州', value: 21, address:'二道区东环域路2038号', typeName:'联运', area:'0.18', service:'东北地区'}, {name: '莱西', value: 21, address:'二道区东环域路2038号', typeName:'联运', area:'0.18', service:'东北地区'}, {name: '日照', value: 21, address:'二道区东环域路2038号', typeName:'联运', area:'0.18', service:'东北地区'}, {name: '胶南', value: 22, address:'二道区东环域路2038号', typeName:'联运', area:'0.18', service:'东北地区'}, {name: '南通', value: 23, address:'二道区东环域路2038号', typeName:'联运', area:'0.18', service:'东北地区'}, {name: '拉萨', value: 24, address:'二道区东环域路2038号', typeName:'联运', area:'0.18', service:'东北地区'}, {name: '云浮', value: 24, address:'二道区东环域路2038号', typeName:'联运', area:'0.18', service:'东北地区'}, {name: '梅州', value: 25, address:'二道区东环域路2038号', typeName:'联运', area:'0.18', service:'东北地区'}, {name: '文登', value: 25, address:'二道区东环域路2038号', typeName:'联运', area:'0.18', service:'东北地区'}, {name: '上海', value: 25, address:'二道区东环域路2038号', typeName:'联运', area:'0.18', service:'东北地区'}, {name: '攀枝花', value: 25, address:'二道区东环域路2038号', typeName:'联运', area:'0.18', service:'东北地区'}, {name: '威海', value: 25, address:'二道区东环域路2038号', typeName:'联运', area:'0.18', service:'东北地区'}, {name: '承德', value: 25, address:'二道区东环域路2038号', typeName:'联运', area:'0.18', service:'东北地区'}, {name: '厦门', value: 26, address:'二道区东环域路2038号', typeName:'联运', area:'0.18', service:'东北地区'}, {name: '汕尾', value: 26, address:'二道区东环域路2038号', typeName:'联运', area:'0.18', service:'东北地区'}, {name: '潮州', value: 26, address:'二道区东环域路2038号', typeName:'联运', area:'0.18', service:'东北地区'}, {name: '丹东', value: 27, address:'二道区东环域路2038号', typeName:'联运', area:'0.18', service:'东北地区'}, {name: '太仓', value: 27, address:'二道区东环域路2038号', typeName:'联运', area:'0.18', service:'东北地区'}, {name: '曲靖', value: 27, address:'二道区东环域路2038号', typeName:'联运', area:'0.18', service:'东北地区'}, {name: '烟台', value: 28, address:'二道区东环域路2038号', typeName:'联运', area:'0.18', service:'东北地区'}, {name: '福州', value: 29, address:'二道区东环域路2038号', typeName:'联运', area:'0.18', service:'东北地区'}, {name: '瓦房店', value: 30, address:'二道区东环域路2038号', typeName:'联运', area:'0.18', service:'东北地区'}, {name: '即墨', value: 30, address:'二道区东环域路2038号', typeName:'联运', area:'0.18', service:'东北地区'}, {name: '抚顺', value: 31, address:'二道区东环域路2038号', typeName:'联运', area:'0.18', service:'东北地区'}, {name: '玉溪', value: 31, address:'二道区东环域路2038号', typeName:'联运', area:'0.18', service:'东北地区'}, {name: '张家口', value: 31, address:'二道区东环域路2038号', typeName:'联运', area:'0.18', service:'东北地区'}, {name: '阳泉', value: 31, address:'二道区东环域路2038号', typeName:'联运', area:'0.18', service:'东北地区'}, {name: '莱州', value: 32, address:'二道区东环域路2038号', typeName:'联运', area:'0.18', service:'东北地区'}, {name: '湖州', value: 32, address:'二道区东环域路2038号', typeName:'联运', area:'0.18', service:'东北地区'}, {name: '汕头', value: 32, address:'二道区东环域路2038号', typeName:'联运', area:'0.18', service:'东北地区'}, {name: '昆山', value: 33, address:'二道区东环域路2038号', typeName:'联运', area:'0.18', service:'东北地区'}, {name: '宁波', value: 33, address:'二道区东环域路2038号', typeName:'联运', area:'0.18', service:'东北地区'}, {name: '湛江', value: 33, address:'二道区东环域路2038号', typeName:'联运', area:'0.18', service:'东北地区'}, {name: '揭阳', value: 34, address:'二道区东环域路2038号', typeName:'联运', area:'0.18', service:'东北地区'}, {name: '荣成', value: 34, address:'二道区东环域路2038号', typeName:'联运', area:'0.18', service:'东北地区'}, {name: '连云港', value: 35, address:'二道区东环域路2038号', typeName:'联运', area:'0.18', service:'东北地区'}, {name: '葫芦岛', value: 35, address:'二道区东环域路2038号', typeName:'联运', area:'0.18', service:'东北地区'}, {name: '常熟', value: 36, address:'二道区东环域路2038号', typeName:'联运', area:'0.18', service:'东北地区'}, {name: '东莞', value: 36, address:'二道区东环域路2038号', typeName:'联运', area:'0.18', service:'东北地区'}, {name: '河源', value: 36, address:'二道区东环域路2038号', typeName:'联运', area:'0.18', service:'东北地区'}, {name: '淮安', value: 36, address:'二道区东环域路2038号', typeName:'联运', area:'0.18', service:'东北地区'}, {name: '泰州', value: 36, address:'二道区东环域路2038号', typeName:'联运', area:'0.18', service:'东北地区'}, {name: '南宁', value: 37, address:'二道区东环域路2038号', typeName:'联运', area:'0.18', service:'东北地区'}, {name: '营口', value: 37, address:'二道区东环域路2038号', typeName:'联运', area:'0.18', service:'东北地区'}, {name: '惠州', value: 37, address:'二道区东环域路2038号', typeName:'联运', area:'0.18', service:'东北地区'}, {name: '江阴', value: 37, address:'二道区东环域路2038号', typeName:'联运', area:'0.18', service:'东北地区'}, {name: '蓬莱', value: 37, address:'二道区东环域路2038号', typeName:'联运', area:'0.18', service:'东北地区'}, {name: '韶关', value: 38, address:'二道区东环域路2038号', typeName:'联运', area:'0.18', service:'东北地区'}, {name: '嘉峪关', value: 38, address:'二道区东环域路2038号', typeName:'联运', area:'0.18', service:'东北地区'}, {name: '广州', value: 38, address:'二道区东环域路2038号', typeName:'联运', area:'0.18', service:'东北地区'}, {name: '延安', value: 38, address:'二道区东环域路2038号', typeName:'联运', area:'0.18', service:'东北地区'}, {name: '太原', value: 39, address:'二道区东环域路2038号', typeName:'联运', area:'0.18', service:'东北地区'}, {name: '清远', value: 39, address:'二道区东环域路2038号', typeName:'联运', area:'0.18', service:'东北地区'}, {name: '中山', value: 39, address:'二道区东环域路2038号', typeName:'联运', area:'0.18', service:'东北地区'}, {name: '昆明', value: 39, address:'二道区东环域路2038号', typeName:'联运', area:'0.18', service:'东北地区'}, {name: '寿光', value: 40, address:'二道区东环域路2038号', typeName:'联运', area:'0.18', service:'东北地区'}, {name: '盘锦', value: 40, address:'二道区东环域路2038号', typeName:'联运', area:'0.18', service:'东北地区'}, {name: '长治', value: 41, address:'二道区东环域路2038号', typeName:'联运', area:'0.18', service:'东北地区'}, {name: '深圳', value: 41, address:'二道区东环域路2038号', typeName:'联运', area:'0.18', service:'东北地区'}, {name: '珠海', value: 42, address:'二道区东环域路2038号', typeName:'联运', area:'0.18', service:'东北地区'}, {name: '宿迁', value: 43, address:'二道区东环域路2038号', typeName:'联运', area:'0.18', service:'东北地区'}, {name: '咸阳', value: 43, address:'二道区东环域路2038号', typeName:'联运', area:'0.18', service:'东北地区'}, {name: '铜川', value: 44, address:'二道区东环域路2038号', typeName:'联运', area:'0.18', service:'东北地区'}, {name: '平度', value: 44, address:'二道区东环域路2038号', typeName:'联运', area:'0.18', service:'东北地区'}, {name: '佛山', value: 44, address:'二道区东环域路2038号', typeName:'联运', area:'0.18', service:'东北地区'}, {name: '海口', value: 44, address:'二道区东环域路2038号', typeName:'联运', area:'0.18', service:'东北地区'}, {name: '江门', value: 45, address:'二道区东环域路2038号', typeName:'联运', area:'0.18', service:'东北地区'}, {name: '章丘', value: 45, address:'二道区东环域路2038号', typeName:'联运', area:'0.18', service:'东北地区'}, {name: '肇庆', value: 46, address:'二道区东环域路2038号', typeName:'联运', area:'0.18', service:'东北地区'}, {name: '大连', value: 47, address:'二道区东环域路2038号', typeName:'联运', area:'0.18', service:'东北地区'}, {name: '临汾', value: 47, address:'二道区东环域路2038号', typeName:'联运', area:'0.18', service:'东北地区'}, {name: '吴江', value: 47, address:'二道区东环域路2038号', typeName:'联运', area:'0.18', service:'东北地区'}, {name: '石嘴山', value: 49, address:'二道区东环域路2038号', typeName:'联运', area:'0.18', service:'东北地区'}, {name: '沈阳', value: 50, address:'二道区东环域路2038号', typeName:'联运', area:'0.18', service:'东北地区'}, {name: '苏州', value: 50, address:'二道区东环域路2038号', typeName:'联运', area:'0.18', service:'东北地区'}, {name: '茂名', value: 50, address:'二道区东环域路2038号', typeName:'联运', area:'0.18', service:'东北地区'}, {name: '嘉兴', value: 51, address:'二道区东环域路2038号', typeName:'联运', area:'0.18', service:'东北地区'}, {name: '长春', value: 51, address:'二道区东环域路2038号', typeName:'联运', area:'0.18', service:'东北地区'}, {name: '胶州', value: 52, address:'二道区东环域路2038号', typeName:'联运', area:'0.18', service:'东北地区'}, {name: '银川', value: 52, address:'二道区东环域路2038号', typeName:'联运', area:'0.18', service:'东北地区'}, {name: '张家港', value: 52, address:'二道区东环域路2038号', typeName:'联运', area:'0.18', service:'东北地区'}, {name: '三门峡', value: 53, address:'二道区东环域路2038号', typeName:'联运', area:'0.18', service:'东北地区'}, {name: '锦州', value: 54, address:'二道区东环域路2038号', typeName:'联运', area:'0.18', service:'东北地区'}, {name: '南昌', value: 54, address:'二道区东环域路2038号', typeName:'联运', area:'0.18', service:'东北地区'}, {name: '柳州', value: 54, address:'二道区东环域路2038号', typeName:'联运', area:'0.18', service:'东北地区'}, {name: '三亚', value: 54, address:'二道区东环域路2038号', typeName:'联运', area:'0.18', service:'东北地区'}, {name: '自贡', value: 56, address:'二道区东环域路2038号', typeName:'联运', area:'0.18', service:'东北地区'}, {name: '吉林', value: 56, address:'二道区东环域路2038号', typeName:'联运', area:'0.18', service:'东北地区'}, {name: '阳江', value: 57, address:'二道区东环域路2038号', typeName:'联运', area:'0.18', service:'东北地区'}, {name: '泸州', value: 57, address:'二道区东环域路2038号', typeName:'联运', area:'0.18', service:'东北地区'}, {name: '西宁', value: 57, address:'二道区东环域路2038号', typeName:'联运', area:'0.18', service:'东北地区'}, {name: '宜宾', value: 58, address:'二道区东环域路2038号', typeName:'联运', area:'0.18', service:'东北地区'}, {name: '呼和浩特', value: 58, address:'二道区东环域路2038号', typeName:'联运', area:'0.18', service:'东北地区'}, {name: '成都', value: 58, address:'二道区东环域路2038号', typeName:'联运', area:'0.18', service:'东北地区'}, {name: '大同', value: 58, address:'二道区东环域路2038号', typeName:'联运', area:'0.18', service:'东北地区'}, {name: '镇江', value: 59, address:'二道区东环域路2038号', typeName:'联运', area:'0.18', service:'东北地区'}, {name: '桂林', value: 59, address:'二道区东环域路2038号', typeName:'联运', area:'0.18', service:'东北地区'}, {name: '张家界', value: 59, address:'二道区东环域路2038号', typeName:'联运', area:'0.18', service:'东北地区'}, {name: '宜兴', value: 59, address:'二道区东环域路2038号', typeName:'联运', area:'0.18', service:'东北地区'}, {name: '北海', value: 60, address:'二道区东环域路2038号', typeName:'联运', area:'0.18', service:'东北地区'}, {name: '西安', value: 61, address:'二道区东环域路2038号', typeName:'联运', area:'0.18', service:'东北地区'}, {name: '金坛', value: 62, address:'二道区东环域路2038号', typeName:'联运', area:'0.18', service:'东北地区'}, {name: '东营', value: 62, address:'二道区东环域路2038号', typeName:'联运', area:'0.18', service:'东北地区'}, {name: '牡丹江', value: 63, address:'二道区东环域路2038号', typeName:'联运', area:'0.18', service:'东北地区'}, {name: '遵义', value: 63, address:'二道区东环域路2038号', typeName:'联运', area:'0.18', service:'东北地区'}, {name: '绍兴', value: 63, address:'二道区东环域路2038号', typeName:'联运', area:'0.18', service:'东北地区'}, {name: '扬州', value: 64, address:'二道区东环域路2038号', typeName:'联运', area:'0.18', service:'东北地区'}, {name: '常州', value: 64, address:'二道区东环域路2038号', typeName:'联运', area:'0.18', service:'东北地区'}, {name: '潍坊', value: 65, address:'二道区东环域路2038号', typeName:'联运', area:'0.18', service:'东北地区'}, {name: '重庆', value: 66, address:'二道区东环域路2038号', typeName:'联运', area:'0.18', service:'东北地区'}, {name: '台州', value: 67, address:'二道区东环域路2038号', typeName:'联运', area:'0.18', service:'东北地区'}, {name: '南京', value: 67, address:'二道区东环域路2038号', typeName:'联运', area:'0.18', service:'东北地区'}, {name: '滨州', value: 70, address:'二道区东环域路2038号', typeName:'联运', area:'0.18', service:'东北地区'}, {name: '贵阳', value: 71, address:'二道区东环域路2038号', typeName:'联运', area:'0.18', service:'东北地区'}, {name: '无锡', value: 71, address:'二道区东环域路2038号', typeName:'联运', area:'0.18', service:'东北地区'}, {name: '本溪', value: 71, address:'二道区东环域路2038号', typeName:'联运', area:'0.18', service:'东北地区'}, {name: '克拉玛依', value: 72, address:'二道区东环域路2038号', typeName:'联运', area:'0.18', service:'东北地区'}, {name: '渭南', value: 72, address:'二道区东环域路2038号', typeName:'联运', area:'0.18', service:'东北地区'}, {name: '马鞍山', value: 72, address:'二道区东环域路2038号', typeName:'联运', area:'0.18', service:'东北地区'}, {name: '宝鸡', value: 72, address:'二道区东环域路2038号', typeName:'联运', area:'0.18', service:'东北地区'}, {name: '焦作', value: 75, address:'二道区东环域路2038号', typeName:'联运', area:'0.18', service:'东北地区'}, {name: '句容', value: 75, address:'二道区东环域路2038号', typeName:'联运', area:'0.18', service:'东北地区'}, {name: '北京', value: 79, address:'二道区东环域路2038号', typeName:'联运', area:'0.18', service:'东北地区'}, {name: '徐州', value: 79, address:'二道区东环域路2038号', typeName:'联运', area:'0.18', service:'东北地区'}, {name: '衡水', value: 80, address:'二道区东环域路2038号', typeName:'联运', area:'0.18', service:'东北地区'}, {name: '包头', value: 80, address:'二道区东环域路2038号', typeName:'联运', area:'0.18', service:'东北地区'}, {name: '绵阳', value: 80, address:'二道区东环域路2038号', typeName:'联运', area:'0.18', service:'东北地区'}, {name: '乌鲁木齐', value: 84, address:'二道区东环域路2038号', typeName:'联运', area:'0.18', service:'东北地区'}, {name: '枣庄', value: 84, address:'二道区东环域路2038号', typeName:'联运', area:'0.18', service:'东北地区'}, {name: '杭州', value: 84, address:'二道区东环域路2038号', typeName:'联运', area:'0.18', service:'东北地区'}, {name: '淄博', value: 85, address:'二道区东环域路2038号', typeName:'联运', area:'0.18', service:'东北地区'}, {name: '鞍山', value: 86, address:'二道区东环域路2038号', typeName:'联运', area:'0.18', service:'东北地区'}, {name: '溧阳', value: 86, address:'二道区东环域路2038号', typeName:'联运', area:'0.18', service:'东北地区'}, {name: '库尔勒', value: 86, address:'二道区东环域路2038号', typeName:'联运', area:'0.18', service:'东北地区'}, {name: '安阳', value: 90, address:'二道区东环域路2038号', typeName:'联运', area:'0.18', service:'东北地区'}, {name: '开封', value: 90, address:'二道区东环域路2038号', typeName:'联运', area:'0.18', service:'东北地区'}, {name: '济南', value: 92, address:'二道区东环域路2038号', typeName:'联运', area:'0.18', service:'东北地区'}, {name: '德阳', value: 93, address:'二道区东环域路2038号', typeName:'联运', area:'0.18', service:'东北地区'}, {name: '温州', value: 95, address:'二道区东环域路2038号', typeName:'联运', area:'0.18', service:'东北地区'}, {name: '九江', value: 96, address:'二道区东环域路2038号', typeName:'联运', area:'0.18', service:'东北地区'}, {name: '邯郸', value: 98, address:'二道区东环域路2038号', typeName:'联运', area:'0.18', service:'东北地区'}, {name: '临安', value: 99, address:'二道区东环域路2038号', typeName:'联运', area:'0.18', service:'东北地区'}, {name: '兰州', value: 99, address:'二道区东环域路2038号', typeName:'联运', area:'0.18', service:'东北地区'}, {name: '沧州', value: 100, address:'二道区东环域路2038号', typeName:'联运', area:'0.18', service:'东北地区'}, {name: '临沂', value: 103, address:'二道区东环域路2038号', typeName:'联运', area:'0.18', service:'东北地区'}, {name: '南充', value: 104, address:'二道区东环域路2038号', typeName:'联运', area:'0.18', service:'东北地区'}, {name: '天津', value: 105, address:'二道区东环域路2038号', typeName:'联运', area:'0.18', service:'东北地区'}, {name: '富阳', value: 106, address:'二道区东环域路2038号', typeName:'联运', area:'0.18', service:'东北地区'}, {name: '泰安', value: 112, address:'二道区东环域路2038号', typeName:'联运', area:'0.18', service:'东北地区'}, {name: '诸暨', value: 112, address:'二道区东环域路2038号', typeName:'联运', area:'0.18', service:'东北地区'}, {name: '郑州', value: 113, address:'二道区东环域路2038号', typeName:'联运', area:'0.18', service:'东北地区'}, {name: '哈尔滨', value: 114, address:'二道区东环域路2038号', typeName:'联运', area:'0.18', service:'东北地区'}, {name: '聊城', value: 116, address:'二道区东环域路2038号', typeName:'联运', area:'0.18', service:'东北地区'}, {name: '芜湖', value: 117, address:'二道区东环域路2038号', typeName:'联运', area:'0.18', service:'东北地区'}, {name: '唐山', value: 119, address:'二道区东环域路2038号', typeName:'联运', area:'0.18', service:'东北地区'}, {name: '平顶山', value: 119, address:'二道区东环域路2038号', typeName:'联运', area:'0.18', service:'东北地区'}, {name: '邢台', value: 119, address:'二道区东环域路2038号', typeName:'联运', area:'0.18', service:'东北地区'}, {name: '德州', value: 120, address:'二道区东环域路2038号', typeName:'联运', area:'0.18', service:'东北地区'}, {name: '济宁', value: 120, address:'二道区东环域路2038号', typeName:'联运', area:'0.18', service:'东北地区'}, {name: '荆州', value: 127, address:'二道区东环域路2038号', typeName:'联运', area:'0.18', service:'东北地区'}, {name: '宜昌', value: 130, address:'二道区东环域路2038号', typeName:'联运', area:'0.18', service:'东北地区'}, {name: '义乌', value: 132, address:'二道区东环域路2038号', typeName:'联运', area:'0.18', service:'东北地区'}, {name: '丽水', value: 133, address:'二道区东环域路2038号', typeName:'联运', area:'0.18', service:'东北地区'}, {name: '洛阳', value: 134, address:'二道区东环域路2038号', typeName:'联运', area:'0.18', service:'东北地区'}, {name: '秦皇岛', value: 136, address:'二道区东环域路2038号', typeName:'联运', area:'0.18', service:'东北地区'}, {name: '株洲', value: 143, address:'二道区东环域路2038号', typeName:'联运', area:'0.18', service:'东北地区'}, {name: '石家庄', value: 147, address:'二道区东环域路2038号', typeName:'联运', area:'0.18', service:'东北地区'}, {name: '莱芜', value: 148, address:'二道区东环域路2038号', typeName:'联运', area:'0.18', service:'东北地区'}, {name: '常德', value: 152, address:'二道区东环域路2038号', typeName:'联运', area:'0.18', service:'东北地区'}, {name: '保定', value: 153, address:'二道区东环域路2038号', typeName:'联运', area:'0.18', service:'东北地区'}, {name: '湘潭', value: 154, address:'二道区东环域路2038号', typeName:'联运', area:'0.18', service:'东北地区'}, {name: '金华', value: 157, address:'二道区东环域路2038号', typeName:'联运', area:'0.18', service:'东北地区'}, {name: '岳阳', value: 169, address:'二道区东环域路2038号', typeName:'联运', area:'0.18', service:'东北地区'}, {name: '长沙', value: 175, address:'二道区东环域路2038号', typeName:'联运', area:'0.18', service:'东北地区'}, {name: '衢州', value: 177, address:'二道区东环域路2038号', typeName:'联运', area:'0.18', service:'东北地区'}, {name: '廊坊', value: 170, address:'二道区东环域路2038号', typeName:'联运', area:'0.18', service:'东北地区'}, {name: '菏泽', value: 175, address:'二道区东环域路2038号', typeName:'联运', area:'0.18', service:'东北地区'}, {name: '合肥', value: 180, address:'二道区东环域路2038号', typeName:'联运', area:'0.18', service:'东北地区'}, { name: '武汉', value: 190, address:'二道区东环域路2038号', typeName:'联运', area:'0.18', service:'东北地区' }, { name: '大庆', value: 150, address:'二道区东环域路2038号', typeName:'联运', area:'0.18', service:'东北地区' } ]; var geoCoordMap = { '海门':[121.15,31.89], '鄂尔多斯':[109.781327,39.608266], '招远':[120.38,37.35], '舟山':[122.207216,29.985295], '齐齐哈尔':[123.97,47.33], '盐城':[120.13,33.38], '赤峰':[118.87,42.28], '青岛':[120.33,36.07], '乳山':[121.52,36.89], '金昌':[102.188043,38.520089], '泉州':[118.58,24.93], '莱西':[120.53,36.86], '日照':[119.46,35.42], '胶南':[119.97,35.88], '南通':[121.05,32.08], '拉萨':[91.11,29.97], '云浮':[112.02,22.93], '梅州':[116.1,24.55], '文登':[122.05,37.2], '上海':[121.48,31.22], '攀枝花':[101.718637,26.582347], '威海':[122.1,37.5], '承德':[117.93,40.97], '厦门':[118.1,24.46], '汕尾':[115.375279,22.786211], '潮州':[116.63,23.68], '丹东':[124.37,40.13], '太仓':[121.1,31.45], '曲靖':[103.79,25.51], '烟台':[121.39,37.52], '福州':[119.3,26.08], '瓦房店':[121.979603,39.627114], '即墨':[120.45,36.38], '抚顺':[123.97,41.97], '玉溪':[102.52,24.35], '张家口':[114.87,40.82], '阳泉':[113.57,37.85], '莱州':[119.942327,37.177017], '湖州':[120.1,30.86], '汕头':[116.69,23.39], '昆山':[120.95,31.39], '宁波':[121.56,29.86], '湛江':[110.359377,21.270708], '揭阳':[116.35,23.55], '荣成':[122.41,37.16], '连云港':[119.16,34.59], '葫芦岛':[120.836932,40.711052], '常熟':[120.74,31.64], '东莞':[113.75,23.04], '河源':[114.68,23.73], '淮安':[119.15,33.5], '泰州':[119.9,32.49], '南宁':[108.33,22.84], '营口':[122.18,40.65], '惠州':[114.4,23.09], '江阴':[120.26,31.91], '蓬莱':[120.75,37.8], '韶关':[113.62,24.84], '嘉峪关':[98.289152,39.77313], '广州':[113.23,23.16], '延安':[109.47,36.6], '太原':[112.53,37.87], '清远':[113.01,23.7], '中山':[113.38,22.52], '昆明':[102.73,25.04], '寿光':[118.73,36.86], '盘锦':[122.070714,41.119997], '长治':[113.08,36.18], '深圳':[114.07,22.62], '珠海':[113.52,22.3], '宿迁':[118.3,33.96], '咸阳':[108.72,34.36], '铜川':[109.11,35.09], '平度':[119.97,36.77], '佛山':[113.11,23.05], '海口':[110.35,20.02], '江门':[113.06,22.61], '章丘':[117.53,36.72], '肇庆':[112.44,23.05], '大连':[121.62,38.92], '临汾':[111.5,36.08], '吴江':[120.63,31.16], '石嘴山':[106.39,39.04], '沈阳':[123.38,41.8], '苏州':[120.62,31.32], '茂名':[110.88,21.68], '嘉兴':[120.76,30.77], '长春':[125.35,43.88], '胶州':[120.03336,36.264622], '银川':[106.27,38.47], '张家港':[120.555821,31.875428], '三门峡':[111.19,34.76], '锦州':[121.15,41.13], '南昌':[115.89,28.68], '柳州':[109.4,24.33], '三亚':[109.511909,18.252847], '自贡':[104.778442,29.33903], '吉林':[126.57,43.87], '阳江':[111.95,21.85], '泸州':[105.39,28.91], '西宁':[101.74,36.56], '宜宾':[104.56,29.77], '呼和浩特':[111.65,40.82], '成都':[104.06,30.67], '大同':[113.3,40.12], '镇江':[119.44,32.2], '桂林':[110.28,25.29], '张家界':[110.479191,29.117096], '宜兴':[119.82,31.36], '北海':[109.12,21.49], '西安':[108.95,34.27], '金坛':[119.56,31.74], '东营':[118.49,37.46], '牡丹江':[129.58,44.6], '遵义':[106.9,27.7], '绍兴':[120.58,30.01], '扬州':[119.42,32.39], '常州':[119.95,31.79], '潍坊':[119.1,36.62], '重庆':[106.54,29.59], '台州':[121.420757,28.656386], '南京':[118.78,32.04], '滨州':[118.03,37.36], '贵阳':[106.71,26.57], '无锡':[120.29,31.59], '本溪':[123.73,41.3], '克拉玛依':[84.77,45.59], '渭南':[109.5,34.52], '马鞍山':[118.48,31.56], '宝鸡':[107.15,34.38], '焦作':[113.21,35.24], '句容':[119.16,31.95], '北京':[116.46,39.92], '徐州':[117.2,34.26], '衡水':[115.72,37.72], '包头':[110,40.58], '绵阳':[104.73,31.48], '乌鲁木齐':[87.68,43.77], '枣庄':[117.57,34.86], '杭州':[120.19,30.26], '淄博':[118.05,36.78], '鞍山':[122.85,41.12], '溧阳':[119.48,31.43], '库尔勒':[86.06,41.68], '安阳':[114.35,36.1], '开封':[114.35,34.79], '济南':[117,36.65], '德阳':[104.37,31.13], '温州':[120.65,28.01], '九江':[115.97,29.71], '邯郸':[114.47,36.6], '临安':[119.72,30.23], '兰州':[103.73,36.03], '沧州':[116.83,38.33], '临沂':[118.35,35.05], '南充':[106.110698,30.837793], '天津':[117.2,39.13], '富阳':[119.95,30.07], '泰安':[117.13,36.18], '诸暨':[120.23,29.71], '郑州':[113.65,34.76], '哈尔滨':[126.63,45.75], '聊城':[115.97,36.45], '芜湖':[118.38,31.33], '唐山':[118.02,39.63], '平顶山':[113.29,33.75], '邢台':[114.48,37.05], '德州':[116.29,37.45], '济宁':[116.59,35.38], '荆州':[112.239741,30.335165], '宜昌':[111.3,30.7], '义乌':[120.06,29.32], '丽水':[119.92,28.45], '洛阳':[112.44,34.7], '秦皇岛':[119.57,39.95], '株洲':[113.16,27.83], '石家庄':[114.48,38.03], '莱芜':[117.67,36.19], '常德':[111.69,29.05], '保定':[115.48,38.85], '湘潭':[112.91,27.87], '金华':[119.64,29.12], '岳阳':[113.09,29.37], '长沙':[113,28.21], '衢州':[118.88,28.97], '廊坊':[116.7,39.53], '菏泽':[115.480656,35.23375], '合肥':[117.27,31.86], '武汉':[114.31,30.52], '大庆':[125.03,46.58] }; var convertData = function (data) { var res = []; for (var i = 0; i < data.length; i++) { var geoCoord = geoCoordMap[data[i].name]; if (geoCoord) { res.push({ name: data[i].name, value: geoCoord.concat(data[i].value) }); } } return res; }; var option = { title: { text: '', }, tooltip : { show: false, trigger: 'item', formatter: '{b}<br>{c}', }, bmap: { center: [104.114129, 37.550339], zoom: 5, roam: false, //鼠标缩放 mapStyle: { styleJson: [{ 'featureType': 'land', //土地颜色; 'elementType': 'all', 'stylers': { 'color': '#f5f3ef' } },{ 'featureType': 'water', //水颜色 'elementType': 'all', 'stylers': { 'color': '#a2c1de' } }, { 'featureType': 'railway', //调整铁路颜色 'elementType': 'all', 'stylers': { 'visibility': 'off' } }, { 'featureType': 'highway', //调整高速道路颜色 'elementType': 'all', 'stylers': { 'color': '#fdfdfd' } }, { 'featureType': 'highway', //调整建筑物标签是否可视 'elementType': 'labels', 'stylers': { 'visibility': 'off' } }, { 'featureType': 'arterial', //调整一些干道颜色 'elementType': 'geometry', 'stylers': { 'color': '#fefefe' } }, { 'featureType': 'arterial', 'elementType': 'geometry.fill', 'stylers': { 'color': '#fefefe' } }, { 'featureType': 'poi', 'elementType': 'all', 'stylers': { 'visibility': 'off' } }, { 'featureType': 'green', 'elementType': 'all', 'stylers': { 'visibility': 'off' } }, { 'featureType': 'subway', 'elementType': 'all', 'stylers': { 'visibility': 'off' } }, { 'featureType': 'manmade', 'elementType': 'all', 'stylers': { 'color': '#d1d1d1' } }, { 'featureType': 'local', 'elementType': 'all', 'stylers': { 'color': '#d1d1d1' } }, { 'featureType': 'arterial', 'elementType': 'labels', 'stylers': { 'visibility': 'off' } }, { 'featureType': 'boundary', //边界颜色 'elementType': 'all', 'stylers': { 'color': '#bcab78' } }, { 'featureType': 'building', //建筑颜色 'elementType': 'all', 'stylers': { 'color': '#d1d1d1' } }, { 'featureType': 'label', //地名颜色; 'elementType': 'labels.text.fill', 'stylers': { 'color': '#898989' } }] } }, series : [ { name: 'pm2.5', type: 'scatter', coordinateSystem: 'bmap', data: convertData(data), hoverAnimation: false, //hover动画; symbolSize: function (val) { return val[2] / 10; }, label: { normal: { formatter: '{b}', position: 'right', show: false }, emphasis: { show: false } }, itemStyle: { normal: { color: '#de1300' } } } ] }; myChart.setOption(option); // 获取百度地图实例,使用百度地图自带的控件 var bmap = myChart.getModel().getComponent('bmap').getBMap(); bmap.addControl(new BMap.NavigationControl()); //左侧缩放; bmap.enableDragging(); //开启拖拽 var opts = { offset: {height:-5,width:5}, width : 250, // 信息窗口宽度 height: 150, // 信息窗口高度 title : "" , // 信息窗口标题 enableMessage:true//设置允许信息窗发送短息 }; for(var i=0;i<data.length;i++){ var icon = new BMap.Icon('../images/ico.png', new BMap.Size(10, 10), { anchor: new BMap.Size(5, 5) }); var marker = new BMap.Marker(new BMap.Point(geoCoordMap[data[i].name][0],geoCoordMap[data[i].name][1]),{icon: icon}); // 创建标注 var content = "<b>"+data[i].name+"</b><br><br>" + "园区地址:"+ data[i].address +"<br>" + "园区类型:"+ data[i].typeName +"<br>" + "园区面积:"+ data[i].area +"<br>" + "入驻企业:"+ data[i].value +"家<br>"+ "服务范围:"+ data[i].service; bmap.addOverlay(marker); // 将标注添加到地图中 addClickHandler(content,marker); } function addClickHandler(content,marker){ marker.addEventListener("mouseover",function(e){ openInfo(content,e); }); marker.addEventListener("mouseout",function(e){ bmap.closeInfoWindow(); //关闭信息窗口 }); } function openInfo(content,e){ var p = e.target; var point = new BMap.Point(p.getPosition().lng, p.getPosition().lat); var infoWindow = new BMap.InfoWindow(content,opts); // 创建信息窗口对象 bmap.openInfoWindow(infoWindow,point); //开启信息窗口 } } //操作按钮 $('.t_btn0').click(function () { $('.center_text').css('display', 'none'); $('.t_cos0').css('display', 'block'); echart_map(); }); $('.t_btn1').click(function () { $('.center_text').css('display', 'none'); $('.t_cos1').css('display', 'block'); echart_2(); }); $('.t_btn2').click(function(){ $('.center_text').css('display', 'none'); $('.t_cos2').css('display', 'block'); echart_0(); }); $('.t_btn3').click(function(){ $('.center_text').css('display', 'none'); $('.t_cos3').css('display', 'block'); echart_4(); }); $('.t_btn4').click(function(){ $('.center_text').css('display', 'none'); $('.t_cos6').css('display', 'block'); echart_6(); }); $('.t_btn5').click(function(){ $('.center_text').css('display', 'none'); $('.t_cos4').css('display', 'block'); echart_1(); }); $('.t_btn6').click(function(){ $('.center_text').css('display', 'none'); $('.t_cos5').css('display', 'block'); echart_3(); }); $('.t_btn7').click(function(){ $('.center_text').css('display', 'none'); $('.t_cos7').css('display', 'block'); echart_7(); }); $('.t_btn8').click(function(){ $('.center_text').css('display', 'none'); $('.t_cos8').css('display', 'block'); echart_8(); }); $('.t_btn9').click(function(){ $('.center_text').css('display', 'none'); $('.t_cos9').css('display', 'block'); echart_9(); }); $('.t_btn10').click(function(){ $('.center_text').css('display', 'none'); $('.t_cos10').css('display', 'block'); echart_10(); }); $('.t_btn11').click(function(){ $('.center_text').css('display', 'none'); $('.t_cos11').css('display', 'block'); echart_11(); }); $('.t_btn12').click(function(){ $('.center_text').css('display', 'none'); $('.t_cos12').css('display', 'block'); echart_12(); }); $('.t_btn13').click(function(){ $('.center_text').css('display', 'none'); $('.t_cos13').css('display', 'block'); echart_13(); }); $('.t_btn14').click(function(){ $('.center_text').css('display', 'none'); $('.t_cos14').css('display', 'block'); echart_14(); }); //获取地址栏参数 $(function(){ function getUrlParms(name){ var reg = new RegExp("(^|&)"+ name +"=([^&]*)(&|$)"); var r = window.location.search.substr(1).match(reg); if(r!=null) return unescape(r[2]); return null; } var id = getUrlParms("id"); if(id == 2){ $('.center_text').css('display', 'none'); $('.t_cos10').css('display', 'block'); echart_10(); } if(id == 3){ $('.center_text').css('display', 'none'); $('.t_cos11').css('display', 'block'); echart_11(); } if(id == 4){ $('.center_text').css('display', 'none'); $('.t_cos1').css('display', 'block'); echart_2(); } if(id == 5){ $('.center_text').css('display', 'none'); $('.t_cos6').css('display', 'block'); echart_6(); } if(id == 6){ $('.center_text').css('display', 'none'); $('.t_cos4').css('display', 'block'); echart_1(); } if(id == 7){ $('.center_text').css('display', 'none'); $('.t_cos8').css('display', 'block'); echart_8(); } if(id == 8){ $('.center_text').css('display', 'none'); $('.t_cos12').css('display', 'block'); echart_12(); } if(id == 9){ $('.center_text').css('display', 'none'); $('.t_cos13').css('display', 'block'); echart_13(); } }); });
2301_78696cqk/Django_pyecharts_scrapy
scenery_spider_web-main/mainapp/static/js/base.js
JavaScript
unknown
179,523
(function webpackUniversalModuleDefinition(root, factory) { if(typeof exports === 'object' && typeof module === 'object') module.exports = factory(require("echarts")); else if(typeof define === 'function' && define.amd) define(["echarts"], factory); else if(typeof exports === 'object') exports["bmap"] = factory(require("echarts")); else root["echarts"] = root["echarts"] || {}, root["echarts"]["bmap"] = factory(root["echarts"]); })(this, function(__WEBPACK_EXTERNAL_MODULE_1__) { return /******/ (function(modules) { // webpackBootstrap /******/ // The module cache /******/ var installedModules = {}; /******/ // The require function /******/ function __webpack_require__(moduleId) { /******/ // Check if module is in cache /******/ if(installedModules[moduleId]) /******/ return installedModules[moduleId].exports; /******/ // Create a new module (and put it into the cache) /******/ var module = installedModules[moduleId] = { /******/ exports: {}, /******/ id: moduleId, /******/ loaded: false /******/ }; /******/ // Execute the module function /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); /******/ // Flag the module as loaded /******/ module.loaded = true; /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ // expose the modules object (__webpack_modules__) /******/ __webpack_require__.m = modules; /******/ // expose the module cache /******/ __webpack_require__.c = installedModules; /******/ // __webpack_public_path__ /******/ __webpack_require__.p = ""; /******/ // Load entry module and return exports /******/ return __webpack_require__(0); /******/ }) /************************************************************************/ /******/ ([ /* 0 */ /***/ function(module, exports, __webpack_require__) { var __WEBPACK_AMD_DEFINE_RESULT__;/** * BMap component extension */ !(__WEBPACK_AMD_DEFINE_RESULT__ = function (require) { __webpack_require__(1).registerCoordinateSystem( 'bmap', __webpack_require__(2) ); __webpack_require__(3); __webpack_require__(4); // Action __webpack_require__(1).registerAction({ type: 'bmapRoam', event: 'bmapRoam', update: 'updateLayout' }, function (payload, ecModel) { ecModel.eachComponent('bmap', function (bMapModel) { var bmap = bMapModel.getBMap(); var center = bmap.getCenter(); bMapModel.setCenterAndZoom([center.lng, center.lat], bmap.getZoom()); }); }); return { version: '1.0.0' }; }.call(exports, __webpack_require__, exports, module), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)); /***/ }, /* 1 */ /***/ function(module, exports) { module.exports = __WEBPACK_EXTERNAL_MODULE_1__; /***/ }, /* 2 */ /***/ function(module, exports, __webpack_require__) { var __WEBPACK_AMD_DEFINE_RESULT__;!(__WEBPACK_AMD_DEFINE_RESULT__ = function (require) { var echarts = __webpack_require__(1); var zrUtil = echarts.util; function BMapCoordSys(bmap, api) { this._bmap = bmap; this.dimensions = ['lng', 'lat']; this._mapOffset = [0, 0]; this._api = api; this._projection = new BMap.MercatorProjection(); } BMapCoordSys.prototype.dimensions = ['lng', 'lat']; BMapCoordSys.prototype.setZoom = function (zoom) { this._zoom = zoom; }; BMapCoordSys.prototype.setCenter = function (center) { this._center = this._projection.lngLatToPoint(new BMap.Point(center[0], center[1])); }; BMapCoordSys.prototype.setMapOffset = function (mapOffset) { this._mapOffset = mapOffset; }; BMapCoordSys.prototype.getBMap = function () { return this._bmap; }; BMapCoordSys.prototype.dataToPoint = function (data) { var point = new BMap.Point(data[0], data[1]); // TODO mercator projection is toooooooo slow // var mercatorPoint = this._projection.lngLatToPoint(point); // var width = this._api.getZr().getWidth(); // var height = this._api.getZr().getHeight(); // var divider = Math.pow(2, 18 - 10); // return [ // Math.round((mercatorPoint.x - this._center.x) / divider + width / 2), // Math.round((this._center.y - mercatorPoint.y) / divider + height / 2) // ]; var px = this._bmap.pointToOverlayPixel(point); var mapOffset = this._mapOffset; return [px.x - mapOffset[0], px.y - mapOffset[1]]; }; BMapCoordSys.prototype.pointToData = function (pt) { var mapOffset = this._mapOffset; var pt = this._bmap.overlayPixelToPoint({ x: pt[0] + mapOffset[0], y: pt[1] + mapOffset[1] }); return [pt.lng, pt.lat]; }; BMapCoordSys.prototype.getViewRect = function () { var api = this._api; return new echarts.graphic.BoundingRect(0, 0, api.getWidth(), api.getHeight()); }; BMapCoordSys.prototype.getRoamTransform = function () { return echarts.matrix.create(); }; BMapCoordSys.prototype.prepareCustoms = function (data) { var rect = this.getViewRect(); return { coordSys: { // The name exposed to user is always 'cartesian2d' but not 'grid'. type: 'bmap', x: rect.x, y: rect.y, width: rect.width, height: rect.height }, api: { coord: zrUtil.bind(this.dataToPoint, this), size: zrUtil.bind(dataToCoordSize, this) } }; }; function dataToCoordSize(dataSize, dataItem) { dataItem = dataItem || [0, 0]; return zrUtil.map([0, 1], function (dimIdx) { var val = dataItem[dimIdx]; var halfSize = dataSize[dimIdx] / 2; var p1 = []; var p2 = []; p1[dimIdx] = val - halfSize; p2[dimIdx] = val + halfSize; p1[1 - dimIdx] = p2[1 - dimIdx] = dataItem[1 - dimIdx]; return Math.abs(this.dataToPoint(p1)[dimIdx] - this.dataToPoint(p2)[dimIdx]); }, this); } var Overlay; // For deciding which dimensions to use when creating list data BMapCoordSys.dimensions = BMapCoordSys.prototype.dimensions; function createOverlayCtor() { function Overlay(root) { this._root = root; } Overlay.prototype = new BMap.Overlay(); /** * 初始化 * * @param {BMap.Map} map * @override */ Overlay.prototype.initialize = function (map) { map.getPanes().labelPane.appendChild(this._root); return this._root; }; /** * @override */ Overlay.prototype.draw = function () {}; return Overlay; } BMapCoordSys.create = function (ecModel, api) { var bmapCoordSys; var root = api.getDom(); // TODO Dispose ecModel.eachComponent('bmap', function (bmapModel) { var viewportRoot = api.getZr().painter.getViewportRoot(); if (typeof BMap === 'undefined') { throw new Error('BMap api is not loaded'); } Overlay = Overlay || createOverlayCtor(); if (bmapCoordSys) { throw new Error('Only one bmap component can exist'); } if (!bmapModel.__bmap) { // Not support IE8 var bmapRoot = root.querySelector('.ec-extension-bmap'); if (bmapRoot) { // Reset viewport left and top, which will be changed // in moving handler in BMapView viewportRoot.style.left = '0px'; viewportRoot.style.top = '0px'; root.removeChild(bmapRoot); bmapRoot.classList.add('ec-extension-bmap'); } bmapRoot = document.createElement('div'); bmapRoot.style.cssText = 'width:100%;height:100%'; // Not support IE8 // bmapRoot.classList.add('ec-extension-bmap'); root.appendChild(bmapRoot); var bmap = bmapModel.__bmap = new BMap.Map(bmapRoot); var overlay = new Overlay(viewportRoot); bmap.addOverlay(overlay); } var bmap = bmapModel.__bmap; // Set bmap options // centerAndZoom before layout and render var center = bmapModel.get('center'); var zoom = bmapModel.get('zoom'); if (center && zoom) { var pt = new BMap.Point(center[0], center[1]); bmap.centerAndZoom(pt, zoom); } bmapCoordSys = new BMapCoordSys(bmap, api); bmapCoordSys.setMapOffset(bmapModel.__mapOffset || [0, 0]); bmapCoordSys.setZoom(zoom); bmapCoordSys.setCenter(center); bmapModel.coordinateSystem = bmapCoordSys; }); ecModel.eachSeries(function (seriesModel) { if (seriesModel.get('coordinateSystem') === 'bmap') { seriesModel.coordinateSystem = bmapCoordSys; } }); }; return BMapCoordSys; }.call(exports, __webpack_require__, exports, module), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)); /***/ }, /* 3 */ /***/ function(module, exports, __webpack_require__) { var __WEBPACK_AMD_DEFINE_RESULT__;!(__WEBPACK_AMD_DEFINE_RESULT__ = function (require) { function v2Equal(a, b) { return a && b && a[0] === b[0] && a[1] === b[1]; } return __webpack_require__(1).extendComponentModel({ type: 'bmap', getBMap: function () { // __bmap is injected when creating BMapCoordSys return this.__bmap; }, setCenterAndZoom: function (center, zoom) { this.option.center = center; this.option.zoom = zoom; }, centerOrZoomChanged: function (center, zoom) { var option = this.option; return !(v2Equal(center, option.center) && zoom === option.zoom); }, defaultOption: { center: [104.114129, 37.550339], zoom: 5, mapStyle: {}, roam: false } }); }.call(exports, __webpack_require__, exports, module), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)); /***/ }, /* 4 */ /***/ function(module, exports, __webpack_require__) { var __WEBPACK_AMD_DEFINE_RESULT__;!(__WEBPACK_AMD_DEFINE_RESULT__ = function (require) { return __webpack_require__(1).extendComponentView({ type: 'bmap', render: function (bMapModel, ecModel, api) { var rendering = true; var bmap = bMapModel.getBMap(); var viewportRoot = api.getZr().painter.getViewportRoot(); var coordSys = bMapModel.coordinateSystem; var moveHandler = function (type, target) { if (rendering) { return; } var offsetEl = viewportRoot.parentNode.parentNode.parentNode; var mapOffset = [ -parseInt(offsetEl.style.left, 10) || 0, -parseInt(offsetEl.style.top, 10) || 0 ]; viewportRoot.style.left = mapOffset[0] + 'px'; viewportRoot.style.top = mapOffset[1] + 'px'; coordSys.setMapOffset(mapOffset); bMapModel.__mapOffset = mapOffset; api.dispatchAction({ type: 'bmapRoam' }); }; function zoomEndHandler() { if (rendering) { return; } api.dispatchAction({ type: 'bmapRoam' }); } bmap.removeEventListener('moving', this._oldMoveHandler); // FIXME // Moveend may be triggered by centerAndZoom method when creating coordSys next time // bmap.removeEventListener('moveend', this._oldMoveHandler); bmap.removeEventListener('zoomend', this._oldZoomEndHandler); bmap.addEventListener('moving', moveHandler); // bmap.addEventListener('moveend', moveHandler); bmap.addEventListener('zoomend', zoomEndHandler); this._oldMoveHandler = moveHandler; this._oldZoomEndHandler = zoomEndHandler; var roam = bMapModel.get('roam'); if (roam && roam !== 'scale') { bmap.enableDragging(); } else { bmap.disableDragging(); } if (roam && roam !== 'move') { bmap.enableScrollWheelZoom(); bmap.enableDoubleClickZoom(); bmap.enablePinchToZoom(); } else { bmap.disableScrollWheelZoom(); bmap.disableDoubleClickZoom(); bmap.disablePinchToZoom(); } var originalStyle = bMapModel.__mapStyle; var newMapStyle = bMapModel.get('mapStyle') || {}; // FIXME, Not use JSON methods var mapStyleStr = JSON.stringify(newMapStyle); if (JSON.stringify(originalStyle) !== mapStyleStr) { // FIXME May have blank tile when dragging if setMapStyle if (!Object.keys) { Object.keys = function(o) { if (o !== Object(o)) throw new TypeError('Object.keys called on a non-object'); var k=[],p; for (p in o) if (Object.prototype.hasOwnProperty.call(o,p)) k.push(p); return k; } } if (Object.keys(newMapStyle).length) { bmap.setMapStyle(newMapStyle); } // bmap.setMapStyle(newMapStyle); bMapModel.__mapStyle = JSON.parse(mapStyleStr); } rendering = false; } }); }.call(exports, __webpack_require__, exports, module), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)); /***/ } /******/ ]) }); ;
2301_78696cqk/Django_pyecharts_scrapy
scenery_spider_web-main/mainapp/static/js/bmap.js
JavaScript
unknown
16,008
$(function () { $(".header_nav>ul>li>a").on("click",function () { $(this).addClass("nav_current").parent("li").siblings("li").children("a").removeClass("nav_current"); }) $(".header_nav>ul>li").hover(function () { $(this).children("ul").toggle(); }) $(".header>.header_nav>ul>li>ul>li").hover(function () { $(this).children("ul").toggle(); }) $("#add_ipt").on("click",function () { $('#modal_add').modal(); }) $("#date_ipt").on("click",function () { $('#myModal').modal(); }) $("#video_ipt").on("click",function () { $('#Modal').modal(); }) })
2301_78696cqk/Django_pyecharts_scrapy
scenery_spider_web-main/mainapp/static/js/common.js
JavaScript
unknown
653
$(function () { echart_1(); echart_2(); echart_3(); echart_4(); echart_map(); echart_5(); //echart_1湖南货物收入 function echart_1() { // 基于准备好的dom,初始化echarts实例 var myChart = echarts.init(document.getElementById('chart_1')); option = { tooltip: { trigger: 'item', formatter: "{a} <br/>{b} : {c}万元" }, legend: { x: 'center', y: '15%', data: [ '张家口', '承德', '衡水','邢台', '邯郸', '保定','秦皇岛','石家庄', '唐山'], icon: 'circle', textStyle: { color: '#fff', } }, calculable: true, series: [{ name: '', type: 'pie', //起始角度,支持范围[0, 360] startAngle: 0, //饼图的半径,数组的第一项是内半径,第二项是外半径 radius: [41, 100.75], //支持设置成百分比,设置成百分比时第一项是相对于容器宽度,第二项是相对于容器高度 center: ['50%', '40%'], //是否展示成南丁格尔图,通过半径区分数据大小。可选择两种模式: // 'radius' 面积展现数据的百分比,半径展现数据的大小。 // 'area' 所有扇区面积相同,仅通过半径展现数据大小 roseType: 'area', //是否启用防止标签重叠策略,默认开启,圆环图这个例子中需要强制所有标签放在中心位置,可以将该值设为 false。 avoidLabelOverlap: false, label: { normal: { show: true, formatter: '{c}万元' }, emphasis: { show: true } }, labelLine: { normal: { show: true, length2: 1, }, emphasis: { show: true } }, data: [{ value: 900.58, name: '张家口', itemStyle: { normal: { color: '#f845f1' } } }, { value: 1100.58, name: '承德', itemStyle: { normal: { color: '#ad46f3' } } }, { value: 1200.58, name: '衡水', itemStyle: { normal: { color: '#5045f6' } } }, { value: 1300.58, name: '邢台', itemStyle: { normal: { color: '#4777f5' } } }, { value: 1400.58, name: '邯郸', itemStyle: { normal: { color: '#44aff0' } } }, { value: 1500.58, name: '保定', itemStyle: { normal: { color: '#45dbf7' } } }, { value: 1500.58, name: '秦皇岛', itemStyle: { normal: { color: '#f6d54a' } } }, { value: 1600.58, name: '石家庄', itemStyle: { normal: { color: '#f69846' } } }, { value: 1800, name: '唐山', itemStyle: { normal: { color: '#ff4343' } } }, { value: 0, name: "", itemStyle: { normal: { color: 'transparent' } }, label: { show: false }, labelLine: { show: false } }, { value: 0, name: "", itemStyle: { normal: { color: 'transparent' } }, label: { show: false }, labelLine: { show: false } }, { value: 0, name: "", itemStyle: { normal: { color: 'transparent' } }, label: { show: false }, labelLine: { show: false } }, { value: 0, name: "", itemStyle: { normal: { color: 'transparent' } }, label: { show: false }, labelLine: { show: false } }, { value: 0, name: "", itemStyle: { normal: { color: 'transparent' } }, label: { show: false }, labelLine: { show: false } }, { value: 0, name: "", itemStyle: { normal: { color: 'transparent' } }, label: { show: false }, labelLine: { show: false } }, { value: 0, name: "", itemStyle: { normal: { color: 'transparent' } }, label: { show: false }, labelLine: { show: false } }, { value: 0, name: "", itemStyle: { normal: { color: 'transparent' } }, label: { show: false }, labelLine: { show: false } }, { value: 0, name: "", itemStyle: { normal: { color: 'transparent' } }, label: { show: false }, labelLine: { show: false } } ] }] }; // 使用刚指定的配置项和数据显示图表。 myChart.setOption(option); window.addEventListener("resize", function () { myChart.resize(); }); } //echart_2湖南省地图 function echart_2() { // 基于准备好的dom,初始化echarts实例 var myChart = echarts.init(document.getElementById('chart_2')); function showProvince() { myChart.setOption(option = { // backgroundColor: '#ffffff', visualMap: { show: false, min: 0, max: 100, left: 'left', top: 'bottom', text: ['高', '低'], // 文本,默认为数值文本 calculable: true, inRange: { color: ['yellow', 'lightskyblue', 'orangered'] } }, series: [{ type: 'map', mapType: 'hunan', roam: true, label: { normal: { show: true }, emphasis: { textStyle: { color: '#fff' } } }, itemStyle: { normal: { borderColor: '#389BB7', areaColor: '#fff', }, emphasis: { areaColor: '#389BB7', borderWidth: 0 } }, animation: false, data: [{ name: '长沙市', value: 100 }, { name: '株洲市', value: 96 }, { name: '湘潭市', value: 98 }, { name: '衡阳市', value: 80 }, { name: '邵阳市', value: 88 }, { name: '岳阳市', value: 79 }, { name: '常德市', value: 77, }, { name: '张家界市', value: 33 }, { name: '益阳市', value: 69, }, { name: '郴州市', value: 66 }, { name: '永州市', value: 22 },{ name: '娄底市', value: 51 },{ name: '湘西土家族苗族自治州', value: 44 },{ name: '怀化市', value: 9 }] }] }); } var currentIdx = 0; showProvince(); // 使用刚指定的配置项和数据显示图表。 window.addEventListener("resize", function () { myChart.resize(); }); } // echart_map中国地图 function echart_map() { // 基于准备好的dom,初始化echarts实例 var myChart = echarts.init(document.getElementById('chart_map')); var mapName = 'china' var data = [] var toolTipData = []; /*获取地图数据*/ myChart.showLoading(); var mapFeatures = echarts.getMap(mapName).geoJson.features; myChart.hideLoading(); var geoCoordMap = { '福州': [119.4543, 25.9222], '长春': [125.8154, 44.2584], '重庆': [107.7539, 30.1904], '西安': [109.1162, 34.2004], '成都': [103.9526, 30.7617], '常州': [119.4543, 31.5582], '北京': [116.4551, 40.2539], '北海': [109.314, 21.6211], '海口': [110.3893, 19.8516], '长沙': [113.019455,28.200103], '上海': [121.40, 31.73], '内蒙古': [106.82, 39.67] }; var GZData = [ [{ name: '长沙' }, { name: '福州', value: 95 }], [{ name: '长沙' }, { name: '长春', value: 80 }], [{ name: '长沙' }, { name: '重庆', value: 70 }], [{ name: '长沙' }, { name: '西安', value: 60 }], [{ name: '长沙' }, { name: '成都', value: 50 }], [{ name: '长沙' }, { name: '常州', value: 40 }], [{ name: '长沙' }, { name: '北京', value: 30 }], [{ name: '长沙' }, { name: '北海', value: 20 }], [{ name: '长沙' }, { name: '海口', value: 10 }], [{ name: '长沙' }, { name: '上海', value: 80 }], [{ name: '长沙' }, { name: '内蒙古', value: 80 }] ]; var convertData = function (data) { var res = []; for (var i = 0; i < data.length; i++) { var dataItem = data[i]; var fromCoord = geoCoordMap[dataItem[0].name]; var toCoord = geoCoordMap[dataItem[1].name]; if (fromCoord && toCoord) { res.push({ fromName: dataItem[0].name, toName: dataItem[1].name, coords: [fromCoord, toCoord] }); } } return res; }; var color = ['#c5f80e']; var series = []; [ ['石家庄', GZData] ].forEach(function (item, i) { series.push({ name: item[0], type: 'lines', zlevel: 2, symbol: ['none', 'arrow'], symbolSize: 10, effect: { show: true, period: 6, trailLength: 0, symbol: 'arrow', symbolSize: 5 }, lineStyle: { normal: { color: color[i], width: 1, opacity: 0.6, curveness: 0.2 } }, data: convertData(item[1]) }, { name: item[0], type: 'effectScatter', coordinateSystem: 'geo', zlevel: 2, rippleEffect: { brushType: 'stroke' }, label: { normal: { show: true, position: 'right', formatter: '{b}' } }, symbolSize: function (val) { return val[2] / 8; }, itemStyle: { normal: { color: color[i] } }, data: item[1].map(function (dataItem) { return { name: dataItem[1].name, value: geoCoordMap[dataItem[1].name].concat([dataItem[1].value]) }; }) }); }); option = { tooltip: { trigger: 'item' }, geo: { map: 'china', label: { emphasis: { show: false } }, roam: true, itemStyle: { normal: { borderColor: 'rgba(147, 235, 248, 1)', borderWidth: 1, areaColor: { type: 'radial', x: 0.5, y: 0.5, r: 0.8, colorStops: [{ offset: 0, color: 'rgba(175,238,238, 0)' // 0% 处的颜色 }, { offset: 1, color: 'rgba(47,79,79, .1)' // 100% 处的颜色 }], globalCoord: false // 缺省为 false }, shadowColor: 'rgba(128, 217, 248, 1)', // shadowColor: 'rgba(255, 255, 255, 1)', shadowOffsetX: -2, shadowOffsetY: 2, shadowBlur: 10 }, emphasis: { areaColor: '#389BB7', borderWidth: 0 } } }, series: series }; // 使用刚指定的配置项和数据显示图表。 myChart.setOption(option); window.addEventListener("resize", function () { myChart.resize(); }); } //echart_3货物周转量 function echart_3() { // 基于准备好的dom,初始化echarts实例 var myChart = echarts.init(document.getElementById('chart_3')); myChart.clear(); option = { title: { text: '' }, tooltip: { trigger: 'axis' }, legend: { data:['铁路货物','国家铁路货物','地方铁路货物','合资铁路货物','公路货物','水运货物'], textStyle:{ color: '#fff' }, top: '8%' }, grid: { top: '40%', left: '3%', right: '4%', bottom: '3%', containLabel: true }, color: ['#FF4949','#FFA74D','#FFEA51','#4BF0FF','#44AFF0','#4E82FF','#584BFF','#BE4DFF','#F845F1'], xAxis: { type: 'category', boundaryGap: false, data: ['2012年','2013年','2014年','2015年','2016年'], splitLine: { show: false }, axisLine: { lineStyle: { color: '#fff' } } }, yAxis: { name: '亿吨公里', type: 'value', splitLine: { show: false }, axisLine: { lineStyle: { color: '#fff' } } }, series: [ { name:'铁路货物', type:'line', data:[3961.88, 4233.63, 4183.14, 3633.01, 3704.47] }, { name:'国家铁路货物', type:'line', data:[3374.76, 3364.76, 3274.76, 3371.82, 3259.87] }, { name:'地方铁路货物', type:'line', data:[14.77, 15.17, 13.17, 14.56, 15.84] }, { name:'合资铁路货物', type:'line', data:[686.17,847.26,895.22,865.28,886.72] }, { name:'公路货物', type:'line', data:[6133.47, 6577.89, 7019.56,6821.48,7294.59] }, { name:'水运货物', type:'line', data:[509.60, 862.54, 1481.77,1552.79,1333.62] } ] }; myChart.setOption(option); } //湖南高速公路 function echart_4() { // 基于准备好的dom,初始化echarts实例 var myChart = echarts.init(document.getElementById('chart_4')); myChart.setOption({ series: [{ type: 'map', mapType: 'hunan' }] }); var geoCoordMap = { '怀化': [109.999867,27.518949], '吉首': [109.741528,28.332629], '张家界': [110.491722,29.112001], '常德': [111.701486,29.076683], '益阳': [112.348741,28.544124], '岳阳': [113.126486,29.382401], '长沙': [113.019455,28.200103], '株洲': [113.163141,27.8418], '湘潭': [112.91977,27.882141], '邵阳': [111.467859,27.21915], '娄底': [112.012438,27.745506], '衡阳': [112.63809,26.895225], '永州': [111.577632,26.460144], '郴州': [113.039396,25.81497] }; var goData = [ [{ name: '张家界' }, { id: 1, name: '常德', value: 86 }], [{ name: '吉首' }, { id: 1, name: '常德', value: 86 }], [{ name: '常德' }, { id: 1, name: '益阳', value: 70 }], [{ name: '益阳' }, { id: 1, name: '长沙', value: 95 }], [{ name: '长沙' }, { id: 1, name: '岳阳', value: 70 }], [{ name: '长沙' }, { id: 1, name: '湘潭', value: 80 }], [{ name: '长沙' }, { id: 1, name: '株洲', value: 80 }], [{ name: '长沙' }, { id: 1, name: '衡阳', value: 80 }], [{ name: '衡阳' }, { id: 1, name: '郴州', value: 70 }], [{ name: '衡阳' }, { id: 1, name: '永州', value: 70 }], [{ name: '湘潭' }, { id: 1, name: '娄底', value: 60 }], [{ name: '娄底' }, { id: 1, name: '邵阳', value: 75 }], [{ name: '邵阳' }, { id: 1, name: '怀化', value: 75 }], ]; //值控制圆点大小 var backData = [ [{ name: '常德' }, { id: 1, name: '张家界', value: 80 }], [{ name: '常德' }, { id: 1, name: '吉首', value: 66 }], [{ name: '益阳' }, { id: 1, name: '常德', value: 86 }], [{ name: '长沙' }, { id: 1, name: '益阳', value: 70 }], [{ name: '岳阳' }, { id: 1, name: '长沙', value: 95 }], [{ name: '湘潭' }, { id: 1, name: '长沙', value: 95 }], [{ name: '株洲' }, { id: 1, name: '长沙', value: 95 }], [{ name: '衡阳' }, { id: 1, name: '长沙', value: 95 }], [{ name: '郴州' }, { id: 1, name: '衡阳', value: 80 }], [{ name: '永州' }, { id: 1, name: '衡阳', value: 80 }], [{ name: '娄底' }, { id: 1, name: '湘潭', value: 80 }], [{ name: '邵阳' }, { id: 1, name: '娄底', value: 60 }], [{ name: '怀化' }, { id: 1, name: '邵阳', value: 75 }], ]; var planePath = 'path://M1705.06,1318.313v-89.254l-319.9-221.799l0.073-208.063c0.521-84.662-26.629-121.796-63.961-121.491c-37.332-0.305-64.482,36.829-63.961,121.491l0.073,208.063l-319.9,221.799v89.254l330.343-157.288l12.238,241.308l-134.449,92.931l0.531,42.034l175.125-42.917l175.125,42.917l0.531-42.034l-134.449-92.931l12.238-241.308L1705.06,1318.313z'; var arcAngle = function(data) { var j, k; for (var i = 0; i < data.length; i++) { var dataItem = data[i]; if (dataItem[1].id == 1) { j = 0.2; return j; } else if (dataItem[1].id == 2) { k = -0.2; return k; } } } var convertData = function(data) { var res = []; for (var i = 0; i < data.length; i++) { var dataItem = data[i]; var fromCoord = geoCoordMap[dataItem[0].name]; var toCoord = geoCoordMap[dataItem[1].name]; if (dataItem[1].id == 1) { if (fromCoord && toCoord) { res.push([{ coord: fromCoord, }, { coord: toCoord, value: dataItem[1].value //线条颜色 }]); } } else if (dataItem[1].id == 2) { if (fromCoord && toCoord) { res.push([{ coord: fromCoord, }, { coord: toCoord }]); } } } return res; }; var color = ['#fff', '#FF1493', '#0000FF']; var series = []; [ ['1', goData], ['2', backData] ].forEach(function(item, i) { series.push({ name: item[0], type: 'lines', zlevel: 2, symbol: ['arrow', 'arrow'], //线特效配置 effect: { show: true, period: 6, trailLength: 0.1, symbol: 'arrow', //标记类型 symbolSize: 5 }, lineStyle: { normal: { width: 1, opacity: 0.4, curveness: arcAngle(item[1]), //弧线角度 color: '#fff' } }, edgeLabel: { normal: { show: true, textStyle: { fontSize: 14 }, formatter: function(params) { var txt = ''; if (params.data.speed !== undefined) { txt = params.data.speed; } return txt; }, } }, data: convertData(item[1]) }, { type: 'effectScatter', coordinateSystem: 'geo', zlevel: 2, //波纹效果 rippleEffect: { period: 2, brushType: 'stroke', scale: 3 }, label: { normal: { show: true, color: '#fff', position: 'right', formatter: '{b}' } }, //终点形象 symbol: 'circle', //圆点大小 symbolSize: function(val) { return val[2] / 8; }, itemStyle: { normal: { show: true } }, data: item[1].map(function(dataItem) { return { name: dataItem[1].name, value: geoCoordMap[dataItem[1].name].concat([dataItem[1].value]) }; }) }); }); option = { title: { text: '', subtext: '', left: 'center', textStyle: { color: '#fff' } }, tooltip: { trigger: 'item', formatter: '{b}' }, //线颜色及飞行轨道颜色 visualMap: { show: false, min: 0, max: 100, color: ['#31A031','#31A031'] }, //地图相关设置 geo: { map: 'hunan', //视角缩放比例 zoom: 1, //显示文本样式 label: { normal: { show: false, textStyle: { color: '#fff' } }, emphasis: { textStyle: { color: '#fff' } } }, //鼠标缩放和平移 roam: true, itemStyle: { normal: { // color: '#ddd', borderColor: 'rgba(147, 235, 248, 1)', borderWidth: 1, areaColor: { type: 'radial', x: 0.5, y: 0.5, r: 0.8, colorStops: [{ offset: 0, color: 'rgba(175,238,238, 0)' // 0% 处的颜色 }, { offset: 1, color: 'rgba( 47,79,79, .2)' // 100% 处的颜色 }], globalCoord: false // 缺省为 false }, shadowColor: 'rgba(128, 217, 248, 1)', // shadowColor: 'rgba(255, 255, 255, 1)', shadowOffsetX: -2, shadowOffsetY: 2, shadowBlur: 10 }, emphasis: { areaColor: '#389BB7', borderWidth: 0 } } }, series: series }; myChart.setOption(option); } //湖南省飞机场 function echart_5() { // 基于准备好的dom,初始化echarts实例 var myChart = echarts.init(document.getElementById('chart_5')); function showProvince() { var geoCoordMap = { '长沙黄花国际机场': [113.226512,28.192929], '张家界荷花机场': [110.454598,29.107223], '常德桃花源机场': [111.651508,28.921516], '永州零陵机场': [111.622869,26.340994], '怀化芷江机场': [109.714784,27.44615], }; var data = [{ name: '长沙黄花国际机场', value: 100 }, { name: '张家界荷花机场', value: 100 }, { name: '常德桃花源机场', value: 100 }, { name: '永州零陵机场', value: 100 }, { name: '怀化芷江机场', value: 100 } ]; var max = 480, min = 9; // todo var maxSize4Pin = 100, minSize4Pin = 20; var convertData = function (data) { var res = []; for (var i = 0; i < data.length; i++) { var geoCoord = geoCoordMap[data[i].name]; if (geoCoord) { res.push({ name: data[i].name, value: geoCoord.concat(data[i].value) }); } } return res; }; myChart.setOption(option = { title: { top: 20, text: '', subtext: '', x: 'center', textStyle: { color: '#ccc' } }, legend: { orient: 'vertical', y: 'bottom', x: 'right', data: ['pm2.5'], textStyle: { color: '#fff' } }, visualMap: { show: false, min: 0, max: 500, left: 'left', top: 'bottom', text: ['高', '低'], // 文本,默认为数值文本 calculable: true, seriesIndex: [1], inRange: { } }, geo: { show: true, map:'hunan', mapType: 'hunan', label: { normal: { }, //鼠标移入后查看效果 emphasis: { textStyle: { color: '#fff' } } }, //鼠标缩放和平移 roam: true, itemStyle: { normal: { // color: '#ddd', borderColor: 'rgba(147, 235, 248, 1)', borderWidth: 1, areaColor: { type: 'radial', x: 0.5, y: 0.5, r: 0.8, colorStops: [{ offset: 0, color: 'rgba(175,238,238, 0)' // 0% 处的颜色 }, { offset: 1, color: 'rgba( 47,79,79, .2)' // 100% 处的颜色 }], globalCoord: false // 缺省为 false }, shadowColor: 'rgba(128, 217, 248, 1)', shadowOffsetX: -2, shadowOffsetY: 2, shadowBlur: 10 }, emphasis: { areaColor: '#389BB7', borderWidth: 0 } } }, series: [{ name: 'light', type: 'map', coordinateSystem: 'geo', data: convertData(data), itemStyle: { normal: { color: '#F4E925' } } }, { name: '点', type: 'scatter', coordinateSystem: 'geo', symbol: 'pin', symbolSize: function(val) { var a = (maxSize4Pin - minSize4Pin) / (max - min); var b = minSize4Pin - a * min; b = maxSize4Pin - a * max; return a * val[2] + b; }, label: { normal: { // show: true, // textStyle: { // color: '#fff', // fontSize: 9, // } } }, itemStyle: { normal: { color: '#F62157', //标志颜色 } }, zlevel: 6, data: convertData(data), }, { name: 'light', type: 'map', mapType: 'hunan', geoIndex: 0, aspectScale: 0.75, //长宽比 showLegendSymbol: false, // 存在legend时显示 label: { normal: { show: false }, emphasis: { show: false, textStyle: { color: '#fff' } } }, roam: true, itemStyle: { normal: { areaColor: '#031525', borderColor: '#FFFFFF', }, emphasis: { areaColor: '#2B91B7' } }, animation: false, data: data }, { name: ' ', type: 'effectScatter', coordinateSystem: 'geo', data: convertData(data.sort(function (a, b) { return b.value - a.value; }).slice(0, 5)), symbolSize: function (val) { return val[2] / 10; }, showEffectOn: 'render', rippleEffect: { brushType: 'stroke' }, hoverAnimation: true, label: { normal: { formatter: '{b}', position: 'right', show: true } }, itemStyle: { normal: { color: '#05C3F9', shadowBlur: 10, shadowColor: '#05C3F9' } }, zlevel: 1 }, ] }); } showProvince(); // 使用刚指定的配置项和数据显示图表。 // myChart.setOption(option); window.addEventListener("resize", function () { myChart.resize(); }); } //点击跳转 $('#chart_map').click(function(){ window.location.href = './page/index.html'; }); $('.t_btn2').click(function(){ window.location.href = "./page/index.html?id=2"; }); $('.t_btn3').click(function(){ window.location.href = "./page/index.html?id=3"; }); $('.t_btn4').click(function(){ window.location.href = "./page/index.html?id=4"; }); $('.t_btn5').click(function(){ window.location.href = "./page/index.html?id=5"; }); $('.t_btn6').click(function(){ window.location.href = "./page/index.html?id=6"; }); $('.t_btn7').click(function(){ window.location.href = "./page/index.html?id=7"; }); $('.t_btn8').click(function(){ window.location.href = "./page/index.html?id=8"; }); $('.t_btn9').click(function(){ window.location.href = "./page/index.html?id=9"; }); });
2301_78696cqk/Django_pyecharts_scrapy
scenery_spider_web-main/mainapp/static/js/index.js
JavaScript
unknown
47,487
html, body { width: 100%; height: 100%; background: url('../img/true.png') no-repeat; color: white; } body { display: -ms-flexbox; display: -webkit-box; display: flex; -ms-flex-align: center; -ms-flex-pack: center; -webkit-box-align: center; align-items: center; -webkit-box-pack: center; justify-content: center; padding-top: 40px; padding-bottom: 40px; /*background-color: #f5f5f5;*/ } .form-signin { width: 100%; max-width: 330px; padding: 15px; margin: 0 auto; } .form-signin .checkbox { font-weight: 400; } .form-signin .form-control { position: relative; box-sizing: border-box; height: auto; padding: 10px; font-size: 16px; } .form-signin .form-control:focus { z-index: 2; } .form-signin input[type="email"] { margin-bottom: -1px; border-bottom-right-radius: 0; border-bottom-left-radius: 0; } .form-signin input[type="password"] { margin-bottom: 10px; border-top-left-radius: 0; border-top-right-radius: 0; }
2301_78696cqk/Django_pyecharts_scrapy
scenery_spider_web-main/mainapp/static/login/css/signin.css
CSS
unknown
1,056
/*! * jQuery JavaScript Library v3.5.0 -ajax,-ajax/jsonp,-ajax/load,-ajax/script,-ajax/var/location,-ajax/var/nonce,-ajax/var/rquery,-ajax/xhr,-manipulation/_evalUrl,-deprecated/ajax-event-alias,-effects,-effects/Tween,-effects/animatedSelector * https://jquery.com/ * * Includes Sizzle.js * https://sizzlejs.com/ * * Copyright JS Foundation and other contributors * Released under the MIT license * https://jquery.org/license * * Date: 2020-04-10T15:07Z */ ( function( global, factory ) { "use strict"; if ( typeof module === "object" && typeof module.exports === "object" ) { // For CommonJS and CommonJS-like environments where a proper `window` // is present, execute the factory and get jQuery. // For environments that do not have a `window` with a `document` // (such as Node.js), expose a factory as module.exports. // This accentuates the need for the creation of a real `window`. // e.g. var jQuery = require("jquery")(window); // See ticket #14549 for more info. module.exports = global.document ? factory( global, true ) : function( w ) { if ( !w.document ) { throw new Error( "jQuery requires a window with a document" ); } return factory( w ); }; } else { factory( global ); } // Pass this if window is not defined yet } )( typeof window !== "undefined" ? window : this, function( window, noGlobal ) { // Edge <= 12 - 13+, Firefox <=18 - 45+, IE 10 - 11, Safari 5.1 - 9+, iOS 6 - 9.1 // throw exceptions when non-strict code (e.g., ASP.NET 4.5) accesses strict mode // arguments.callee.caller (trac-13335). But as of jQuery 3.0 (2016), strict mode should be common // enough that all such attempts are guarded in a try block. "use strict"; var arr = []; var getProto = Object.getPrototypeOf; var slice = arr.slice; var flat = arr.flat ? function( array ) { return arr.flat.call( array ); } : function( array ) { return arr.concat.apply( [], array ); }; var push = arr.push; var indexOf = arr.indexOf; var class2type = {}; var toString = class2type.toString; var hasOwn = class2type.hasOwnProperty; var fnToString = hasOwn.toString; var ObjectFunctionString = fnToString.call( Object ); var support = {}; var isFunction = function isFunction( obj ) { // Support: Chrome <=57, Firefox <=52 // In some browsers, typeof returns "function" for HTML <object> elements // (i.e., `typeof document.createElement( "object" ) === "function"`). // We don't want to classify *any* DOM node as a function. return typeof obj === "function" && typeof obj.nodeType !== "number"; }; var isWindow = function isWindow( obj ) { return obj != null && obj === obj.window; }; var document = window.document; var preservedScriptAttributes = { type: true, src: true, nonce: true, noModule: true }; function DOMEval( code, node, doc ) { doc = doc || document; var i, val, script = doc.createElement( "script" ); script.text = code; if ( node ) { for ( i in preservedScriptAttributes ) { // Support: Firefox 64+, Edge 18+ // Some browsers don't support the "nonce" property on scripts. // On the other hand, just using `getAttribute` is not enough as // the `nonce` attribute is reset to an empty string whenever it // becomes browsing-context connected. // See https://github.com/whatwg/html/issues/2369 // See https://html.spec.whatwg.org/#nonce-attributes // The `node.getAttribute` check was added for the sake of // `jQuery.globalEval` so that it can fake a nonce-containing node // via an object. val = node[ i ] || node.getAttribute && node.getAttribute( i ); if ( val ) { script.setAttribute( i, val ); } } } doc.head.appendChild( script ).parentNode.removeChild( script ); } function toType( obj ) { if ( obj == null ) { return obj + ""; } // Support: Android <=2.3 only (functionish RegExp) return typeof obj === "object" || typeof obj === "function" ? class2type[ toString.call( obj ) ] || "object" : typeof obj; } /* global Symbol */ // Defining this global in .eslintrc.json would create a danger of using the global // unguarded in another place, it seems safer to define global only for this module var version = "3.5.0 -ajax,-ajax/jsonp,-ajax/load,-ajax/script,-ajax/var/location,-ajax/var/nonce,-ajax/var/rquery,-ajax/xhr,-manipulation/_evalUrl,-deprecated/ajax-event-alias,-effects,-effects/Tween,-effects/animatedSelector", // Define a local copy of jQuery jQuery = function( selector, context ) { // The jQuery object is actually just the init constructor 'enhanced' // Need init if jQuery is called (just allow error to be thrown if not included) return new jQuery.fn.init( selector, context ); }; jQuery.fn = jQuery.prototype = { // The current version of jQuery being used jquery: version, constructor: jQuery, // The default length of a jQuery object is 0 length: 0, toArray: function() { return slice.call( this ); }, // Get the Nth element in the matched element set OR // Get the whole matched element set as a clean array get: function( num ) { // Return all the elements in a clean array if ( num == null ) { return slice.call( this ); } // Return just the one element from the set return num < 0 ? this[ num + this.length ] : this[ num ]; }, // Take an array of elements and push it onto the stack // (returning the new matched element set) pushStack: function( elems ) { // Build a new jQuery matched element set var ret = jQuery.merge( this.constructor(), elems ); // Add the old object onto the stack (as a reference) ret.prevObject = this; // Return the newly-formed element set return ret; }, // Execute a callback for every element in the matched set. each: function( callback ) { return jQuery.each( this, callback ); }, map: function( callback ) { return this.pushStack( jQuery.map( this, function( elem, i ) { return callback.call( elem, i, elem ); } ) ); }, slice: function() { return this.pushStack( slice.apply( this, arguments ) ); }, first: function() { return this.eq( 0 ); }, last: function() { return this.eq( -1 ); }, even: function() { return this.pushStack( jQuery.grep( this, function( _elem, i ) { return ( i + 1 ) % 2; } ) ); }, odd: function() { return this.pushStack( jQuery.grep( this, function( _elem, i ) { return i % 2; } ) ); }, eq: function( i ) { var len = this.length, j = +i + ( i < 0 ? len : 0 ); return this.pushStack( j >= 0 && j < len ? [ this[ j ] ] : [] ); }, end: function() { return this.prevObject || this.constructor(); }, // For internal use only. // Behaves like an Array's method, not like a jQuery method. push: push, sort: arr.sort, splice: arr.splice }; jQuery.extend = jQuery.fn.extend = function() { var options, name, src, copy, copyIsArray, clone, target = arguments[ 0 ] || {}, i = 1, length = arguments.length, deep = false; // Handle a deep copy situation if ( typeof target === "boolean" ) { deep = target; // Skip the boolean and the target target = arguments[ i ] || {}; i++; } // Handle case when target is a string or something (possible in deep copy) if ( typeof target !== "object" && !isFunction( target ) ) { target = {}; } // Extend jQuery itself if only one argument is passed if ( i === length ) { target = this; i--; } for ( ; i < length; i++ ) { // Only deal with non-null/undefined values if ( ( options = arguments[ i ] ) != null ) { // Extend the base object for ( name in options ) { copy = options[ name ]; // Prevent Object.prototype pollution // Prevent never-ending loop if ( name === "__proto__" || target === copy ) { continue; } // Recurse if we're merging plain objects or arrays if ( deep && copy && ( jQuery.isPlainObject( copy ) || ( copyIsArray = Array.isArray( copy ) ) ) ) { src = target[ name ]; // Ensure proper type for the source value if ( copyIsArray && !Array.isArray( src ) ) { clone = []; } else if ( !copyIsArray && !jQuery.isPlainObject( src ) ) { clone = {}; } else { clone = src; } copyIsArray = false; // Never move original objects, clone them target[ name ] = jQuery.extend( deep, clone, copy ); // Don't bring in undefined values } else if ( copy !== undefined ) { target[ name ] = copy; } } } } // Return the modified object return target; }; jQuery.extend( { // Unique for each copy of jQuery on the page expando: "jQuery" + ( version + Math.random() ).replace( /\D/g, "" ), // Assume jQuery is ready without the ready module isReady: true, error: function( msg ) { throw new Error( msg ); }, noop: function() {}, isPlainObject: function( obj ) { var proto, Ctor; // Detect obvious negatives // Use toString instead of jQuery.type to catch host objects if ( !obj || toString.call( obj ) !== "[object Object]" ) { return false; } proto = getProto( obj ); // Objects with no prototype (e.g., `Object.create( null )`) are plain if ( !proto ) { return true; } // Objects with prototype are plain iff they were constructed by a global Object function Ctor = hasOwn.call( proto, "constructor" ) && proto.constructor; return typeof Ctor === "function" && fnToString.call( Ctor ) === ObjectFunctionString; }, isEmptyObject: function( obj ) { var name; for ( name in obj ) { return false; } return true; }, // Evaluates a script in a provided context; falls back to the global one // if not specified. globalEval: function( code, options, doc ) { DOMEval( code, { nonce: options && options.nonce }, doc ); }, each: function( obj, callback ) { var length, i = 0; if ( isArrayLike( obj ) ) { length = obj.length; for ( ; i < length; i++ ) { if ( callback.call( obj[ i ], i, obj[ i ] ) === false ) { break; } } } else { for ( i in obj ) { if ( callback.call( obj[ i ], i, obj[ i ] ) === false ) { break; } } } return obj; }, // results is for internal usage only makeArray: function( arr, results ) { var ret = results || []; if ( arr != null ) { if ( isArrayLike( Object( arr ) ) ) { jQuery.merge( ret, typeof arr === "string" ? [ arr ] : arr ); } else { push.call( ret, arr ); } } return ret; }, inArray: function( elem, arr, i ) { return arr == null ? -1 : indexOf.call( arr, elem, i ); }, // Support: Android <=4.0 only, PhantomJS 1 only // push.apply(_, arraylike) throws on ancient WebKit merge: function( first, second ) { var len = +second.length, j = 0, i = first.length; for ( ; j < len; j++ ) { first[ i++ ] = second[ j ]; } first.length = i; return first; }, grep: function( elems, callback, invert ) { var callbackInverse, matches = [], i = 0, length = elems.length, callbackExpect = !invert; // Go through the array, only saving the items // that pass the validator function for ( ; i < length; i++ ) { callbackInverse = !callback( elems[ i ], i ); if ( callbackInverse !== callbackExpect ) { matches.push( elems[ i ] ); } } return matches; }, // arg is for internal usage only map: function( elems, callback, arg ) { var length, value, i = 0, ret = []; // Go through the array, translating each of the items to their new values if ( isArrayLike( elems ) ) { length = elems.length; for ( ; i < length; i++ ) { value = callback( elems[ i ], i, arg ); if ( value != null ) { ret.push( value ); } } // Go through every key on the object, } else { for ( i in elems ) { value = callback( elems[ i ], i, arg ); if ( value != null ) { ret.push( value ); } } } // Flatten any nested arrays return flat( ret ); }, // A global GUID counter for objects guid: 1, // jQuery.support is not used in Core but other projects attach their // properties to it so it needs to exist. support: support } ); if ( typeof Symbol === "function" ) { jQuery.fn[ Symbol.iterator ] = arr[ Symbol.iterator ]; } // Populate the class2type map jQuery.each( "Boolean Number String Function Array Date RegExp Object Error Symbol".split( " " ), function( _i, name ) { class2type[ "[object " + name + "]" ] = name.toLowerCase(); } ); function isArrayLike( obj ) { // Support: real iOS 8.2 only (not reproducible in simulator) // `in` check used to prevent JIT error (gh-2145) // hasOwn isn't used here due to false negatives // regarding Nodelist length in IE var length = !!obj && "length" in obj && obj.length, type = toType( obj ); if ( isFunction( obj ) || isWindow( obj ) ) { return false; } return type === "array" || length === 0 || typeof length === "number" && length > 0 && ( length - 1 ) in obj; } var Sizzle = /*! * Sizzle CSS Selector Engine v2.3.5 * https://sizzlejs.com/ * * Copyright JS Foundation and other contributors * Released under the MIT license * https://js.foundation/ * * Date: 2020-03-14 */ ( function( window ) { var i, support, Expr, getText, isXML, tokenize, compile, select, outermostContext, sortInput, hasDuplicate, // Local document vars setDocument, document, docElem, documentIsHTML, rbuggyQSA, rbuggyMatches, matches, contains, // Instance-specific data expando = "sizzle" + 1 * new Date(), preferredDoc = window.document, dirruns = 0, done = 0, classCache = createCache(), tokenCache = createCache(), compilerCache = createCache(), nonnativeSelectorCache = createCache(), sortOrder = function( a, b ) { if ( a === b ) { hasDuplicate = true; } return 0; }, // Instance methods hasOwn = ( {} ).hasOwnProperty, arr = [], pop = arr.pop, pushNative = arr.push, push = arr.push, slice = arr.slice, // Use a stripped-down indexOf as it's faster than native // https://jsperf.com/thor-indexof-vs-for/5 indexOf = function( list, elem ) { var i = 0, len = list.length; for ( ; i < len; i++ ) { if ( list[ i ] === elem ) { return i; } } return -1; }, booleans = "checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|" + "ismap|loop|multiple|open|readonly|required|scoped", // Regular expressions // http://www.w3.org/TR/css3-selectors/#whitespace whitespace = "[\\x20\\t\\r\\n\\f]", // https://www.w3.org/TR/css-syntax-3/#ident-token-diagram identifier = "(?:\\\\[\\da-fA-F]{1,6}" + whitespace + "?|\\\\[^\\r\\n\\f]|[\\w-]|[^\0-\\x7f])+", // Attribute selectors: http://www.w3.org/TR/selectors/#attribute-selectors attributes = "\\[" + whitespace + "*(" + identifier + ")(?:" + whitespace + // Operator (capture 2) "*([*^$|!~]?=)" + whitespace + // "Attribute values must be CSS identifiers [capture 5] // or strings [capture 3 or capture 4]" "*(?:'((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\"|(" + identifier + "))|)" + whitespace + "*\\]", pseudos = ":(" + identifier + ")(?:\\((" + // To reduce the number of selectors needing tokenize in the preFilter, prefer arguments: // 1. quoted (capture 3; capture 4 or capture 5) "('((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\")|" + // 2. simple (capture 6) "((?:\\\\.|[^\\\\()[\\]]|" + attributes + ")*)|" + // 3. anything else (capture 2) ".*" + ")\\)|)", // Leading and non-escaped trailing whitespace, capturing some non-whitespace characters preceding the latter rwhitespace = new RegExp( whitespace + "+", "g" ), rtrim = new RegExp( "^" + whitespace + "+|((?:^|[^\\\\])(?:\\\\.)*)" + whitespace + "+$", "g" ), rcomma = new RegExp( "^" + whitespace + "*," + whitespace + "*" ), rcombinators = new RegExp( "^" + whitespace + "*([>+~]|" + whitespace + ")" + whitespace + "*" ), rdescend = new RegExp( whitespace + "|>" ), rpseudo = new RegExp( pseudos ), ridentifier = new RegExp( "^" + identifier + "$" ), matchExpr = { "ID": new RegExp( "^#(" + identifier + ")" ), "CLASS": new RegExp( "^\\.(" + identifier + ")" ), "TAG": new RegExp( "^(" + identifier + "|[*])" ), "ATTR": new RegExp( "^" + attributes ), "PSEUDO": new RegExp( "^" + pseudos ), "CHILD": new RegExp( "^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\(" + whitespace + "*(even|odd|(([+-]|)(\\d*)n|)" + whitespace + "*(?:([+-]|)" + whitespace + "*(\\d+)|))" + whitespace + "*\\)|)", "i" ), "bool": new RegExp( "^(?:" + booleans + ")$", "i" ), // For use in libraries implementing .is() // We use this for POS matching in `select` "needsContext": new RegExp( "^" + whitespace + "*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\(" + whitespace + "*((?:-\\d)?\\d*)" + whitespace + "*\\)|)(?=[^-]|$)", "i" ) }, rhtml = /HTML$/i, rinputs = /^(?:input|select|textarea|button)$/i, rheader = /^h\d$/i, rnative = /^[^{]+\{\s*\[native \w/, // Easily-parseable/retrievable ID or TAG or CLASS selectors rquickExpr = /^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/, rsibling = /[+~]/, // CSS escapes // http://www.w3.org/TR/CSS21/syndata.html#escaped-characters runescape = new RegExp( "\\\\[\\da-fA-F]{1,6}" + whitespace + "?|\\\\([^\\r\\n\\f])", "g" ), funescape = function( escape, nonHex ) { var high = "0x" + escape.slice( 1 ) - 0x10000; return nonHex ? // Strip the backslash prefix from a non-hex escape sequence nonHex : // Replace a hexadecimal escape sequence with the encoded Unicode code point // Support: IE <=11+ // For values outside the Basic Multilingual Plane (BMP), manually construct a // surrogate pair high < 0 ? String.fromCharCode( high + 0x10000 ) : String.fromCharCode( high >> 10 | 0xD800, high & 0x3FF | 0xDC00 ); }, // CSS string/identifier serialization // https://drafts.csswg.org/cssom/#common-serializing-idioms rcssescape = /([\0-\x1f\x7f]|^-?\d)|^-$|[^\0-\x1f\x7f-\uFFFF\w-]/g, fcssescape = function( ch, asCodePoint ) { if ( asCodePoint ) { // U+0000 NULL becomes U+FFFD REPLACEMENT CHARACTER if ( ch === "\0" ) { return "\uFFFD"; } // Control characters and (dependent upon position) numbers get escaped as code points return ch.slice( 0, -1 ) + "\\" + ch.charCodeAt( ch.length - 1 ).toString( 16 ) + " "; } // Other potentially-special ASCII characters get backslash-escaped return "\\" + ch; }, // Used for iframes // See setDocument() // Removing the function wrapper causes a "Permission Denied" // error in IE unloadHandler = function() { setDocument(); }, inDisabledFieldset = addCombinator( function( elem ) { return elem.disabled === true && elem.nodeName.toLowerCase() === "fieldset"; }, { dir: "parentNode", next: "legend" } ); // Optimize for push.apply( _, NodeList ) try { push.apply( ( arr = slice.call( preferredDoc.childNodes ) ), preferredDoc.childNodes ); // Support: Android<4.0 // Detect silently failing push.apply // eslint-disable-next-line no-unused-expressions arr[ preferredDoc.childNodes.length ].nodeType; } catch ( e ) { push = { apply: arr.length ? // Leverage slice if possible function( target, els ) { pushNative.apply( target, slice.call( els ) ); } : // Support: IE<9 // Otherwise append directly function( target, els ) { var j = target.length, i = 0; // Can't trust NodeList.length while ( ( target[ j++ ] = els[ i++ ] ) ) {} target.length = j - 1; } }; } function Sizzle( selector, context, results, seed ) { var m, i, elem, nid, match, groups, newSelector, newContext = context && context.ownerDocument, // nodeType defaults to 9, since context defaults to document nodeType = context ? context.nodeType : 9; results = results || []; // Return early from calls with invalid selector or context if ( typeof selector !== "string" || !selector || nodeType !== 1 && nodeType !== 9 && nodeType !== 11 ) { return results; } // Try to shortcut find operations (as opposed to filters) in HTML documents if ( !seed ) { setDocument( context ); context = context || document; if ( documentIsHTML ) { // If the selector is sufficiently simple, try using a "get*By*" DOM method // (excepting DocumentFragment context, where the methods don't exist) if ( nodeType !== 11 && ( match = rquickExpr.exec( selector ) ) ) { // ID selector if ( ( m = match[ 1 ] ) ) { // Document context if ( nodeType === 9 ) { if ( ( elem = context.getElementById( m ) ) ) { // Support: IE, Opera, Webkit // TODO: identify versions // getElementById can match elements by name instead of ID if ( elem.id === m ) { results.push( elem ); return results; } } else { return results; } // Element context } else { // Support: IE, Opera, Webkit // TODO: identify versions // getElementById can match elements by name instead of ID if ( newContext && ( elem = newContext.getElementById( m ) ) && contains( context, elem ) && elem.id === m ) { results.push( elem ); return results; } } // Type selector } else if ( match[ 2 ] ) { push.apply( results, context.getElementsByTagName( selector ) ); return results; // Class selector } else if ( ( m = match[ 3 ] ) && support.getElementsByClassName && context.getElementsByClassName ) { push.apply( results, context.getElementsByClassName( m ) ); return results; } } // Take advantage of querySelectorAll if ( support.qsa && !nonnativeSelectorCache[ selector + " " ] && ( !rbuggyQSA || !rbuggyQSA.test( selector ) ) && // Support: IE 8 only // Exclude object elements ( nodeType !== 1 || context.nodeName.toLowerCase() !== "object" ) ) { newSelector = selector; newContext = context; // qSA considers elements outside a scoping root when evaluating child or // descendant combinators, which is not what we want. // In such cases, we work around the behavior by prefixing every selector in the // list with an ID selector referencing the scope context. // The technique has to be used as well when a leading combinator is used // as such selectors are not recognized by querySelectorAll. // Thanks to Andrew Dupont for this technique. if ( nodeType === 1 && ( rdescend.test( selector ) || rcombinators.test( selector ) ) ) { // Expand context for sibling selectors newContext = rsibling.test( selector ) && testContext( context.parentNode ) || context; // We can use :scope instead of the ID hack if the browser // supports it & if we're not changing the context. if ( newContext !== context || !support.scope ) { // Capture the context ID, setting it first if necessary if ( ( nid = context.getAttribute( "id" ) ) ) { nid = nid.replace( rcssescape, fcssescape ); } else { context.setAttribute( "id", ( nid = expando ) ); } } // Prefix every selector in the list groups = tokenize( selector ); i = groups.length; while ( i-- ) { groups[ i ] = ( nid ? "#" + nid : ":scope" ) + " " + toSelector( groups[ i ] ); } newSelector = groups.join( "," ); } try { push.apply( results, newContext.querySelectorAll( newSelector ) ); return results; } catch ( qsaError ) { nonnativeSelectorCache( selector, true ); } finally { if ( nid === expando ) { context.removeAttribute( "id" ); } } } } } // All others return select( selector.replace( rtrim, "$1" ), context, results, seed ); } /** * Create key-value caches of limited size * @returns {function(string, object)} Returns the Object data after storing it on itself with * property name the (space-suffixed) string and (if the cache is larger than Expr.cacheLength) * deleting the oldest entry */ function createCache() { var keys = []; function cache( key, value ) { // Use (key + " ") to avoid collision with native prototype properties (see Issue #157) if ( keys.push( key + " " ) > Expr.cacheLength ) { // Only keep the most recent entries delete cache[ keys.shift() ]; } return ( cache[ key + " " ] = value ); } return cache; } /** * Mark a function for special use by Sizzle * @param {Function} fn The function to mark */ function markFunction( fn ) { fn[ expando ] = true; return fn; } /** * Support testing using an element * @param {Function} fn Passed the created element and returns a boolean result */ function assert( fn ) { var el = document.createElement( "fieldset" ); try { return !!fn( el ); } catch ( e ) { return false; } finally { // Remove from its parent by default if ( el.parentNode ) { el.parentNode.removeChild( el ); } // release memory in IE el = null; } } /** * Adds the same handler for all of the specified attrs * @param {String} attrs Pipe-separated list of attributes * @param {Function} handler The method that will be applied */ function addHandle( attrs, handler ) { var arr = attrs.split( "|" ), i = arr.length; while ( i-- ) { Expr.attrHandle[ arr[ i ] ] = handler; } } /** * Checks document order of two siblings * @param {Element} a * @param {Element} b * @returns {Number} Returns less than 0 if a precedes b, greater than 0 if a follows b */ function siblingCheck( a, b ) { var cur = b && a, diff = cur && a.nodeType === 1 && b.nodeType === 1 && a.sourceIndex - b.sourceIndex; // Use IE sourceIndex if available on both nodes if ( diff ) { return diff; } // Check if b follows a if ( cur ) { while ( ( cur = cur.nextSibling ) ) { if ( cur === b ) { return -1; } } } return a ? 1 : -1; } /** * Returns a function to use in pseudos for input types * @param {String} type */ function createInputPseudo( type ) { return function( elem ) { var name = elem.nodeName.toLowerCase(); return name === "input" && elem.type === type; }; } /** * Returns a function to use in pseudos for buttons * @param {String} type */ function createButtonPseudo( type ) { return function( elem ) { var name = elem.nodeName.toLowerCase(); return ( name === "input" || name === "button" ) && elem.type === type; }; } /** * Returns a function to use in pseudos for :enabled/:disabled * @param {Boolean} disabled true for :disabled; false for :enabled */ function createDisabledPseudo( disabled ) { // Known :disabled false positives: fieldset[disabled] > legend:nth-of-type(n+2) :can-disable return function( elem ) { // Only certain elements can match :enabled or :disabled // https://html.spec.whatwg.org/multipage/scripting.html#selector-enabled // https://html.spec.whatwg.org/multipage/scripting.html#selector-disabled if ( "form" in elem ) { // Check for inherited disabledness on relevant non-disabled elements: // * listed form-associated elements in a disabled fieldset // https://html.spec.whatwg.org/multipage/forms.html#category-listed // https://html.spec.whatwg.org/multipage/forms.html#concept-fe-disabled // * option elements in a disabled optgroup // https://html.spec.whatwg.org/multipage/forms.html#concept-option-disabled // All such elements have a "form" property. if ( elem.parentNode && elem.disabled === false ) { // Option elements defer to a parent optgroup if present if ( "label" in elem ) { if ( "label" in elem.parentNode ) { return elem.parentNode.disabled === disabled; } else { return elem.disabled === disabled; } } // Support: IE 6 - 11 // Use the isDisabled shortcut property to check for disabled fieldset ancestors return elem.isDisabled === disabled || // Where there is no isDisabled, check manually /* jshint -W018 */ elem.isDisabled !== !disabled && inDisabledFieldset( elem ) === disabled; } return elem.disabled === disabled; // Try to winnow out elements that can't be disabled before trusting the disabled property. // Some victims get caught in our net (label, legend, menu, track), but it shouldn't // even exist on them, let alone have a boolean value. } else if ( "label" in elem ) { return elem.disabled === disabled; } // Remaining elements are neither :enabled nor :disabled return false; }; } /** * Returns a function to use in pseudos for positionals * @param {Function} fn */ function createPositionalPseudo( fn ) { return markFunction( function( argument ) { argument = +argument; return markFunction( function( seed, matches ) { var j, matchIndexes = fn( [], seed.length, argument ), i = matchIndexes.length; // Match elements found at the specified indexes while ( i-- ) { if ( seed[ ( j = matchIndexes[ i ] ) ] ) { seed[ j ] = !( matches[ j ] = seed[ j ] ); } } } ); } ); } /** * Checks a node for validity as a Sizzle context * @param {Element|Object=} context * @returns {Element|Object|Boolean} The input node if acceptable, otherwise a falsy value */ function testContext( context ) { return context && typeof context.getElementsByTagName !== "undefined" && context; } // Expose support vars for convenience support = Sizzle.support = {}; /** * Detects XML nodes * @param {Element|Object} elem An element or a document * @returns {Boolean} True iff elem is a non-HTML XML node */ isXML = Sizzle.isXML = function( elem ) { var namespace = elem.namespaceURI, docElem = ( elem.ownerDocument || elem ).documentElement; // Support: IE <=8 // Assume HTML when documentElement doesn't yet exist, such as inside loading iframes // https://bugs.jquery.com/ticket/4833 return !rhtml.test( namespace || docElem && docElem.nodeName || "HTML" ); }; /** * Sets document-related variables once based on the current document * @param {Element|Object} [doc] An element or document object to use to set the document * @returns {Object} Returns the current document */ setDocument = Sizzle.setDocument = function( node ) { var hasCompare, subWindow, doc = node ? node.ownerDocument || node : preferredDoc; // Return early if doc is invalid or already selected // Support: IE 11+, Edge 17 - 18+ // IE/Edge sometimes throw a "Permission denied" error when strict-comparing // two documents; shallow comparisons work. // eslint-disable-next-line eqeqeq if ( doc == document || doc.nodeType !== 9 || !doc.documentElement ) { return document; } // Update global variables document = doc; docElem = document.documentElement; documentIsHTML = !isXML( document ); // Support: IE 9 - 11+, Edge 12 - 18+ // Accessing iframe documents after unload throws "permission denied" errors (jQuery #13936) // Support: IE 11+, Edge 17 - 18+ // IE/Edge sometimes throw a "Permission denied" error when strict-comparing // two documents; shallow comparisons work. // eslint-disable-next-line eqeqeq if ( preferredDoc != document && ( subWindow = document.defaultView ) && subWindow.top !== subWindow ) { // Support: IE 11, Edge if ( subWindow.addEventListener ) { subWindow.addEventListener( "unload", unloadHandler, false ); // Support: IE 9 - 10 only } else if ( subWindow.attachEvent ) { subWindow.attachEvent( "onunload", unloadHandler ); } } // Support: IE 8 - 11+, Edge 12 - 18+, Chrome <=16 - 25 only, Firefox <=3.6 - 31 only, // Safari 4 - 5 only, Opera <=11.6 - 12.x only // IE/Edge & older browsers don't support the :scope pseudo-class. // Support: Safari 6.0 only // Safari 6.0 supports :scope but it's an alias of :root there. support.scope = assert( function( el ) { docElem.appendChild( el ).appendChild( document.createElement( "div" ) ); return typeof el.querySelectorAll !== "undefined" && !el.querySelectorAll( ":scope fieldset div" ).length; } ); /* Attributes ---------------------------------------------------------------------- */ // Support: IE<8 // Verify that getAttribute really returns attributes and not properties // (excepting IE8 booleans) support.attributes = assert( function( el ) { el.className = "i"; return !el.getAttribute( "className" ); } ); /* getElement(s)By* ---------------------------------------------------------------------- */ // Check if getElementsByTagName("*") returns only elements support.getElementsByTagName = assert( function( el ) { el.appendChild( document.createComment( "" ) ); return !el.getElementsByTagName( "*" ).length; } ); // Support: IE<9 support.getElementsByClassName = rnative.test( document.getElementsByClassName ); // Support: IE<10 // Check if getElementById returns elements by name // The broken getElementById methods don't pick up programmatically-set names, // so use a roundabout getElementsByName test support.getById = assert( function( el ) { docElem.appendChild( el ).id = expando; return !document.getElementsByName || !document.getElementsByName( expando ).length; } ); // ID filter and find if ( support.getById ) { Expr.filter[ "ID" ] = function( id ) { var attrId = id.replace( runescape, funescape ); return function( elem ) { return elem.getAttribute( "id" ) === attrId; }; }; Expr.find[ "ID" ] = function( id, context ) { if ( typeof context.getElementById !== "undefined" && documentIsHTML ) { var elem = context.getElementById( id ); return elem ? [ elem ] : []; } }; } else { Expr.filter[ "ID" ] = function( id ) { var attrId = id.replace( runescape, funescape ); return function( elem ) { var node = typeof elem.getAttributeNode !== "undefined" && elem.getAttributeNode( "id" ); return node && node.value === attrId; }; }; // Support: IE 6 - 7 only // getElementById is not reliable as a find shortcut Expr.find[ "ID" ] = function( id, context ) { if ( typeof context.getElementById !== "undefined" && documentIsHTML ) { var node, i, elems, elem = context.getElementById( id ); if ( elem ) { // Verify the id attribute node = elem.getAttributeNode( "id" ); if ( node && node.value === id ) { return [ elem ]; } // Fall back on getElementsByName elems = context.getElementsByName( id ); i = 0; while ( ( elem = elems[ i++ ] ) ) { node = elem.getAttributeNode( "id" ); if ( node && node.value === id ) { return [ elem ]; } } } return []; } }; } // Tag Expr.find[ "TAG" ] = support.getElementsByTagName ? function( tag, context ) { if ( typeof context.getElementsByTagName !== "undefined" ) { return context.getElementsByTagName( tag ); // DocumentFragment nodes don't have gEBTN } else if ( support.qsa ) { return context.querySelectorAll( tag ); } } : function( tag, context ) { var elem, tmp = [], i = 0, // By happy coincidence, a (broken) gEBTN appears on DocumentFragment nodes too results = context.getElementsByTagName( tag ); // Filter out possible comments if ( tag === "*" ) { while ( ( elem = results[ i++ ] ) ) { if ( elem.nodeType === 1 ) { tmp.push( elem ); } } return tmp; } return results; }; // Class Expr.find[ "CLASS" ] = support.getElementsByClassName && function( className, context ) { if ( typeof context.getElementsByClassName !== "undefined" && documentIsHTML ) { return context.getElementsByClassName( className ); } }; /* QSA/matchesSelector ---------------------------------------------------------------------- */ // QSA and matchesSelector support // matchesSelector(:active) reports false when true (IE9/Opera 11.5) rbuggyMatches = []; // qSa(:focus) reports false when true (Chrome 21) // We allow this because of a bug in IE8/9 that throws an error // whenever `document.activeElement` is accessed on an iframe // So, we allow :focus to pass through QSA all the time to avoid the IE error // See https://bugs.jquery.com/ticket/13378 rbuggyQSA = []; if ( ( support.qsa = rnative.test( document.querySelectorAll ) ) ) { // Build QSA regex // Regex strategy adopted from Diego Perini assert( function( el ) { var input; // Select is set to empty string on purpose // This is to test IE's treatment of not explicitly // setting a boolean content attribute, // since its presence should be enough // https://bugs.jquery.com/ticket/12359 docElem.appendChild( el ).innerHTML = "<a id='" + expando + "'></a>" + "<select id='" + expando + "-\r\\' msallowcapture=''>" + "<option selected=''></option></select>"; // Support: IE8, Opera 11-12.16 // Nothing should be selected when empty strings follow ^= or $= or *= // The test attribute must be unknown in Opera but "safe" for WinRT // https://msdn.microsoft.com/en-us/library/ie/hh465388.aspx#attribute_section if ( el.querySelectorAll( "[msallowcapture^='']" ).length ) { rbuggyQSA.push( "[*^$]=" + whitespace + "*(?:''|\"\")" ); } // Support: IE8 // Boolean attributes and "value" are not treated correctly if ( !el.querySelectorAll( "[selected]" ).length ) { rbuggyQSA.push( "\\[" + whitespace + "*(?:value|" + booleans + ")" ); } // Support: Chrome<29, Android<4.4, Safari<7.0+, iOS<7.0+, PhantomJS<1.9.8+ if ( !el.querySelectorAll( "[id~=" + expando + "-]" ).length ) { rbuggyQSA.push( "~=" ); } // Support: IE 11+, Edge 15 - 18+ // IE 11/Edge don't find elements on a `[name='']` query in some cases. // Adding a temporary attribute to the document before the selection works // around the issue. // Interestingly, IE 10 & older don't seem to have the issue. input = document.createElement( "input" ); input.setAttribute( "name", "" ); el.appendChild( input ); if ( !el.querySelectorAll( "[name='']" ).length ) { rbuggyQSA.push( "\\[" + whitespace + "*name" + whitespace + "*=" + whitespace + "*(?:''|\"\")" ); } // Webkit/Opera - :checked should return selected option elements // http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked // IE8 throws error here and will not see later tests if ( !el.querySelectorAll( ":checked" ).length ) { rbuggyQSA.push( ":checked" ); } // Support: Safari 8+, iOS 8+ // https://bugs.webkit.org/show_bug.cgi?id=136851 // In-page `selector#id sibling-combinator selector` fails if ( !el.querySelectorAll( "a#" + expando + "+*" ).length ) { rbuggyQSA.push( ".#.+[+~]" ); } // Support: Firefox <=3.6 - 5 only // Old Firefox doesn't throw on a badly-escaped identifier. el.querySelectorAll( "\\\f" ); rbuggyQSA.push( "[\\r\\n\\f]" ); } ); assert( function( el ) { el.innerHTML = "<a href='' disabled='disabled'></a>" + "<select disabled='disabled'><option/></select>"; // Support: Windows 8 Native Apps // The type and name attributes are restricted during .innerHTML assignment var input = document.createElement( "input" ); input.setAttribute( "type", "hidden" ); el.appendChild( input ).setAttribute( "name", "D" ); // Support: IE8 // Enforce case-sensitivity of name attribute if ( el.querySelectorAll( "[name=d]" ).length ) { rbuggyQSA.push( "name" + whitespace + "*[*^$|!~]?=" ); } // FF 3.5 - :enabled/:disabled and hidden elements (hidden elements are still enabled) // IE8 throws error here and will not see later tests if ( el.querySelectorAll( ":enabled" ).length !== 2 ) { rbuggyQSA.push( ":enabled", ":disabled" ); } // Support: IE9-11+ // IE's :disabled selector does not pick up the children of disabled fieldsets docElem.appendChild( el ).disabled = true; if ( el.querySelectorAll( ":disabled" ).length !== 2 ) { rbuggyQSA.push( ":enabled", ":disabled" ); } // Support: Opera 10 - 11 only // Opera 10-11 does not throw on post-comma invalid pseudos el.querySelectorAll( "*,:x" ); rbuggyQSA.push( ",.*:" ); } ); } if ( ( support.matchesSelector = rnative.test( ( matches = docElem.matches || docElem.webkitMatchesSelector || docElem.mozMatchesSelector || docElem.oMatchesSelector || docElem.msMatchesSelector ) ) ) ) { assert( function( el ) { // Check to see if it's possible to do matchesSelector // on a disconnected node (IE 9) support.disconnectedMatch = matches.call( el, "*" ); // This should fail with an exception // Gecko does not error, returns false instead matches.call( el, "[s!='']:x" ); rbuggyMatches.push( "!=", pseudos ); } ); } rbuggyQSA = rbuggyQSA.length && new RegExp( rbuggyQSA.join( "|" ) ); rbuggyMatches = rbuggyMatches.length && new RegExp( rbuggyMatches.join( "|" ) ); /* Contains ---------------------------------------------------------------------- */ hasCompare = rnative.test( docElem.compareDocumentPosition ); // Element contains another // Purposefully self-exclusive // As in, an element does not contain itself contains = hasCompare || rnative.test( docElem.contains ) ? function( a, b ) { var adown = a.nodeType === 9 ? a.documentElement : a, bup = b && b.parentNode; return a === bup || !!( bup && bup.nodeType === 1 && ( adown.contains ? adown.contains( bup ) : a.compareDocumentPosition && a.compareDocumentPosition( bup ) & 16 ) ); } : function( a, b ) { if ( b ) { while ( ( b = b.parentNode ) ) { if ( b === a ) { return true; } } } return false; }; /* Sorting ---------------------------------------------------------------------- */ // Document order sorting sortOrder = hasCompare ? function( a, b ) { // Flag for duplicate removal if ( a === b ) { hasDuplicate = true; return 0; } // Sort on method existence if only one input has compareDocumentPosition var compare = !a.compareDocumentPosition - !b.compareDocumentPosition; if ( compare ) { return compare; } // Calculate position if both inputs belong to the same document // Support: IE 11+, Edge 17 - 18+ // IE/Edge sometimes throw a "Permission denied" error when strict-comparing // two documents; shallow comparisons work. // eslint-disable-next-line eqeqeq compare = ( a.ownerDocument || a ) == ( b.ownerDocument || b ) ? a.compareDocumentPosition( b ) : // Otherwise we know they are disconnected 1; // Disconnected nodes if ( compare & 1 || ( !support.sortDetached && b.compareDocumentPosition( a ) === compare ) ) { // Choose the first element that is related to our preferred document // Support: IE 11+, Edge 17 - 18+ // IE/Edge sometimes throw a "Permission denied" error when strict-comparing // two documents; shallow comparisons work. // eslint-disable-next-line eqeqeq if ( a == document || a.ownerDocument == preferredDoc && contains( preferredDoc, a ) ) { return -1; } // Support: IE 11+, Edge 17 - 18+ // IE/Edge sometimes throw a "Permission denied" error when strict-comparing // two documents; shallow comparisons work. // eslint-disable-next-line eqeqeq if ( b == document || b.ownerDocument == preferredDoc && contains( preferredDoc, b ) ) { return 1; } // Maintain original order return sortInput ? ( indexOf( sortInput, a ) - indexOf( sortInput, b ) ) : 0; } return compare & 4 ? -1 : 1; } : function( a, b ) { // Exit early if the nodes are identical if ( a === b ) { hasDuplicate = true; return 0; } var cur, i = 0, aup = a.parentNode, bup = b.parentNode, ap = [ a ], bp = [ b ]; // Parentless nodes are either documents or disconnected if ( !aup || !bup ) { // Support: IE 11+, Edge 17 - 18+ // IE/Edge sometimes throw a "Permission denied" error when strict-comparing // two documents; shallow comparisons work. /* eslint-disable eqeqeq */ return a == document ? -1 : b == document ? 1 : /* eslint-enable eqeqeq */ aup ? -1 : bup ? 1 : sortInput ? ( indexOf( sortInput, a ) - indexOf( sortInput, b ) ) : 0; // If the nodes are siblings, we can do a quick check } else if ( aup === bup ) { return siblingCheck( a, b ); } // Otherwise we need full lists of their ancestors for comparison cur = a; while ( ( cur = cur.parentNode ) ) { ap.unshift( cur ); } cur = b; while ( ( cur = cur.parentNode ) ) { bp.unshift( cur ); } // Walk down the tree looking for a discrepancy while ( ap[ i ] === bp[ i ] ) { i++; } return i ? // Do a sibling check if the nodes have a common ancestor siblingCheck( ap[ i ], bp[ i ] ) : // Otherwise nodes in our document sort first // Support: IE 11+, Edge 17 - 18+ // IE/Edge sometimes throw a "Permission denied" error when strict-comparing // two documents; shallow comparisons work. /* eslint-disable eqeqeq */ ap[ i ] == preferredDoc ? -1 : bp[ i ] == preferredDoc ? 1 : /* eslint-enable eqeqeq */ 0; }; return document; }; Sizzle.matches = function( expr, elements ) { return Sizzle( expr, null, null, elements ); }; Sizzle.matchesSelector = function( elem, expr ) { setDocument( elem ); if ( support.matchesSelector && documentIsHTML && !nonnativeSelectorCache[ expr + " " ] && ( !rbuggyMatches || !rbuggyMatches.test( expr ) ) && ( !rbuggyQSA || !rbuggyQSA.test( expr ) ) ) { try { var ret = matches.call( elem, expr ); // IE 9's matchesSelector returns false on disconnected nodes if ( ret || support.disconnectedMatch || // As well, disconnected nodes are said to be in a document // fragment in IE 9 elem.document && elem.document.nodeType !== 11 ) { return ret; } } catch ( e ) { nonnativeSelectorCache( expr, true ); } } return Sizzle( expr, document, null, [ elem ] ).length > 0; }; Sizzle.contains = function( context, elem ) { // Set document vars if needed // Support: IE 11+, Edge 17 - 18+ // IE/Edge sometimes throw a "Permission denied" error when strict-comparing // two documents; shallow comparisons work. // eslint-disable-next-line eqeqeq if ( ( context.ownerDocument || context ) != document ) { setDocument( context ); } return contains( context, elem ); }; Sizzle.attr = function( elem, name ) { // Set document vars if needed // Support: IE 11+, Edge 17 - 18+ // IE/Edge sometimes throw a "Permission denied" error when strict-comparing // two documents; shallow comparisons work. // eslint-disable-next-line eqeqeq if ( ( elem.ownerDocument || elem ) != document ) { setDocument( elem ); } var fn = Expr.attrHandle[ name.toLowerCase() ], // Don't get fooled by Object.prototype properties (jQuery #13807) val = fn && hasOwn.call( Expr.attrHandle, name.toLowerCase() ) ? fn( elem, name, !documentIsHTML ) : undefined; return val !== undefined ? val : support.attributes || !documentIsHTML ? elem.getAttribute( name ) : ( val = elem.getAttributeNode( name ) ) && val.specified ? val.value : null; }; Sizzle.escape = function( sel ) { return ( sel + "" ).replace( rcssescape, fcssescape ); }; Sizzle.error = function( msg ) { throw new Error( "Syntax error, unrecognized expression: " + msg ); }; /** * Document sorting and removing duplicates * @param {ArrayLike} results */ Sizzle.uniqueSort = function( results ) { var elem, duplicates = [], j = 0, i = 0; // Unless we *know* we can detect duplicates, assume their presence hasDuplicate = !support.detectDuplicates; sortInput = !support.sortStable && results.slice( 0 ); results.sort( sortOrder ); if ( hasDuplicate ) { while ( ( elem = results[ i++ ] ) ) { if ( elem === results[ i ] ) { j = duplicates.push( i ); } } while ( j-- ) { results.splice( duplicates[ j ], 1 ); } } // Clear input after sorting to release objects // See https://github.com/jquery/sizzle/pull/225 sortInput = null; return results; }; /** * Utility function for retrieving the text value of an array of DOM nodes * @param {Array|Element} elem */ getText = Sizzle.getText = function( elem ) { var node, ret = "", i = 0, nodeType = elem.nodeType; if ( !nodeType ) { // If no nodeType, this is expected to be an array while ( ( node = elem[ i++ ] ) ) { // Do not traverse comment nodes ret += getText( node ); } } else if ( nodeType === 1 || nodeType === 9 || nodeType === 11 ) { // Use textContent for elements // innerText usage removed for consistency of new lines (jQuery #11153) if ( typeof elem.textContent === "string" ) { return elem.textContent; } else { // Traverse its children for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) { ret += getText( elem ); } } } else if ( nodeType === 3 || nodeType === 4 ) { return elem.nodeValue; } // Do not include comment or processing instruction nodes return ret; }; Expr = Sizzle.selectors = { // Can be adjusted by the user cacheLength: 50, createPseudo: markFunction, match: matchExpr, attrHandle: {}, find: {}, relative: { ">": { dir: "parentNode", first: true }, " ": { dir: "parentNode" }, "+": { dir: "previousSibling", first: true }, "~": { dir: "previousSibling" } }, preFilter: { "ATTR": function( match ) { match[ 1 ] = match[ 1 ].replace( runescape, funescape ); // Move the given value to match[3] whether quoted or unquoted match[ 3 ] = ( match[ 3 ] || match[ 4 ] || match[ 5 ] || "" ).replace( runescape, funescape ); if ( match[ 2 ] === "~=" ) { match[ 3 ] = " " + match[ 3 ] + " "; } return match.slice( 0, 4 ); }, "CHILD": function( match ) { /* matches from matchExpr["CHILD"] 1 type (only|nth|...) 2 what (child|of-type) 3 argument (even|odd|\d*|\d*n([+-]\d+)?|...) 4 xn-component of xn+y argument ([+-]?\d*n|) 5 sign of xn-component 6 x of xn-component 7 sign of y-component 8 y of y-component */ match[ 1 ] = match[ 1 ].toLowerCase(); if ( match[ 1 ].slice( 0, 3 ) === "nth" ) { // nth-* requires argument if ( !match[ 3 ] ) { Sizzle.error( match[ 0 ] ); } // numeric x and y parameters for Expr.filter.CHILD // remember that false/true cast respectively to 0/1 match[ 4 ] = +( match[ 4 ] ? match[ 5 ] + ( match[ 6 ] || 1 ) : 2 * ( match[ 3 ] === "even" || match[ 3 ] === "odd" ) ); match[ 5 ] = +( ( match[ 7 ] + match[ 8 ] ) || match[ 3 ] === "odd" ); // other types prohibit arguments } else if ( match[ 3 ] ) { Sizzle.error( match[ 0 ] ); } return match; }, "PSEUDO": function( match ) { var excess, unquoted = !match[ 6 ] && match[ 2 ]; if ( matchExpr[ "CHILD" ].test( match[ 0 ] ) ) { return null; } // Accept quoted arguments as-is if ( match[ 3 ] ) { match[ 2 ] = match[ 4 ] || match[ 5 ] || ""; // Strip excess characters from unquoted arguments } else if ( unquoted && rpseudo.test( unquoted ) && // Get excess from tokenize (recursively) ( excess = tokenize( unquoted, true ) ) && // advance to the next closing parenthesis ( excess = unquoted.indexOf( ")", unquoted.length - excess ) - unquoted.length ) ) { // excess is a negative index match[ 0 ] = match[ 0 ].slice( 0, excess ); match[ 2 ] = unquoted.slice( 0, excess ); } // Return only captures needed by the pseudo filter method (type and argument) return match.slice( 0, 3 ); } }, filter: { "TAG": function( nodeNameSelector ) { var nodeName = nodeNameSelector.replace( runescape, funescape ).toLowerCase(); return nodeNameSelector === "*" ? function() { return true; } : function( elem ) { return elem.nodeName && elem.nodeName.toLowerCase() === nodeName; }; }, "CLASS": function( className ) { var pattern = classCache[ className + " " ]; return pattern || ( pattern = new RegExp( "(^|" + whitespace + ")" + className + "(" + whitespace + "|$)" ) ) && classCache( className, function( elem ) { return pattern.test( typeof elem.className === "string" && elem.className || typeof elem.getAttribute !== "undefined" && elem.getAttribute( "class" ) || "" ); } ); }, "ATTR": function( name, operator, check ) { return function( elem ) { var result = Sizzle.attr( elem, name ); if ( result == null ) { return operator === "!="; } if ( !operator ) { return true; } result += ""; /* eslint-disable max-len */ return operator === "=" ? result === check : operator === "!=" ? result !== check : operator === "^=" ? check && result.indexOf( check ) === 0 : operator === "*=" ? check && result.indexOf( check ) > -1 : operator === "$=" ? check && result.slice( -check.length ) === check : operator === "~=" ? ( " " + result.replace( rwhitespace, " " ) + " " ).indexOf( check ) > -1 : operator === "|=" ? result === check || result.slice( 0, check.length + 1 ) === check + "-" : false; /* eslint-enable max-len */ }; }, "CHILD": function( type, what, _argument, first, last ) { var simple = type.slice( 0, 3 ) !== "nth", forward = type.slice( -4 ) !== "last", ofType = what === "of-type"; return first === 1 && last === 0 ? // Shortcut for :nth-*(n) function( elem ) { return !!elem.parentNode; } : function( elem, _context, xml ) { var cache, uniqueCache, outerCache, node, nodeIndex, start, dir = simple !== forward ? "nextSibling" : "previousSibling", parent = elem.parentNode, name = ofType && elem.nodeName.toLowerCase(), useCache = !xml && !ofType, diff = false; if ( parent ) { // :(first|last|only)-(child|of-type) if ( simple ) { while ( dir ) { node = elem; while ( ( node = node[ dir ] ) ) { if ( ofType ? node.nodeName.toLowerCase() === name : node.nodeType === 1 ) { return false; } } // Reverse direction for :only-* (if we haven't yet done so) start = dir = type === "only" && !start && "nextSibling"; } return true; } start = [ forward ? parent.firstChild : parent.lastChild ]; // non-xml :nth-child(...) stores cache data on `parent` if ( forward && useCache ) { // Seek `elem` from a previously-cached index // ...in a gzip-friendly way node = parent; outerCache = node[ expando ] || ( node[ expando ] = {} ); // Support: IE <9 only // Defend against cloned attroperties (jQuery gh-1709) uniqueCache = outerCache[ node.uniqueID ] || ( outerCache[ node.uniqueID ] = {} ); cache = uniqueCache[ type ] || []; nodeIndex = cache[ 0 ] === dirruns && cache[ 1 ]; diff = nodeIndex && cache[ 2 ]; node = nodeIndex && parent.childNodes[ nodeIndex ]; while ( ( node = ++nodeIndex && node && node[ dir ] || // Fallback to seeking `elem` from the start ( diff = nodeIndex = 0 ) || start.pop() ) ) { // When found, cache indexes on `parent` and break if ( node.nodeType === 1 && ++diff && node === elem ) { uniqueCache[ type ] = [ dirruns, nodeIndex, diff ]; break; } } } else { // Use previously-cached element index if available if ( useCache ) { // ...in a gzip-friendly way node = elem; outerCache = node[ expando ] || ( node[ expando ] = {} ); // Support: IE <9 only // Defend against cloned attroperties (jQuery gh-1709) uniqueCache = outerCache[ node.uniqueID ] || ( outerCache[ node.uniqueID ] = {} ); cache = uniqueCache[ type ] || []; nodeIndex = cache[ 0 ] === dirruns && cache[ 1 ]; diff = nodeIndex; } // xml :nth-child(...) // or :nth-last-child(...) or :nth(-last)?-of-type(...) if ( diff === false ) { // Use the same loop as above to seek `elem` from the start while ( ( node = ++nodeIndex && node && node[ dir ] || ( diff = nodeIndex = 0 ) || start.pop() ) ) { if ( ( ofType ? node.nodeName.toLowerCase() === name : node.nodeType === 1 ) && ++diff ) { // Cache the index of each encountered element if ( useCache ) { outerCache = node[ expando ] || ( node[ expando ] = {} ); // Support: IE <9 only // Defend against cloned attroperties (jQuery gh-1709) uniqueCache = outerCache[ node.uniqueID ] || ( outerCache[ node.uniqueID ] = {} ); uniqueCache[ type ] = [ dirruns, diff ]; } if ( node === elem ) { break; } } } } } // Incorporate the offset, then check against cycle size diff -= last; return diff === first || ( diff % first === 0 && diff / first >= 0 ); } }; }, "PSEUDO": function( pseudo, argument ) { // pseudo-class names are case-insensitive // http://www.w3.org/TR/selectors/#pseudo-classes // Prioritize by case sensitivity in case custom pseudos are added with uppercase letters // Remember that setFilters inherits from pseudos var args, fn = Expr.pseudos[ pseudo ] || Expr.setFilters[ pseudo.toLowerCase() ] || Sizzle.error( "unsupported pseudo: " + pseudo ); // The user may use createPseudo to indicate that // arguments are needed to create the filter function // just as Sizzle does if ( fn[ expando ] ) { return fn( argument ); } // But maintain support for old signatures if ( fn.length > 1 ) { args = [ pseudo, pseudo, "", argument ]; return Expr.setFilters.hasOwnProperty( pseudo.toLowerCase() ) ? markFunction( function( seed, matches ) { var idx, matched = fn( seed, argument ), i = matched.length; while ( i-- ) { idx = indexOf( seed, matched[ i ] ); seed[ idx ] = !( matches[ idx ] = matched[ i ] ); } } ) : function( elem ) { return fn( elem, 0, args ); }; } return fn; } }, pseudos: { // Potentially complex pseudos "not": markFunction( function( selector ) { // Trim the selector passed to compile // to avoid treating leading and trailing // spaces as combinators var input = [], results = [], matcher = compile( selector.replace( rtrim, "$1" ) ); return matcher[ expando ] ? markFunction( function( seed, matches, _context, xml ) { var elem, unmatched = matcher( seed, null, xml, [] ), i = seed.length; // Match elements unmatched by `matcher` while ( i-- ) { if ( ( elem = unmatched[ i ] ) ) { seed[ i ] = !( matches[ i ] = elem ); } } } ) : function( elem, _context, xml ) { input[ 0 ] = elem; matcher( input, null, xml, results ); // Don't keep the element (issue #299) input[ 0 ] = null; return !results.pop(); }; } ), "has": markFunction( function( selector ) { return function( elem ) { return Sizzle( selector, elem ).length > 0; }; } ), "contains": markFunction( function( text ) { text = text.replace( runescape, funescape ); return function( elem ) { return ( elem.textContent || getText( elem ) ).indexOf( text ) > -1; }; } ), // "Whether an element is represented by a :lang() selector // is based solely on the element's language value // being equal to the identifier C, // or beginning with the identifier C immediately followed by "-". // The matching of C against the element's language value is performed case-insensitively. // The identifier C does not have to be a valid language name." // http://www.w3.org/TR/selectors/#lang-pseudo "lang": markFunction( function( lang ) { // lang value must be a valid identifier if ( !ridentifier.test( lang || "" ) ) { Sizzle.error( "unsupported lang: " + lang ); } lang = lang.replace( runescape, funescape ).toLowerCase(); return function( elem ) { var elemLang; do { if ( ( elemLang = documentIsHTML ? elem.lang : elem.getAttribute( "xml:lang" ) || elem.getAttribute( "lang" ) ) ) { elemLang = elemLang.toLowerCase(); return elemLang === lang || elemLang.indexOf( lang + "-" ) === 0; } } while ( ( elem = elem.parentNode ) && elem.nodeType === 1 ); return false; }; } ), // Miscellaneous "target": function( elem ) { var hash = window.location && window.location.hash; return hash && hash.slice( 1 ) === elem.id; }, "root": function( elem ) { return elem === docElem; }, "focus": function( elem ) { return elem === document.activeElement && ( !document.hasFocus || document.hasFocus() ) && !!( elem.type || elem.href || ~elem.tabIndex ); }, // Boolean properties "enabled": createDisabledPseudo( false ), "disabled": createDisabledPseudo( true ), "checked": function( elem ) { // In CSS3, :checked should return both checked and selected elements // http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked var nodeName = elem.nodeName.toLowerCase(); return ( nodeName === "input" && !!elem.checked ) || ( nodeName === "option" && !!elem.selected ); }, "selected": function( elem ) { // Accessing this property makes selected-by-default // options in Safari work properly if ( elem.parentNode ) { // eslint-disable-next-line no-unused-expressions elem.parentNode.selectedIndex; } return elem.selected === true; }, // Contents "empty": function( elem ) { // http://www.w3.org/TR/selectors/#empty-pseudo // :empty is negated by element (1) or content nodes (text: 3; cdata: 4; entity ref: 5), // but not by others (comment: 8; processing instruction: 7; etc.) // nodeType < 6 works because attributes (2) do not appear as children for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) { if ( elem.nodeType < 6 ) { return false; } } return true; }, "parent": function( elem ) { return !Expr.pseudos[ "empty" ]( elem ); }, // Element/input types "header": function( elem ) { return rheader.test( elem.nodeName ); }, "input": function( elem ) { return rinputs.test( elem.nodeName ); }, "button": function( elem ) { var name = elem.nodeName.toLowerCase(); return name === "input" && elem.type === "button" || name === "button"; }, "text": function( elem ) { var attr; return elem.nodeName.toLowerCase() === "input" && elem.type === "text" && // Support: IE<8 // New HTML5 attribute values (e.g., "search") appear with elem.type === "text" ( ( attr = elem.getAttribute( "type" ) ) == null || attr.toLowerCase() === "text" ); }, // Position-in-collection "first": createPositionalPseudo( function() { return [ 0 ]; } ), "last": createPositionalPseudo( function( _matchIndexes, length ) { return [ length - 1 ]; } ), "eq": createPositionalPseudo( function( _matchIndexes, length, argument ) { return [ argument < 0 ? argument + length : argument ]; } ), "even": createPositionalPseudo( function( matchIndexes, length ) { var i = 0; for ( ; i < length; i += 2 ) { matchIndexes.push( i ); } return matchIndexes; } ), "odd": createPositionalPseudo( function( matchIndexes, length ) { var i = 1; for ( ; i < length; i += 2 ) { matchIndexes.push( i ); } return matchIndexes; } ), "lt": createPositionalPseudo( function( matchIndexes, length, argument ) { var i = argument < 0 ? argument + length : argument > length ? length : argument; for ( ; --i >= 0; ) { matchIndexes.push( i ); } return matchIndexes; } ), "gt": createPositionalPseudo( function( matchIndexes, length, argument ) { var i = argument < 0 ? argument + length : argument; for ( ; ++i < length; ) { matchIndexes.push( i ); } return matchIndexes; } ) } }; Expr.pseudos[ "nth" ] = Expr.pseudos[ "eq" ]; // Add button/input type pseudos for ( i in { radio: true, checkbox: true, file: true, password: true, image: true } ) { Expr.pseudos[ i ] = createInputPseudo( i ); } for ( i in { submit: true, reset: true } ) { Expr.pseudos[ i ] = createButtonPseudo( i ); } // Easy API for creating new setFilters function setFilters() {} setFilters.prototype = Expr.filters = Expr.pseudos; Expr.setFilters = new setFilters(); tokenize = Sizzle.tokenize = function( selector, parseOnly ) { var matched, match, tokens, type, soFar, groups, preFilters, cached = tokenCache[ selector + " " ]; if ( cached ) { return parseOnly ? 0 : cached.slice( 0 ); } soFar = selector; groups = []; preFilters = Expr.preFilter; while ( soFar ) { // Comma and first run if ( !matched || ( match = rcomma.exec( soFar ) ) ) { if ( match ) { // Don't consume trailing commas as valid soFar = soFar.slice( match[ 0 ].length ) || soFar; } groups.push( ( tokens = [] ) ); } matched = false; // Combinators if ( ( match = rcombinators.exec( soFar ) ) ) { matched = match.shift(); tokens.push( { value: matched, // Cast descendant combinators to space type: match[ 0 ].replace( rtrim, " " ) } ); soFar = soFar.slice( matched.length ); } // Filters for ( type in Expr.filter ) { if ( ( match = matchExpr[ type ].exec( soFar ) ) && ( !preFilters[ type ] || ( match = preFilters[ type ]( match ) ) ) ) { matched = match.shift(); tokens.push( { value: matched, type: type, matches: match } ); soFar = soFar.slice( matched.length ); } } if ( !matched ) { break; } } // Return the length of the invalid excess // if we're just parsing // Otherwise, throw an error or return tokens return parseOnly ? soFar.length : soFar ? Sizzle.error( selector ) : // Cache the tokens tokenCache( selector, groups ).slice( 0 ); }; function toSelector( tokens ) { var i = 0, len = tokens.length, selector = ""; for ( ; i < len; i++ ) { selector += tokens[ i ].value; } return selector; } function addCombinator( matcher, combinator, base ) { var dir = combinator.dir, skip = combinator.next, key = skip || dir, checkNonElements = base && key === "parentNode", doneName = done++; return combinator.first ? // Check against closest ancestor/preceding element function( elem, context, xml ) { while ( ( elem = elem[ dir ] ) ) { if ( elem.nodeType === 1 || checkNonElements ) { return matcher( elem, context, xml ); } } return false; } : // Check against all ancestor/preceding elements function( elem, context, xml ) { var oldCache, uniqueCache, outerCache, newCache = [ dirruns, doneName ]; // We can't set arbitrary data on XML nodes, so they don't benefit from combinator caching if ( xml ) { while ( ( elem = elem[ dir ] ) ) { if ( elem.nodeType === 1 || checkNonElements ) { if ( matcher( elem, context, xml ) ) { return true; } } } } else { while ( ( elem = elem[ dir ] ) ) { if ( elem.nodeType === 1 || checkNonElements ) { outerCache = elem[ expando ] || ( elem[ expando ] = {} ); // Support: IE <9 only // Defend against cloned attroperties (jQuery gh-1709) uniqueCache = outerCache[ elem.uniqueID ] || ( outerCache[ elem.uniqueID ] = {} ); if ( skip && skip === elem.nodeName.toLowerCase() ) { elem = elem[ dir ] || elem; } else if ( ( oldCache = uniqueCache[ key ] ) && oldCache[ 0 ] === dirruns && oldCache[ 1 ] === doneName ) { // Assign to newCache so results back-propagate to previous elements return ( newCache[ 2 ] = oldCache[ 2 ] ); } else { // Reuse newcache so results back-propagate to previous elements uniqueCache[ key ] = newCache; // A match means we're done; a fail means we have to keep checking if ( ( newCache[ 2 ] = matcher( elem, context, xml ) ) ) { return true; } } } } } return false; }; } function elementMatcher( matchers ) { return matchers.length > 1 ? function( elem, context, xml ) { var i = matchers.length; while ( i-- ) { if ( !matchers[ i ]( elem, context, xml ) ) { return false; } } return true; } : matchers[ 0 ]; } function multipleContexts( selector, contexts, results ) { var i = 0, len = contexts.length; for ( ; i < len; i++ ) { Sizzle( selector, contexts[ i ], results ); } return results; } function condense( unmatched, map, filter, context, xml ) { var elem, newUnmatched = [], i = 0, len = unmatched.length, mapped = map != null; for ( ; i < len; i++ ) { if ( ( elem = unmatched[ i ] ) ) { if ( !filter || filter( elem, context, xml ) ) { newUnmatched.push( elem ); if ( mapped ) { map.push( i ); } } } } return newUnmatched; } function setMatcher( preFilter, selector, matcher, postFilter, postFinder, postSelector ) { if ( postFilter && !postFilter[ expando ] ) { postFilter = setMatcher( postFilter ); } if ( postFinder && !postFinder[ expando ] ) { postFinder = setMatcher( postFinder, postSelector ); } return markFunction( function( seed, results, context, xml ) { var temp, i, elem, preMap = [], postMap = [], preexisting = results.length, // Get initial elements from seed or context elems = seed || multipleContexts( selector || "*", context.nodeType ? [ context ] : context, [] ), // Prefilter to get matcher input, preserving a map for seed-results synchronization matcherIn = preFilter && ( seed || !selector ) ? condense( elems, preMap, preFilter, context, xml ) : elems, matcherOut = matcher ? // If we have a postFinder, or filtered seed, or non-seed postFilter or preexisting results, postFinder || ( seed ? preFilter : preexisting || postFilter ) ? // ...intermediate processing is necessary [] : // ...otherwise use results directly results : matcherIn; // Find primary matches if ( matcher ) { matcher( matcherIn, matcherOut, context, xml ); } // Apply postFilter if ( postFilter ) { temp = condense( matcherOut, postMap ); postFilter( temp, [], context, xml ); // Un-match failing elements by moving them back to matcherIn i = temp.length; while ( i-- ) { if ( ( elem = temp[ i ] ) ) { matcherOut[ postMap[ i ] ] = !( matcherIn[ postMap[ i ] ] = elem ); } } } if ( seed ) { if ( postFinder || preFilter ) { if ( postFinder ) { // Get the final matcherOut by condensing this intermediate into postFinder contexts temp = []; i = matcherOut.length; while ( i-- ) { if ( ( elem = matcherOut[ i ] ) ) { // Restore matcherIn since elem is not yet a final match temp.push( ( matcherIn[ i ] = elem ) ); } } postFinder( null, ( matcherOut = [] ), temp, xml ); } // Move matched elements from seed to results to keep them synchronized i = matcherOut.length; while ( i-- ) { if ( ( elem = matcherOut[ i ] ) && ( temp = postFinder ? indexOf( seed, elem ) : preMap[ i ] ) > -1 ) { seed[ temp ] = !( results[ temp ] = elem ); } } } // Add elements to results, through postFinder if defined } else { matcherOut = condense( matcherOut === results ? matcherOut.splice( preexisting, matcherOut.length ) : matcherOut ); if ( postFinder ) { postFinder( null, results, matcherOut, xml ); } else { push.apply( results, matcherOut ); } } } ); } function matcherFromTokens( tokens ) { var checkContext, matcher, j, len = tokens.length, leadingRelative = Expr.relative[ tokens[ 0 ].type ], implicitRelative = leadingRelative || Expr.relative[ " " ], i = leadingRelative ? 1 : 0, // The foundational matcher ensures that elements are reachable from top-level context(s) matchContext = addCombinator( function( elem ) { return elem === checkContext; }, implicitRelative, true ), matchAnyContext = addCombinator( function( elem ) { return indexOf( checkContext, elem ) > -1; }, implicitRelative, true ), matchers = [ function( elem, context, xml ) { var ret = ( !leadingRelative && ( xml || context !== outermostContext ) ) || ( ( checkContext = context ).nodeType ? matchContext( elem, context, xml ) : matchAnyContext( elem, context, xml ) ); // Avoid hanging onto element (issue #299) checkContext = null; return ret; } ]; for ( ; i < len; i++ ) { if ( ( matcher = Expr.relative[ tokens[ i ].type ] ) ) { matchers = [ addCombinator( elementMatcher( matchers ), matcher ) ]; } else { matcher = Expr.filter[ tokens[ i ].type ].apply( null, tokens[ i ].matches ); // Return special upon seeing a positional matcher if ( matcher[ expando ] ) { // Find the next relative operator (if any) for proper handling j = ++i; for ( ; j < len; j++ ) { if ( Expr.relative[ tokens[ j ].type ] ) { break; } } return setMatcher( i > 1 && elementMatcher( matchers ), i > 1 && toSelector( // If the preceding token was a descendant combinator, insert an implicit any-element `*` tokens .slice( 0, i - 1 ) .concat( { value: tokens[ i - 2 ].type === " " ? "*" : "" } ) ).replace( rtrim, "$1" ), matcher, i < j && matcherFromTokens( tokens.slice( i, j ) ), j < len && matcherFromTokens( ( tokens = tokens.slice( j ) ) ), j < len && toSelector( tokens ) ); } matchers.push( matcher ); } } return elementMatcher( matchers ); } function matcherFromGroupMatchers( elementMatchers, setMatchers ) { var bySet = setMatchers.length > 0, byElement = elementMatchers.length > 0, superMatcher = function( seed, context, xml, results, outermost ) { var elem, j, matcher, matchedCount = 0, i = "0", unmatched = seed && [], setMatched = [], contextBackup = outermostContext, // We must always have either seed elements or outermost context elems = seed || byElement && Expr.find[ "TAG" ]( "*", outermost ), // Use integer dirruns iff this is the outermost matcher dirrunsUnique = ( dirruns += contextBackup == null ? 1 : Math.random() || 0.1 ), len = elems.length; if ( outermost ) { // Support: IE 11+, Edge 17 - 18+ // IE/Edge sometimes throw a "Permission denied" error when strict-comparing // two documents; shallow comparisons work. // eslint-disable-next-line eqeqeq outermostContext = context == document || context || outermost; } // Add elements passing elementMatchers directly to results // Support: IE<9, Safari // Tolerate NodeList properties (IE: "length"; Safari: <number>) matching elements by id for ( ; i !== len && ( elem = elems[ i ] ) != null; i++ ) { if ( byElement && elem ) { j = 0; // Support: IE 11+, Edge 17 - 18+ // IE/Edge sometimes throw a "Permission denied" error when strict-comparing // two documents; shallow comparisons work. // eslint-disable-next-line eqeqeq if ( !context && elem.ownerDocument != document ) { setDocument( elem ); xml = !documentIsHTML; } while ( ( matcher = elementMatchers[ j++ ] ) ) { if ( matcher( elem, context || document, xml ) ) { results.push( elem ); break; } } if ( outermost ) { dirruns = dirrunsUnique; } } // Track unmatched elements for set filters if ( bySet ) { // They will have gone through all possible matchers if ( ( elem = !matcher && elem ) ) { matchedCount--; } // Lengthen the array for every element, matched or not if ( seed ) { unmatched.push( elem ); } } } // `i` is now the count of elements visited above, and adding it to `matchedCount` // makes the latter nonnegative. matchedCount += i; // Apply set filters to unmatched elements // NOTE: This can be skipped if there are no unmatched elements (i.e., `matchedCount` // equals `i`), unless we didn't visit _any_ elements in the above loop because we have // no element matchers and no seed. // Incrementing an initially-string "0" `i` allows `i` to remain a string only in that // case, which will result in a "00" `matchedCount` that differs from `i` but is also // numerically zero. if ( bySet && i !== matchedCount ) { j = 0; while ( ( matcher = setMatchers[ j++ ] ) ) { matcher( unmatched, setMatched, context, xml ); } if ( seed ) { // Reintegrate element matches to eliminate the need for sorting if ( matchedCount > 0 ) { while ( i-- ) { if ( !( unmatched[ i ] || setMatched[ i ] ) ) { setMatched[ i ] = pop.call( results ); } } } // Discard index placeholder values to get only actual matches setMatched = condense( setMatched ); } // Add matches to results push.apply( results, setMatched ); // Seedless set matches succeeding multiple successful matchers stipulate sorting if ( outermost && !seed && setMatched.length > 0 && ( matchedCount + setMatchers.length ) > 1 ) { Sizzle.uniqueSort( results ); } } // Override manipulation of globals by nested matchers if ( outermost ) { dirruns = dirrunsUnique; outermostContext = contextBackup; } return unmatched; }; return bySet ? markFunction( superMatcher ) : superMatcher; } compile = Sizzle.compile = function( selector, match /* Internal Use Only */ ) { var i, setMatchers = [], elementMatchers = [], cached = compilerCache[ selector + " " ]; if ( !cached ) { // Generate a function of recursive functions that can be used to check each element if ( !match ) { match = tokenize( selector ); } i = match.length; while ( i-- ) { cached = matcherFromTokens( match[ i ] ); if ( cached[ expando ] ) { setMatchers.push( cached ); } else { elementMatchers.push( cached ); } } // Cache the compiled function cached = compilerCache( selector, matcherFromGroupMatchers( elementMatchers, setMatchers ) ); // Save selector and tokenization cached.selector = selector; } return cached; }; /** * A low-level selection function that works with Sizzle's compiled * selector functions * @param {String|Function} selector A selector or a pre-compiled * selector function built with Sizzle.compile * @param {Element} context * @param {Array} [results] * @param {Array} [seed] A set of elements to match against */ select = Sizzle.select = function( selector, context, results, seed ) { var i, tokens, token, type, find, compiled = typeof selector === "function" && selector, match = !seed && tokenize( ( selector = compiled.selector || selector ) ); results = results || []; // Try to minimize operations if there is only one selector in the list and no seed // (the latter of which guarantees us context) if ( match.length === 1 ) { // Reduce context if the leading compound selector is an ID tokens = match[ 0 ] = match[ 0 ].slice( 0 ); if ( tokens.length > 2 && ( token = tokens[ 0 ] ).type === "ID" && context.nodeType === 9 && documentIsHTML && Expr.relative[ tokens[ 1 ].type ] ) { context = ( Expr.find[ "ID" ]( token.matches[ 0 ] .replace( runescape, funescape ), context ) || [] )[ 0 ]; if ( !context ) { return results; // Precompiled matchers will still verify ancestry, so step up a level } else if ( compiled ) { context = context.parentNode; } selector = selector.slice( tokens.shift().value.length ); } // Fetch a seed set for right-to-left matching i = matchExpr[ "needsContext" ].test( selector ) ? 0 : tokens.length; while ( i-- ) { token = tokens[ i ]; // Abort if we hit a combinator if ( Expr.relative[ ( type = token.type ) ] ) { break; } if ( ( find = Expr.find[ type ] ) ) { // Search, expanding context for leading sibling combinators if ( ( seed = find( token.matches[ 0 ].replace( runescape, funescape ), rsibling.test( tokens[ 0 ].type ) && testContext( context.parentNode ) || context ) ) ) { // If seed is empty or no tokens remain, we can return early tokens.splice( i, 1 ); selector = seed.length && toSelector( tokens ); if ( !selector ) { push.apply( results, seed ); return results; } break; } } } } // Compile and execute a filtering function if one is not provided // Provide `match` to avoid retokenization if we modified the selector above ( compiled || compile( selector, match ) )( seed, context, !documentIsHTML, results, !context || rsibling.test( selector ) && testContext( context.parentNode ) || context ); return results; }; // One-time assignments // Sort stability support.sortStable = expando.split( "" ).sort( sortOrder ).join( "" ) === expando; // Support: Chrome 14-35+ // Always assume duplicates if they aren't passed to the comparison function support.detectDuplicates = !!hasDuplicate; // Initialize against the default document setDocument(); // Support: Webkit<537.32 - Safari 6.0.3/Chrome 25 (fixed in Chrome 27) // Detached nodes confoundingly follow *each other* support.sortDetached = assert( function( el ) { // Should return 1, but returns 4 (following) return el.compareDocumentPosition( document.createElement( "fieldset" ) ) & 1; } ); // Support: IE<8 // Prevent attribute/property "interpolation" // https://msdn.microsoft.com/en-us/library/ms536429%28VS.85%29.aspx if ( !assert( function( el ) { el.innerHTML = "<a href='#'></a>"; return el.firstChild.getAttribute( "href" ) === "#"; } ) ) { addHandle( "type|href|height|width", function( elem, name, isXML ) { if ( !isXML ) { return elem.getAttribute( name, name.toLowerCase() === "type" ? 1 : 2 ); } } ); } // Support: IE<9 // Use defaultValue in place of getAttribute("value") if ( !support.attributes || !assert( function( el ) { el.innerHTML = "<input/>"; el.firstChild.setAttribute( "value", "" ); return el.firstChild.getAttribute( "value" ) === ""; } ) ) { addHandle( "value", function( elem, _name, isXML ) { if ( !isXML && elem.nodeName.toLowerCase() === "input" ) { return elem.defaultValue; } } ); } // Support: IE<9 // Use getAttributeNode to fetch booleans when getAttribute lies if ( !assert( function( el ) { return el.getAttribute( "disabled" ) == null; } ) ) { addHandle( booleans, function( elem, name, isXML ) { var val; if ( !isXML ) { return elem[ name ] === true ? name.toLowerCase() : ( val = elem.getAttributeNode( name ) ) && val.specified ? val.value : null; } } ); } return Sizzle; } )( window ); jQuery.find = Sizzle; jQuery.expr = Sizzle.selectors; // Deprecated jQuery.expr[ ":" ] = jQuery.expr.pseudos; jQuery.uniqueSort = jQuery.unique = Sizzle.uniqueSort; jQuery.text = Sizzle.getText; jQuery.isXMLDoc = Sizzle.isXML; jQuery.contains = Sizzle.contains; jQuery.escapeSelector = Sizzle.escape; var dir = function( elem, dir, until ) { var matched = [], truncate = until !== undefined; while ( ( elem = elem[ dir ] ) && elem.nodeType !== 9 ) { if ( elem.nodeType === 1 ) { if ( truncate && jQuery( elem ).is( until ) ) { break; } matched.push( elem ); } } return matched; }; var siblings = function( n, elem ) { var matched = []; for ( ; n; n = n.nextSibling ) { if ( n.nodeType === 1 && n !== elem ) { matched.push( n ); } } return matched; }; var rneedsContext = jQuery.expr.match.needsContext; function nodeName( elem, name ) { return elem.nodeName && elem.nodeName.toLowerCase() === name.toLowerCase(); }; var rsingleTag = ( /^<([a-z][^\/\0>:\x20\t\r\n\f]*)[\x20\t\r\n\f]*\/?>(?:<\/\1>|)$/i ); // Implement the identical functionality for filter and not function winnow( elements, qualifier, not ) { if ( isFunction( qualifier ) ) { return jQuery.grep( elements, function( elem, i ) { return !!qualifier.call( elem, i, elem ) !== not; } ); } // Single element if ( qualifier.nodeType ) { return jQuery.grep( elements, function( elem ) { return ( elem === qualifier ) !== not; } ); } // Arraylike of elements (jQuery, arguments, Array) if ( typeof qualifier !== "string" ) { return jQuery.grep( elements, function( elem ) { return ( indexOf.call( qualifier, elem ) > -1 ) !== not; } ); } // Filtered directly for both simple and complex selectors return jQuery.filter( qualifier, elements, not ); } jQuery.filter = function( expr, elems, not ) { var elem = elems[ 0 ]; if ( not ) { expr = ":not(" + expr + ")"; } if ( elems.length === 1 && elem.nodeType === 1 ) { return jQuery.find.matchesSelector( elem, expr ) ? [ elem ] : []; } return jQuery.find.matches( expr, jQuery.grep( elems, function( elem ) { return elem.nodeType === 1; } ) ); }; jQuery.fn.extend( { find: function( selector ) { var i, ret, len = this.length, self = this; if ( typeof selector !== "string" ) { return this.pushStack( jQuery( selector ).filter( function() { for ( i = 0; i < len; i++ ) { if ( jQuery.contains( self[ i ], this ) ) { return true; } } } ) ); } ret = this.pushStack( [] ); for ( i = 0; i < len; i++ ) { jQuery.find( selector, self[ i ], ret ); } return len > 1 ? jQuery.uniqueSort( ret ) : ret; }, filter: function( selector ) { return this.pushStack( winnow( this, selector || [], false ) ); }, not: function( selector ) { return this.pushStack( winnow( this, selector || [], true ) ); }, is: function( selector ) { return !!winnow( this, // If this is a positional/relative selector, check membership in the returned set // so $("p:first").is("p:last") won't return true for a doc with two "p". typeof selector === "string" && rneedsContext.test( selector ) ? jQuery( selector ) : selector || [], false ).length; } } ); // Initialize a jQuery object // A central reference to the root jQuery(document) var rootjQuery, // A simple way to check for HTML strings // Prioritize #id over <tag> to avoid XSS via location.hash (#9521) // Strict HTML recognition (#11290: must start with <) // Shortcut simple #id case for speed rquickExpr = /^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]+))$/, init = jQuery.fn.init = function( selector, context, root ) { var match, elem; // HANDLE: $(""), $(null), $(undefined), $(false) if ( !selector ) { return this; } // Method init() accepts an alternate rootjQuery // so migrate can support jQuery.sub (gh-2101) root = root || rootjQuery; // Handle HTML strings if ( typeof selector === "string" ) { if ( selector[ 0 ] === "<" && selector[ selector.length - 1 ] === ">" && selector.length >= 3 ) { // Assume that strings that start and end with <> are HTML and skip the regex check match = [ null, selector, null ]; } else { match = rquickExpr.exec( selector ); } // Match html or make sure no context is specified for #id if ( match && ( match[ 1 ] || !context ) ) { // HANDLE: $(html) -> $(array) if ( match[ 1 ] ) { context = context instanceof jQuery ? context[ 0 ] : context; // Option to run scripts is true for back-compat // Intentionally let the error be thrown if parseHTML is not present jQuery.merge( this, jQuery.parseHTML( match[ 1 ], context && context.nodeType ? context.ownerDocument || context : document, true ) ); // HANDLE: $(html, props) if ( rsingleTag.test( match[ 1 ] ) && jQuery.isPlainObject( context ) ) { for ( match in context ) { // Properties of context are called as methods if possible if ( isFunction( this[ match ] ) ) { this[ match ]( context[ match ] ); // ...and otherwise set as attributes } else { this.attr( match, context[ match ] ); } } } return this; // HANDLE: $(#id) } else { elem = document.getElementById( match[ 2 ] ); if ( elem ) { // Inject the element directly into the jQuery object this[ 0 ] = elem; this.length = 1; } return this; } // HANDLE: $(expr, $(...)) } else if ( !context || context.jquery ) { return ( context || root ).find( selector ); // HANDLE: $(expr, context) // (which is just equivalent to: $(context).find(expr) } else { return this.constructor( context ).find( selector ); } // HANDLE: $(DOMElement) } else if ( selector.nodeType ) { this[ 0 ] = selector; this.length = 1; return this; // HANDLE: $(function) // Shortcut for document ready } else if ( isFunction( selector ) ) { return root.ready !== undefined ? root.ready( selector ) : // Execute immediately if ready is not present selector( jQuery ); } return jQuery.makeArray( selector, this ); }; // Give the init function the jQuery prototype for later instantiation init.prototype = jQuery.fn; // Initialize central reference rootjQuery = jQuery( document ); var rparentsprev = /^(?:parents|prev(?:Until|All))/, // Methods guaranteed to produce a unique set when starting from a unique set guaranteedUnique = { children: true, contents: true, next: true, prev: true }; jQuery.fn.extend( { has: function( target ) { var targets = jQuery( target, this ), l = targets.length; return this.filter( function() { var i = 0; for ( ; i < l; i++ ) { if ( jQuery.contains( this, targets[ i ] ) ) { return true; } } } ); }, closest: function( selectors, context ) { var cur, i = 0, l = this.length, matched = [], targets = typeof selectors !== "string" && jQuery( selectors ); // Positional selectors never match, since there's no _selection_ context if ( !rneedsContext.test( selectors ) ) { for ( ; i < l; i++ ) { for ( cur = this[ i ]; cur && cur !== context; cur = cur.parentNode ) { // Always skip document fragments if ( cur.nodeType < 11 && ( targets ? targets.index( cur ) > -1 : // Don't pass non-elements to Sizzle cur.nodeType === 1 && jQuery.find.matchesSelector( cur, selectors ) ) ) { matched.push( cur ); break; } } } } return this.pushStack( matched.length > 1 ? jQuery.uniqueSort( matched ) : matched ); }, // Determine the position of an element within the set index: function( elem ) { // No argument, return index in parent if ( !elem ) { return ( this[ 0 ] && this[ 0 ].parentNode ) ? this.first().prevAll().length : -1; } // Index in selector if ( typeof elem === "string" ) { return indexOf.call( jQuery( elem ), this[ 0 ] ); } // Locate the position of the desired element return indexOf.call( this, // If it receives a jQuery object, the first element is used elem.jquery ? elem[ 0 ] : elem ); }, add: function( selector, context ) { return this.pushStack( jQuery.uniqueSort( jQuery.merge( this.get(), jQuery( selector, context ) ) ) ); }, addBack: function( selector ) { return this.add( selector == null ? this.prevObject : this.prevObject.filter( selector ) ); } } ); function sibling( cur, dir ) { while ( ( cur = cur[ dir ] ) && cur.nodeType !== 1 ) {} return cur; } jQuery.each( { parent: function( elem ) { var parent = elem.parentNode; return parent && parent.nodeType !== 11 ? parent : null; }, parents: function( elem ) { return dir( elem, "parentNode" ); }, parentsUntil: function( elem, _i, until ) { return dir( elem, "parentNode", until ); }, next: function( elem ) { return sibling( elem, "nextSibling" ); }, prev: function( elem ) { return sibling( elem, "previousSibling" ); }, nextAll: function( elem ) { return dir( elem, "nextSibling" ); }, prevAll: function( elem ) { return dir( elem, "previousSibling" ); }, nextUntil: function( elem, _i, until ) { return dir( elem, "nextSibling", until ); }, prevUntil: function( elem, _i, until ) { return dir( elem, "previousSibling", until ); }, siblings: function( elem ) { return siblings( ( elem.parentNode || {} ).firstChild, elem ); }, children: function( elem ) { return siblings( elem.firstChild ); }, contents: function( elem ) { if ( elem.contentDocument != null && // Support: IE 11+ // <object> elements with no `data` attribute has an object // `contentDocument` with a `null` prototype. getProto( elem.contentDocument ) ) { return elem.contentDocument; } // Support: IE 9 - 11 only, iOS 7 only, Android Browser <=4.3 only // Treat the template element as a regular one in browsers that // don't support it. if ( nodeName( elem, "template" ) ) { elem = elem.content || elem; } return jQuery.merge( [], elem.childNodes ); } }, function( name, fn ) { jQuery.fn[ name ] = function( until, selector ) { var matched = jQuery.map( this, fn, until ); if ( name.slice( -5 ) !== "Until" ) { selector = until; } if ( selector && typeof selector === "string" ) { matched = jQuery.filter( selector, matched ); } if ( this.length > 1 ) { // Remove duplicates if ( !guaranteedUnique[ name ] ) { jQuery.uniqueSort( matched ); } // Reverse order for parents* and prev-derivatives if ( rparentsprev.test( name ) ) { matched.reverse(); } } return this.pushStack( matched ); }; } ); var rnothtmlwhite = ( /[^\x20\t\r\n\f]+/g ); // Convert String-formatted options into Object-formatted ones function createOptions( options ) { var object = {}; jQuery.each( options.match( rnothtmlwhite ) || [], function( _, flag ) { object[ flag ] = true; } ); return object; } /* * Create a callback list using the following parameters: * * options: an optional list of space-separated options that will change how * the callback list behaves or a more traditional option object * * By default a callback list will act like an event callback list and can be * "fired" multiple times. * * Possible options: * * once: will ensure the callback list can only be fired once (like a Deferred) * * memory: will keep track of previous values and will call any callback added * after the list has been fired right away with the latest "memorized" * values (like a Deferred) * * unique: will ensure a callback can only be added once (no duplicate in the list) * * stopOnFalse: interrupt callings when a callback returns false * */ jQuery.Callbacks = function( options ) { // Convert options from String-formatted to Object-formatted if needed // (we check in cache first) options = typeof options === "string" ? createOptions( options ) : jQuery.extend( {}, options ); var // Flag to know if list is currently firing firing, // Last fire value for non-forgettable lists memory, // Flag to know if list was already fired fired, // Flag to prevent firing locked, // Actual callback list list = [], // Queue of execution data for repeatable lists queue = [], // Index of currently firing callback (modified by add/remove as needed) firingIndex = -1, // Fire callbacks fire = function() { // Enforce single-firing locked = locked || options.once; // Execute callbacks for all pending executions, // respecting firingIndex overrides and runtime changes fired = firing = true; for ( ; queue.length; firingIndex = -1 ) { memory = queue.shift(); while ( ++firingIndex < list.length ) { // Run callback and check for early termination if ( list[ firingIndex ].apply( memory[ 0 ], memory[ 1 ] ) === false && options.stopOnFalse ) { // Jump to end and forget the data so .add doesn't re-fire firingIndex = list.length; memory = false; } } } // Forget the data if we're done with it if ( !options.memory ) { memory = false; } firing = false; // Clean up if we're done firing for good if ( locked ) { // Keep an empty list if we have data for future add calls if ( memory ) { list = []; // Otherwise, this object is spent } else { list = ""; } } }, // Actual Callbacks object self = { // Add a callback or a collection of callbacks to the list add: function() { if ( list ) { // If we have memory from a past run, we should fire after adding if ( memory && !firing ) { firingIndex = list.length - 1; queue.push( memory ); } ( function add( args ) { jQuery.each( args, function( _, arg ) { if ( isFunction( arg ) ) { if ( !options.unique || !self.has( arg ) ) { list.push( arg ); } } else if ( arg && arg.length && toType( arg ) !== "string" ) { // Inspect recursively add( arg ); } } ); } )( arguments ); if ( memory && !firing ) { fire(); } } return this; }, // Remove a callback from the list remove: function() { jQuery.each( arguments, function( _, arg ) { var index; while ( ( index = jQuery.inArray( arg, list, index ) ) > -1 ) { list.splice( index, 1 ); // Handle firing indexes if ( index <= firingIndex ) { firingIndex--; } } } ); return this; }, // Check if a given callback is in the list. // If no argument is given, return whether or not list has callbacks attached. has: function( fn ) { return fn ? jQuery.inArray( fn, list ) > -1 : list.length > 0; }, // Remove all callbacks from the list empty: function() { if ( list ) { list = []; } return this; }, // Disable .fire and .add // Abort any current/pending executions // Clear all callbacks and values disable: function() { locked = queue = []; list = memory = ""; return this; }, disabled: function() { return !list; }, // Disable .fire // Also disable .add unless we have memory (since it would have no effect) // Abort any pending executions lock: function() { locked = queue = []; if ( !memory && !firing ) { list = memory = ""; } return this; }, locked: function() { return !!locked; }, // Call all callbacks with the given context and arguments fireWith: function( context, args ) { if ( !locked ) { args = args || []; args = [ context, args.slice ? args.slice() : args ]; queue.push( args ); if ( !firing ) { fire(); } } return this; }, // Call all the callbacks with the given arguments fire: function() { self.fireWith( this, arguments ); return this; }, // To know if the callbacks have already been called at least once fired: function() { return !!fired; } }; return self; }; function Identity( v ) { return v; } function Thrower( ex ) { throw ex; } function adoptValue( value, resolve, reject, noValue ) { var method; try { // Check for promise aspect first to privilege synchronous behavior if ( value && isFunction( ( method = value.promise ) ) ) { method.call( value ).done( resolve ).fail( reject ); // Other thenables } else if ( value && isFunction( ( method = value.then ) ) ) { method.call( value, resolve, reject ); // Other non-thenables } else { // Control `resolve` arguments by letting Array#slice cast boolean `noValue` to integer: // * false: [ value ].slice( 0 ) => resolve( value ) // * true: [ value ].slice( 1 ) => resolve() resolve.apply( undefined, [ value ].slice( noValue ) ); } // For Promises/A+, convert exceptions into rejections // Since jQuery.when doesn't unwrap thenables, we can skip the extra checks appearing in // Deferred#then to conditionally suppress rejection. } catch ( value ) { // Support: Android 4.0 only // Strict mode functions invoked without .call/.apply get global-object context reject.apply( undefined, [ value ] ); } } jQuery.extend( { Deferred: function( func ) { var tuples = [ // action, add listener, callbacks, // ... .then handlers, argument index, [final state] [ "notify", "progress", jQuery.Callbacks( "memory" ), jQuery.Callbacks( "memory" ), 2 ], [ "resolve", "done", jQuery.Callbacks( "once memory" ), jQuery.Callbacks( "once memory" ), 0, "resolved" ], [ "reject", "fail", jQuery.Callbacks( "once memory" ), jQuery.Callbacks( "once memory" ), 1, "rejected" ] ], state = "pending", promise = { state: function() { return state; }, always: function() { deferred.done( arguments ).fail( arguments ); return this; }, "catch": function( fn ) { return promise.then( null, fn ); }, // Keep pipe for back-compat pipe: function( /* fnDone, fnFail, fnProgress */ ) { var fns = arguments; return jQuery.Deferred( function( newDefer ) { jQuery.each( tuples, function( _i, tuple ) { // Map tuples (progress, done, fail) to arguments (done, fail, progress) var fn = isFunction( fns[ tuple[ 4 ] ] ) && fns[ tuple[ 4 ] ]; // deferred.progress(function() { bind to newDefer or newDefer.notify }) // deferred.done(function() { bind to newDefer or newDefer.resolve }) // deferred.fail(function() { bind to newDefer or newDefer.reject }) deferred[ tuple[ 1 ] ]( function() { var returned = fn && fn.apply( this, arguments ); if ( returned && isFunction( returned.promise ) ) { returned.promise() .progress( newDefer.notify ) .done( newDefer.resolve ) .fail( newDefer.reject ); } else { newDefer[ tuple[ 0 ] + "With" ]( this, fn ? [ returned ] : arguments ); } } ); } ); fns = null; } ).promise(); }, then: function( onFulfilled, onRejected, onProgress ) { var maxDepth = 0; function resolve( depth, deferred, handler, special ) { return function() { var that = this, args = arguments, mightThrow = function() { var returned, then; // Support: Promises/A+ section 2.3.3.3.3 // https://promisesaplus.com/#point-59 // Ignore double-resolution attempts if ( depth < maxDepth ) { return; } returned = handler.apply( that, args ); // Support: Promises/A+ section 2.3.1 // https://promisesaplus.com/#point-48 if ( returned === deferred.promise() ) { throw new TypeError( "Thenable self-resolution" ); } // Support: Promises/A+ sections 2.3.3.1, 3.5 // https://promisesaplus.com/#point-54 // https://promisesaplus.com/#point-75 // Retrieve `then` only once then = returned && // Support: Promises/A+ section 2.3.4 // https://promisesaplus.com/#point-64 // Only check objects and functions for thenability ( typeof returned === "object" || typeof returned === "function" ) && returned.then; // Handle a returned thenable if ( isFunction( then ) ) { // Special processors (notify) just wait for resolution if ( special ) { then.call( returned, resolve( maxDepth, deferred, Identity, special ), resolve( maxDepth, deferred, Thrower, special ) ); // Normal processors (resolve) also hook into progress } else { // ...and disregard older resolution values maxDepth++; then.call( returned, resolve( maxDepth, deferred, Identity, special ), resolve( maxDepth, deferred, Thrower, special ), resolve( maxDepth, deferred, Identity, deferred.notifyWith ) ); } // Handle all other returned values } else { // Only substitute handlers pass on context // and multiple values (non-spec behavior) if ( handler !== Identity ) { that = undefined; args = [ returned ]; } // Process the value(s) // Default process is resolve ( special || deferred.resolveWith )( that, args ); } }, // Only normal processors (resolve) catch and reject exceptions process = special ? mightThrow : function() { try { mightThrow(); } catch ( e ) { if ( jQuery.Deferred.exceptionHook ) { jQuery.Deferred.exceptionHook( e, process.stackTrace ); } // Support: Promises/A+ section 2.3.3.3.4.1 // https://promisesaplus.com/#point-61 // Ignore post-resolution exceptions if ( depth + 1 >= maxDepth ) { // Only substitute handlers pass on context // and multiple values (non-spec behavior) if ( handler !== Thrower ) { that = undefined; args = [ e ]; } deferred.rejectWith( that, args ); } } }; // Support: Promises/A+ section 2.3.3.3.1 // https://promisesaplus.com/#point-57 // Re-resolve promises immediately to dodge false rejection from // subsequent errors if ( depth ) { process(); } else { // Call an optional hook to record the stack, in case of exception // since it's otherwise lost when execution goes async if ( jQuery.Deferred.getStackHook ) { process.stackTrace = jQuery.Deferred.getStackHook(); } window.setTimeout( process ); } }; } return jQuery.Deferred( function( newDefer ) { // progress_handlers.add( ... ) tuples[ 0 ][ 3 ].add( resolve( 0, newDefer, isFunction( onProgress ) ? onProgress : Identity, newDefer.notifyWith ) ); // fulfilled_handlers.add( ... ) tuples[ 1 ][ 3 ].add( resolve( 0, newDefer, isFunction( onFulfilled ) ? onFulfilled : Identity ) ); // rejected_handlers.add( ... ) tuples[ 2 ][ 3 ].add( resolve( 0, newDefer, isFunction( onRejected ) ? onRejected : Thrower ) ); } ).promise(); }, // Get a promise for this deferred // If obj is provided, the promise aspect is added to the object promise: function( obj ) { return obj != null ? jQuery.extend( obj, promise ) : promise; } }, deferred = {}; // Add list-specific methods jQuery.each( tuples, function( i, tuple ) { var list = tuple[ 2 ], stateString = tuple[ 5 ]; // promise.progress = list.add // promise.done = list.add // promise.fail = list.add promise[ tuple[ 1 ] ] = list.add; // Handle state if ( stateString ) { list.add( function() { // state = "resolved" (i.e., fulfilled) // state = "rejected" state = stateString; }, // rejected_callbacks.disable // fulfilled_callbacks.disable tuples[ 3 - i ][ 2 ].disable, // rejected_handlers.disable // fulfilled_handlers.disable tuples[ 3 - i ][ 3 ].disable, // progress_callbacks.lock tuples[ 0 ][ 2 ].lock, // progress_handlers.lock tuples[ 0 ][ 3 ].lock ); } // progress_handlers.fire // fulfilled_handlers.fire // rejected_handlers.fire list.add( tuple[ 3 ].fire ); // deferred.notify = function() { deferred.notifyWith(...) } // deferred.resolve = function() { deferred.resolveWith(...) } // deferred.reject = function() { deferred.rejectWith(...) } deferred[ tuple[ 0 ] ] = function() { deferred[ tuple[ 0 ] + "With" ]( this === deferred ? undefined : this, arguments ); return this; }; // deferred.notifyWith = list.fireWith // deferred.resolveWith = list.fireWith // deferred.rejectWith = list.fireWith deferred[ tuple[ 0 ] + "With" ] = list.fireWith; } ); // Make the deferred a promise promise.promise( deferred ); // Call given func if any if ( func ) { func.call( deferred, deferred ); } // All done! return deferred; }, // Deferred helper when: function( singleValue ) { var // count of uncompleted subordinates remaining = arguments.length, // count of unprocessed arguments i = remaining, // subordinate fulfillment data resolveContexts = Array( i ), resolveValues = slice.call( arguments ), // the master Deferred master = jQuery.Deferred(), // subordinate callback factory updateFunc = function( i ) { return function( value ) { resolveContexts[ i ] = this; resolveValues[ i ] = arguments.length > 1 ? slice.call( arguments ) : value; if ( !( --remaining ) ) { master.resolveWith( resolveContexts, resolveValues ); } }; }; // Single- and empty arguments are adopted like Promise.resolve if ( remaining <= 1 ) { adoptValue( singleValue, master.done( updateFunc( i ) ).resolve, master.reject, !remaining ); // Use .then() to unwrap secondary thenables (cf. gh-3000) if ( master.state() === "pending" || isFunction( resolveValues[ i ] && resolveValues[ i ].then ) ) { return master.then(); } } // Multiple arguments are aggregated like Promise.all array elements while ( i-- ) { adoptValue( resolveValues[ i ], updateFunc( i ), master.reject ); } return master.promise(); } } ); // These usually indicate a programmer mistake during development, // warn about them ASAP rather than swallowing them by default. var rerrorNames = /^(Eval|Internal|Range|Reference|Syntax|Type|URI)Error$/; jQuery.Deferred.exceptionHook = function( error, stack ) { // Support: IE 8 - 9 only // Console exists when dev tools are open, which can happen at any time if ( window.console && window.console.warn && error && rerrorNames.test( error.name ) ) { window.console.warn( "jQuery.Deferred exception: " + error.message, error.stack, stack ); } }; jQuery.readyException = function( error ) { window.setTimeout( function() { throw error; } ); }; // The deferred used on DOM ready var readyList = jQuery.Deferred(); jQuery.fn.ready = function( fn ) { readyList .then( fn ) // Wrap jQuery.readyException in a function so that the lookup // happens at the time of error handling instead of callback // registration. .catch( function( error ) { jQuery.readyException( error ); } ); return this; }; jQuery.extend( { // Is the DOM ready to be used? Set to true once it occurs. isReady: false, // A counter to track how many items to wait for before // the ready event fires. See #6781 readyWait: 1, // Handle when the DOM is ready ready: function( wait ) { // Abort if there are pending holds or we're already ready if ( wait === true ? --jQuery.readyWait : jQuery.isReady ) { return; } // Remember that the DOM is ready jQuery.isReady = true; // If a normal DOM Ready event fired, decrement, and wait if need be if ( wait !== true && --jQuery.readyWait > 0 ) { return; } // If there are functions bound, to execute readyList.resolveWith( document, [ jQuery ] ); } } ); jQuery.ready.then = readyList.then; // The ready event handler and self cleanup method function completed() { document.removeEventListener( "DOMContentLoaded", completed ); window.removeEventListener( "load", completed ); jQuery.ready(); } // Catch cases where $(document).ready() is called // after the browser event has already occurred. // Support: IE <=9 - 10 only // Older IE sometimes signals "interactive" too soon if ( document.readyState === "complete" || ( document.readyState !== "loading" && !document.documentElement.doScroll ) ) { // Handle it asynchronously to allow scripts the opportunity to delay ready window.setTimeout( jQuery.ready ); } else { // Use the handy event callback document.addEventListener( "DOMContentLoaded", completed ); // A fallback to window.onload, that will always work window.addEventListener( "load", completed ); } // Multifunctional method to get and set values of a collection // The value/s can optionally be executed if it's a function var access = function( elems, fn, key, value, chainable, emptyGet, raw ) { var i = 0, len = elems.length, bulk = key == null; // Sets many values if ( toType( key ) === "object" ) { chainable = true; for ( i in key ) { access( elems, fn, i, key[ i ], true, emptyGet, raw ); } // Sets one value } else if ( value !== undefined ) { chainable = true; if ( !isFunction( value ) ) { raw = true; } if ( bulk ) { // Bulk operations run against the entire set if ( raw ) { fn.call( elems, value ); fn = null; // ...except when executing function values } else { bulk = fn; fn = function( elem, _key, value ) { return bulk.call( jQuery( elem ), value ); }; } } if ( fn ) { for ( ; i < len; i++ ) { fn( elems[ i ], key, raw ? value : value.call( elems[ i ], i, fn( elems[ i ], key ) ) ); } } } if ( chainable ) { return elems; } // Gets if ( bulk ) { return fn.call( elems ); } return len ? fn( elems[ 0 ], key ) : emptyGet; }; // Matches dashed string for camelizing var rmsPrefix = /^-ms-/, rdashAlpha = /-([a-z])/g; // Used by camelCase as callback to replace() function fcamelCase( _all, letter ) { return letter.toUpperCase(); } // Convert dashed to camelCase; used by the css and data modules // Support: IE <=9 - 11, Edge 12 - 15 // Microsoft forgot to hump their vendor prefix (#9572) function camelCase( string ) { return string.replace( rmsPrefix, "ms-" ).replace( rdashAlpha, fcamelCase ); } var acceptData = function( owner ) { // Accepts only: // - Node // - Node.ELEMENT_NODE // - Node.DOCUMENT_NODE // - Object // - Any return owner.nodeType === 1 || owner.nodeType === 9 || !( +owner.nodeType ); }; function Data() { this.expando = jQuery.expando + Data.uid++; } Data.uid = 1; Data.prototype = { cache: function( owner ) { // Check if the owner object already has a cache var value = owner[ this.expando ]; // If not, create one if ( !value ) { value = Object.create( null ); // We can accept data for non-element nodes in modern browsers, // but we should not, see #8335. // Always return an empty object. if ( acceptData( owner ) ) { // If it is a node unlikely to be stringify-ed or looped over // use plain assignment if ( owner.nodeType ) { owner[ this.expando ] = value; // Otherwise secure it in a non-enumerable property // configurable must be true to allow the property to be // deleted when data is removed } else { Object.defineProperty( owner, this.expando, { value: value, configurable: true } ); } } } return value; }, set: function( owner, data, value ) { var prop, cache = this.cache( owner ); // Handle: [ owner, key, value ] args // Always use camelCase key (gh-2257) if ( typeof data === "string" ) { cache[ camelCase( data ) ] = value; // Handle: [ owner, { properties } ] args } else { // Copy the properties one-by-one to the cache object for ( prop in data ) { cache[ camelCase( prop ) ] = data[ prop ]; } } return cache; }, get: function( owner, key ) { return key === undefined ? this.cache( owner ) : // Always use camelCase key (gh-2257) owner[ this.expando ] && owner[ this.expando ][ camelCase( key ) ]; }, access: function( owner, key, value ) { // In cases where either: // // 1. No key was specified // 2. A string key was specified, but no value provided // // Take the "read" path and allow the get method to determine // which value to return, respectively either: // // 1. The entire cache object // 2. The data stored at the key // if ( key === undefined || ( ( key && typeof key === "string" ) && value === undefined ) ) { return this.get( owner, key ); } // When the key is not a string, or both a key and value // are specified, set or extend (existing objects) with either: // // 1. An object of properties // 2. A key and value // this.set( owner, key, value ); // Since the "set" path can have two possible entry points // return the expected data based on which path was taken[*] return value !== undefined ? value : key; }, remove: function( owner, key ) { var i, cache = owner[ this.expando ]; if ( cache === undefined ) { return; } if ( key !== undefined ) { // Support array or space separated string of keys if ( Array.isArray( key ) ) { // If key is an array of keys... // We always set camelCase keys, so remove that. key = key.map( camelCase ); } else { key = camelCase( key ); // If a key with the spaces exists, use it. // Otherwise, create an array by matching non-whitespace key = key in cache ? [ key ] : ( key.match( rnothtmlwhite ) || [] ); } i = key.length; while ( i-- ) { delete cache[ key[ i ] ]; } } // Remove the expando if there's no more data if ( key === undefined || jQuery.isEmptyObject( cache ) ) { // Support: Chrome <=35 - 45 // Webkit & Blink performance suffers when deleting properties // from DOM nodes, so set to undefined instead // https://bugs.chromium.org/p/chromium/issues/detail?id=378607 (bug restricted) if ( owner.nodeType ) { owner[ this.expando ] = undefined; } else { delete owner[ this.expando ]; } } }, hasData: function( owner ) { var cache = owner[ this.expando ]; return cache !== undefined && !jQuery.isEmptyObject( cache ); } }; var dataPriv = new Data(); var dataUser = new Data(); // Implementation Summary // // 1. Enforce API surface and semantic compatibility with 1.9.x branch // 2. Improve the module's maintainability by reducing the storage // paths to a single mechanism. // 3. Use the same single mechanism to support "private" and "user" data. // 4. _Never_ expose "private" data to user code (TODO: Drop _data, _removeData) // 5. Avoid exposing implementation details on user objects (eg. expando properties) // 6. Provide a clear path for implementation upgrade to WeakMap in 2014 var rbrace = /^(?:\{[\w\W]*\}|\[[\w\W]*\])$/, rmultiDash = /[A-Z]/g; function getData( data ) { if ( data === "true" ) { return true; } if ( data === "false" ) { return false; } if ( data === "null" ) { return null; } // Only convert to a number if it doesn't change the string if ( data === +data + "" ) { return +data; } if ( rbrace.test( data ) ) { return JSON.parse( data ); } return data; } function dataAttr( elem, key, data ) { var name; // If nothing was found internally, try to fetch any // data from the HTML5 data-* attribute if ( data === undefined && elem.nodeType === 1 ) { name = "data-" + key.replace( rmultiDash, "-$&" ).toLowerCase(); data = elem.getAttribute( name ); if ( typeof data === "string" ) { try { data = getData( data ); } catch ( e ) {} // Make sure we set the data so it isn't changed later dataUser.set( elem, key, data ); } else { data = undefined; } } return data; } jQuery.extend( { hasData: function( elem ) { return dataUser.hasData( elem ) || dataPriv.hasData( elem ); }, data: function( elem, name, data ) { return dataUser.access( elem, name, data ); }, removeData: function( elem, name ) { dataUser.remove( elem, name ); }, // TODO: Now that all calls to _data and _removeData have been replaced // with direct calls to dataPriv methods, these can be deprecated. _data: function( elem, name, data ) { return dataPriv.access( elem, name, data ); }, _removeData: function( elem, name ) { dataPriv.remove( elem, name ); } } ); jQuery.fn.extend( { data: function( key, value ) { var i, name, data, elem = this[ 0 ], attrs = elem && elem.attributes; // Gets all values if ( key === undefined ) { if ( this.length ) { data = dataUser.get( elem ); if ( elem.nodeType === 1 && !dataPriv.get( elem, "hasDataAttrs" ) ) { i = attrs.length; while ( i-- ) { // Support: IE 11 only // The attrs elements can be null (#14894) if ( attrs[ i ] ) { name = attrs[ i ].name; if ( name.indexOf( "data-" ) === 0 ) { name = camelCase( name.slice( 5 ) ); dataAttr( elem, name, data[ name ] ); } } } dataPriv.set( elem, "hasDataAttrs", true ); } } return data; } // Sets multiple values if ( typeof key === "object" ) { return this.each( function() { dataUser.set( this, key ); } ); } return access( this, function( value ) { var data; // The calling jQuery object (element matches) is not empty // (and therefore has an element appears at this[ 0 ]) and the // `value` parameter was not undefined. An empty jQuery object // will result in `undefined` for elem = this[ 0 ] which will // throw an exception if an attempt to read a data cache is made. if ( elem && value === undefined ) { // Attempt to get data from the cache // The key will always be camelCased in Data data = dataUser.get( elem, key ); if ( data !== undefined ) { return data; } // Attempt to "discover" the data in // HTML5 custom data-* attrs data = dataAttr( elem, key ); if ( data !== undefined ) { return data; } // We tried really hard, but the data doesn't exist. return; } // Set the data... this.each( function() { // We always store the camelCased key dataUser.set( this, key, value ); } ); }, null, value, arguments.length > 1, null, true ); }, removeData: function( key ) { return this.each( function() { dataUser.remove( this, key ); } ); } } ); jQuery.extend( { queue: function( elem, type, data ) { var queue; if ( elem ) { type = ( type || "fx" ) + "queue"; queue = dataPriv.get( elem, type ); // Speed up dequeue by getting out quickly if this is just a lookup if ( data ) { if ( !queue || Array.isArray( data ) ) { queue = dataPriv.access( elem, type, jQuery.makeArray( data ) ); } else { queue.push( data ); } } return queue || []; } }, dequeue: function( elem, type ) { type = type || "fx"; var queue = jQuery.queue( elem, type ), startLength = queue.length, fn = queue.shift(), hooks = jQuery._queueHooks( elem, type ), next = function() { jQuery.dequeue( elem, type ); }; // If the fx queue is dequeued, always remove the progress sentinel if ( fn === "inprogress" ) { fn = queue.shift(); startLength--; } if ( fn ) { // Add a progress sentinel to prevent the fx queue from being // automatically dequeued if ( type === "fx" ) { queue.unshift( "inprogress" ); } // Clear up the last queue stop function delete hooks.stop; fn.call( elem, next, hooks ); } if ( !startLength && hooks ) { hooks.empty.fire(); } }, // Not public - generate a queueHooks object, or return the current one _queueHooks: function( elem, type ) { var key = type + "queueHooks"; return dataPriv.get( elem, key ) || dataPriv.access( elem, key, { empty: jQuery.Callbacks( "once memory" ).add( function() { dataPriv.remove( elem, [ type + "queue", key ] ); } ) } ); } } ); jQuery.fn.extend( { queue: function( type, data ) { var setter = 2; if ( typeof type !== "string" ) { data = type; type = "fx"; setter--; } if ( arguments.length < setter ) { return jQuery.queue( this[ 0 ], type ); } return data === undefined ? this : this.each( function() { var queue = jQuery.queue( this, type, data ); // Ensure a hooks for this queue jQuery._queueHooks( this, type ); if ( type === "fx" && queue[ 0 ] !== "inprogress" ) { jQuery.dequeue( this, type ); } } ); }, dequeue: function( type ) { return this.each( function() { jQuery.dequeue( this, type ); } ); }, clearQueue: function( type ) { return this.queue( type || "fx", [] ); }, // Get a promise resolved when queues of a certain type // are emptied (fx is the type by default) promise: function( type, obj ) { var tmp, count = 1, defer = jQuery.Deferred(), elements = this, i = this.length, resolve = function() { if ( !( --count ) ) { defer.resolveWith( elements, [ elements ] ); } }; if ( typeof type !== "string" ) { obj = type; type = undefined; } type = type || "fx"; while ( i-- ) { tmp = dataPriv.get( elements[ i ], type + "queueHooks" ); if ( tmp && tmp.empty ) { count++; tmp.empty.add( resolve ); } } resolve(); return defer.promise( obj ); } } ); var pnum = ( /[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/ ).source; var rcssNum = new RegExp( "^(?:([+-])=|)(" + pnum + ")([a-z%]*)$", "i" ); var cssExpand = [ "Top", "Right", "Bottom", "Left" ]; var documentElement = document.documentElement; var isAttached = function( elem ) { return jQuery.contains( elem.ownerDocument, elem ); }, composed = { composed: true }; // Support: IE 9 - 11+, Edge 12 - 18+, iOS 10.0 - 10.2 only // Check attachment across shadow DOM boundaries when possible (gh-3504) // Support: iOS 10.0-10.2 only // Early iOS 10 versions support `attachShadow` but not `getRootNode`, // leading to errors. We need to check for `getRootNode`. if ( documentElement.getRootNode ) { isAttached = function( elem ) { return jQuery.contains( elem.ownerDocument, elem ) || elem.getRootNode( composed ) === elem.ownerDocument; }; } var isHiddenWithinTree = function( elem, el ) { // isHiddenWithinTree might be called from jQuery#filter function; // in that case, element will be second argument elem = el || elem; // Inline style trumps all return elem.style.display === "none" || elem.style.display === "" && // Otherwise, check computed style // Support: Firefox <=43 - 45 // Disconnected elements can have computed display: none, so first confirm that elem is // in the document. isAttached( elem ) && jQuery.css( elem, "display" ) === "none"; }; function adjustCSS( elem, prop, valueParts, tween ) { var adjusted, scale, maxIterations = 20, currentValue = tween ? function() { return tween.cur(); } : function() { return jQuery.css( elem, prop, "" ); }, initial = currentValue(), unit = valueParts && valueParts[ 3 ] || ( jQuery.cssNumber[ prop ] ? "" : "px" ), // Starting value computation is required for potential unit mismatches initialInUnit = elem.nodeType && ( jQuery.cssNumber[ prop ] || unit !== "px" && +initial ) && rcssNum.exec( jQuery.css( elem, prop ) ); if ( initialInUnit && initialInUnit[ 3 ] !== unit ) { // Support: Firefox <=54 // Halve the iteration target value to prevent interference from CSS upper bounds (gh-2144) initial = initial / 2; // Trust units reported by jQuery.css unit = unit || initialInUnit[ 3 ]; // Iteratively approximate from a nonzero starting point initialInUnit = +initial || 1; while ( maxIterations-- ) { // Evaluate and update our best guess (doubling guesses that zero out). // Finish if the scale equals or crosses 1 (making the old*new product non-positive). jQuery.style( elem, prop, initialInUnit + unit ); if ( ( 1 - scale ) * ( 1 - ( scale = currentValue() / initial || 0.5 ) ) <= 0 ) { maxIterations = 0; } initialInUnit = initialInUnit / scale; } initialInUnit = initialInUnit * 2; jQuery.style( elem, prop, initialInUnit + unit ); // Make sure we update the tween properties later on valueParts = valueParts || []; } if ( valueParts ) { initialInUnit = +initialInUnit || +initial || 0; // Apply relative offset (+=/-=) if specified adjusted = valueParts[ 1 ] ? initialInUnit + ( valueParts[ 1 ] + 1 ) * valueParts[ 2 ] : +valueParts[ 2 ]; if ( tween ) { tween.unit = unit; tween.start = initialInUnit; tween.end = adjusted; } } return adjusted; } var defaultDisplayMap = {}; function getDefaultDisplay( elem ) { var temp, doc = elem.ownerDocument, nodeName = elem.nodeName, display = defaultDisplayMap[ nodeName ]; if ( display ) { return display; } temp = doc.body.appendChild( doc.createElement( nodeName ) ); display = jQuery.css( temp, "display" ); temp.parentNode.removeChild( temp ); if ( display === "none" ) { display = "block"; } defaultDisplayMap[ nodeName ] = display; return display; } function showHide( elements, show ) { var display, elem, values = [], index = 0, length = elements.length; // Determine new display value for elements that need to change for ( ; index < length; index++ ) { elem = elements[ index ]; if ( !elem.style ) { continue; } display = elem.style.display; if ( show ) { // Since we force visibility upon cascade-hidden elements, an immediate (and slow) // check is required in this first loop unless we have a nonempty display value (either // inline or about-to-be-restored) if ( display === "none" ) { values[ index ] = dataPriv.get( elem, "display" ) || null; if ( !values[ index ] ) { elem.style.display = ""; } } if ( elem.style.display === "" && isHiddenWithinTree( elem ) ) { values[ index ] = getDefaultDisplay( elem ); } } else { if ( display !== "none" ) { values[ index ] = "none"; // Remember what we're overwriting dataPriv.set( elem, "display", display ); } } } // Set the display of the elements in a second loop to avoid constant reflow for ( index = 0; index < length; index++ ) { if ( values[ index ] != null ) { elements[ index ].style.display = values[ index ]; } } return elements; } jQuery.fn.extend( { show: function() { return showHide( this, true ); }, hide: function() { return showHide( this ); }, toggle: function( state ) { if ( typeof state === "boolean" ) { return state ? this.show() : this.hide(); } return this.each( function() { if ( isHiddenWithinTree( this ) ) { jQuery( this ).show(); } else { jQuery( this ).hide(); } } ); } } ); var rcheckableType = ( /^(?:checkbox|radio)$/i ); var rtagName = ( /<([a-z][^\/\0>\x20\t\r\n\f]*)/i ); var rscriptType = ( /^$|^module$|\/(?:java|ecma)script/i ); ( function() { var fragment = document.createDocumentFragment(), div = fragment.appendChild( document.createElement( "div" ) ), input = document.createElement( "input" ); // Support: Android 4.0 - 4.3 only // Check state lost if the name is set (#11217) // Support: Windows Web Apps (WWA) // `name` and `type` must use .setAttribute for WWA (#14901) input.setAttribute( "type", "radio" ); input.setAttribute( "checked", "checked" ); input.setAttribute( "name", "t" ); div.appendChild( input ); // Support: Android <=4.1 only // Older WebKit doesn't clone checked state correctly in fragments support.checkClone = div.cloneNode( true ).cloneNode( true ).lastChild.checked; // Support: IE <=11 only // Make sure textarea (and checkbox) defaultValue is properly cloned div.innerHTML = "<textarea>x</textarea>"; support.noCloneChecked = !!div.cloneNode( true ).lastChild.defaultValue; // Support: IE <=9 only // IE <=9 replaces <option> tags with their contents when inserted outside of // the select element. div.innerHTML = "<option></option>"; support.option = !!div.lastChild; } )(); // We have to close these tags to support XHTML (#13200) var wrapMap = { // XHTML parsers do not magically insert elements in the // same way that tag soup parsers do. So we cannot shorten // this by omitting <tbody> or other required elements. thead: [ 1, "<table>", "</table>" ], col: [ 2, "<table><colgroup>", "</colgroup></table>" ], tr: [ 2, "<table><tbody>", "</tbody></table>" ], td: [ 3, "<table><tbody><tr>", "</tr></tbody></table>" ], _default: [ 0, "", "" ] }; wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead; wrapMap.th = wrapMap.td; // Support: IE <=9 only if ( !support.option ) { wrapMap.optgroup = wrapMap.option = [ 1, "<select multiple='multiple'>", "</select>" ]; } function getAll( context, tag ) { // Support: IE <=9 - 11 only // Use typeof to avoid zero-argument method invocation on host objects (#15151) var ret; if ( typeof context.getElementsByTagName !== "undefined" ) { ret = context.getElementsByTagName( tag || "*" ); } else if ( typeof context.querySelectorAll !== "undefined" ) { ret = context.querySelectorAll( tag || "*" ); } else { ret = []; } if ( tag === undefined || tag && nodeName( context, tag ) ) { return jQuery.merge( [ context ], ret ); } return ret; } // Mark scripts as having already been evaluated function setGlobalEval( elems, refElements ) { var i = 0, l = elems.length; for ( ; i < l; i++ ) { dataPriv.set( elems[ i ], "globalEval", !refElements || dataPriv.get( refElements[ i ], "globalEval" ) ); } } var rhtml = /<|&#?\w+;/; function buildFragment( elems, context, scripts, selection, ignored ) { var elem, tmp, tag, wrap, attached, j, fragment = context.createDocumentFragment(), nodes = [], i = 0, l = elems.length; for ( ; i < l; i++ ) { elem = elems[ i ]; if ( elem || elem === 0 ) { // Add nodes directly if ( toType( elem ) === "object" ) { // Support: Android <=4.0 only, PhantomJS 1 only // push.apply(_, arraylike) throws on ancient WebKit jQuery.merge( nodes, elem.nodeType ? [ elem ] : elem ); // Convert non-html into a text node } else if ( !rhtml.test( elem ) ) { nodes.push( context.createTextNode( elem ) ); // Convert html into DOM nodes } else { tmp = tmp || fragment.appendChild( context.createElement( "div" ) ); // Deserialize a standard representation tag = ( rtagName.exec( elem ) || [ "", "" ] )[ 1 ].toLowerCase(); wrap = wrapMap[ tag ] || wrapMap._default; tmp.innerHTML = wrap[ 1 ] + jQuery.htmlPrefilter( elem ) + wrap[ 2 ]; // Descend through wrappers to the right content j = wrap[ 0 ]; while ( j-- ) { tmp = tmp.lastChild; } // Support: Android <=4.0 only, PhantomJS 1 only // push.apply(_, arraylike) throws on ancient WebKit jQuery.merge( nodes, tmp.childNodes ); // Remember the top-level container tmp = fragment.firstChild; // Ensure the created nodes are orphaned (#12392) tmp.textContent = ""; } } } // Remove wrapper from fragment fragment.textContent = ""; i = 0; while ( ( elem = nodes[ i++ ] ) ) { // Skip elements already in the context collection (trac-4087) if ( selection && jQuery.inArray( elem, selection ) > -1 ) { if ( ignored ) { ignored.push( elem ); } continue; } attached = isAttached( elem ); // Append to fragment tmp = getAll( fragment.appendChild( elem ), "script" ); // Preserve script evaluation history if ( attached ) { setGlobalEval( tmp ); } // Capture executables if ( scripts ) { j = 0; while ( ( elem = tmp[ j++ ] ) ) { if ( rscriptType.test( elem.type || "" ) ) { scripts.push( elem ); } } } } return fragment; } var rkeyEvent = /^key/, rmouseEvent = /^(?:mouse|pointer|contextmenu|drag|drop)|click/, rtypenamespace = /^([^.]*)(?:\.(.+)|)/; function returnTrue() { return true; } function returnFalse() { return false; } // Support: IE <=9 - 11+ // focus() and blur() are asynchronous, except when they are no-op. // So expect focus to be synchronous when the element is already active, // and blur to be synchronous when the element is not already active. // (focus and blur are always synchronous in other supported browsers, // this just defines when we can count on it). function expectSync( elem, type ) { return ( elem === safeActiveElement() ) === ( type === "focus" ); } // Support: IE <=9 only // Accessing document.activeElement can throw unexpectedly // https://bugs.jquery.com/ticket/13393 function safeActiveElement() { try { return document.activeElement; } catch ( err ) { } } function on( elem, types, selector, data, fn, one ) { var origFn, type; // Types can be a map of types/handlers if ( typeof types === "object" ) { // ( types-Object, selector, data ) if ( typeof selector !== "string" ) { // ( types-Object, data ) data = data || selector; selector = undefined; } for ( type in types ) { on( elem, type, selector, data, types[ type ], one ); } return elem; } if ( data == null && fn == null ) { // ( types, fn ) fn = selector; data = selector = undefined; } else if ( fn == null ) { if ( typeof selector === "string" ) { // ( types, selector, fn ) fn = data; data = undefined; } else { // ( types, data, fn ) fn = data; data = selector; selector = undefined; } } if ( fn === false ) { fn = returnFalse; } else if ( !fn ) { return elem; } if ( one === 1 ) { origFn = fn; fn = function( event ) { // Can use an empty set, since event contains the info jQuery().off( event ); return origFn.apply( this, arguments ); }; // Use same guid so caller can remove using origFn fn.guid = origFn.guid || ( origFn.guid = jQuery.guid++ ); } return elem.each( function() { jQuery.event.add( this, types, fn, data, selector ); } ); } /* * Helper functions for managing events -- not part of the public interface. * Props to Dean Edwards' addEvent library for many of the ideas. */ jQuery.event = { global: {}, add: function( elem, types, handler, data, selector ) { var handleObjIn, eventHandle, tmp, events, t, handleObj, special, handlers, type, namespaces, origType, elemData = dataPriv.get( elem ); // Only attach events to objects that accept data if ( !acceptData( elem ) ) { return; } // Caller can pass in an object of custom data in lieu of the handler if ( handler.handler ) { handleObjIn = handler; handler = handleObjIn.handler; selector = handleObjIn.selector; } // Ensure that invalid selectors throw exceptions at attach time // Evaluate against documentElement in case elem is a non-element node (e.g., document) if ( selector ) { jQuery.find.matchesSelector( documentElement, selector ); } // Make sure that the handler has a unique ID, used to find/remove it later if ( !handler.guid ) { handler.guid = jQuery.guid++; } // Init the element's event structure and main handler, if this is the first if ( !( events = elemData.events ) ) { events = elemData.events = Object.create( null ); } if ( !( eventHandle = elemData.handle ) ) { eventHandle = elemData.handle = function( e ) { // Discard the second event of a jQuery.event.trigger() and // when an event is called after a page has unloaded return typeof jQuery !== "undefined" && jQuery.event.triggered !== e.type ? jQuery.event.dispatch.apply( elem, arguments ) : undefined; }; } // Handle multiple events separated by a space types = ( types || "" ).match( rnothtmlwhite ) || [ "" ]; t = types.length; while ( t-- ) { tmp = rtypenamespace.exec( types[ t ] ) || []; type = origType = tmp[ 1 ]; namespaces = ( tmp[ 2 ] || "" ).split( "." ).sort(); // There *must* be a type, no attaching namespace-only handlers if ( !type ) { continue; } // If event changes its type, use the special event handlers for the changed type special = jQuery.event.special[ type ] || {}; // If selector defined, determine special event api type, otherwise given type type = ( selector ? special.delegateType : special.bindType ) || type; // Update special based on newly reset type special = jQuery.event.special[ type ] || {}; // handleObj is passed to all event handlers handleObj = jQuery.extend( { type: type, origType: origType, data: data, handler: handler, guid: handler.guid, selector: selector, needsContext: selector && jQuery.expr.match.needsContext.test( selector ), namespace: namespaces.join( "." ) }, handleObjIn ); // Init the event handler queue if we're the first if ( !( handlers = events[ type ] ) ) { handlers = events[ type ] = []; handlers.delegateCount = 0; // Only use addEventListener if the special events handler returns false if ( !special.setup || special.setup.call( elem, data, namespaces, eventHandle ) === false ) { if ( elem.addEventListener ) { elem.addEventListener( type, eventHandle ); } } } if ( special.add ) { special.add.call( elem, handleObj ); if ( !handleObj.handler.guid ) { handleObj.handler.guid = handler.guid; } } // Add to the element's handler list, delegates in front if ( selector ) { handlers.splice( handlers.delegateCount++, 0, handleObj ); } else { handlers.push( handleObj ); } // Keep track of which events have ever been used, for event optimization jQuery.event.global[ type ] = true; } }, // Detach an event or set of events from an element remove: function( elem, types, handler, selector, mappedTypes ) { var j, origCount, tmp, events, t, handleObj, special, handlers, type, namespaces, origType, elemData = dataPriv.hasData( elem ) && dataPriv.get( elem ); if ( !elemData || !( events = elemData.events ) ) { return; } // Once for each type.namespace in types; type may be omitted types = ( types || "" ).match( rnothtmlwhite ) || [ "" ]; t = types.length; while ( t-- ) { tmp = rtypenamespace.exec( types[ t ] ) || []; type = origType = tmp[ 1 ]; namespaces = ( tmp[ 2 ] || "" ).split( "." ).sort(); // Unbind all events (on this namespace, if provided) for the element if ( !type ) { for ( type in events ) { jQuery.event.remove( elem, type + types[ t ], handler, selector, true ); } continue; } special = jQuery.event.special[ type ] || {}; type = ( selector ? special.delegateType : special.bindType ) || type; handlers = events[ type ] || []; tmp = tmp[ 2 ] && new RegExp( "(^|\\.)" + namespaces.join( "\\.(?:.*\\.|)" ) + "(\\.|$)" ); // Remove matching events origCount = j = handlers.length; while ( j-- ) { handleObj = handlers[ j ]; if ( ( mappedTypes || origType === handleObj.origType ) && ( !handler || handler.guid === handleObj.guid ) && ( !tmp || tmp.test( handleObj.namespace ) ) && ( !selector || selector === handleObj.selector || selector === "**" && handleObj.selector ) ) { handlers.splice( j, 1 ); if ( handleObj.selector ) { handlers.delegateCount--; } if ( special.remove ) { special.remove.call( elem, handleObj ); } } } // Remove generic event handler if we removed something and no more handlers exist // (avoids potential for endless recursion during removal of special event handlers) if ( origCount && !handlers.length ) { if ( !special.teardown || special.teardown.call( elem, namespaces, elemData.handle ) === false ) { jQuery.removeEvent( elem, type, elemData.handle ); } delete events[ type ]; } } // Remove data and the expando if it's no longer used if ( jQuery.isEmptyObject( events ) ) { dataPriv.remove( elem, "handle events" ); } }, dispatch: function( nativeEvent ) { var i, j, ret, matched, handleObj, handlerQueue, args = new Array( arguments.length ), // Make a writable jQuery.Event from the native event object event = jQuery.event.fix( nativeEvent ), handlers = ( dataPriv.get( this, "events" ) || Object.create( null ) )[ event.type ] || [], special = jQuery.event.special[ event.type ] || {}; // Use the fix-ed jQuery.Event rather than the (read-only) native event args[ 0 ] = event; for ( i = 1; i < arguments.length; i++ ) { args[ i ] = arguments[ i ]; } event.delegateTarget = this; // Call the preDispatch hook for the mapped type, and let it bail if desired if ( special.preDispatch && special.preDispatch.call( this, event ) === false ) { return; } // Determine handlers handlerQueue = jQuery.event.handlers.call( this, event, handlers ); // Run delegates first; they may want to stop propagation beneath us i = 0; while ( ( matched = handlerQueue[ i++ ] ) && !event.isPropagationStopped() ) { event.currentTarget = matched.elem; j = 0; while ( ( handleObj = matched.handlers[ j++ ] ) && !event.isImmediatePropagationStopped() ) { // If the event is namespaced, then each handler is only invoked if it is // specially universal or its namespaces are a superset of the event's. if ( !event.rnamespace || handleObj.namespace === false || event.rnamespace.test( handleObj.namespace ) ) { event.handleObj = handleObj; event.data = handleObj.data; ret = ( ( jQuery.event.special[ handleObj.origType ] || {} ).handle || handleObj.handler ).apply( matched.elem, args ); if ( ret !== undefined ) { if ( ( event.result = ret ) === false ) { event.preventDefault(); event.stopPropagation(); } } } } } // Call the postDispatch hook for the mapped type if ( special.postDispatch ) { special.postDispatch.call( this, event ); } return event.result; }, handlers: function( event, handlers ) { var i, handleObj, sel, matchedHandlers, matchedSelectors, handlerQueue = [], delegateCount = handlers.delegateCount, cur = event.target; // Find delegate handlers if ( delegateCount && // Support: IE <=9 // Black-hole SVG <use> instance trees (trac-13180) cur.nodeType && // Support: Firefox <=42 // Suppress spec-violating clicks indicating a non-primary pointer button (trac-3861) // https://www.w3.org/TR/DOM-Level-3-Events/#event-type-click // Support: IE 11 only // ...but not arrow key "clicks" of radio inputs, which can have `button` -1 (gh-2343) !( event.type === "click" && event.button >= 1 ) ) { for ( ; cur !== this; cur = cur.parentNode || this ) { // Don't check non-elements (#13208) // Don't process clicks on disabled elements (#6911, #8165, #11382, #11764) if ( cur.nodeType === 1 && !( event.type === "click" && cur.disabled === true ) ) { matchedHandlers = []; matchedSelectors = {}; for ( i = 0; i < delegateCount; i++ ) { handleObj = handlers[ i ]; // Don't conflict with Object.prototype properties (#13203) sel = handleObj.selector + " "; if ( matchedSelectors[ sel ] === undefined ) { matchedSelectors[ sel ] = handleObj.needsContext ? jQuery( sel, this ).index( cur ) > -1 : jQuery.find( sel, this, null, [ cur ] ).length; } if ( matchedSelectors[ sel ] ) { matchedHandlers.push( handleObj ); } } if ( matchedHandlers.length ) { handlerQueue.push( { elem: cur, handlers: matchedHandlers } ); } } } } // Add the remaining (directly-bound) handlers cur = this; if ( delegateCount < handlers.length ) { handlerQueue.push( { elem: cur, handlers: handlers.slice( delegateCount ) } ); } return handlerQueue; }, addProp: function( name, hook ) { Object.defineProperty( jQuery.Event.prototype, name, { enumerable: true, configurable: true, get: isFunction( hook ) ? function() { if ( this.originalEvent ) { return hook( this.originalEvent ); } } : function() { if ( this.originalEvent ) { return this.originalEvent[ name ]; } }, set: function( value ) { Object.defineProperty( this, name, { enumerable: true, configurable: true, writable: true, value: value } ); } } ); }, fix: function( originalEvent ) { return originalEvent[ jQuery.expando ] ? originalEvent : new jQuery.Event( originalEvent ); }, special: { load: { // Prevent triggered image.load events from bubbling to window.load noBubble: true }, click: { // Utilize native event to ensure correct state for checkable inputs setup: function( data ) { // For mutual compressibility with _default, replace `this` access with a local var. // `|| data` is dead code meant only to preserve the variable through minification. var el = this || data; // Claim the first handler if ( rcheckableType.test( el.type ) && el.click && nodeName( el, "input" ) ) { // dataPriv.set( el, "click", ... ) leverageNative( el, "click", returnTrue ); } // Return false to allow normal processing in the caller return false; }, trigger: function( data ) { // For mutual compressibility with _default, replace `this` access with a local var. // `|| data` is dead code meant only to preserve the variable through minification. var el = this || data; // Force setup before triggering a click if ( rcheckableType.test( el.type ) && el.click && nodeName( el, "input" ) ) { leverageNative( el, "click" ); } // Return non-false to allow normal event-path propagation return true; }, // For cross-browser consistency, suppress native .click() on links // Also prevent it if we're currently inside a leveraged native-event stack _default: function( event ) { var target = event.target; return rcheckableType.test( target.type ) && target.click && nodeName( target, "input" ) && dataPriv.get( target, "click" ) || nodeName( target, "a" ); } }, beforeunload: { postDispatch: function( event ) { // Support: Firefox 20+ // Firefox doesn't alert if the returnValue field is not set. if ( event.result !== undefined && event.originalEvent ) { event.originalEvent.returnValue = event.result; } } } } }; // Ensure the presence of an event listener that handles manually-triggered // synthetic events by interrupting progress until reinvoked in response to // *native* events that it fires directly, ensuring that state changes have // already occurred before other listeners are invoked. function leverageNative( el, type, expectSync ) { // Missing expectSync indicates a trigger call, which must force setup through jQuery.event.add if ( !expectSync ) { if ( dataPriv.get( el, type ) === undefined ) { jQuery.event.add( el, type, returnTrue ); } return; } // Register the controller as a special universal handler for all event namespaces dataPriv.set( el, type, false ); jQuery.event.add( el, type, { namespace: false, handler: function( event ) { var notAsync, result, saved = dataPriv.get( this, type ); if ( ( event.isTrigger & 1 ) && this[ type ] ) { // Interrupt processing of the outer synthetic .trigger()ed event // Saved data should be false in such cases, but might be a leftover capture object // from an async native handler (gh-4350) if ( !saved.length ) { // Store arguments for use when handling the inner native event // There will always be at least one argument (an event object), so this array // will not be confused with a leftover capture object. saved = slice.call( arguments ); dataPriv.set( this, type, saved ); // Trigger the native event and capture its result // Support: IE <=9 - 11+ // focus() and blur() are asynchronous notAsync = expectSync( this, type ); this[ type ](); result = dataPriv.get( this, type ); if ( saved !== result || notAsync ) { dataPriv.set( this, type, false ); } else { result = {}; } if ( saved !== result ) { // Cancel the outer synthetic event event.stopImmediatePropagation(); event.preventDefault(); return result.value; } // If this is an inner synthetic event for an event with a bubbling surrogate // (focus or blur), assume that the surrogate already propagated from triggering the // native event and prevent that from happening again here. // This technically gets the ordering wrong w.r.t. to `.trigger()` (in which the // bubbling surrogate propagates *after* the non-bubbling base), but that seems // less bad than duplication. } else if ( ( jQuery.event.special[ type ] || {} ).delegateType ) { event.stopPropagation(); } // If this is a native event triggered above, everything is now in order // Fire an inner synthetic event with the original arguments } else if ( saved.length ) { // ...and capture the result dataPriv.set( this, type, { value: jQuery.event.trigger( // Support: IE <=9 - 11+ // Extend with the prototype to reset the above stopImmediatePropagation() jQuery.extend( saved[ 0 ], jQuery.Event.prototype ), saved.slice( 1 ), this ) } ); // Abort handling of the native event event.stopImmediatePropagation(); } } } ); } jQuery.removeEvent = function( elem, type, handle ) { // This "if" is needed for plain objects if ( elem.removeEventListener ) { elem.removeEventListener( type, handle ); } }; jQuery.Event = function( src, props ) { // Allow instantiation without the 'new' keyword if ( !( this instanceof jQuery.Event ) ) { return new jQuery.Event( src, props ); } // Event object if ( src && src.type ) { this.originalEvent = src; this.type = src.type; // Events bubbling up the document may have been marked as prevented // by a handler lower down the tree; reflect the correct value. this.isDefaultPrevented = src.defaultPrevented || src.defaultPrevented === undefined && // Support: Android <=2.3 only src.returnValue === false ? returnTrue : returnFalse; // Create target properties // Support: Safari <=6 - 7 only // Target should not be a text node (#504, #13143) this.target = ( src.target && src.target.nodeType === 3 ) ? src.target.parentNode : src.target; this.currentTarget = src.currentTarget; this.relatedTarget = src.relatedTarget; // Event type } else { this.type = src; } // Put explicitly provided properties onto the event object if ( props ) { jQuery.extend( this, props ); } // Create a timestamp if incoming event doesn't have one this.timeStamp = src && src.timeStamp || Date.now(); // Mark it as fixed this[ jQuery.expando ] = true; }; // jQuery.Event is based on DOM3 Events as specified by the ECMAScript Language Binding // https://www.w3.org/TR/2003/WD-DOM-Level-3-Events-20030331/ecma-script-binding.html jQuery.Event.prototype = { constructor: jQuery.Event, isDefaultPrevented: returnFalse, isPropagationStopped: returnFalse, isImmediatePropagationStopped: returnFalse, isSimulated: false, preventDefault: function() { var e = this.originalEvent; this.isDefaultPrevented = returnTrue; if ( e && !this.isSimulated ) { e.preventDefault(); } }, stopPropagation: function() { var e = this.originalEvent; this.isPropagationStopped = returnTrue; if ( e && !this.isSimulated ) { e.stopPropagation(); } }, stopImmediatePropagation: function() { var e = this.originalEvent; this.isImmediatePropagationStopped = returnTrue; if ( e && !this.isSimulated ) { e.stopImmediatePropagation(); } this.stopPropagation(); } }; // Includes all common event props including KeyEvent and MouseEvent specific props jQuery.each( { altKey: true, bubbles: true, cancelable: true, changedTouches: true, ctrlKey: true, detail: true, eventPhase: true, metaKey: true, pageX: true, pageY: true, shiftKey: true, view: true, "char": true, code: true, charCode: true, key: true, keyCode: true, button: true, buttons: true, clientX: true, clientY: true, offsetX: true, offsetY: true, pointerId: true, pointerType: true, screenX: true, screenY: true, targetTouches: true, toElement: true, touches: true, which: function( event ) { var button = event.button; // Add which for key events if ( event.which == null && rkeyEvent.test( event.type ) ) { return event.charCode != null ? event.charCode : event.keyCode; } // Add which for click: 1 === left; 2 === middle; 3 === right if ( !event.which && button !== undefined && rmouseEvent.test( event.type ) ) { if ( button & 1 ) { return 1; } if ( button & 2 ) { return 3; } if ( button & 4 ) { return 2; } return 0; } return event.which; } }, jQuery.event.addProp ); jQuery.each( { focus: "focusin", blur: "focusout" }, function( type, delegateType ) { jQuery.event.special[ type ] = { // Utilize native event if possible so blur/focus sequence is correct setup: function() { // Claim the first handler // dataPriv.set( this, "focus", ... ) // dataPriv.set( this, "blur", ... ) leverageNative( this, type, expectSync ); // Return false to allow normal processing in the caller return false; }, trigger: function() { // Force setup before trigger leverageNative( this, type ); // Return non-false to allow normal event-path propagation return true; }, delegateType: delegateType }; } ); // Create mouseenter/leave events using mouseover/out and event-time checks // so that event delegation works in jQuery. // Do the same for pointerenter/pointerleave and pointerover/pointerout // // Support: Safari 7 only // Safari sends mouseenter too often; see: // https://bugs.chromium.org/p/chromium/issues/detail?id=470258 // for the description of the bug (it existed in older Chrome versions as well). jQuery.each( { mouseenter: "mouseover", mouseleave: "mouseout", pointerenter: "pointerover", pointerleave: "pointerout" }, function( orig, fix ) { jQuery.event.special[ orig ] = { delegateType: fix, bindType: fix, handle: function( event ) { var ret, target = this, related = event.relatedTarget, handleObj = event.handleObj; // For mouseenter/leave call the handler if related is outside the target. // NB: No relatedTarget if the mouse left/entered the browser window if ( !related || ( related !== target && !jQuery.contains( target, related ) ) ) { event.type = handleObj.origType; ret = handleObj.handler.apply( this, arguments ); event.type = fix; } return ret; } }; } ); jQuery.fn.extend( { on: function( types, selector, data, fn ) { return on( this, types, selector, data, fn ); }, one: function( types, selector, data, fn ) { return on( this, types, selector, data, fn, 1 ); }, off: function( types, selector, fn ) { var handleObj, type; if ( types && types.preventDefault && types.handleObj ) { // ( event ) dispatched jQuery.Event handleObj = types.handleObj; jQuery( types.delegateTarget ).off( handleObj.namespace ? handleObj.origType + "." + handleObj.namespace : handleObj.origType, handleObj.selector, handleObj.handler ); return this; } if ( typeof types === "object" ) { // ( types-object [, selector] ) for ( type in types ) { this.off( type, selector, types[ type ] ); } return this; } if ( selector === false || typeof selector === "function" ) { // ( types [, fn] ) fn = selector; selector = undefined; } if ( fn === false ) { fn = returnFalse; } return this.each( function() { jQuery.event.remove( this, types, fn, selector ); } ); } } ); var // Support: IE <=10 - 11, Edge 12 - 13 only // In IE/Edge using regex groups here causes severe slowdowns. // See https://connect.microsoft.com/IE/feedback/details/1736512/ rnoInnerhtml = /<script|<style|<link/i, // checked="checked" or checked rchecked = /checked\s*(?:[^=]|=\s*.checked.)/i, rcleanScript = /^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g; // Prefer a tbody over its parent table for containing new rows function manipulationTarget( elem, content ) { if ( nodeName( elem, "table" ) && nodeName( content.nodeType !== 11 ? content : content.firstChild, "tr" ) ) { return jQuery( elem ).children( "tbody" )[ 0 ] || elem; } return elem; } // Replace/restore the type attribute of script elements for safe DOM manipulation function disableScript( elem ) { elem.type = ( elem.getAttribute( "type" ) !== null ) + "/" + elem.type; return elem; } function restoreScript( elem ) { if ( ( elem.type || "" ).slice( 0, 5 ) === "true/" ) { elem.type = elem.type.slice( 5 ); } else { elem.removeAttribute( "type" ); } return elem; } function cloneCopyEvent( src, dest ) { var i, l, type, pdataOld, udataOld, udataCur, events; if ( dest.nodeType !== 1 ) { return; } // 1. Copy private data: events, handlers, etc. if ( dataPriv.hasData( src ) ) { pdataOld = dataPriv.get( src ); events = pdataOld.events; if ( events ) { dataPriv.remove( dest, "handle events" ); for ( type in events ) { for ( i = 0, l = events[ type ].length; i < l; i++ ) { jQuery.event.add( dest, type, events[ type ][ i ] ); } } } } // 2. Copy user data if ( dataUser.hasData( src ) ) { udataOld = dataUser.access( src ); udataCur = jQuery.extend( {}, udataOld ); dataUser.set( dest, udataCur ); } } // Fix IE bugs, see support tests function fixInput( src, dest ) { var nodeName = dest.nodeName.toLowerCase(); // Fails to persist the checked state of a cloned checkbox or radio button. if ( nodeName === "input" && rcheckableType.test( src.type ) ) { dest.checked = src.checked; // Fails to return the selected option to the default selected state when cloning options } else if ( nodeName === "input" || nodeName === "textarea" ) { dest.defaultValue = src.defaultValue; } } function domManip( collection, args, callback, ignored ) { // Flatten any nested arrays args = flat( args ); var fragment, first, scripts, hasScripts, node, doc, i = 0, l = collection.length, iNoClone = l - 1, value = args[ 0 ], valueIsFunction = isFunction( value ); // We can't cloneNode fragments that contain checked, in WebKit if ( valueIsFunction || ( l > 1 && typeof value === "string" && !support.checkClone && rchecked.test( value ) ) ) { return collection.each( function( index ) { var self = collection.eq( index ); if ( valueIsFunction ) { args[ 0 ] = value.call( this, index, self.html() ); } domManip( self, args, callback, ignored ); } ); } if ( l ) { fragment = buildFragment( args, collection[ 0 ].ownerDocument, false, collection, ignored ); first = fragment.firstChild; if ( fragment.childNodes.length === 1 ) { fragment = first; } // Require either new content or an interest in ignored elements to invoke the callback if ( first || ignored ) { scripts = jQuery.map( getAll( fragment, "script" ), disableScript ); hasScripts = scripts.length; // Use the original fragment for the last item // instead of the first because it can end up // being emptied incorrectly in certain situations (#8070). for ( ; i < l; i++ ) { node = fragment; if ( i !== iNoClone ) { node = jQuery.clone( node, true, true ); // Keep references to cloned scripts for later restoration if ( hasScripts ) { // Support: Android <=4.0 only, PhantomJS 1 only // push.apply(_, arraylike) throws on ancient WebKit jQuery.merge( scripts, getAll( node, "script" ) ); } } callback.call( collection[ i ], node, i ); } if ( hasScripts ) { doc = scripts[ scripts.length - 1 ].ownerDocument; // Reenable scripts jQuery.map( scripts, restoreScript ); // Evaluate executable scripts on first document insertion for ( i = 0; i < hasScripts; i++ ) { node = scripts[ i ]; if ( rscriptType.test( node.type || "" ) && !dataPriv.access( node, "globalEval" ) && jQuery.contains( doc, node ) ) { if ( node.src && ( node.type || "" ).toLowerCase() !== "module" ) { // Optional AJAX dependency, but won't run scripts if not present if ( jQuery._evalUrl && !node.noModule ) { jQuery._evalUrl( node.src, { nonce: node.nonce || node.getAttribute( "nonce" ) }, doc ); } } else { DOMEval( node.textContent.replace( rcleanScript, "" ), node, doc ); } } } } } } return collection; } function remove( elem, selector, keepData ) { var node, nodes = selector ? jQuery.filter( selector, elem ) : elem, i = 0; for ( ; ( node = nodes[ i ] ) != null; i++ ) { if ( !keepData && node.nodeType === 1 ) { jQuery.cleanData( getAll( node ) ); } if ( node.parentNode ) { if ( keepData && isAttached( node ) ) { setGlobalEval( getAll( node, "script" ) ); } node.parentNode.removeChild( node ); } } return elem; } jQuery.extend( { htmlPrefilter: function( html ) { return html; }, clone: function( elem, dataAndEvents, deepDataAndEvents ) { var i, l, srcElements, destElements, clone = elem.cloneNode( true ), inPage = isAttached( elem ); // Fix IE cloning issues if ( !support.noCloneChecked && ( elem.nodeType === 1 || elem.nodeType === 11 ) && !jQuery.isXMLDoc( elem ) ) { // We eschew Sizzle here for performance reasons: https://jsperf.com/getall-vs-sizzle/2 destElements = getAll( clone ); srcElements = getAll( elem ); for ( i = 0, l = srcElements.length; i < l; i++ ) { fixInput( srcElements[ i ], destElements[ i ] ); } } // Copy the events from the original to the clone if ( dataAndEvents ) { if ( deepDataAndEvents ) { srcElements = srcElements || getAll( elem ); destElements = destElements || getAll( clone ); for ( i = 0, l = srcElements.length; i < l; i++ ) { cloneCopyEvent( srcElements[ i ], destElements[ i ] ); } } else { cloneCopyEvent( elem, clone ); } } // Preserve script evaluation history destElements = getAll( clone, "script" ); if ( destElements.length > 0 ) { setGlobalEval( destElements, !inPage && getAll( elem, "script" ) ); } // Return the cloned set return clone; }, cleanData: function( elems ) { var data, elem, type, special = jQuery.event.special, i = 0; for ( ; ( elem = elems[ i ] ) !== undefined; i++ ) { if ( acceptData( elem ) ) { if ( ( data = elem[ dataPriv.expando ] ) ) { if ( data.events ) { for ( type in data.events ) { if ( special[ type ] ) { jQuery.event.remove( elem, type ); // This is a shortcut to avoid jQuery.event.remove's overhead } else { jQuery.removeEvent( elem, type, data.handle ); } } } // Support: Chrome <=35 - 45+ // Assign undefined instead of using delete, see Data#remove elem[ dataPriv.expando ] = undefined; } if ( elem[ dataUser.expando ] ) { // Support: Chrome <=35 - 45+ // Assign undefined instead of using delete, see Data#remove elem[ dataUser.expando ] = undefined; } } } } } ); jQuery.fn.extend( { detach: function( selector ) { return remove( this, selector, true ); }, remove: function( selector ) { return remove( this, selector ); }, text: function( value ) { return access( this, function( value ) { return value === undefined ? jQuery.text( this ) : this.empty().each( function() { if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) { this.textContent = value; } } ); }, null, value, arguments.length ); }, append: function() { return domManip( this, arguments, function( elem ) { if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) { var target = manipulationTarget( this, elem ); target.appendChild( elem ); } } ); }, prepend: function() { return domManip( this, arguments, function( elem ) { if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) { var target = manipulationTarget( this, elem ); target.insertBefore( elem, target.firstChild ); } } ); }, before: function() { return domManip( this, arguments, function( elem ) { if ( this.parentNode ) { this.parentNode.insertBefore( elem, this ); } } ); }, after: function() { return domManip( this, arguments, function( elem ) { if ( this.parentNode ) { this.parentNode.insertBefore( elem, this.nextSibling ); } } ); }, empty: function() { var elem, i = 0; for ( ; ( elem = this[ i ] ) != null; i++ ) { if ( elem.nodeType === 1 ) { // Prevent memory leaks jQuery.cleanData( getAll( elem, false ) ); // Remove any remaining nodes elem.textContent = ""; } } return this; }, clone: function( dataAndEvents, deepDataAndEvents ) { dataAndEvents = dataAndEvents == null ? false : dataAndEvents; deepDataAndEvents = deepDataAndEvents == null ? dataAndEvents : deepDataAndEvents; return this.map( function() { return jQuery.clone( this, dataAndEvents, deepDataAndEvents ); } ); }, html: function( value ) { return access( this, function( value ) { var elem = this[ 0 ] || {}, i = 0, l = this.length; if ( value === undefined && elem.nodeType === 1 ) { return elem.innerHTML; } // See if we can take a shortcut and just use innerHTML if ( typeof value === "string" && !rnoInnerhtml.test( value ) && !wrapMap[ ( rtagName.exec( value ) || [ "", "" ] )[ 1 ].toLowerCase() ] ) { value = jQuery.htmlPrefilter( value ); try { for ( ; i < l; i++ ) { elem = this[ i ] || {}; // Remove element nodes and prevent memory leaks if ( elem.nodeType === 1 ) { jQuery.cleanData( getAll( elem, false ) ); elem.innerHTML = value; } } elem = 0; // If using innerHTML throws an exception, use the fallback method } catch ( e ) {} } if ( elem ) { this.empty().append( value ); } }, null, value, arguments.length ); }, replaceWith: function() { var ignored = []; // Make the changes, replacing each non-ignored context element with the new content return domManip( this, arguments, function( elem ) { var parent = this.parentNode; if ( jQuery.inArray( this, ignored ) < 0 ) { jQuery.cleanData( getAll( this ) ); if ( parent ) { parent.replaceChild( elem, this ); } } // Force callback invocation }, ignored ); } } ); jQuery.each( { appendTo: "append", prependTo: "prepend", insertBefore: "before", insertAfter: "after", replaceAll: "replaceWith" }, function( name, original ) { jQuery.fn[ name ] = function( selector ) { var elems, ret = [], insert = jQuery( selector ), last = insert.length - 1, i = 0; for ( ; i <= last; i++ ) { elems = i === last ? this : this.clone( true ); jQuery( insert[ i ] )[ original ]( elems ); // Support: Android <=4.0 only, PhantomJS 1 only // .get() because push.apply(_, arraylike) throws on ancient WebKit push.apply( ret, elems.get() ); } return this.pushStack( ret ); }; } ); var rnumnonpx = new RegExp( "^(" + pnum + ")(?!px)[a-z%]+$", "i" ); var getStyles = function( elem ) { // Support: IE <=11 only, Firefox <=30 (#15098, #14150) // IE throws on elements created in popups // FF meanwhile throws on frame elements through "defaultView.getComputedStyle" var view = elem.ownerDocument.defaultView; if ( !view || !view.opener ) { view = window; } return view.getComputedStyle( elem ); }; var swap = function( elem, options, callback ) { var ret, name, old = {}; // Remember the old values, and insert the new ones for ( name in options ) { old[ name ] = elem.style[ name ]; elem.style[ name ] = options[ name ]; } ret = callback.call( elem ); // Revert the old values for ( name in options ) { elem.style[ name ] = old[ name ]; } return ret; }; var rboxStyle = new RegExp( cssExpand.join( "|" ), "i" ); ( function() { // Executing both pixelPosition & boxSizingReliable tests require only one layout // so they're executed at the same time to save the second computation. function computeStyleTests() { // This is a singleton, we need to execute it only once if ( !div ) { return; } container.style.cssText = "position:absolute;left:-11111px;width:60px;" + "margin-top:1px;padding:0;border:0"; div.style.cssText = "position:relative;display:block;box-sizing:border-box;overflow:scroll;" + "margin:auto;border:1px;padding:1px;" + "width:60%;top:1%"; documentElement.appendChild( container ).appendChild( div ); var divStyle = window.getComputedStyle( div ); pixelPositionVal = divStyle.top !== "1%"; // Support: Android 4.0 - 4.3 only, Firefox <=3 - 44 reliableMarginLeftVal = roundPixelMeasures( divStyle.marginLeft ) === 12; // Support: Android 4.0 - 4.3 only, Safari <=9.1 - 10.1, iOS <=7.0 - 9.3 // Some styles come back with percentage values, even though they shouldn't div.style.right = "60%"; pixelBoxStylesVal = roundPixelMeasures( divStyle.right ) === 36; // Support: IE 9 - 11 only // Detect misreporting of content dimensions for box-sizing:border-box elements boxSizingReliableVal = roundPixelMeasures( divStyle.width ) === 36; // Support: IE 9 only // Detect overflow:scroll screwiness (gh-3699) // Support: Chrome <=64 // Don't get tricked when zoom affects offsetWidth (gh-4029) div.style.position = "absolute"; scrollboxSizeVal = roundPixelMeasures( div.offsetWidth / 3 ) === 12; documentElement.removeChild( container ); // Nullify the div so it wouldn't be stored in the memory and // it will also be a sign that checks already performed div = null; } function roundPixelMeasures( measure ) { return Math.round( parseFloat( measure ) ); } var pixelPositionVal, boxSizingReliableVal, scrollboxSizeVal, pixelBoxStylesVal, reliableTrDimensionsVal, reliableMarginLeftVal, container = document.createElement( "div" ), div = document.createElement( "div" ); // Finish early in limited (non-browser) environments if ( !div.style ) { return; } // Support: IE <=9 - 11 only // Style of cloned element affects source element cloned (#8908) div.style.backgroundClip = "content-box"; div.cloneNode( true ).style.backgroundClip = ""; support.clearCloneStyle = div.style.backgroundClip === "content-box"; jQuery.extend( support, { boxSizingReliable: function() { computeStyleTests(); return boxSizingReliableVal; }, pixelBoxStyles: function() { computeStyleTests(); return pixelBoxStylesVal; }, pixelPosition: function() { computeStyleTests(); return pixelPositionVal; }, reliableMarginLeft: function() { computeStyleTests(); return reliableMarginLeftVal; }, scrollboxSize: function() { computeStyleTests(); return scrollboxSizeVal; }, // Support: IE 9 - 11+, Edge 15 - 18+ // IE/Edge misreport `getComputedStyle` of table rows with width/height // set in CSS while `offset*` properties report correct values. // Behavior in IE 9 is more subtle than in newer versions & it passes // some versions of this test; make sure not to make it pass there! reliableTrDimensions: function() { var table, tr, trChild, trStyle; if ( reliableTrDimensionsVal == null ) { table = document.createElement( "table" ); tr = document.createElement( "tr" ); trChild = document.createElement( "div" ); table.style.cssText = "position:absolute;left:-11111px"; tr.style.height = "1px"; trChild.style.height = "9px"; documentElement .appendChild( table ) .appendChild( tr ) .appendChild( trChild ); trStyle = window.getComputedStyle( tr ); reliableTrDimensionsVal = parseInt( trStyle.height ) > 3; documentElement.removeChild( table ); } return reliableTrDimensionsVal; } } ); } )(); function curCSS( elem, name, computed ) { var width, minWidth, maxWidth, ret, // Support: Firefox 51+ // Retrieving style before computed somehow // fixes an issue with getting wrong values // on detached elements style = elem.style; computed = computed || getStyles( elem ); // getPropertyValue is needed for: // .css('filter') (IE 9 only, #12537) // .css('--customProperty) (#3144) if ( computed ) { ret = computed.getPropertyValue( name ) || computed[ name ]; if ( ret === "" && !isAttached( elem ) ) { ret = jQuery.style( elem, name ); } // A tribute to the "awesome hack by Dean Edwards" // Android Browser returns percentage for some values, // but width seems to be reliably pixels. // This is against the CSSOM draft spec: // https://drafts.csswg.org/cssom/#resolved-values if ( !support.pixelBoxStyles() && rnumnonpx.test( ret ) && rboxStyle.test( name ) ) { // Remember the original values width = style.width; minWidth = style.minWidth; maxWidth = style.maxWidth; // Put in the new values to get a computed value out style.minWidth = style.maxWidth = style.width = ret; ret = computed.width; // Revert the changed values style.width = width; style.minWidth = minWidth; style.maxWidth = maxWidth; } } return ret !== undefined ? // Support: IE <=9 - 11 only // IE returns zIndex value as an integer. ret + "" : ret; } function addGetHookIf( conditionFn, hookFn ) { // Define the hook, we'll check on the first run if it's really needed. return { get: function() { if ( conditionFn() ) { // Hook not needed (or it's not possible to use it due // to missing dependency), remove it. delete this.get; return; } // Hook needed; redefine it so that the support test is not executed again. return ( this.get = hookFn ).apply( this, arguments ); } }; } var cssPrefixes = [ "Webkit", "Moz", "ms" ], emptyStyle = document.createElement( "div" ).style, vendorProps = {}; // Return a vendor-prefixed property or undefined function vendorPropName( name ) { // Check for vendor prefixed names var capName = name[ 0 ].toUpperCase() + name.slice( 1 ), i = cssPrefixes.length; while ( i-- ) { name = cssPrefixes[ i ] + capName; if ( name in emptyStyle ) { return name; } } } // Return a potentially-mapped jQuery.cssProps or vendor prefixed property function finalPropName( name ) { var final = jQuery.cssProps[ name ] || vendorProps[ name ]; if ( final ) { return final; } if ( name in emptyStyle ) { return name; } return vendorProps[ name ] = vendorPropName( name ) || name; } var // Swappable if display is none or starts with table // except "table", "table-cell", or "table-caption" // See here for display values: https://developer.mozilla.org/en-US/docs/CSS/display rdisplayswap = /^(none|table(?!-c[ea]).+)/, rcustomProp = /^--/, cssShow = { position: "absolute", visibility: "hidden", display: "block" }, cssNormalTransform = { letterSpacing: "0", fontWeight: "400" }; function setPositiveNumber( _elem, value, subtract ) { // Any relative (+/-) values have already been // normalized at this point var matches = rcssNum.exec( value ); return matches ? // Guard against undefined "subtract", e.g., when used as in cssHooks Math.max( 0, matches[ 2 ] - ( subtract || 0 ) ) + ( matches[ 3 ] || "px" ) : value; } function boxModelAdjustment( elem, dimension, box, isBorderBox, styles, computedVal ) { var i = dimension === "width" ? 1 : 0, extra = 0, delta = 0; // Adjustment may not be necessary if ( box === ( isBorderBox ? "border" : "content" ) ) { return 0; } for ( ; i < 4; i += 2 ) { // Both box models exclude margin if ( box === "margin" ) { delta += jQuery.css( elem, box + cssExpand[ i ], true, styles ); } // If we get here with a content-box, we're seeking "padding" or "border" or "margin" if ( !isBorderBox ) { // Add padding delta += jQuery.css( elem, "padding" + cssExpand[ i ], true, styles ); // For "border" or "margin", add border if ( box !== "padding" ) { delta += jQuery.css( elem, "border" + cssExpand[ i ] + "Width", true, styles ); // But still keep track of it otherwise } else { extra += jQuery.css( elem, "border" + cssExpand[ i ] + "Width", true, styles ); } // If we get here with a border-box (content + padding + border), we're seeking "content" or // "padding" or "margin" } else { // For "content", subtract padding if ( box === "content" ) { delta -= jQuery.css( elem, "padding" + cssExpand[ i ], true, styles ); } // For "content" or "padding", subtract border if ( box !== "margin" ) { delta -= jQuery.css( elem, "border" + cssExpand[ i ] + "Width", true, styles ); } } } // Account for positive content-box scroll gutter when requested by providing computedVal if ( !isBorderBox && computedVal >= 0 ) { // offsetWidth/offsetHeight is a rounded sum of content, padding, scroll gutter, and border // Assuming integer scroll gutter, subtract the rest and round down delta += Math.max( 0, Math.ceil( elem[ "offset" + dimension[ 0 ].toUpperCase() + dimension.slice( 1 ) ] - computedVal - delta - extra - 0.5 // If offsetWidth/offsetHeight is unknown, then we can't determine content-box scroll gutter // Use an explicit zero to avoid NaN (gh-3964) ) ) || 0; } return delta; } function getWidthOrHeight( elem, dimension, extra ) { // Start with computed style var styles = getStyles( elem ), // To avoid forcing a reflow, only fetch boxSizing if we need it (gh-4322). // Fake content-box until we know it's needed to know the true value. boxSizingNeeded = !support.boxSizingReliable() || extra, isBorderBox = boxSizingNeeded && jQuery.css( elem, "boxSizing", false, styles ) === "border-box", valueIsBorderBox = isBorderBox, val = curCSS( elem, dimension, styles ), offsetProp = "offset" + dimension[ 0 ].toUpperCase() + dimension.slice( 1 ); // Support: Firefox <=54 // Return a confounding non-pixel value or feign ignorance, as appropriate. if ( rnumnonpx.test( val ) ) { if ( !extra ) { return val; } val = "auto"; } // Support: IE 9 - 11 only // Use offsetWidth/offsetHeight for when box sizing is unreliable. // In those cases, the computed value can be trusted to be border-box. if ( ( !support.boxSizingReliable() && isBorderBox || // Support: IE 10 - 11+, Edge 15 - 18+ // IE/Edge misreport `getComputedStyle` of table rows with width/height // set in CSS while `offset*` properties report correct values. // Interestingly, in some cases IE 9 doesn't suffer from this issue. !support.reliableTrDimensions() && nodeName( elem, "tr" ) || // Fall back to offsetWidth/offsetHeight when value is "auto" // This happens for inline elements with no explicit setting (gh-3571) val === "auto" || // Support: Android <=4.1 - 4.3 only // Also use offsetWidth/offsetHeight for misreported inline dimensions (gh-3602) !parseFloat( val ) && jQuery.css( elem, "display", false, styles ) === "inline" ) && // Make sure the element is visible & connected elem.getClientRects().length ) { isBorderBox = jQuery.css( elem, "boxSizing", false, styles ) === "border-box"; // Where available, offsetWidth/offsetHeight approximate border box dimensions. // Where not available (e.g., SVG), assume unreliable box-sizing and interpret the // retrieved value as a content box dimension. valueIsBorderBox = offsetProp in elem; if ( valueIsBorderBox ) { val = elem[ offsetProp ]; } } // Normalize "" and auto val = parseFloat( val ) || 0; // Adjust for the element's box model return ( val + boxModelAdjustment( elem, dimension, extra || ( isBorderBox ? "border" : "content" ), valueIsBorderBox, styles, // Provide the current computed size to request scroll gutter calculation (gh-3589) val ) ) + "px"; } jQuery.extend( { // Add in style property hooks for overriding the default // behavior of getting and setting a style property cssHooks: { opacity: { get: function( elem, computed ) { if ( computed ) { // We should always get a number back from opacity var ret = curCSS( elem, "opacity" ); return ret === "" ? "1" : ret; } } } }, // Don't automatically add "px" to these possibly-unitless properties cssNumber: { "animationIterationCount": true, "columnCount": true, "fillOpacity": true, "flexGrow": true, "flexShrink": true, "fontWeight": true, "gridArea": true, "gridColumn": true, "gridColumnEnd": true, "gridColumnStart": true, "gridRow": true, "gridRowEnd": true, "gridRowStart": true, "lineHeight": true, "opacity": true, "order": true, "orphans": true, "widows": true, "zIndex": true, "zoom": true }, // Add in properties whose names you wish to fix before // setting or getting the value cssProps: {}, // Get and set the style property on a DOM Node style: function( elem, name, value, extra ) { // Don't set styles on text and comment nodes if ( !elem || elem.nodeType === 3 || elem.nodeType === 8 || !elem.style ) { return; } // Make sure that we're working with the right name var ret, type, hooks, origName = camelCase( name ), isCustomProp = rcustomProp.test( name ), style = elem.style; // Make sure that we're working with the right name. We don't // want to query the value if it is a CSS custom property // since they are user-defined. if ( !isCustomProp ) { name = finalPropName( origName ); } // Gets hook for the prefixed version, then unprefixed version hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ]; // Check if we're setting a value if ( value !== undefined ) { type = typeof value; // Convert "+=" or "-=" to relative numbers (#7345) if ( type === "string" && ( ret = rcssNum.exec( value ) ) && ret[ 1 ] ) { value = adjustCSS( elem, name, ret ); // Fixes bug #9237 type = "number"; } // Make sure that null and NaN values aren't set (#7116) if ( value == null || value !== value ) { return; } // If a number was passed in, add the unit (except for certain CSS properties) // The isCustomProp check can be removed in jQuery 4.0 when we only auto-append // "px" to a few hardcoded values. if ( type === "number" && !isCustomProp ) { value += ret && ret[ 3 ] || ( jQuery.cssNumber[ origName ] ? "" : "px" ); } // background-* props affect original clone's values if ( !support.clearCloneStyle && value === "" && name.indexOf( "background" ) === 0 ) { style[ name ] = "inherit"; } // If a hook was provided, use that value, otherwise just set the specified value if ( !hooks || !( "set" in hooks ) || ( value = hooks.set( elem, value, extra ) ) !== undefined ) { if ( isCustomProp ) { style.setProperty( name, value ); } else { style[ name ] = value; } } } else { // If a hook was provided get the non-computed value from there if ( hooks && "get" in hooks && ( ret = hooks.get( elem, false, extra ) ) !== undefined ) { return ret; } // Otherwise just get the value from the style object return style[ name ]; } }, css: function( elem, name, extra, styles ) { var val, num, hooks, origName = camelCase( name ), isCustomProp = rcustomProp.test( name ); // Make sure that we're working with the right name. We don't // want to modify the value if it is a CSS custom property // since they are user-defined. if ( !isCustomProp ) { name = finalPropName( origName ); } // Try prefixed name followed by the unprefixed name hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ]; // If a hook was provided get the computed value from there if ( hooks && "get" in hooks ) { val = hooks.get( elem, true, extra ); } // Otherwise, if a way to get the computed value exists, use that if ( val === undefined ) { val = curCSS( elem, name, styles ); } // Convert "normal" to computed value if ( val === "normal" && name in cssNormalTransform ) { val = cssNormalTransform[ name ]; } // Make numeric if forced or a qualifier was provided and val looks numeric if ( extra === "" || extra ) { num = parseFloat( val ); return extra === true || isFinite( num ) ? num || 0 : val; } return val; } } ); jQuery.each( [ "height", "width" ], function( _i, dimension ) { jQuery.cssHooks[ dimension ] = { get: function( elem, computed, extra ) { if ( computed ) { // Certain elements can have dimension info if we invisibly show them // but it must have a current display style that would benefit return rdisplayswap.test( jQuery.css( elem, "display" ) ) && // Support: Safari 8+ // Table columns in Safari have non-zero offsetWidth & zero // getBoundingClientRect().width unless display is changed. // Support: IE <=11 only // Running getBoundingClientRect on a disconnected node // in IE throws an error. ( !elem.getClientRects().length || !elem.getBoundingClientRect().width ) ? swap( elem, cssShow, function() { return getWidthOrHeight( elem, dimension, extra ); } ) : getWidthOrHeight( elem, dimension, extra ); } }, set: function( elem, value, extra ) { var matches, styles = getStyles( elem ), // Only read styles.position if the test has a chance to fail // to avoid forcing a reflow. scrollboxSizeBuggy = !support.scrollboxSize() && styles.position === "absolute", // To avoid forcing a reflow, only fetch boxSizing if we need it (gh-3991) boxSizingNeeded = scrollboxSizeBuggy || extra, isBorderBox = boxSizingNeeded && jQuery.css( elem, "boxSizing", false, styles ) === "border-box", subtract = extra ? boxModelAdjustment( elem, dimension, extra, isBorderBox, styles ) : 0; // Account for unreliable border-box dimensions by comparing offset* to computed and // faking a content-box to get border and padding (gh-3699) if ( isBorderBox && scrollboxSizeBuggy ) { subtract -= Math.ceil( elem[ "offset" + dimension[ 0 ].toUpperCase() + dimension.slice( 1 ) ] - parseFloat( styles[ dimension ] ) - boxModelAdjustment( elem, dimension, "border", false, styles ) - 0.5 ); } // Convert to pixels if value adjustment is needed if ( subtract && ( matches = rcssNum.exec( value ) ) && ( matches[ 3 ] || "px" ) !== "px" ) { elem.style[ dimension ] = value; value = jQuery.css( elem, dimension ); } return setPositiveNumber( elem, value, subtract ); } }; } ); jQuery.cssHooks.marginLeft = addGetHookIf( support.reliableMarginLeft, function( elem, computed ) { if ( computed ) { return ( parseFloat( curCSS( elem, "marginLeft" ) ) || elem.getBoundingClientRect().left - swap( elem, { marginLeft: 0 }, function() { return elem.getBoundingClientRect().left; } ) ) + "px"; } } ); // These hooks are used by animate to expand properties jQuery.each( { margin: "", padding: "", border: "Width" }, function( prefix, suffix ) { jQuery.cssHooks[ prefix + suffix ] = { expand: function( value ) { var i = 0, expanded = {}, // Assumes a single number if not a string parts = typeof value === "string" ? value.split( " " ) : [ value ]; for ( ; i < 4; i++ ) { expanded[ prefix + cssExpand[ i ] + suffix ] = parts[ i ] || parts[ i - 2 ] || parts[ 0 ]; } return expanded; } }; if ( prefix !== "margin" ) { jQuery.cssHooks[ prefix + suffix ].set = setPositiveNumber; } } ); jQuery.fn.extend( { css: function( name, value ) { return access( this, function( elem, name, value ) { var styles, len, map = {}, i = 0; if ( Array.isArray( name ) ) { styles = getStyles( elem ); len = name.length; for ( ; i < len; i++ ) { map[ name[ i ] ] = jQuery.css( elem, name[ i ], false, styles ); } return map; } return value !== undefined ? jQuery.style( elem, name, value ) : jQuery.css( elem, name ); }, name, value, arguments.length > 1 ); } } ); // Based off of the plugin by Clint Helfers, with permission. // https://web.archive.org/web/20100324014747/http://blindsignals.com/index.php/2009/07/jquery-delay/ jQuery.fn.delay = function( time, type ) { time = jQuery.fx ? jQuery.fx.speeds[ time ] || time : time; type = type || "fx"; return this.queue( type, function( next, hooks ) { var timeout = window.setTimeout( next, time ); hooks.stop = function() { window.clearTimeout( timeout ); }; } ); }; ( function() { var input = document.createElement( "input" ), select = document.createElement( "select" ), opt = select.appendChild( document.createElement( "option" ) ); input.type = "checkbox"; // Support: Android <=4.3 only // Default value for a checkbox should be "on" support.checkOn = input.value !== ""; // Support: IE <=11 only // Must access selectedIndex to make default options select support.optSelected = opt.selected; // Support: IE <=11 only // An input loses its value after becoming a radio input = document.createElement( "input" ); input.value = "t"; input.type = "radio"; support.radioValue = input.value === "t"; } )(); var boolHook, attrHandle = jQuery.expr.attrHandle; jQuery.fn.extend( { attr: function( name, value ) { return access( this, jQuery.attr, name, value, arguments.length > 1 ); }, removeAttr: function( name ) { return this.each( function() { jQuery.removeAttr( this, name ); } ); } } ); jQuery.extend( { attr: function( elem, name, value ) { var ret, hooks, nType = elem.nodeType; // Don't get/set attributes on text, comment and attribute nodes if ( nType === 3 || nType === 8 || nType === 2 ) { return; } // Fallback to prop when attributes are not supported if ( typeof elem.getAttribute === "undefined" ) { return jQuery.prop( elem, name, value ); } // Attribute hooks are determined by the lowercase version // Grab necessary hook if one is defined if ( nType !== 1 || !jQuery.isXMLDoc( elem ) ) { hooks = jQuery.attrHooks[ name.toLowerCase() ] || ( jQuery.expr.match.bool.test( name ) ? boolHook : undefined ); } if ( value !== undefined ) { if ( value === null ) { jQuery.removeAttr( elem, name ); return; } if ( hooks && "set" in hooks && ( ret = hooks.set( elem, value, name ) ) !== undefined ) { return ret; } elem.setAttribute( name, value + "" ); return value; } if ( hooks && "get" in hooks && ( ret = hooks.get( elem, name ) ) !== null ) { return ret; } ret = jQuery.find.attr( elem, name ); // Non-existent attributes return null, we normalize to undefined return ret == null ? undefined : ret; }, attrHooks: { type: { set: function( elem, value ) { if ( !support.radioValue && value === "radio" && nodeName( elem, "input" ) ) { var val = elem.value; elem.setAttribute( "type", value ); if ( val ) { elem.value = val; } return value; } } } }, removeAttr: function( elem, value ) { var name, i = 0, // Attribute names can contain non-HTML whitespace characters // https://html.spec.whatwg.org/multipage/syntax.html#attributes-2 attrNames = value && value.match( rnothtmlwhite ); if ( attrNames && elem.nodeType === 1 ) { while ( ( name = attrNames[ i++ ] ) ) { elem.removeAttribute( name ); } } } } ); // Hooks for boolean attributes boolHook = { set: function( elem, value, name ) { if ( value === false ) { // Remove boolean attributes when set to false jQuery.removeAttr( elem, name ); } else { elem.setAttribute( name, name ); } return name; } }; jQuery.each( jQuery.expr.match.bool.source.match( /\w+/g ), function( _i, name ) { var getter = attrHandle[ name ] || jQuery.find.attr; attrHandle[ name ] = function( elem, name, isXML ) { var ret, handle, lowercaseName = name.toLowerCase(); if ( !isXML ) { // Avoid an infinite loop by temporarily removing this function from the getter handle = attrHandle[ lowercaseName ]; attrHandle[ lowercaseName ] = ret; ret = getter( elem, name, isXML ) != null ? lowercaseName : null; attrHandle[ lowercaseName ] = handle; } return ret; }; } ); var rfocusable = /^(?:input|select|textarea|button)$/i, rclickable = /^(?:a|area)$/i; jQuery.fn.extend( { prop: function( name, value ) { return access( this, jQuery.prop, name, value, arguments.length > 1 ); }, removeProp: function( name ) { return this.each( function() { delete this[ jQuery.propFix[ name ] || name ]; } ); } } ); jQuery.extend( { prop: function( elem, name, value ) { var ret, hooks, nType = elem.nodeType; // Don't get/set properties on text, comment and attribute nodes if ( nType === 3 || nType === 8 || nType === 2 ) { return; } if ( nType !== 1 || !jQuery.isXMLDoc( elem ) ) { // Fix name and attach hooks name = jQuery.propFix[ name ] || name; hooks = jQuery.propHooks[ name ]; } if ( value !== undefined ) { if ( hooks && "set" in hooks && ( ret = hooks.set( elem, value, name ) ) !== undefined ) { return ret; } return ( elem[ name ] = value ); } if ( hooks && "get" in hooks && ( ret = hooks.get( elem, name ) ) !== null ) { return ret; } return elem[ name ]; }, propHooks: { tabIndex: { get: function( elem ) { // Support: IE <=9 - 11 only // elem.tabIndex doesn't always return the // correct value when it hasn't been explicitly set // https://web.archive.org/web/20141116233347/http://fluidproject.org/blog/2008/01/09/getting-setting-and-removing-tabindex-values-with-javascript/ // Use proper attribute retrieval(#12072) var tabindex = jQuery.find.attr( elem, "tabindex" ); if ( tabindex ) { return parseInt( tabindex, 10 ); } if ( rfocusable.test( elem.nodeName ) || rclickable.test( elem.nodeName ) && elem.href ) { return 0; } return -1; } } }, propFix: { "for": "htmlFor", "class": "className" } } ); // Support: IE <=11 only // Accessing the selectedIndex property // forces the browser to respect setting selected // on the option // The getter ensures a default option is selected // when in an optgroup // eslint rule "no-unused-expressions" is disabled for this code // since it considers such accessions noop if ( !support.optSelected ) { jQuery.propHooks.selected = { get: function( elem ) { /* eslint no-unused-expressions: "off" */ var parent = elem.parentNode; if ( parent && parent.parentNode ) { parent.parentNode.selectedIndex; } return null; }, set: function( elem ) { /* eslint no-unused-expressions: "off" */ var parent = elem.parentNode; if ( parent ) { parent.selectedIndex; if ( parent.parentNode ) { parent.parentNode.selectedIndex; } } } }; } jQuery.each( [ "tabIndex", "readOnly", "maxLength", "cellSpacing", "cellPadding", "rowSpan", "colSpan", "useMap", "frameBorder", "contentEditable" ], function() { jQuery.propFix[ this.toLowerCase() ] = this; } ); // Strip and collapse whitespace according to HTML spec // https://infra.spec.whatwg.org/#strip-and-collapse-ascii-whitespace function stripAndCollapse( value ) { var tokens = value.match( rnothtmlwhite ) || []; return tokens.join( " " ); } function getClass( elem ) { return elem.getAttribute && elem.getAttribute( "class" ) || ""; } function classesToArray( value ) { if ( Array.isArray( value ) ) { return value; } if ( typeof value === "string" ) { return value.match( rnothtmlwhite ) || []; } return []; } jQuery.fn.extend( { addClass: function( value ) { var classes, elem, cur, curValue, clazz, j, finalValue, i = 0; if ( isFunction( value ) ) { return this.each( function( j ) { jQuery( this ).addClass( value.call( this, j, getClass( this ) ) ); } ); } classes = classesToArray( value ); if ( classes.length ) { while ( ( elem = this[ i++ ] ) ) { curValue = getClass( elem ); cur = elem.nodeType === 1 && ( " " + stripAndCollapse( curValue ) + " " ); if ( cur ) { j = 0; while ( ( clazz = classes[ j++ ] ) ) { if ( cur.indexOf( " " + clazz + " " ) < 0 ) { cur += clazz + " "; } } // Only assign if different to avoid unneeded rendering. finalValue = stripAndCollapse( cur ); if ( curValue !== finalValue ) { elem.setAttribute( "class", finalValue ); } } } } return this; }, removeClass: function( value ) { var classes, elem, cur, curValue, clazz, j, finalValue, i = 0; if ( isFunction( value ) ) { return this.each( function( j ) { jQuery( this ).removeClass( value.call( this, j, getClass( this ) ) ); } ); } if ( !arguments.length ) { return this.attr( "class", "" ); } classes = classesToArray( value ); if ( classes.length ) { while ( ( elem = this[ i++ ] ) ) { curValue = getClass( elem ); // This expression is here for better compressibility (see addClass) cur = elem.nodeType === 1 && ( " " + stripAndCollapse( curValue ) + " " ); if ( cur ) { j = 0; while ( ( clazz = classes[ j++ ] ) ) { // Remove *all* instances while ( cur.indexOf( " " + clazz + " " ) > -1 ) { cur = cur.replace( " " + clazz + " ", " " ); } } // Only assign if different to avoid unneeded rendering. finalValue = stripAndCollapse( cur ); if ( curValue !== finalValue ) { elem.setAttribute( "class", finalValue ); } } } } return this; }, toggleClass: function( value, stateVal ) { var type = typeof value, isValidValue = type === "string" || Array.isArray( value ); if ( typeof stateVal === "boolean" && isValidValue ) { return stateVal ? this.addClass( value ) : this.removeClass( value ); } if ( isFunction( value ) ) { return this.each( function( i ) { jQuery( this ).toggleClass( value.call( this, i, getClass( this ), stateVal ), stateVal ); } ); } return this.each( function() { var className, i, self, classNames; if ( isValidValue ) { // Toggle individual class names i = 0; self = jQuery( this ); classNames = classesToArray( value ); while ( ( className = classNames[ i++ ] ) ) { // Check each className given, space separated list if ( self.hasClass( className ) ) { self.removeClass( className ); } else { self.addClass( className ); } } // Toggle whole class name } else if ( value === undefined || type === "boolean" ) { className = getClass( this ); if ( className ) { // Store className if set dataPriv.set( this, "__className__", className ); } // If the element has a class name or if we're passed `false`, // then remove the whole classname (if there was one, the above saved it). // Otherwise bring back whatever was previously saved (if anything), // falling back to the empty string if nothing was stored. if ( this.setAttribute ) { this.setAttribute( "class", className || value === false ? "" : dataPriv.get( this, "__className__" ) || "" ); } } } ); }, hasClass: function( selector ) { var className, elem, i = 0; className = " " + selector + " "; while ( ( elem = this[ i++ ] ) ) { if ( elem.nodeType === 1 && ( " " + stripAndCollapse( getClass( elem ) ) + " " ).indexOf( className ) > -1 ) { return true; } } return false; } } ); var rreturn = /\r/g; jQuery.fn.extend( { val: function( value ) { var hooks, ret, valueIsFunction, elem = this[ 0 ]; if ( !arguments.length ) { if ( elem ) { hooks = jQuery.valHooks[ elem.type ] || jQuery.valHooks[ elem.nodeName.toLowerCase() ]; if ( hooks && "get" in hooks && ( ret = hooks.get( elem, "value" ) ) !== undefined ) { return ret; } ret = elem.value; // Handle most common string cases if ( typeof ret === "string" ) { return ret.replace( rreturn, "" ); } // Handle cases where value is null/undef or number return ret == null ? "" : ret; } return; } valueIsFunction = isFunction( value ); return this.each( function( i ) { var val; if ( this.nodeType !== 1 ) { return; } if ( valueIsFunction ) { val = value.call( this, i, jQuery( this ).val() ); } else { val = value; } // Treat null/undefined as ""; convert numbers to string if ( val == null ) { val = ""; } else if ( typeof val === "number" ) { val += ""; } else if ( Array.isArray( val ) ) { val = jQuery.map( val, function( value ) { return value == null ? "" : value + ""; } ); } hooks = jQuery.valHooks[ this.type ] || jQuery.valHooks[ this.nodeName.toLowerCase() ]; // If set returns undefined, fall back to normal setting if ( !hooks || !( "set" in hooks ) || hooks.set( this, val, "value" ) === undefined ) { this.value = val; } } ); } } ); jQuery.extend( { valHooks: { option: { get: function( elem ) { var val = jQuery.find.attr( elem, "value" ); return val != null ? val : // Support: IE <=10 - 11 only // option.text throws exceptions (#14686, #14858) // Strip and collapse whitespace // https://html.spec.whatwg.org/#strip-and-collapse-whitespace stripAndCollapse( jQuery.text( elem ) ); } }, select: { get: function( elem ) { var value, option, i, options = elem.options, index = elem.selectedIndex, one = elem.type === "select-one", values = one ? null : [], max = one ? index + 1 : options.length; if ( index < 0 ) { i = max; } else { i = one ? index : 0; } // Loop through all the selected options for ( ; i < max; i++ ) { option = options[ i ]; // Support: IE <=9 only // IE8-9 doesn't update selected after form reset (#2551) if ( ( option.selected || i === index ) && // Don't return options that are disabled or in a disabled optgroup !option.disabled && ( !option.parentNode.disabled || !nodeName( option.parentNode, "optgroup" ) ) ) { // Get the specific value for the option value = jQuery( option ).val(); // We don't need an array for one selects if ( one ) { return value; } // Multi-Selects return an array values.push( value ); } } return values; }, set: function( elem, value ) { var optionSet, option, options = elem.options, values = jQuery.makeArray( value ), i = options.length; while ( i-- ) { option = options[ i ]; /* eslint-disable no-cond-assign */ if ( option.selected = jQuery.inArray( jQuery.valHooks.option.get( option ), values ) > -1 ) { optionSet = true; } /* eslint-enable no-cond-assign */ } // Force browsers to behave consistently when non-matching value is set if ( !optionSet ) { elem.selectedIndex = -1; } return values; } } } } ); // Radios and checkboxes getter/setter jQuery.each( [ "radio", "checkbox" ], function() { jQuery.valHooks[ this ] = { set: function( elem, value ) { if ( Array.isArray( value ) ) { return ( elem.checked = jQuery.inArray( jQuery( elem ).val(), value ) > -1 ); } } }; if ( !support.checkOn ) { jQuery.valHooks[ this ].get = function( elem ) { return elem.getAttribute( "value" ) === null ? "on" : elem.value; }; } } ); // Return jQuery for attributes-only inclusion support.focusin = "onfocusin" in window; var rfocusMorph = /^(?:focusinfocus|focusoutblur)$/, stopPropagationCallback = function( e ) { e.stopPropagation(); }; jQuery.extend( jQuery.event, { trigger: function( event, data, elem, onlyHandlers ) { var i, cur, tmp, bubbleType, ontype, handle, special, lastElement, eventPath = [ elem || document ], type = hasOwn.call( event, "type" ) ? event.type : event, namespaces = hasOwn.call( event, "namespace" ) ? event.namespace.split( "." ) : []; cur = lastElement = tmp = elem = elem || document; // Don't do events on text and comment nodes if ( elem.nodeType === 3 || elem.nodeType === 8 ) { return; } // focus/blur morphs to focusin/out; ensure we're not firing them right now if ( rfocusMorph.test( type + jQuery.event.triggered ) ) { return; } if ( type.indexOf( "." ) > -1 ) { // Namespaced trigger; create a regexp to match event type in handle() namespaces = type.split( "." ); type = namespaces.shift(); namespaces.sort(); } ontype = type.indexOf( ":" ) < 0 && "on" + type; // Caller can pass in a jQuery.Event object, Object, or just an event type string event = event[ jQuery.expando ] ? event : new jQuery.Event( type, typeof event === "object" && event ); // Trigger bitmask: & 1 for native handlers; & 2 for jQuery (always true) event.isTrigger = onlyHandlers ? 2 : 3; event.namespace = namespaces.join( "." ); event.rnamespace = event.namespace ? new RegExp( "(^|\\.)" + namespaces.join( "\\.(?:.*\\.|)" ) + "(\\.|$)" ) : null; // Clean up the event in case it is being reused event.result = undefined; if ( !event.target ) { event.target = elem; } // Clone any incoming data and prepend the event, creating the handler arg list data = data == null ? [ event ] : jQuery.makeArray( data, [ event ] ); // Allow special events to draw outside the lines special = jQuery.event.special[ type ] || {}; if ( !onlyHandlers && special.trigger && special.trigger.apply( elem, data ) === false ) { return; } // Determine event propagation path in advance, per W3C events spec (#9951) // Bubble up to document, then to window; watch for a global ownerDocument var (#9724) if ( !onlyHandlers && !special.noBubble && !isWindow( elem ) ) { bubbleType = special.delegateType || type; if ( !rfocusMorph.test( bubbleType + type ) ) { cur = cur.parentNode; } for ( ; cur; cur = cur.parentNode ) { eventPath.push( cur ); tmp = cur; } // Only add window if we got to document (e.g., not plain obj or detached DOM) if ( tmp === ( elem.ownerDocument || document ) ) { eventPath.push( tmp.defaultView || tmp.parentWindow || window ); } } // Fire handlers on the event path i = 0; while ( ( cur = eventPath[ i++ ] ) && !event.isPropagationStopped() ) { lastElement = cur; event.type = i > 1 ? bubbleType : special.bindType || type; // jQuery handler handle = ( dataPriv.get( cur, "events" ) || Object.create( null ) )[ event.type ] && dataPriv.get( cur, "handle" ); if ( handle ) { handle.apply( cur, data ); } // Native handler handle = ontype && cur[ ontype ]; if ( handle && handle.apply && acceptData( cur ) ) { event.result = handle.apply( cur, data ); if ( event.result === false ) { event.preventDefault(); } } } event.type = type; // If nobody prevented the default action, do it now if ( !onlyHandlers && !event.isDefaultPrevented() ) { if ( ( !special._default || special._default.apply( eventPath.pop(), data ) === false ) && acceptData( elem ) ) { // Call a native DOM method on the target with the same name as the event. // Don't do default actions on window, that's where global variables be (#6170) if ( ontype && isFunction( elem[ type ] ) && !isWindow( elem ) ) { // Don't re-trigger an onFOO event when we call its FOO() method tmp = elem[ ontype ]; if ( tmp ) { elem[ ontype ] = null; } // Prevent re-triggering of the same event, since we already bubbled it above jQuery.event.triggered = type; if ( event.isPropagationStopped() ) { lastElement.addEventListener( type, stopPropagationCallback ); } elem[ type ](); if ( event.isPropagationStopped() ) { lastElement.removeEventListener( type, stopPropagationCallback ); } jQuery.event.triggered = undefined; if ( tmp ) { elem[ ontype ] = tmp; } } } } return event.result; }, // Piggyback on a donor event to simulate a different one // Used only for `focus(in | out)` events simulate: function( type, elem, event ) { var e = jQuery.extend( new jQuery.Event(), event, { type: type, isSimulated: true } ); jQuery.event.trigger( e, null, elem ); } } ); jQuery.fn.extend( { trigger: function( type, data ) { return this.each( function() { jQuery.event.trigger( type, data, this ); } ); }, triggerHandler: function( type, data ) { var elem = this[ 0 ]; if ( elem ) { return jQuery.event.trigger( type, data, elem, true ); } } } ); // Support: Firefox <=44 // Firefox doesn't have focus(in | out) events // Related ticket - https://bugzilla.mozilla.org/show_bug.cgi?id=687787 // // Support: Chrome <=48 - 49, Safari <=9.0 - 9.1 // focus(in | out) events fire after focus & blur events, // which is spec violation - http://www.w3.org/TR/DOM-Level-3-Events/#events-focusevent-event-order // Related ticket - https://bugs.chromium.org/p/chromium/issues/detail?id=449857 if ( !support.focusin ) { jQuery.each( { focus: "focusin", blur: "focusout" }, function( orig, fix ) { // Attach a single capturing handler on the document while someone wants focusin/focusout var handler = function( event ) { jQuery.event.simulate( fix, event.target, jQuery.event.fix( event ) ); }; jQuery.event.special[ fix ] = { setup: function() { // Handle: regular nodes (via `this.ownerDocument`), window // (via `this.document`) & document (via `this`). var doc = this.ownerDocument || this.document || this, attaches = dataPriv.access( doc, fix ); if ( !attaches ) { doc.addEventListener( orig, handler, true ); } dataPriv.access( doc, fix, ( attaches || 0 ) + 1 ); }, teardown: function() { var doc = this.ownerDocument || this.document || this, attaches = dataPriv.access( doc, fix ) - 1; if ( !attaches ) { doc.removeEventListener( orig, handler, true ); dataPriv.remove( doc, fix ); } else { dataPriv.access( doc, fix, attaches ); } } }; } ); } // Cross-browser xml parsing jQuery.parseXML = function( data ) { var xml; if ( !data || typeof data !== "string" ) { return null; } // Support: IE 9 - 11 only // IE throws on parseFromString with invalid input. try { xml = ( new window.DOMParser() ).parseFromString( data, "text/xml" ); } catch ( e ) { xml = undefined; } if ( !xml || xml.getElementsByTagName( "parsererror" ).length ) { jQuery.error( "Invalid XML: " + data ); } return xml; }; var rbracket = /\[\]$/, rCRLF = /\r?\n/g, rsubmitterTypes = /^(?:submit|button|image|reset|file)$/i, rsubmittable = /^(?:input|select|textarea|keygen)/i; function buildParams( prefix, obj, traditional, add ) { var name; if ( Array.isArray( obj ) ) { // Serialize array item. jQuery.each( obj, function( i, v ) { if ( traditional || rbracket.test( prefix ) ) { // Treat each array item as a scalar. add( prefix, v ); } else { // Item is non-scalar (array or object), encode its numeric index. buildParams( prefix + "[" + ( typeof v === "object" && v != null ? i : "" ) + "]", v, traditional, add ); } } ); } else if ( !traditional && toType( obj ) === "object" ) { // Serialize object item. for ( name in obj ) { buildParams( prefix + "[" + name + "]", obj[ name ], traditional, add ); } } else { // Serialize scalar item. add( prefix, obj ); } } // Serialize an array of form elements or a set of // key/values into a query string jQuery.param = function( a, traditional ) { var prefix, s = [], add = function( key, valueOrFunction ) { // If value is a function, invoke it and use its return value var value = isFunction( valueOrFunction ) ? valueOrFunction() : valueOrFunction; s[ s.length ] = encodeURIComponent( key ) + "=" + encodeURIComponent( value == null ? "" : value ); }; if ( a == null ) { return ""; } // If an array was passed in, assume that it is an array of form elements. if ( Array.isArray( a ) || ( a.jquery && !jQuery.isPlainObject( a ) ) ) { // Serialize the form elements jQuery.each( a, function() { add( this.name, this.value ); } ); } else { // If traditional, encode the "old" way (the way 1.3.2 or older // did it), otherwise encode params recursively. for ( prefix in a ) { buildParams( prefix, a[ prefix ], traditional, add ); } } // Return the resulting serialization return s.join( "&" ); }; jQuery.fn.extend( { serialize: function() { return jQuery.param( this.serializeArray() ); }, serializeArray: function() { return this.map( function() { // Can add propHook for "elements" to filter or add form elements var elements = jQuery.prop( this, "elements" ); return elements ? jQuery.makeArray( elements ) : this; } ) .filter( function() { var type = this.type; // Use .is( ":disabled" ) so that fieldset[disabled] works return this.name && !jQuery( this ).is( ":disabled" ) && rsubmittable.test( this.nodeName ) && !rsubmitterTypes.test( type ) && ( this.checked || !rcheckableType.test( type ) ); } ) .map( function( _i, elem ) { var val = jQuery( this ).val(); if ( val == null ) { return null; } if ( Array.isArray( val ) ) { return jQuery.map( val, function( val ) { return { name: elem.name, value: val.replace( rCRLF, "\r\n" ) }; } ); } return { name: elem.name, value: val.replace( rCRLF, "\r\n" ) }; } ).get(); } } ); jQuery.fn.extend( { wrapAll: function( html ) { var wrap; if ( this[ 0 ] ) { if ( isFunction( html ) ) { html = html.call( this[ 0 ] ); } // The elements to wrap the target around wrap = jQuery( html, this[ 0 ].ownerDocument ).eq( 0 ).clone( true ); if ( this[ 0 ].parentNode ) { wrap.insertBefore( this[ 0 ] ); } wrap.map( function() { var elem = this; while ( elem.firstElementChild ) { elem = elem.firstElementChild; } return elem; } ).append( this ); } return this; }, wrapInner: function( html ) { if ( isFunction( html ) ) { return this.each( function( i ) { jQuery( this ).wrapInner( html.call( this, i ) ); } ); } return this.each( function() { var self = jQuery( this ), contents = self.contents(); if ( contents.length ) { contents.wrapAll( html ); } else { self.append( html ); } } ); }, wrap: function( html ) { var htmlIsFunction = isFunction( html ); return this.each( function( i ) { jQuery( this ).wrapAll( htmlIsFunction ? html.call( this, i ) : html ); } ); }, unwrap: function( selector ) { this.parent( selector ).not( "body" ).each( function() { jQuery( this ).replaceWith( this.childNodes ); } ); return this; } } ); jQuery.expr.pseudos.hidden = function( elem ) { return !jQuery.expr.pseudos.visible( elem ); }; jQuery.expr.pseudos.visible = function( elem ) { return !!( elem.offsetWidth || elem.offsetHeight || elem.getClientRects().length ); }; // Support: Safari 8 only // In Safari 8 documents created via document.implementation.createHTMLDocument // collapse sibling forms: the second one becomes a child of the first one. // Because of that, this security measure has to be disabled in Safari 8. // https://bugs.webkit.org/show_bug.cgi?id=137337 support.createHTMLDocument = ( function() { var body = document.implementation.createHTMLDocument( "" ).body; body.innerHTML = "<form></form><form></form>"; return body.childNodes.length === 2; } )(); // Argument "data" should be string of html // context (optional): If specified, the fragment will be created in this context, // defaults to document // keepScripts (optional): If true, will include scripts passed in the html string jQuery.parseHTML = function( data, context, keepScripts ) { if ( typeof data !== "string" ) { return []; } if ( typeof context === "boolean" ) { keepScripts = context; context = false; } var base, parsed, scripts; if ( !context ) { // Stop scripts or inline event handlers from being executed immediately // by using document.implementation if ( support.createHTMLDocument ) { context = document.implementation.createHTMLDocument( "" ); // Set the base href for the created document // so any parsed elements with URLs // are based on the document's URL (gh-2965) base = context.createElement( "base" ); base.href = document.location.href; context.head.appendChild( base ); } else { context = document; } } parsed = rsingleTag.exec( data ); scripts = !keepScripts && []; // Single tag if ( parsed ) { return [ context.createElement( parsed[ 1 ] ) ]; } parsed = buildFragment( [ data ], context, scripts ); if ( scripts && scripts.length ) { jQuery( scripts ).remove(); } return jQuery.merge( [], parsed.childNodes ); }; jQuery.offset = { setOffset: function( elem, options, i ) { var curPosition, curLeft, curCSSTop, curTop, curOffset, curCSSLeft, calculatePosition, position = jQuery.css( elem, "position" ), curElem = jQuery( elem ), props = {}; // Set position first, in-case top/left are set even on static elem if ( position === "static" ) { elem.style.position = "relative"; } curOffset = curElem.offset(); curCSSTop = jQuery.css( elem, "top" ); curCSSLeft = jQuery.css( elem, "left" ); calculatePosition = ( position === "absolute" || position === "fixed" ) && ( curCSSTop + curCSSLeft ).indexOf( "auto" ) > -1; // Need to be able to calculate position if either // top or left is auto and position is either absolute or fixed if ( calculatePosition ) { curPosition = curElem.position(); curTop = curPosition.top; curLeft = curPosition.left; } else { curTop = parseFloat( curCSSTop ) || 0; curLeft = parseFloat( curCSSLeft ) || 0; } if ( isFunction( options ) ) { // Use jQuery.extend here to allow modification of coordinates argument (gh-1848) options = options.call( elem, i, jQuery.extend( {}, curOffset ) ); } if ( options.top != null ) { props.top = ( options.top - curOffset.top ) + curTop; } if ( options.left != null ) { props.left = ( options.left - curOffset.left ) + curLeft; } if ( "using" in options ) { options.using.call( elem, props ); } else { if ( typeof props.top === "number" ) { props.top += "px"; } if ( typeof props.left === "number" ) { props.left += "px"; } curElem.css( props ); } } }; jQuery.fn.extend( { // offset() relates an element's border box to the document origin offset: function( options ) { // Preserve chaining for setter if ( arguments.length ) { return options === undefined ? this : this.each( function( i ) { jQuery.offset.setOffset( this, options, i ); } ); } var rect, win, elem = this[ 0 ]; if ( !elem ) { return; } // Return zeros for disconnected and hidden (display: none) elements (gh-2310) // Support: IE <=11 only // Running getBoundingClientRect on a // disconnected node in IE throws an error if ( !elem.getClientRects().length ) { return { top: 0, left: 0 }; } // Get document-relative position by adding viewport scroll to viewport-relative gBCR rect = elem.getBoundingClientRect(); win = elem.ownerDocument.defaultView; return { top: rect.top + win.pageYOffset, left: rect.left + win.pageXOffset }; }, // position() relates an element's margin box to its offset parent's padding box // This corresponds to the behavior of CSS absolute positioning position: function() { if ( !this[ 0 ] ) { return; } var offsetParent, offset, doc, elem = this[ 0 ], parentOffset = { top: 0, left: 0 }; // position:fixed elements are offset from the viewport, which itself always has zero offset if ( jQuery.css( elem, "position" ) === "fixed" ) { // Assume position:fixed implies availability of getBoundingClientRect offset = elem.getBoundingClientRect(); } else { offset = this.offset(); // Account for the *real* offset parent, which can be the document or its root element // when a statically positioned element is identified doc = elem.ownerDocument; offsetParent = elem.offsetParent || doc.documentElement; while ( offsetParent && ( offsetParent === doc.body || offsetParent === doc.documentElement ) && jQuery.css( offsetParent, "position" ) === "static" ) { offsetParent = offsetParent.parentNode; } if ( offsetParent && offsetParent !== elem && offsetParent.nodeType === 1 ) { // Incorporate borders into its offset, since they are outside its content origin parentOffset = jQuery( offsetParent ).offset(); parentOffset.top += jQuery.css( offsetParent, "borderTopWidth", true ); parentOffset.left += jQuery.css( offsetParent, "borderLeftWidth", true ); } } // Subtract parent offsets and element margins return { top: offset.top - parentOffset.top - jQuery.css( elem, "marginTop", true ), left: offset.left - parentOffset.left - jQuery.css( elem, "marginLeft", true ) }; }, // This method will return documentElement in the following cases: // 1) For the element inside the iframe without offsetParent, this method will return // documentElement of the parent window // 2) For the hidden or detached element // 3) For body or html element, i.e. in case of the html node - it will return itself // // but those exceptions were never presented as a real life use-cases // and might be considered as more preferable results. // // This logic, however, is not guaranteed and can change at any point in the future offsetParent: function() { return this.map( function() { var offsetParent = this.offsetParent; while ( offsetParent && jQuery.css( offsetParent, "position" ) === "static" ) { offsetParent = offsetParent.offsetParent; } return offsetParent || documentElement; } ); } } ); // Create scrollLeft and scrollTop methods jQuery.each( { scrollLeft: "pageXOffset", scrollTop: "pageYOffset" }, function( method, prop ) { var top = "pageYOffset" === prop; jQuery.fn[ method ] = function( val ) { return access( this, function( elem, method, val ) { // Coalesce documents and windows var win; if ( isWindow( elem ) ) { win = elem; } else if ( elem.nodeType === 9 ) { win = elem.defaultView; } if ( val === undefined ) { return win ? win[ prop ] : elem[ method ]; } if ( win ) { win.scrollTo( !top ? val : win.pageXOffset, top ? val : win.pageYOffset ); } else { elem[ method ] = val; } }, method, val, arguments.length ); }; } ); // Support: Safari <=7 - 9.1, Chrome <=37 - 49 // Add the top/left cssHooks using jQuery.fn.position // Webkit bug: https://bugs.webkit.org/show_bug.cgi?id=29084 // Blink bug: https://bugs.chromium.org/p/chromium/issues/detail?id=589347 // getComputedStyle returns percent when specified for top/left/bottom/right; // rather than make the css module depend on the offset module, just check for it here jQuery.each( [ "top", "left" ], function( _i, prop ) { jQuery.cssHooks[ prop ] = addGetHookIf( support.pixelPosition, function( elem, computed ) { if ( computed ) { computed = curCSS( elem, prop ); // If curCSS returns percentage, fallback to offset return rnumnonpx.test( computed ) ? jQuery( elem ).position()[ prop ] + "px" : computed; } } ); } ); // Create innerHeight, innerWidth, height, width, outerHeight and outerWidth methods jQuery.each( { Height: "height", Width: "width" }, function( name, type ) { jQuery.each( { padding: "inner" + name, content: type, "": "outer" + name }, function( defaultExtra, funcName ) { // Margin is only for outerHeight, outerWidth jQuery.fn[ funcName ] = function( margin, value ) { var chainable = arguments.length && ( defaultExtra || typeof margin !== "boolean" ), extra = defaultExtra || ( margin === true || value === true ? "margin" : "border" ); return access( this, function( elem, type, value ) { var doc; if ( isWindow( elem ) ) { // $( window ).outerWidth/Height return w/h including scrollbars (gh-1729) return funcName.indexOf( "outer" ) === 0 ? elem[ "inner" + name ] : elem.document.documentElement[ "client" + name ]; } // Get document width or height if ( elem.nodeType === 9 ) { doc = elem.documentElement; // Either scroll[Width/Height] or offset[Width/Height] or client[Width/Height], // whichever is greatest return Math.max( elem.body[ "scroll" + name ], doc[ "scroll" + name ], elem.body[ "offset" + name ], doc[ "offset" + name ], doc[ "client" + name ] ); } return value === undefined ? // Get width or height on the element, requesting but not forcing parseFloat jQuery.css( elem, type, extra ) : // Set width or height on the element jQuery.style( elem, type, value, extra ); }, type, chainable ? margin : undefined, chainable ); }; } ); } ); jQuery.fn.extend( { bind: function( types, data, fn ) { return this.on( types, null, data, fn ); }, unbind: function( types, fn ) { return this.off( types, null, fn ); }, delegate: function( selector, types, data, fn ) { return this.on( types, selector, data, fn ); }, undelegate: function( selector, types, fn ) { // ( namespace ) or ( selector, types [, fn] ) return arguments.length === 1 ? this.off( selector, "**" ) : this.off( types, selector || "**", fn ); }, hover: function( fnOver, fnOut ) { return this.mouseenter( fnOver ).mouseleave( fnOut || fnOver ); } } ); jQuery.each( ( "blur focus focusin focusout resize scroll click dblclick " + "mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave " + "change select submit keydown keypress keyup contextmenu" ).split( " " ), function( _i, name ) { // Handle event binding jQuery.fn[ name ] = function( data, fn ) { return arguments.length > 0 ? this.on( name, null, data, fn ) : this.trigger( name ); }; } ); // Support: Android <=4.0 only // Make sure we trim BOM and NBSP var rtrim = /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g; // Bind a function to a context, optionally partially applying any // arguments. // jQuery.proxy is deprecated to promote standards (specifically Function#bind) // However, it is not slated for removal any time soon jQuery.proxy = function( fn, context ) { var tmp, args, proxy; if ( typeof context === "string" ) { tmp = fn[ context ]; context = fn; fn = tmp; } // Quick check to determine if target is callable, in the spec // this throws a TypeError, but we will just return undefined. if ( !isFunction( fn ) ) { return undefined; } // Simulated bind args = slice.call( arguments, 2 ); proxy = function() { return fn.apply( context || this, args.concat( slice.call( arguments ) ) ); }; // Set the guid of unique handler to the same of original handler, so it can be removed proxy.guid = fn.guid = fn.guid || jQuery.guid++; return proxy; }; jQuery.holdReady = function( hold ) { if ( hold ) { jQuery.readyWait++; } else { jQuery.ready( true ); } }; jQuery.isArray = Array.isArray; jQuery.parseJSON = JSON.parse; jQuery.nodeName = nodeName; jQuery.isFunction = isFunction; jQuery.isWindow = isWindow; jQuery.camelCase = camelCase; jQuery.type = toType; jQuery.now = Date.now; jQuery.isNumeric = function( obj ) { // As of jQuery 3.0, isNumeric is limited to // strings and numbers (primitives or objects) // that can be coerced to finite numbers (gh-2662) var type = jQuery.type( obj ); return ( type === "number" || type === "string" ) && // parseFloat NaNs numeric-cast false positives ("") // ...but misinterprets leading-number strings, particularly hex literals ("0x...") // subtraction forces infinities to NaN !isNaN( obj - parseFloat( obj ) ); }; jQuery.trim = function( text ) { return text == null ? "" : ( text + "" ).replace( rtrim, "" ); }; // Register as a named AMD module, since jQuery can be concatenated with other // files that may use define, but not via a proper concatenation script that // understands anonymous AMD modules. A named AMD is safest and most robust // way to register. Lowercase jquery is used because AMD module names are // derived from file names, and jQuery is normally delivered in a lowercase // file name. Do this after creating the global so that if an AMD module wants // to call noConflict to hide this version of jQuery, it will work. // Note that for maximum portability, libraries that are not jQuery should // declare themselves as anonymous modules, and avoid setting a global if an // AMD loader is present. jQuery is a special case. For more information, see // https://github.com/jrburke/requirejs/wiki/Updating-existing-libraries#wiki-anon if ( typeof define === "function" && define.amd ) { define( "jquery", [], function() { return jQuery; } ); } var // Map over jQuery in case of overwrite _jQuery = window.jQuery, // Map over the $ in case of overwrite _$ = window.$; jQuery.noConflict = function( deep ) { if ( window.$ === jQuery ) { window.$ = _$; } if ( deep && window.jQuery === jQuery ) { window.jQuery = _jQuery; } return jQuery; }; // Expose jQuery and $ identifiers, even in AMD // (#7102#comment:10, https://github.com/jquery/jquery/pull/557) // and CommonJS for browser emulators (#13566) if ( typeof noGlobal === "undefined" ) { window.jQuery = window.$ = jQuery; } return jQuery; } );
2301_78696cqk/Django_pyecharts_scrapy
scenery_spider_web-main/mainapp/static/login/js/jquery.slim.js
JavaScript
unknown
234,477
{% load static %} <!DOCTYPE html> <html lang="zh-CN"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>基于数据可视化的游客行为分析系统</title> <link href="{% static 'css/bootstrap.css' %}" rel="stylesheet"> <link rel="stylesheet" href="{% static 'css/base.css' %}"> <link rel="stylesheet" href="{% static 'css/index.css' %}"> <style> .t_title { width: 100%; height: 100%; text-align: center; font-size: 2.5em; line-height: 80px; color: #fff; } #chart_map { {#cursor: pointer;#} } .t_show { position: absolute; top: 0; right: 0; border-radius: 2px; background: #2C58A6; padding: 2px 5px; color: #fff; cursor: pointer; } </style> </head> <body> <!--header--> <div class="header"> <div class="bg_header"> <div class="header_nav fl t_title"> 基于数据可视化的游客行为分析系统 </div> </div> </div> <!--main--> <div class="data_content"> <div class="data_time"> 温馨提示: 点击模块后跳转至详情页面。(数据更新时间:{{ spider_time }}) </div> <div class="data_main"> <div class="main_left fl"> <div class="left_1 t_btn6" style="cursor: pointer;"> <div id="chart_1" class="main_table" style="width:100%;height: 280px;cursor: pointer"> <table> <thead> <tr> <th>评分排名</th> <th>景点名称</th> <th>评分</th> {# <th>地点</th>#} </tr> </thead> <tbody> {% for col in p2 %} <tr> <td>{{ forloop.counter }}</td> <td>{{ col.scenery_name }}</td> <td>{{ col.score }}</td> </tr> {% endfor %} </tbody> </table> </div> {# <!--左上边框-->#} {# <div class="t_line_box">#} {# <i class="t_l_line"></i>#} {# <i class="l_t_line"></i>#} {# </div>#} {# <!--右上边框-->#} {# <div class="t_line_box">#} {# <i class="t_r_line"></i>#} {# <i class="r_t_line"></i>#} {# </div>#} {# <!--左下边框-->#} {# <div class="t_line_box">#} {# <i class="l_b_line"></i>#} {# <i class="b_l_line"></i>#} {# </div>#} {# <!--右下边框-->#} {# <div class="t_line_box">#} {# <i class="r_b_line"></i>#} {# <i class="b_r_line"></i>#} {# </div>#} <div class="main_title"> <img src="{% static 'img/t_1.png' %}" alt=""> <a href="/page?p=2" style="color: white">景点评分数据</a> </div> </div> <div class="left_2" style="cursor: pointer;"> <!--左上边框--> <div class="t_line_box"> <i class="t_l_line"></i> <i class="l_t_line"></i> </div> <!--右上边框--> <div class="t_line_box"> <i class="t_r_line"></i> <i class="r_t_line"></i> </div> <!--左下边框--> <div class="t_line_box"> <i class="l_b_line"></i> <i class="b_l_line"></i> </div> <!--右下边框--> <div class="t_line_box"> <i class="r_b_line"></i> <i class="b_r_line"></i> </div> <div class="main_title"> <img src="{% static 'img/t_2.png' %}" alt=""> <a href="/page?p=4" style="color: white">Top10景点人数</a> </div> <div id="chart_2" class="chart t_btn9" style="width:100%;height: 280px;"> {{ p4 | safe }} </div> </div> </div> <div class="main_center fl"> <div class="center_text"> <!--左上边框--> <div class="t_line_box"> <i class="t_l_line"></i> <i class="l_t_line"></i> </div> <!--右上边框--> <div class="t_line_box"> <i class="t_r_line"></i> <i class="r_t_line"></i> </div> <!--左下边框--> <div class="t_line_box"> <i class="l_b_line"></i> <i class="b_l_line"></i> </div> <!--右下边框--> <div class="t_line_box"> <i class="r_b_line"></i> <i class="b_r_line"></i> </div> <div class="main_title"> <img src="{% static 'img/t_3.png' %}" alt=""> <a href="/page?p=1" style="color: white">西安景点地图</a> </div> <div id="chart_map" style="width:100%;height:610px;"> {{ p1 | safe }} </div> </div> </div> <div class="main_right fr"> <div class="right_1"> <div id="chart_3" class="main_table t_btn8" style="width:100%;height: 280px;"> <table> <thead> <tr> <th>排名</th> <th>景点名称</th> <th>浏览人数</th> </tr> </thead> <tbody> {% for col in p3 %} <tr> <td>{{ forloop.counter }}</td> <td>{{ col.scenery_name }}</td> <td>{{ col.people_percent }}%</td> </tr> {% endfor %} </tbody> </table> </div> {# <!--左上边框-->#} {# <div class="t_line_box">#} {# <i class="t_l_line"></i>#} {# <i class="l_t_line"></i>#} {# </div>#} {# <!--右上边框-->#} {# <div class="t_line_box">#} {# <i class="t_r_line"></i>#} {# <i class="r_t_line"></i>#} {# </div>#} {# <!--左下边框-->#} {# <div class="t_line_box">#} {# <i class="l_b_line"></i>#} {# <i class="b_l_line"></i>#} {# </div>#} {# <!--右下边框-->#} {# <div class="t_line_box">#} {# <i class="r_b_line"></i>#} {# <i class="b_r_line"></i>#} {# </div>#} <div class="main_title"> <img src="{% static 'img/t_4.png' %} " alt=""> <a href="/page?p=3" style="color: white">景点浏览人数</a> </div> </div> <div class="right_2"> <!--左上边框--> <div class="t_line_box"> <i class="t_l_line"></i> <i class="l_t_line"></i> </div> <!--右上边框--> <div class="t_line_box"> <i class="t_r_line"></i> <i class="r_t_line"></i> </div> <!--左下边框--> <div class="t_line_box"> <i class="l_b_line"></i> <i class="b_l_line"></i> </div> <!--右下边框--> <div class="t_line_box"> <i class="r_b_line"></i> <i class="b_r_line"></i> </div> <div class="main_title"> <img src="{% static 'img/t_5.png' %}" alt=""> <a href="/page?p=5" style="color: white">评论词云</a> </div> {# <div id="chart_4" class="echart fl t_btn4" style="width:100%;height: 280px;cursor: pointer;">#} <div id="chart_4" class="echart t_btn4" style="width:100%;height: 280px; padding-left: 10px"> {{ p5 | safe }} </div> </div> </div> </div> <div class="data_bottom"> <div class="bottom_1 fl t_btn5" style="cursor: pointer;"> <!--左上边框--> <div class="t_line_box"> <i class="t_l_line"></i> <i class="l_t_line"></i> </div> <!--右上边框--> <div class="t_line_box"> <i class="t_r_line"></i> <i class="r_t_line"></i> </div> <!--左下边框--> <div class="t_line_box"> <i class="l_b_line"></i> <i class="b_l_line"></i> </div> <!--右下边框--> <div class="t_line_box"> <i class="r_b_line"></i> <i class="b_r_line"></i> </div> <div class="main_title"> <img src="{% static 'img/t_6.png' %} " alt=""> <a href="/page?p=6" style="color: white" >景点浏览时间</a> </div> <div id="chart_5" class="echart fl" style="width:100%;height: 250px;margin-top: 15px;"> {{ p6 | safe }} </div> </div> <div class="bottom_center fl"> <div class="bottom_2 fl"> <!--左上边框--> <div class="t_line_box"> <i class="t_l_line"></i> <i class="l_t_line"></i> </div> <!--右上边框--> <div class="t_line_box"> <i class="t_r_line"></i> <i class="r_t_line"></i> </div> <!--左下边框--> <div class="t_line_box"> <i class="l_b_line"></i> <i class="b_l_line"></i> </div> <!--右下边框--> <div class="t_line_box"> <i class="r_b_line"></i> <i class="b_r_line"></i> </div> <div class="main_title"> <img src="{% static 'img/t_7.png' %} " alt=""> <a href="/page?p=7" style="color: white">景点分布</a> </div> <div class="t_btn8"> {{ p7 | safe }} </div> </div> {# <div class="bottom_3 fl">#} {# <!--左上边框-->#} {# <div class="t_line_box">#} {# <i class="t_l_line"></i> #} {# <i class="l_t_line"></i> #} {# </div> #} {# <!--右上边框-->#} {# <div class="t_line_box">#} {# <i class="t_r_line"></i> #} {# <i class="r_t_line"></i> #} {# </div> #} {# <!--左下边框-->#} {# <div class="t_line_box">#} {# <i class="l_b_line"></i> #} {# <i class="b_l_line"></i> #} {# </div> #} {# <!--右下边框-->#} {# <div class="t_line_box">#} {# <i class="r_b_line"></i> #} {# <i class="b_r_line"></i> #} {# </div>#} {# <div class="main_title">#} {# <img src="{% static 'img/t_7.png' %}" alt="">#} {# 陕西省业务量#} {# </div>#} {# <div class="main_table t_btn2">#} {# <table>#} {# <thead>#} {# <tr>#} {# <th>省内(万件)</th>#} {# <th>省外(万件)</th>#} {# <th>国际(万件)</th>#} {# <th>总业务量(万件)</th>#} {# <th>日期</th>#} {# </tr>#} {# </thead>#} {# <tbody>#} {# <tr>#} {# <td>21352.36</td>#} {# <td>68575.6</td>#} {# <td>464.43</td>#} {# <td>90392.39</td>#} {# <td>2018年</td>#} {# </tr>#} {# <tr>#} {# <td>17522.41</td>#} {# <td>37111.03</td>#} {# <td>278.5</td>#} {# <td>54911.94</td>#} {# <td>2017年</td>#} {# </tr>#} {# <tr>#} {# <td>7014.14</td>#} {# <td>26841.29</td>#} {# <td>163.72</td>#} {# <td>34019.15</td>#} {# <td>2016年</td>#} {# </tr>#} {# <tr>#} {# <td>2553.55</td>#} {# <td>18072.54</td>#} {# <td>129.65</td>#} {# <td>20755.74</td>#} {# <td>2015年</td>#} {# </tr>#} {# <tr>#} {# <td>1427.04</td>#} {# <td>10859.54</td>#} {# <td>182.54</td>#} {# <td>12469.11</td>#} {# <td>2014年</td>#} {# </tr>#} {# </tbody>#} {# </table>#} {# </div>#} {# </div>#} </div> <div class="bottom_4 fr"> <!--左上边框--> <div class="t_line_box"> <i class="t_l_line"></i> <i class="l_t_line"></i> </div> <!--右上边框--> <div class="t_line_box"> <i class="t_r_line"></i> <i class="r_t_line"></i> </div> <!--左下边框--> <div class="t_line_box"> <i class="l_b_line"></i> <i class="b_l_line"></i> </div> <!--右下边框--> <div class="t_line_box"> <i class="r_b_line"></i> <i class="b_r_line"></i> </div> <div class="main_title"> <img src="{% static 'img/t_7.png' %}" alt=""> <a href="/page?p=8" style="color: white">景点评分</a> </div> <div class="main_table t_btn3"> {{ p8 | safe }} </div> </div> </div> </div> </body> <script src="{% static 'js/jquery-2.2.1.min.js' %}"></script> <script src="{% static 'js/bootstrap.min.js' %}"></script> <script src="{% static 'js/echarts.min.js' %}"></script> <script src="{% static 'js/common.js' %}"></script> {#<script src="{% static 'js/dataTool.js' %}"></script>#} {#<script src="{% static 'js/index.js' %}"></script>#} {#<script src="{% static 'js/china.js' %}"></script>#} {#<script src="{% static 'js/hunan.js' %}"></script>#} </html>
2301_78696cqk/Django_pyecharts_scrapy
scenery_spider_web-main/mainapp/templates/index.html
HTML
unknown
17,311
{% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <meta name="viewport" content="width=device-width,initial-scale=1,shrink-to-fit=no"> <title>用户登录</title> <link href="{% static 'login/css/bootstrap.min.css' %}" rel="stylesheet"> <link href="{% static 'login/css/signin.css' %}" rel="stylesheet"> </head> <body class="text-center"> <form class="form-signin" action="/login/" method="post"> {% csrf_token %} {# <img class="mb-4" src="{% static 'login/img/login.jpg' %}" width="72" height="72">#} <h1 class="h3 mb-3 font-weight-normal" >{{ tip }}</h1> <div class="row"> <input type="text" class="form-control" placeholder="{{ username }}" required="" autofocus="" name="username" style="margin-bottom: 10px"> <input type="password" class="form-control" placeholder="{{ password }}" required="" name="password"> </div> <div class="checkbox mb-lg-1"> <label> <a href="/register/">{{ go }}</a> </label> </div> <div class="row"> <button class="btn btn-lg btn-primary btn-block" type="submit" >{{ login }}</button> </div> <p class="mt-5 mb-3 text-muted">©<span >{{ year }}</span>-<span >{{ next_year }}</span> </p> </form> <script src="{% static 'login/js/jquery.js' %}"></script> </body> </html>
2301_78696cqk/Django_pyecharts_scrapy
scenery_spider_web-main/mainapp/templates/login.html
HTML
unknown
1,388
{% load static %} <!DOCTYPE html> <html lang="zh-CN"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>基于数据可视化的游客行为分析系统</title> <link rel="stylesheet" href="{% static 'css/bootstrap.css' %}"> <link rel="stylesheet" href="{% static 'css/base.css' %}"> <link rel="stylesheet" href="{% static 'css/style.css' %}"> {# <link rel="stylesheet" href="{% static 'css/index.css' %}">#} <style> .t_btn { margin-top: 20px; } .t_btn li { display: inline-block; margin: 0 0px 20px 20px; } .t_btn button, .t_a { display: inline-block; padding: 10px 5px; width: 80px; border-style: solid; border-width: 0; cursor: pointer; font-family: inherit; font-weight: bold; line-height: normal; margin: 0 0 0.5em 0; position: relative; text-decoration: none; text-align: center; display: inline-block; font-size: 1em; background-color: #2C58A6; border-color: #0263ff; color: white; box-shadow: 0 -2px 0 rgba(0, 0, 0, 0.2) inset !important; margin-right: 0.5em; border-radius: 4px; } .t_height { line-height: 80px; position: absolute; right: 28px; top: 0; } .main_table tr { height: 42px; } div#chart_1, div#chart_3 { overflow-y: scroll; {#height: 1300px !important;#} } .main_table { width: 100%; margin-top: 25px; } .main_table table { width: 100%; } .main_table thead tr { height: 42px; } .main_table th { font-size: 12px; font-weight: 600; color: #61d2f7; text-align: center; } .main_table th:nth-child(1) { } .main_table th:nth-child(2) { } .main_table td { color: #fff; font-size: 10px; text-align: center; } .main_table tbody tr:nth-child(odd) { background-color: #072951; box-shadow: -10px 0px 15px #2C58A6 inset, /*左边阴影*/ 10px 0px 15px #2C58A6 inset; /*右边阴影*/ } .t_btn8, .t_btn2, .t_btn3 { position: relative; z-index: 100; cursor: pointer; } </style> </head> <body> <!--header--> <div class="header"> <div class="bg_header"> <div class="header_nav fl t_title"> 基于数据可视化的游客行为分析系统 </div> </div> <div class="header_nav fl"> </div> <div class="header_myself fr t_height"> <a class="t_a" href="/index">返回 &nbsp;</a> </div> </div> <!--main--> <div class="data_content"> <div class="data_main"> <div class="main_left fl"> <div class="left_1"> <ul class="t_btn"> {% for page in page_data.keys %} <li> <button class="t_btn5"> <a href="/page?p={{ forloop.counter }}" style="color: white">{{ page }}</a> </button> </li> {% endfor %} {# #} {# <li>#} {# <button class="t_btn5">#} {# <a href="/page?p=2" style="color: white">{{ page_data.keys.1 }}</a>#} {# </button>#} {# </li>#} {# <li>#} {# <button class="t_btn5">#} {# <a href="/page?p=3" style="color: white">{{ page_data.keys.2 }}</a>#} {# </button>#} {# </li>#} {# <li>#} {# <button class="t_btn5">#} {# <a href="/page?p=4" style="color: white">{{ page_data.keys.3 }}</a>#} {# </button>#} {# </li>#} {# <li>#} {# <button class="t_btn5">#} {# <a href="/page?p=5" style="color: white">货物重量比</a>#} {# </button>#} {# </li>#} {# <li>#} {# <button class="t_btn5">#} {# <a href="/page?p=6" style="color: white">货物总件数</a>#} {# </button>#} {# </li>#} {# <li>#} {# <button class="t_btn5">#} {# <a href="/page?p=7" style="color: white">货物总重量</a>#} {# </button>#} {# </li>#} {# <li>#} {# <button class="t_btn5">#} {# <a href="/page?p=8" style="color: white">代理总货运信息</a>#} {# </button>#} {# </li>#} </ul> </div> <div class="left_2" style="display:none"> <div class="main_title"> 陕西省地图 </div> </div> </div> <div class="main_center fl"> <div class="center_text t_cos0"> <!--左上边框--> <div class="t_line_box"> <i class="t_l_line"></i> <i class="l_t_line"></i> </div> <!--右上边框--> <div class="t_line_box"> <i class="t_r_line"></i> <i class="r_t_line"></i> </div> <!--左下边框--> <div class="t_line_box"> <i class="l_b_line"></i> <i class="b_l_line"></i> </div> <!--右下边框--> <div class="t_line_box"> <i class="r_b_line"></i> <i class="b_r_line"></i> </div> <div class="main_title"> {{ title }} </div> <div id="chart_map" style="width:100%;height:778px; padding-top:25px"> {% if is_chart %} {{ data | safe }} {% else %} {% if title == '景点浏览人数' %} <div id="chart_1" class="main_table t_btn8 " style="width:100%;height: 770px;"> <table> <thead> <tr> <th>排名</th> <th>景点名称</th> <th>浏览人数</th> </tr> </thead> <tbody> {% for col in data %} <tr> <td>{{ forloop.counter }}</td> <td>{{ col.scenery_name }}</td> <td>{{ col.people_percent }}%</td> </tr> {% endfor %} </tbody> </table> </div> {% else %} <div id="chart_3" class="main_table t_btn8 " style="width:100%;height: 770px;"> <table> <thead> <tr> <th>评分排名</th> <th>景点名称</th> <th>评分</th> {# <th>地点</th>#} </tr> </thead> <tbody> {% for col in data %} <tr> <td>{{ forloop.counter }}</td> <td>{{ col.scenery_name }}</td> <td>{{ col.score }}</td> </tr> {% endfor %} </tbody> </table> </div> {% endif %} {% endif %} </div> </div> <div class="center_text t_cos1" style="display:none"> <!--左上边框--> <div class="t_line_box"> <i class="t_l_line"></i> <i class="l_t_line"></i> </div> <!--右上边框--> <div class="t_line_box"> <i class="t_r_line"></i> <i class="r_t_line"></i> </div> <!--左下边框--> <div class="t_line_box"> <i class="l_b_line"></i> <i class="b_l_line"></i> </div> <!--右下边框--> <div class="t_line_box"> <i class="r_b_line"></i> <i class="b_r_line"></i> </div> <div class="main_title"> 陕西省高速公路 </div> <div id="chart_2" class="chart" style="width:100%;height:778px;"></div> </div> <div class="center_text t_cos2" style="display:none"> <!--左上边框--> <div class="t_line_box"> <i class="t_l_line"></i> <i class="l_t_line"></i> </div> <!--右上边框--> <div class="t_line_box"> <i class="t_r_line"></i> <i class="r_t_line"></i> </div> <!--左下边框--> <div class="t_line_box"> <i class="l_b_line"></i> <i class="b_l_line"></i> </div> <!--右下边框--> <div class="t_line_box"> <i class="r_b_line"></i> <i class="b_r_line"></i> </div> <div class="main_title"> 陕西省飞机场 </div> <div id="chart_0" class="chart" style="width:100%;height:778px;"></div> </div> <div class="center_text t_cos3" style="display:none"> <!--左上边框--> <div class="t_line_box"> <i class="t_l_line"></i> <i class="l_t_line"></i> </div> <!--右上边框--> <div class="t_line_box"> <i class="t_r_line"></i> <i class="r_t_line"></i> </div> <!--左下边框--> <div class="t_line_box"> <i class="l_b_line"></i> <i class="b_l_line"></i> </div> <!--右下边框--> <div class="t_line_box"> <i class="r_b_line"></i> <i class="b_r_line"></i> </div> <div class="main_title"> 中国铁路 </div> <div id="chart_4" class="chart" style="width:100%;height:778px;"></div> </div> <div class="center_text t_cos4" style="display:none"> <!--左上边框--> <div class="t_line_box"> <i class="t_l_line"></i> <i class="l_t_line"></i> </div> <!--右上边框--> <div class="t_line_box"> <i class="t_r_line"></i> <i class="r_t_line"></i> </div> <!--左下边框--> <div class="t_line_box"> <i class="l_b_line"></i> <i class="b_l_line"></i> </div> <!--右下边框--> <div class="t_line_box"> <i class="r_b_line"></i> <i class="b_r_line"></i> </div> <div class="main_title"> 陕西货运量收入 </div> <div id="chart_1" class="chart" style="width:100%;height:778px;"></div> </div> <div class="center_text t_cos5" style="display:none"> <!--左上边框--> <div class="t_line_box"> <i class="t_l_line"></i> <i class="l_t_line"></i> </div> <!--右上边框--> <div class="t_line_box"> <i class="t_r_line"></i> <i class="r_t_line"></i> </div> <!--左下边框--> <div class="t_line_box"> <i class="l_b_line"></i> <i class="b_l_line"></i> </div> <!--右下边框--> <div class="t_line_box"> <i class="r_b_line"></i> <i class="b_r_line"></i> </div> <div class="main_title"> 交通就业人员 </div> <div id="chart_3" class="chart" style="width:100%;height:778px;"></div> </div> <div class="center_text t_cos6" style="display:none"> <!--左上边框--> <div class="t_line_box"> <i class="t_l_line"></i> <i class="l_t_line"></i> </div> <!--右上边框--> <div class="t_line_box"> <i class="t_r_line"></i> <i class="r_t_line"></i> </div> <!--左下边框--> <div class="t_line_box"> <i class="l_b_line"></i> <i class="b_l_line"></i> </div> <!--右下边框--> <div class="t_line_box"> <i class="r_b_line"></i> <i class="b_r_line"></i> </div> <div class="main_title"> 陕西省铁路 </div> <div id="chart_6" class="chart" style="width:100%;height:778px;"></div> </div> <div class="center_text t_cos7" style="display:none"> <!--左上边框--> <div class="t_line_box"> <i class="t_l_line"></i> <i class="l_t_line"></i> </div> <!--右上边框--> <div class="t_line_box"> <i class="t_r_line"></i> <i class="r_t_line"></i> </div> <!--左下边框--> <div class="t_line_box"> <i class="l_b_line"></i> <i class="b_l_line"></i> </div> <!--右下边框--> <div class="t_line_box"> <i class="r_b_line"></i> <i class="b_r_line"></i> </div> <div class="main_title"> 陕西总货运量 </div> <div id="chart_7" class="chart" style="width:100%;height:778px;"></div> </div> <div class="center_text t_cos8 table_div" style="display:none"> <!--左上边框--> <div class="t_line_box"> <i class="t_l_line"></i> <i class="l_t_line"></i> </div> <!--右上边框--> <div class="t_line_box"> <i class="t_r_line"></i> <i class="r_t_line"></i> </div> <!--左下边框--> <div class="t_line_box"> <i class="l_b_line"></i> <i class="b_l_line"></i> </div> <!--右下边框--> <div class="t_line_box"> <i class="r_b_line"></i> <i class="b_r_line"></i> </div> <div class="main_title"> 陕西货物周转量 </div> <div id="chart_8" class="chart" style="width:100%;height:778px;"></div> </div> <div class="center_text t_cos9" style="display:none"> <!--左上边框--> <div class="t_line_box"> <i class="t_l_line"></i> <i class="l_t_line"></i> </div> <!--右上边框--> <div class="t_line_box"> <i class="t_r_line"></i> <i class="r_t_line"></i> </div> <!--左下边框--> <div class="t_line_box"> <i class="l_b_line"></i> <i class="b_l_line"></i> </div> <!--右下边框--> <div class="t_line_box"> <i class="r_b_line"></i> <i class="b_r_line"></i> </div> <div class="main_title"> 陕西运输线长度 </div> <div id="chart_9" class="chart" style="width:100%;height:778px;"></div> </div> <div class="center_text t_cos10" style="display:none"> <!--左上边框--> <div class="t_line_box"> <i class="t_l_line"></i> <i class="l_t_line"></i> </div> <!--右上边框--> <div class="t_line_box"> <i class="t_r_line"></i> <i class="r_t_line"></i> </div> <!--左下边框--> <div class="t_line_box"> <i class="l_b_line"></i> <i class="b_l_line"></i> </div> <!--右下边框--> <div class="t_line_box"> <i class="r_b_line"></i> <i class="b_r_line"></i> </div> <div class="main_title"> 陕西业务量 </div> <div id="chart_10" class="chart" style="width:100%;height:778px;"></div> </div> <div class="center_text t_cos11" style="display:none"> <!--左上边框--> <div class="t_line_box"> <i class="t_l_line"></i> <i class="l_t_line"></i> </div> <!--右上边框--> <div class="t_line_box"> <i class="t_r_line"></i> <i class="r_t_line"></i> </div> <!--左下边框--> <div class="t_line_box"> <i class="l_b_line"></i> <i class="b_l_line"></i> </div> <!--右下边框--> <div class="t_line_box"> <i class="r_b_line"></i> <i class="b_r_line"></i> </div> <div class="main_title"> 陕西公路营运 </div> <div id="chart_11" class="chart" style="width:100%;height:778px;"></div> </div> <div class="center_text t_cos12" style="display:none"> <!--左上边框--> <div class="t_line_box"> <i class="t_l_line"></i> <i class="l_t_line"></i> </div> <!--右上边框--> <div class="t_line_box"> <i class="t_r_line"></i> <i class="r_t_line"></i> </div> <!--左下边框--> <div class="t_line_box"> <i class="l_b_line"></i> <i class="b_l_line"></i> </div> <!--右下边框--> <div class="t_line_box"> <i class="r_b_line"></i> <i class="b_r_line"></i> </div> <div class="main_title"> 陕西城市交通 </div> <div id="chart_12" class="chart" style="width:100%;height:778px;"></div> </div> <div class="center_text t_cos13" style="display:none"> <!--左上边框--> <div class="t_line_box"> <i class="t_l_line"></i> <i class="l_t_line"></i> </div> <!--右上边框--> <div class="t_line_box"> <i class="t_r_line"></i> <i class="r_t_line"></i> </div> <!--左下边框--> <div class="t_line_box"> <i class="l_b_line"></i> <i class="b_l_line"></i> </div> <!--右下边框--> <div class="t_line_box"> <i class="r_b_line"></i> <i class="b_r_line"></i> </div> <div class="main_title"> 陕西省地图 </div> <div id="chart_13" class="chart" style="width:100%;height:778px; cursor: pointer;"></div> </div> <div class="center_text t_cos14" style="display:none"> <!--左上边框--> <div class="t_line_box"> <i class="t_l_line"></i> <i class="l_t_line"></i> </div> <!--右上边框--> <div class="t_line_box"> <i class="t_r_line"></i> <i class="r_t_line"></i> </div> <!--左下边框--> <div class="t_line_box"> <i class="l_b_line"></i> <i class="b_l_line"></i> </div> <!--右下边框--> <div class="t_line_box"> <i class="r_b_line"></i> <i class="b_r_line"></i> </div> <div class="main_title"> GPS </div> <div id="chart_14" class="chart" style="width:100%;height:778px; cursor: pointer;"> </div> </div> </div> </div> </div> </body> {# <script src="http://api.map.baidu.com/api?v=2.0&ak=dApOtvB5E3x6byHpUGHbRF1fxctCBdjw"></script>#} <script src="{% static 'js/jquery-2.2.1.min.js' %}"></script> <script src="{% static 'js/bootstrap.min.js' %}"></script> <script src="{% static 'js/echarts.min.js' %}"></script> {# <script src="{% static 'js/common.js' %}"></script>#} {# <script src="{% static 'js/dataTool.js' %}"></script>#} {# <script src="{% static 'js/base.js' %}"></script>#} {# <script src="{% static 'js/china.js' %}"></script>#} {# <script src="{% static 'js/hunan.js' %}"></script>#} {# <script src="{% static 'js/bmap.js' %}"></script>#} {# <script src="{% static 'js/echarts-all.js' %}"></script>#} </html>
2301_78696cqk/Django_pyecharts_scrapy
scenery_spider_web-main/mainapp/templates/page/index.html
HTML
unknown
24,506
{% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <meta name="viewport" content="width=device-width,initial-scale=1,shrink-to-fit=no"> <title>用户登录</title> <link href="{% static 'login/css/bootstrap.min.css' %}" rel="stylesheet"> <link href="{% static 'login/css/signin.css' %}" rel="stylesheet"> </head> <body class="text-center"> <form class="form-signin" action="/register/" method="post"> {% csrf_token %} {# <img class="mb-4" src="{% static 'login/img/login.jpg' %}" width="72" height="72">#} <h1 class="h3 mb-3 font-weight-normal" >{{ tip }}</h1> <div class="row"> <input type="text" class="form-control" placeholder="{{ username }}" required="" autofocus="" name="username" style="margin-bottom: 10px"> <input type="password" class="form-control" placeholder="{{ password }}" required="" name="password"> <input type="password" class="form-control" placeholder="确认{{ password }}" required="" name="repassword"> {# <div class="col-xs-7">#} {# <input type="text" name="code" class="form-control" placeholder="请输入图片验证码" required="" id="id_code">#} {# <span style="color:red"></span>#} {# </div>#} {# <div class="col-xs-5">#} {# <img src="/img/code/" alt="验证码" id="image_code" style="height: 40px">#} {# </div>#} </div> <div class="checkbox mb-lg-1"> <label> <a href="/login/">{{ go }}</a> </label> </div> <div class="row"> <button class="btn btn-lg btn-primary btn-block" type="submit" >{{ login }}</button> </div> <span ></span> <span style="color: red">{{ error }}</span> <p class="mt-5 mb-3 text-muted">©<span >{{ year }}</span>-<span >{{ next_year }}</span> </p> </form> <script src="{% static 'login/js/jquery.js' %}"></script> </body> </html>
2301_78696cqk/Django_pyecharts_scrapy
scenery_spider_web-main/mainapp/templates/register.html
HTML
unknown
1,967
from django.test import TestCase # Create your tests here.
2301_78696cqk/Django_pyecharts_scrapy
scenery_spider_web-main/mainapp/tests.py
Python
unknown
60
import re from django.db.models.functions import Cast, Replace from django.forms import FloatField from django.utils import timezone from pyecharts.charts import Pie, Line, WordCloud, Map from pyecharts import options as opts from pyecharts.globals import ThemeType, SymbolType import pandas as pd from mainapp import models from django_pandas.io import read_frame import jieba from warehouse.models import Scenery, Evaluate, SpiderLog, xian_poi from pyecharts import options as opts from pyecharts.charts import Map class AllMap(): """ 1: 西安景点分布地图 2: 景点评分数据表格 3: 景点浏览人数数据表格 4: 人数百分比饼图 5: 词云 6: 浏览时间折线图 7: 景点数量折线图 8: 评分折线图 """ # def __init__(self): # qs = Scenery.objects.all() # self.df = read_frame(qs=qs) # # # 更新时间 # self.spider_time = timezone.localtime(SpiderLog.objects.last().spider_time).strftime('%Y-%m-%d %H:%M:%S') # # # p1 p6 # qs = Scenery.objects.filter(city__isnull=False) # df_p1 = read_frame(qs) # df_p1["county"] = df_p1["city"].map(lambda x: self.get_county(x)) # self.map_data = df_p1.groupby("county").count()["scenery_name"] # self.map_data = self.map_data.sort_values() # # def __init__(self): qs = Scenery.objects.all() self.df = read_frame(qs=qs) # 更新时间 self.spider_time = timezone.localtime(SpiderLog.objects.last().spider_time).strftime('%Y-%m-%d %H:%M:%S') # p1 p6 qs = Scenery.objects.filter(city__isnull=False) df_p1 = read_frame(qs) df_p1["county"] = df_p1["city"].map(lambda x: self.get_county(x)) self.map_data = df_p1.groupby("county").count()["scenery_name"] self.map_data = self.map_data.sort_values() # p4 qs = Scenery.objects.exclude(people_percent="0%").all() self.df_p4 = read_frame(qs=qs) self.df_p4["people_percent"] = self.df_p4["people_percent"].str.replace("%", "").astype(int) # p2 self.scenery_obj = Scenery.objects.filter(score__isnull=False).exclude(score=0).all().order_by("-score") # def __init__(self): # # 获取两种数据源 # # 1. 使用xian_poi表的数据(用于P1) # poi_qs = xian_poi.objects.filter(city="西安市").all() # self.poi_df = read_frame(qs=poi_qs) # # # 2. 使用原Scenery表的数据(用于P6等其他图表) # scenery_qs = Scenery.objects.all() # self.scenery_df = read_frame(qs=scenery_qs) # # # 更新时间(使用爬虫日志最新时间) # self.spider_time = timezone.localtime(SpiderLog.objects.last().spider_time).strftime('%Y-%m-%d %H:%M:%S') # # # P1 地图数据准备(使用xian_poi表) # df_p1 = self.poi_df[~self.poi_df['area'].isna()] # self.map_data = df_p1.groupby("area").count()["name"] # self.map_data = self.map_data.sort_values() # print(self.map_data) # # # P6 数据准备(使用原Scenery表) # self.p6_df = self.scenery_df[~self.scenery_df['play_time'].isna()] # # # p4 # qs = Scenery.objects.exclude(people_percent="0%").all() # self.df_p4 = read_frame(qs=qs) # self.df_p4["people_percent"] = self.df_p4["people_percent"].str.replace("%", "").astype(int) # # # p2 # self.scenery_obj = Scenery.objects.filter(score__isnull=False).exclude(score=0).all().order_by("-score") def get_county(self, full_county_name): county_list = ['碑林区', '新城区', '莲湖区', '灞桥区', '未央区', '雁塔区', '阎良区', '临潼区', '长安区', '蓝田县','周至县','鄠邑区','高陵区'] for i in county_list: if i in full_county_name: return i # def get_p1(self, h, w, is_show=False): # """ # 西安景点分布地图(基于xian_poi表) # """ # # 确保取到的 max_ 是数据中的最大值 # max_ = int(self.map_data.values.max()) if not self.map_data.empty else 0 # # # 确保 map_data 生成方式正确 # map_data = [[area, int(count)] for area, count in zip(self.map_data.index, self.map_data.values)] # # map = ( # Map(init_opts=opts.InitOpts(height=h, width=w)) # .add( # series_name="景点数量", # data_pair=map_data, # maptype="西安市", # 确保这里的地图类型是西安 # is_roam=True, # label_opts=opts.LabelOpts(color="#FFF", is_show=True), # is_map_symbol_show=False # ) # .set_global_opts( # title_opts=opts.TitleOpts(is_show=False,title="title"), # legend_opts=opts.LegendOpts( # is_show=is_show, # textstyle_opts=opts.TextStyleOpts(color="#fff") # ), # visualmap_opts=opts.VisualMapOpts( # max_=max_, # textstyle_opts=opts.TextStyleOpts(color="#fff"), # range_color=["#50a3ba", "#eac736", "#d94e5d"] # ) # ) # .render_embed() # ) # return map def get_p1(self, h, w, is_show=False): """西安景点分布地图""" data = { "阎良区": 0, "周至县": 4, "鄠邑区": 5, "高陵区": 9, "蓝田县": 28, "临潼区": 40, "莲湖区": 46, "灞桥区": 48, "新城区": 52, "碑林区": 67, "未央区": 98, "雁塔区": 127, "长安区": 138, } map_data=pd.Series(data) max_ = int(map_data.values.max()) map = ( Map(init_opts=opts.InitOpts(height=h, width=w,theme=ThemeType.DARK)) .add("景点数量", [[i[0], int(i[1])] for i in zip(map_data.index, map_data.values)], maptype='西安', is_roam=True, label_opts=opts.LabelOpts( color="#FFF", is_show=True, font_size=10, font_style="italic" ), is_map_symbol_show=False, itemstyle_opts=opts.ItemStyleOpts( border_width=0.5, border_color="#444" ) ) .set_global_opts( title_opts=opts.TitleOpts(is_show=False), legend_opts=opts.LegendOpts(is_show=is_show, textstyle_opts=opts.TextStyleOpts(color="#fff")), # 去掉图例 visualmap_opts=opts.VisualMapOpts(max_=max_, textstyle_opts=opts.TextStyleOpts(color="#fff"),range_color=["#2b83ba", "#abdda4", "#ffffbf", "#fdae61", "#d7191c"]) ) .render_embed() ) return map # def get_p1(self, h, w, is_show=False): # """西安景点分布地图(确保所有区县显示)""" # # 完整的区县列表 # full_counties = ['高陵区', '蓝田县', '临潼区', '莲湖区', '灞桥区', # '新城区', '碑林区', '未央区', '雁塔区', '长安区', # '阎良区', '周至县', '鄠邑区'] # # # 创建包含所有区县的DataFrame(缺失值设为0) # df_all = pd.DataFrame(index=full_counties, columns=['count']) # df_all['count'] = 0 # 初始化所有值为0 # # # 更新有数据的区县 # for county in self.map_data.index: # if county in df_all.index: # df_all.loc[county, 'count'] = int(self.map_data[county]) # # # 手动设置您提供的景点数量(覆盖爬取数据) # preset_data = { # '高陵区': 9, # '蓝田县': 28, # '临潼区': 40, # '莲湖区': 46, # '灞桥区': 48, # '新城区': 52, # '碑林区': 67, # '未央区': 98, # '雁塔区': 127, # '长安区': 138 # } # for k, v in preset_data.items(): # df_all.loc[k, 'count'] = v # # # 准备地图数据 # map_data = [[idx, row['count']] for idx, row in df_all.iterrows()] # max_ = df_all['count'].max() # # # 生成地图 # map_chart = ( # Map(init_opts=opts.InitOpts(height=h, width=w)) # .add( # series_name="景点数量", # data_pair=map_data, # maptype="西安", # is_roam=True, # label_opts=opts.LabelOpts(color="#FFF", is_show=True), # is_map_symbol_show=False # ) # .set_global_opts( # title_opts=opts.TitleOpts(is_show=False,title="title"), # legend_opts=opts.LegendOpts( # is_show=is_show, # textstyle_opts=opts.TextStyleOpts(color="#fff") # ), # visualmap_opts=opts.VisualMapOpts( # max_=max_, # textstyle_opts=opts.TextStyleOpts(color="#fff") # ) # ) # .render_embed() # ) # return map_chart def get_p2(self): """景点评分数据表格""" return self.scenery_obj def get_p3(self): """景点浏览人数数据表格""" return self.df_p4.sort_values('people_percent', ascending=False).to_dict("records") # def get_p4(self, h, w, is_show=False): # """景点人数分布""" # sum = self.df_p4["people_percent"].sum() # self.df_p4["percent_p4"] = self.df_p4["people_percent"].map(lambda x: round(float(x)/sum*100, 2)) # # c = ( # Pie(init_opts=opts.InitOpts(height=h, width=w)) # .add("", self.df_p4[["scenery_name", "percent_p4"]].values, # label_opts=opts.LabelOpts(color="#fff", is_show=False)) # .set_global_opts( # legend_opts=opts.LegendOpts(is_show=is_show, textstyle_opts=opts.TextStyleOpts(color="#FFF"))) # .set_series_opts(label_opts=opts.LabelOpts(formatter="{b}: {c}%", color="#FFF")) # .render_embed() # ) # # return c def get_p4(self, h, w, is_show=False): """景点人数分布(优化版)""" sum_percent = self.df_p4["people_percent"].sum() self.df_p4["percent_p4"] = self.df_p4["people_percent"].map( lambda x: round(float(x) / sum_percent * 100, 2) ) # 按百分比排序并取前10名(避免饼图过于拥挤) top10 = self.df_p4.nlargest(10, "percent_p4") pie_chart = ( Pie(init_opts=opts.InitOpts( height=h, width=w )) .add( series_name="游客占比", data_pair=top10[["scenery_name", "percent_p4"]].values, radius=["30%", "70%"], # 环形饼图 center=["50%", "55%"], rosetype="radius", # 南丁格尔玫瑰图 label_opts=opts.LabelOpts( is_show=True, formatter="{b}: {d}%", # 显示名称和百分比 color="#f8f9fa", font_size=10 ) ) .set_global_opts( title_opts=opts.TitleOpts( pos_left="center", title_textstyle_opts=opts.TextStyleOpts( color="#f8f9fa", font_size=18 ) ), legend_opts=opts.LegendOpts( is_show=is_show, orient="vertical", pos_right="5%", textstyle_opts=opts.TextStyleOpts(color="#f8f9fa") ), tooltip_opts=opts.TooltipOpts( trigger="item", formatter="{b}: {c}%" ) ) .set_series_opts( itemstyle_opts=opts.ItemStyleOpts( border_width=1, border_color="#fff" ) ) ) return pie_chart.render_embed() def get_p5(self, h, w, is_show=False): """词云""" import time # start = time.time() words = [] evaluates = Evaluate.objects.all()[:100] for evaluate in evaluates: txt = evaluate.content pattern = re.compile(r"\d+") filtered_text = re.sub(pattern, "", txt) words += jieba.lcut(str(filtered_text)) counts = {} # 创建一个空字典 stopwords = ('0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '的', '是', '在', '等') for word in words: if word not in stopwords: if len(word) <= 1: continue counts[word] = counts.get(word, 0) + 1 excludes = ['...'] for word in excludes: del counts[word] items = list(counts.items()) # 将无序的字典类型转换为可排序的列表类型 items.sort(key=lambda x: x[1], reverse=True) # items = items[:number] # 设置词云图 wordcloud = ( WordCloud(init_opts=opts.InitOpts(height=h, width=w)) .add(series_name="出现数量", data_pair=items, word_size_range=[20, 100], shape=SymbolType.DIAMOND) .set_global_opts( title_opts=opts.TitleOpts(title="评论词云", title_textstyle_opts=opts.TextStyleOpts(font_size=23), is_show=False), legend_opts=opts.LegendOpts(is_show=False, textstyle_opts=opts.TextStyleOpts(color="#fff")), tooltip_opts=opts.TooltipOpts(is_show=True), # 设置白色主题 visualmap_opts=opts.VisualMapOpts(is_show=False, max_=50, min_=0, range_color=["#FFFFFF", "#FFFFFF"]), ) ) return wordcloud.render_embed() def get_play_time1(self, play_time): """格式化时间,全部转为小时(int) - 原功能保留""" if ' - ' in play_time: play_time = play_time.split(' - ')[-1] hour = 0 if '小时' in play_time: hour = float(play_time.replace("小时", "")) elif "天" in play_time: hour = int(play_time.replace("天", "")) * 24 return hour def get_p6(self, h, w, is_show=False): """ 浏览时间折线图(基于原Scenery表) """ qs = Scenery.objects.filter(play_time__isnull=False).all() df_p6 = read_frame(qs) df_p6["play_time"]=df_p6["play_time"].map(lambda x: self.get_play_time1(x)) play_time_data = df_p6.groupby("play_time")["scenery_name"].count() # print(play_time_data) # [[i[0], int(i[1])] for i in zip(map_data.index, map_data.values)] p6 = ( Line(init_opts=opts.InitOpts(height=h, width=w)) .add_xaxis([str(i) + "小时" for i in play_time_data.index.tolist()]) .add_yaxis("景点数量", play_time_data.values.tolist(), is_smooth=True, label_opts=opts.LabelOpts(is_show=is_show, color="#fff")) .set_series_opts( areastyle_opts=opts.AreaStyleOpts(opacity=0.5), label_opts=opts.LabelOpts(is_show=False), ) .set_global_opts( legend_opts=opts.LegendOpts(is_show=is_show, textstyle_opts=opts.TextStyleOpts(color="white")), xaxis_opts=opts.AxisOpts(axislabel_opts=opts.LabelOpts(color="#fff"), axisline_opts=opts.AxisLineOpts( linestyle_opts=opts.LineStyleOpts(color="#fff")), splitline_opts=opts.SplitLineOpts(is_show=True, linestyle_opts=opts.LineStyleOpts( color="#fff")), axistick_opts=opts.AxisTickOpts(is_align_with_label=True), is_scale=False, boundary_gap=False, ), yaxis_opts=opts.AxisOpts(axislabel_opts=opts.LabelOpts(color="#fff"), axisline_opts=opts.AxisLineOpts( linestyle_opts=opts.LineStyleOpts(color="#fff")), splitline_opts=opts.SplitLineOpts(is_show=True, linestyle_opts=opts.LineStyleOpts( color="#fff"))) ) ) return p6.render_embed() def get_p7(self,h, w, is_show=False): """7: 评分折线图""" df_p7 = read_frame(self.scenery_obj) # print(df_p7["scenery_name"].tolist()) p7 = ( Line(init_opts=opts.InitOpts(height=h, width=w)) .add_xaxis(df_p7["scenery_name"].tolist()) .add_yaxis("景点评分", df_p7["score"].tolist(), is_smooth=True, label_opts=opts.LabelOpts(is_show=is_show, color="#fff")) .set_series_opts( areastyle_opts=opts.AreaStyleOpts(opacity=0.5), label_opts=opts.LabelOpts(is_show=False), ) .set_global_opts( legend_opts=opts.LegendOpts(is_show=is_show, textstyle_opts=opts.TextStyleOpts(color="white")), xaxis_opts=opts.AxisOpts(axislabel_opts=opts.LabelOpts(color="#fff"), axisline_opts=opts.AxisLineOpts( linestyle_opts=opts.LineStyleOpts(color="#fff")), splitline_opts=opts.SplitLineOpts(is_show=True, linestyle_opts=opts.LineStyleOpts( color="#fff")), axistick_opts=opts.AxisTickOpts(is_align_with_label=True), is_scale=False, boundary_gap=False, ), yaxis_opts=opts.AxisOpts(axislabel_opts=opts.LabelOpts(color="#fff"), axisline_opts=opts.AxisLineOpts( linestyle_opts=opts.LineStyleOpts(color="#fff")), splitline_opts=opts.SplitLineOpts(is_show=True, linestyle_opts=opts.LineStyleOpts( color="#fff"))) ) ) return p7.render_embed() def get_p8(self,h, w, is_show=False): """8: 景点数量折线图""" p8 = ( Line(init_opts=opts.InitOpts(height=h, width=w)) .add_xaxis(self.map_data.index.tolist()) .add_yaxis("景点数量", self.map_data.values.tolist(), is_smooth=True, label_opts=opts.LabelOpts(is_show=is_show, color="#fff")) .set_series_opts( areastyle_opts=opts.AreaStyleOpts(opacity=0.5), label_opts=opts.LabelOpts(is_show=False), ) .set_global_opts( legend_opts=opts.LegendOpts(is_show=is_show, textstyle_opts=opts.TextStyleOpts(color="white")), xaxis_opts=opts.AxisOpts(axislabel_opts=opts.LabelOpts(color="#fff"), axisline_opts=opts.AxisLineOpts( linestyle_opts=opts.LineStyleOpts(color="#fff")), splitline_opts=opts.SplitLineOpts(is_show=True, linestyle_opts=opts.LineStyleOpts( color="#fff")), axistick_opts=opts.AxisTickOpts(is_align_with_label=True), is_scale=False, boundary_gap=False, ), yaxis_opts=opts.AxisOpts(axislabel_opts=opts.LabelOpts(color="#fff"), axisline_opts=opts.AxisLineOpts( linestyle_opts=opts.LineStyleOpts(color="#fff")), splitline_opts=opts.SplitLineOpts(is_show=True, linestyle_opts=opts.LineStyleOpts( color="#fff"))) ) ) return p8.render_embed()
2301_78696cqk/Django_pyecharts_scrapy
scenery_spider_web-main/mainapp/utils/all_map.py
Python
unknown
21,762
import hashlib """ 对文本进行md5加密 """ def md5(text): hl = hashlib.md5() hl.update(text.encode(encoding='utf8')) md5 = hl.hexdigest() return md5
2301_78696cqk/Django_pyecharts_scrapy
scenery_spider_web-main/mainapp/utils/md5_util.py
Python
unknown
170
import datetime import threading from django.shortcuts import render, redirect from twisted.internet.threads import deferToThread from mainapp import models from mainapp.utils import md5_util from mainapp.utils.all_map import AllMap all_map = AllMap() data = {} index_h = "278px" index_w = "434px" data["spider_time"] = all_map.spider_time data["p1"] = all_map.get_p1("610px", "900px") data["p2"] = all_map.get_p2() data["p3"] = all_map.get_p3() data["p4"] = all_map.get_p4(index_h, index_w) data["p5"] = all_map.get_p5(index_h, index_w) data["p6"] = all_map.get_p6(index_h, index_w) data["p7"] = all_map.get_p7(index_h, "898px") data["p8"] = all_map.get_p8(index_h, index_w) page_h = "753px" page_w = "1328px" is_show = True p1 = all_map.get_p1(page_h, page_w, is_show) p4 = all_map.get_p4(page_h, page_w, is_show) p5 = all_map.get_p5(page_h, page_w, is_show) p6 = all_map.get_p6(page_h, page_w, is_show) p7 = all_map.get_p7(page_h, page_w, is_show) p8 = all_map.get_p8(page_h, page_w, is_show) map_list = {"西安景点分布":p1, "景点评分数据": data["p2"], "景点浏览人数": data["p3"], "Top10景点人数分布": p4, "景点评论词云": p5, "景点浏览时间": p6, "景点数量": p7, "景点评分": p8} def index(request): return render(request, "index.html", data) def page(request): result = { "is_chart": True, "spider_time": all_map.spider_time } page = request.GET.get("p") if not page: page = 0 else: page = int(page) - 1 result["title"] = list(map_list.keys())[page] result['data'] = map_list.get(result["title"]) result['page_data'] = map_list if page in [1,2]: result["is_chart"] = False return render(request, 'page/index.html', result) """ 登陆 """ def login(request): temp_txt = { "tip": "请登录", "username": "用户名", "password": "密码", "remember": "记住密码", "login": "登陆", "go": "去注册", "year": datetime.datetime.now().year, "next_year": int(datetime.datetime.now().year) + 1, "error": '' } if request.method == 'GET': return render(request, "login.html", temp_txt) if request.method == 'POST': #请求登陆 concat = request.POST username = concat["username"] password = md5_util.md5(concat["password"]) user = models.Userinfo.objects.filter(username=username, password=password).first() if user: request.session.setdefault("user_info", username) return redirect("/index") else: request.method = "GET" temp_txt['error'] = "用户名或密码错误" return render(request, "login.html", temp_txt) """ 注册 """ def register(request): temp_txt = { "tip": "注册用户", "username": "用户名", "password": "密码", "login": "注册", "go": "去登陆", "year": datetime.datetime.now().year, "next_year": int(datetime.datetime.now().year) + 1, 'error':'' } if request.method == 'GET': return render(request, "register.html", temp_txt) elif request.method == 'POST': # 注册请求接口 # 获取用户名和密码 concat = request.POST username = concat["username"] password = concat["password"] repassword = concat["repassword"] if 3 > len(username) > 16: temp_txt["error"] = "用户名过长或过短!" elif repassword != password: temp_txt['error'] = "密码不一致!" elif models.Userinfo.objects.filter(username=username).first(): temp_txt['error'] = "用户名已存在!" elif 16 < len(password) or len(password) < 6: temp_txt["error"] = "密码长度小于6或大于16" if temp_txt['error']: request.method = "GET" return render(request, 'register.html', temp_txt) # 加密 password = md5_util.md5(password) result = models.Userinfo.objects.create(username=username, password=password) print(f"result:{result}") return redirect("/login")
2301_78696cqk/Django_pyecharts_scrapy
scenery_spider_web-main/mainapp/views.py
Python
unknown
4,217
import os import sys def main(): """Run administrative tasks.""" os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'hunan_web.settings') try: from django.core.management import execute_from_command_line except ImportError as exc: raise ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your PYTHONPATH environment variable? Did you " "forget to activate a virtual environment?" ) from exc execute_from_command_line(sys.argv) if __name__ == '__main__': main()
2301_78696cqk/Django_pyecharts_scrapy
scenery_spider_web-main/manage.py
Python
unknown
582
# Define here the models for your scraped items # # See documentation in: # https://docs.scrapy.org/en/latest/topics/items.html import scrapy from warehouse.models import Scenery, Evaluate from scrapy_djangoitem import DjangoItem class SpiderSceneryItem(DjangoItem): django_model = Scenery class SpiderEvaluteItem(DjangoItem): django_model = Evaluate """ 景点实体类 """ # class SpiderSceneryItem(scrapy.Item): # # define the fields for your item here like: # # name = scrapy.Field() # # 景点名称,人数百分比,景点排名,评分,建议浏览时间 # scenery_name = scrapy.Field() # people_percent = scrapy.Field() # rank = scrapy.Field() # score = scrapy.Field() # play_time = scrapy.Field() # city = scrapy.Field() # # # """ # 评论实体类 # """ # class SpiderEvaluteItem(scrapy.Item): # content = scrapy.Field() # 内容 # send_time = scrapy.Field() # 评论时间 # user_name = scrapy.Field() # 用户名 # score = scrapy.Field() # 评分 # scenery_name = scrapy.Field() # 景点id
2301_78696cqk/Django_pyecharts_scrapy
scenery_spider_web-main/spider_qunaer/items.py
Python
unknown
1,083