repo_id
stringlengths
6
101
file_path
stringlengths
2
269
content
stringlengths
367
5.14M
size
int64
367
5.14M
filename
stringlengths
1
248
ext
stringlengths
0
87
lang
stringclasses
88 values
program_lang
stringclasses
232 values
doc_type
stringclasses
5 values
quality_signal
stringlengths
2
1.9k
effective
stringclasses
2 values
hit_map
stringlengths
2
1.4k
0015/esp_rlottie
rlottie/src/lottie/rapidjson/writer.h
// Tencent is pleased to support the open source community by making RapidJSON available. // // Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip. All rights reserved. // // Licensed under the MIT License (the "License"); you may not use this file except // in compliance with the License. You may obtain a copy of the License at // // http://opensource.org/licenses/MIT // // Unless required by applicable law or agreed to in writing, software distributed // under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR // CONDITIONS OF ANY KIND, either express or implied. See the License for the // specific language governing permissions and limitations under the License. #ifndef RAPIDJSON_WRITER_H_ #define RAPIDJSON_WRITER_H_ #include "stream.h" #include "internal/clzll.h" #include "internal/meta.h" #include "internal/stack.h" #include "internal/strfunc.h" #include "internal/dtoa.h" #include "internal/itoa.h" #include "stringbuffer.h" #include <new> // placement new #if defined(RAPIDJSON_SIMD) && defined(_MSC_VER) #include <intrin.h> #pragma intrinsic(_BitScanForward) #endif #ifdef RAPIDJSON_SSE42 #include <nmmintrin.h> #elif defined(RAPIDJSON_SSE2) #include <emmintrin.h> #elif defined(RAPIDJSON_NEON) #include <arm_neon.h> #endif #ifdef __clang__ RAPIDJSON_DIAG_PUSH RAPIDJSON_DIAG_OFF(padded) RAPIDJSON_DIAG_OFF(unreachable-code) RAPIDJSON_DIAG_OFF(c++98-compat) #elif defined(_MSC_VER) RAPIDJSON_DIAG_PUSH RAPIDJSON_DIAG_OFF(4127) // conditional expression is constant #endif RAPIDJSON_NAMESPACE_BEGIN /////////////////////////////////////////////////////////////////////////////// // WriteFlag /*! \def RAPIDJSON_WRITE_DEFAULT_FLAGS \ingroup RAPIDJSON_CONFIG \brief User-defined kWriteDefaultFlags definition. User can define this as any \c WriteFlag combinations. */ #ifndef RAPIDJSON_WRITE_DEFAULT_FLAGS #define RAPIDJSON_WRITE_DEFAULT_FLAGS kWriteNoFlags #endif //! Combination of writeFlags enum WriteFlag { kWriteNoFlags = 0, //!< No flags are set. kWriteValidateEncodingFlag = 1, //!< Validate encoding of JSON strings. kWriteNanAndInfFlag = 2, //!< Allow writing of Infinity, -Infinity and NaN. kWriteDefaultFlags = RAPIDJSON_WRITE_DEFAULT_FLAGS //!< Default write flags. Can be customized by defining RAPIDJSON_WRITE_DEFAULT_FLAGS }; //! JSON writer /*! Writer implements the concept Handler. It generates JSON text by events to an output os. User may programmatically calls the functions of a writer to generate JSON text. On the other side, a writer can also be passed to objects that generates events, for example Reader::Parse() and Document::Accept(). \tparam OutputStream Type of output stream. \tparam SourceEncoding Encoding of source string. \tparam TargetEncoding Encoding of output stream. \tparam StackAllocator Type of allocator for allocating memory of stack. \note implements Handler concept */ template<typename OutputStream, typename SourceEncoding = UTF8<>, typename TargetEncoding = UTF8<>, typename StackAllocator = CrtAllocator, unsigned writeFlags = kWriteDefaultFlags> class Writer { public: typedef typename SourceEncoding::Ch Ch; static const int kDefaultMaxDecimalPlaces = 324; //! Constructor /*! \param os Output stream. \param stackAllocator User supplied allocator. If it is null, it will create a private one. \param levelDepth Initial capacity of stack. */ explicit Writer(OutputStream& os, StackAllocator* stackAllocator = 0, size_t levelDepth = kDefaultLevelDepth) : os_(&os), level_stack_(stackAllocator, levelDepth * sizeof(Level)), maxDecimalPlaces_(kDefaultMaxDecimalPlaces), hasRoot_(false) {} explicit Writer(StackAllocator* allocator = 0, size_t levelDepth = kDefaultLevelDepth) : os_(0), level_stack_(allocator, levelDepth * sizeof(Level)), maxDecimalPlaces_(kDefaultMaxDecimalPlaces), hasRoot_(false) {} #if RAPIDJSON_HAS_CXX11_RVALUE_REFS Writer(Writer&& rhs) : os_(rhs.os_), level_stack_(std::move(rhs.level_stack_)), maxDecimalPlaces_(rhs.maxDecimalPlaces_), hasRoot_(rhs.hasRoot_) { rhs.os_ = 0; } #endif //! Reset the writer with a new stream. /*! This function reset the writer with a new stream and default settings, in order to make a Writer object reusable for output multiple JSONs. \param os New output stream. \code Writer<OutputStream> writer(os1); writer.StartObject(); // ... writer.EndObject(); writer.Reset(os2); writer.StartObject(); // ... writer.EndObject(); \endcode */ void Reset(OutputStream& os) { os_ = &os; hasRoot_ = false; level_stack_.Clear(); } //! Checks whether the output is a complete JSON. /*! A complete JSON has a complete root object or array. */ bool IsComplete() const { return hasRoot_ && level_stack_.Empty(); } int GetMaxDecimalPlaces() const { return maxDecimalPlaces_; } //! Sets the maximum number of decimal places for double output. /*! This setting truncates the output with specified number of decimal places. For example, \code writer.SetMaxDecimalPlaces(3); writer.StartArray(); writer.Double(0.12345); // "0.123" writer.Double(0.0001); // "0.0" writer.Double(1.234567890123456e30); // "1.234567890123456e30" (do not truncate significand for positive exponent) writer.Double(1.23e-4); // "0.0" (do truncate significand for negative exponent) writer.EndArray(); \endcode The default setting does not truncate any decimal places. You can restore to this setting by calling \code writer.SetMaxDecimalPlaces(Writer::kDefaultMaxDecimalPlaces); \endcode */ void SetMaxDecimalPlaces(int maxDecimalPlaces) { maxDecimalPlaces_ = maxDecimalPlaces; } /*!@name Implementation of Handler \see Handler */ //@{ bool Null() { Prefix(kNullType); return EndValue(WriteNull()); } bool Bool(bool b) { Prefix(b ? kTrueType : kFalseType); return EndValue(WriteBool(b)); } bool Int(int i) { Prefix(kNumberType); return EndValue(WriteInt(i)); } bool Uint(unsigned u) { Prefix(kNumberType); return EndValue(WriteUint(u)); } bool Int64(int64_t i64) { Prefix(kNumberType); return EndValue(WriteInt64(i64)); } bool Uint64(uint64_t u64) { Prefix(kNumberType); return EndValue(WriteUint64(u64)); } //! Writes the given \c double value to the stream /*! \param d The value to be written. \return Whether it is succeed. */ bool Double(double d) { Prefix(kNumberType); return EndValue(WriteDouble(d)); } bool RawNumber(const Ch* str, SizeType length, bool copy = false) { RAPIDJSON_ASSERT(str != 0); (void)copy; Prefix(kNumberType); return EndValue(WriteString(str, length)); } bool String(const Ch* str, SizeType length, bool copy = false) { RAPIDJSON_ASSERT(str != 0); (void)copy; Prefix(kStringType); return EndValue(WriteString(str, length)); } #if RAPIDJSON_HAS_STDSTRING bool String(const std::basic_string<Ch>& str) { return String(str.data(), SizeType(str.size())); } #endif bool StartObject() { Prefix(kObjectType); new (level_stack_.template Push<Level>()) Level(false); return WriteStartObject(); } bool Key(const Ch* str, SizeType length, bool copy = false) { return String(str, length, copy); } #if RAPIDJSON_HAS_STDSTRING bool Key(const std::basic_string<Ch>& str) { return Key(str.data(), SizeType(str.size())); } #endif bool EndObject(SizeType memberCount = 0) { (void)memberCount; RAPIDJSON_ASSERT(level_stack_.GetSize() >= sizeof(Level)); // not inside an Object RAPIDJSON_ASSERT(!level_stack_.template Top<Level>()->inArray); // currently inside an Array, not Object RAPIDJSON_ASSERT(0 == level_stack_.template Top<Level>()->valueCount % 2); // Object has a Key without a Value level_stack_.template Pop<Level>(1); return EndValue(WriteEndObject()); } bool StartArray() { Prefix(kArrayType); new (level_stack_.template Push<Level>()) Level(true); return WriteStartArray(); } bool EndArray(SizeType elementCount = 0) { (void)elementCount; RAPIDJSON_ASSERT(level_stack_.GetSize() >= sizeof(Level)); RAPIDJSON_ASSERT(level_stack_.template Top<Level>()->inArray); level_stack_.template Pop<Level>(1); return EndValue(WriteEndArray()); } //@} /*! @name Convenience extensions */ //@{ //! Simpler but slower overload. bool String(const Ch* const& str) { return String(str, internal::StrLen(str)); } bool Key(const Ch* const& str) { return Key(str, internal::StrLen(str)); } //@} //! Write a raw JSON value. /*! For user to write a stringified JSON as a value. \param json A well-formed JSON value. It should not contain null character within [0, length - 1] range. \param length Length of the json. \param type Type of the root of json. */ bool RawValue(const Ch* json, size_t length, Type type) { RAPIDJSON_ASSERT(json != 0); Prefix(type); return EndValue(WriteRawValue(json, length)); } //! Flush the output stream. /*! Allows the user to flush the output stream immediately. */ void Flush() { os_->Flush(); } static const size_t kDefaultLevelDepth = 32; protected: //! Information for each nested level struct Level { Level(bool inArray_) : valueCount(0), inArray(inArray_) {} size_t valueCount; //!< number of values in this level bool inArray; //!< true if in array, otherwise in object }; bool WriteNull() { PutReserve(*os_, 4); PutUnsafe(*os_, 'n'); PutUnsafe(*os_, 'u'); PutUnsafe(*os_, 'l'); PutUnsafe(*os_, 'l'); return true; } bool WriteBool(bool b) { if (b) { PutReserve(*os_, 4); PutUnsafe(*os_, 't'); PutUnsafe(*os_, 'r'); PutUnsafe(*os_, 'u'); PutUnsafe(*os_, 'e'); } else { PutReserve(*os_, 5); PutUnsafe(*os_, 'f'); PutUnsafe(*os_, 'a'); PutUnsafe(*os_, 'l'); PutUnsafe(*os_, 's'); PutUnsafe(*os_, 'e'); } return true; } bool WriteInt(int i) { char buffer[11]; const char* end = internal::i32toa(i, buffer); PutReserve(*os_, static_cast<size_t>(end - buffer)); for (const char* p = buffer; p != end; ++p) PutUnsafe(*os_, static_cast<typename OutputStream::Ch>(*p)); return true; } bool WriteUint(unsigned u) { char buffer[10]; const char* end = internal::u32toa(u, buffer); PutReserve(*os_, static_cast<size_t>(end - buffer)); for (const char* p = buffer; p != end; ++p) PutUnsafe(*os_, static_cast<typename OutputStream::Ch>(*p)); return true; } bool WriteInt64(int64_t i64) { char buffer[21]; const char* end = internal::i64toa(i64, buffer); PutReserve(*os_, static_cast<size_t>(end - buffer)); for (const char* p = buffer; p != end; ++p) PutUnsafe(*os_, static_cast<typename OutputStream::Ch>(*p)); return true; } bool WriteUint64(uint64_t u64) { char buffer[20]; char* end = internal::u64toa(u64, buffer); PutReserve(*os_, static_cast<size_t>(end - buffer)); for (char* p = buffer; p != end; ++p) PutUnsafe(*os_, static_cast<typename OutputStream::Ch>(*p)); return true; } bool WriteDouble(double d) { if (internal::Double(d).IsNanOrInf()) { if (!(writeFlags & kWriteNanAndInfFlag)) return false; if (internal::Double(d).IsNan()) { PutReserve(*os_, 3); PutUnsafe(*os_, 'N'); PutUnsafe(*os_, 'a'); PutUnsafe(*os_, 'N'); return true; } if (internal::Double(d).Sign()) { PutReserve(*os_, 9); PutUnsafe(*os_, '-'); } else PutReserve(*os_, 8); PutUnsafe(*os_, 'I'); PutUnsafe(*os_, 'n'); PutUnsafe(*os_, 'f'); PutUnsafe(*os_, 'i'); PutUnsafe(*os_, 'n'); PutUnsafe(*os_, 'i'); PutUnsafe(*os_, 't'); PutUnsafe(*os_, 'y'); return true; } char buffer[25]; char* end = internal::dtoa(d, buffer, maxDecimalPlaces_); PutReserve(*os_, static_cast<size_t>(end - buffer)); for (char* p = buffer; p != end; ++p) PutUnsafe(*os_, static_cast<typename OutputStream::Ch>(*p)); return true; } bool WriteString(const Ch* str, SizeType length) { static const typename OutputStream::Ch hexDigits[16] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' }; static const char escape[256] = { #define Z16 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 //0 1 2 3 4 5 6 7 8 9 A B C D E F 'u', 'u', 'u', 'u', 'u', 'u', 'u', 'u', 'b', 't', 'n', 'u', 'f', 'r', 'u', 'u', // 00 'u', 'u', 'u', 'u', 'u', 'u', 'u', 'u', 'u', 'u', 'u', 'u', 'u', 'u', 'u', 'u', // 10 0, 0, '"', 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 20 Z16, Z16, // 30~4F 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,'\\', 0, 0, 0, // 50 Z16, Z16, Z16, Z16, Z16, Z16, Z16, Z16, Z16, Z16 // 60~FF #undef Z16 }; if (TargetEncoding::supportUnicode) PutReserve(*os_, 2 + length * 6); // "\uxxxx..." else PutReserve(*os_, 2 + length * 12); // "\uxxxx\uyyyy..." PutUnsafe(*os_, '\"'); GenericStringStream<SourceEncoding> is(str); while (ScanWriteUnescapedString(is, length)) { const Ch c = is.Peek(); if (!TargetEncoding::supportUnicode && static_cast<unsigned>(c) >= 0x80) { // Unicode escaping unsigned codepoint; if (RAPIDJSON_UNLIKELY(!SourceEncoding::Decode(is, &codepoint))) return false; PutUnsafe(*os_, '\\'); PutUnsafe(*os_, 'u'); if (codepoint <= 0xD7FF || (codepoint >= 0xE000 && codepoint <= 0xFFFF)) { PutUnsafe(*os_, hexDigits[(codepoint >> 12) & 15]); PutUnsafe(*os_, hexDigits[(codepoint >> 8) & 15]); PutUnsafe(*os_, hexDigits[(codepoint >> 4) & 15]); PutUnsafe(*os_, hexDigits[(codepoint ) & 15]); } else { RAPIDJSON_ASSERT(codepoint >= 0x010000 && codepoint <= 0x10FFFF); // Surrogate pair unsigned s = codepoint - 0x010000; unsigned lead = (s >> 10) + 0xD800; unsigned trail = (s & 0x3FF) + 0xDC00; PutUnsafe(*os_, hexDigits[(lead >> 12) & 15]); PutUnsafe(*os_, hexDigits[(lead >> 8) & 15]); PutUnsafe(*os_, hexDigits[(lead >> 4) & 15]); PutUnsafe(*os_, hexDigits[(lead ) & 15]); PutUnsafe(*os_, '\\'); PutUnsafe(*os_, 'u'); PutUnsafe(*os_, hexDigits[(trail >> 12) & 15]); PutUnsafe(*os_, hexDigits[(trail >> 8) & 15]); PutUnsafe(*os_, hexDigits[(trail >> 4) & 15]); PutUnsafe(*os_, hexDigits[(trail ) & 15]); } } else if ((sizeof(Ch) == 1 || static_cast<unsigned>(c) < 256) && RAPIDJSON_UNLIKELY(escape[static_cast<unsigned char>(c)])) { is.Take(); PutUnsafe(*os_, '\\'); PutUnsafe(*os_, static_cast<typename OutputStream::Ch>(escape[static_cast<unsigned char>(c)])); if (escape[static_cast<unsigned char>(c)] == 'u') { PutUnsafe(*os_, '0'); PutUnsafe(*os_, '0'); PutUnsafe(*os_, hexDigits[static_cast<unsigned char>(c) >> 4]); PutUnsafe(*os_, hexDigits[static_cast<unsigned char>(c) & 0xF]); } } else if (RAPIDJSON_UNLIKELY(!(writeFlags & kWriteValidateEncodingFlag ? Transcoder<SourceEncoding, TargetEncoding>::Validate(is, *os_) : Transcoder<SourceEncoding, TargetEncoding>::TranscodeUnsafe(is, *os_)))) return false; } PutUnsafe(*os_, '\"'); return true; } bool ScanWriteUnescapedString(GenericStringStream<SourceEncoding>& is, size_t length) { return RAPIDJSON_LIKELY(is.Tell() < length); } bool WriteStartObject() { os_->Put('{'); return true; } bool WriteEndObject() { os_->Put('}'); return true; } bool WriteStartArray() { os_->Put('['); return true; } bool WriteEndArray() { os_->Put(']'); return true; } bool WriteRawValue(const Ch* json, size_t length) { PutReserve(*os_, length); GenericStringStream<SourceEncoding> is(json); while (RAPIDJSON_LIKELY(is.Tell() < length)) { RAPIDJSON_ASSERT(is.Peek() != '\0'); if (RAPIDJSON_UNLIKELY(!(writeFlags & kWriteValidateEncodingFlag ? Transcoder<SourceEncoding, TargetEncoding>::Validate(is, *os_) : Transcoder<SourceEncoding, TargetEncoding>::TranscodeUnsafe(is, *os_)))) return false; } return true; } void Prefix(Type type) { (void)type; if (RAPIDJSON_LIKELY(level_stack_.GetSize() != 0)) { // this value is not at root Level* level = level_stack_.template Top<Level>(); if (level->valueCount > 0) { if (level->inArray) os_->Put(','); // add comma if it is not the first element in array else // in object os_->Put((level->valueCount % 2 == 0) ? ',' : ':'); } if (!level->inArray && level->valueCount % 2 == 0) RAPIDJSON_ASSERT(type == kStringType); // if it's in object, then even number should be a name level->valueCount++; } else { RAPIDJSON_ASSERT(!hasRoot_); // Should only has one and only one root. hasRoot_ = true; } } // Flush the value if it is the top level one. bool EndValue(bool ret) { if (RAPIDJSON_UNLIKELY(level_stack_.Empty())) // end of json text Flush(); return ret; } OutputStream* os_; internal::Stack<StackAllocator> level_stack_; int maxDecimalPlaces_; bool hasRoot_; private: // Prohibit copy constructor & assignment operator. Writer(const Writer&); Writer& operator=(const Writer&); }; // Full specialization for StringStream to prevent memory copying template<> inline bool Writer<StringBuffer>::WriteInt(int i) { char *buffer = os_->Push(11); const char* end = internal::i32toa(i, buffer); os_->Pop(static_cast<size_t>(11 - (end - buffer))); return true; } template<> inline bool Writer<StringBuffer>::WriteUint(unsigned u) { char *buffer = os_->Push(10); const char* end = internal::u32toa(u, buffer); os_->Pop(static_cast<size_t>(10 - (end - buffer))); return true; } template<> inline bool Writer<StringBuffer>::WriteInt64(int64_t i64) { char *buffer = os_->Push(21); const char* end = internal::i64toa(i64, buffer); os_->Pop(static_cast<size_t>(21 - (end - buffer))); return true; } template<> inline bool Writer<StringBuffer>::WriteUint64(uint64_t u) { char *buffer = os_->Push(20); const char* end = internal::u64toa(u, buffer); os_->Pop(static_cast<size_t>(20 - (end - buffer))); return true; } template<> inline bool Writer<StringBuffer>::WriteDouble(double d) { if (internal::Double(d).IsNanOrInf()) { // Note: This code path can only be reached if (RAPIDJSON_WRITE_DEFAULT_FLAGS & kWriteNanAndInfFlag). if (!(kWriteDefaultFlags & kWriteNanAndInfFlag)) return false; if (internal::Double(d).IsNan()) { PutReserve(*os_, 3); PutUnsafe(*os_, 'N'); PutUnsafe(*os_, 'a'); PutUnsafe(*os_, 'N'); return true; } if (internal::Double(d).Sign()) { PutReserve(*os_, 9); PutUnsafe(*os_, '-'); } else PutReserve(*os_, 8); PutUnsafe(*os_, 'I'); PutUnsafe(*os_, 'n'); PutUnsafe(*os_, 'f'); PutUnsafe(*os_, 'i'); PutUnsafe(*os_, 'n'); PutUnsafe(*os_, 'i'); PutUnsafe(*os_, 't'); PutUnsafe(*os_, 'y'); return true; } char *buffer = os_->Push(25); char* end = internal::dtoa(d, buffer, maxDecimalPlaces_); os_->Pop(static_cast<size_t>(25 - (end - buffer))); return true; } #if defined(RAPIDJSON_SSE2) || defined(RAPIDJSON_SSE42) template<> inline bool Writer<StringBuffer>::ScanWriteUnescapedString(StringStream& is, size_t length) { if (length < 16) return RAPIDJSON_LIKELY(is.Tell() < length); if (!RAPIDJSON_LIKELY(is.Tell() < length)) return false; const char* p = is.src_; const char* end = is.head_ + length; const char* nextAligned = reinterpret_cast<const char*>((reinterpret_cast<size_t>(p) + 15) & static_cast<size_t>(~15)); const char* endAligned = reinterpret_cast<const char*>(reinterpret_cast<size_t>(end) & static_cast<size_t>(~15)); if (nextAligned > end) return true; while (p != nextAligned) if (*p < 0x20 || *p == '\"' || *p == '\\') { is.src_ = p; return RAPIDJSON_LIKELY(is.Tell() < length); } else os_->PutUnsafe(*p++); // The rest of string using SIMD static const char dquote[16] = { '\"', '\"', '\"', '\"', '\"', '\"', '\"', '\"', '\"', '\"', '\"', '\"', '\"', '\"', '\"', '\"' }; static const char bslash[16] = { '\\', '\\', '\\', '\\', '\\', '\\', '\\', '\\', '\\', '\\', '\\', '\\', '\\', '\\', '\\', '\\' }; static const char space[16] = { 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F }; const __m128i dq = _mm_loadu_si128(reinterpret_cast<const __m128i *>(&dquote[0])); const __m128i bs = _mm_loadu_si128(reinterpret_cast<const __m128i *>(&bslash[0])); const __m128i sp = _mm_loadu_si128(reinterpret_cast<const __m128i *>(&space[0])); for (; p != endAligned; p += 16) { const __m128i s = _mm_load_si128(reinterpret_cast<const __m128i *>(p)); const __m128i t1 = _mm_cmpeq_epi8(s, dq); const __m128i t2 = _mm_cmpeq_epi8(s, bs); const __m128i t3 = _mm_cmpeq_epi8(_mm_max_epu8(s, sp), sp); // s < 0x20 <=> max(s, 0x1F) == 0x1F const __m128i x = _mm_or_si128(_mm_or_si128(t1, t2), t3); unsigned short r = static_cast<unsigned short>(_mm_movemask_epi8(x)); if (RAPIDJSON_UNLIKELY(r != 0)) { // some of characters is escaped SizeType len; #ifdef _MSC_VER // Find the index of first escaped unsigned long offset; _BitScanForward(&offset, r); len = offset; #else len = static_cast<SizeType>(__builtin_ffs(r) - 1); #endif char* q = reinterpret_cast<char*>(os_->PushUnsafe(len)); for (size_t i = 0; i < len; i++) q[i] = p[i]; p += len; break; } _mm_storeu_si128(reinterpret_cast<__m128i *>(os_->PushUnsafe(16)), s); } is.src_ = p; return RAPIDJSON_LIKELY(is.Tell() < length); } #elif defined(RAPIDJSON_NEON) template<> inline bool Writer<StringBuffer>::ScanWriteUnescapedString(StringStream& is, size_t length) { if (length < 16) return RAPIDJSON_LIKELY(is.Tell() < length); if (!RAPIDJSON_LIKELY(is.Tell() < length)) return false; const char* p = is.src_; const char* end = is.head_ + length; const char* nextAligned = reinterpret_cast<const char*>((reinterpret_cast<size_t>(p) + 15) & static_cast<size_t>(~15)); const char* endAligned = reinterpret_cast<const char*>(reinterpret_cast<size_t>(end) & static_cast<size_t>(~15)); if (nextAligned > end) return true; while (p != nextAligned) if (*p < 0x20 || *p == '\"' || *p == '\\') { is.src_ = p; return RAPIDJSON_LIKELY(is.Tell() < length); } else os_->PutUnsafe(*p++); // The rest of string using SIMD const uint8x16_t s0 = vmovq_n_u8('"'); const uint8x16_t s1 = vmovq_n_u8('\\'); const uint8x16_t s2 = vmovq_n_u8('\b'); const uint8x16_t s3 = vmovq_n_u8(32); for (; p != endAligned; p += 16) { const uint8x16_t s = vld1q_u8(reinterpret_cast<const uint8_t *>(p)); uint8x16_t x = vceqq_u8(s, s0); x = vorrq_u8(x, vceqq_u8(s, s1)); x = vorrq_u8(x, vceqq_u8(s, s2)); x = vorrq_u8(x, vcltq_u8(s, s3)); x = vrev64q_u8(x); // Rev in 64 uint64_t low = vgetq_lane_u64(vreinterpretq_u64_u8(x), 0); // extract uint64_t high = vgetq_lane_u64(vreinterpretq_u64_u8(x), 1); // extract SizeType len = 0; bool escaped = false; if (low == 0) { if (high != 0) { uint32_t lz = internal::clzll(high); len = 8 + (lz >> 3); escaped = true; } } else { uint32_t lz = internal::clzll(low); len = lz >> 3; escaped = true; } if (RAPIDJSON_UNLIKELY(escaped)) { // some of characters is escaped char* q = reinterpret_cast<char*>(os_->PushUnsafe(len)); for (size_t i = 0; i < len; i++) q[i] = p[i]; p += len; break; } vst1q_u8(reinterpret_cast<uint8_t *>(os_->PushUnsafe(16)), s); } is.src_ = p; return RAPIDJSON_LIKELY(is.Tell() < length); } #endif // RAPIDJSON_NEON RAPIDJSON_NAMESPACE_END #if defined(_MSC_VER) || defined(__clang__) RAPIDJSON_DIAG_POP #endif #endif // RAPIDJSON_RAPIDJSON_H_
26,877
writer
h
en
c
code
{"qsc_code_num_words": 3053, "qsc_code_num_chars": 26877.0, "qsc_code_mean_word_length": 4.9354733, "qsc_code_frac_words_unique": 0.17720275, "qsc_code_frac_chars_top_2grams": 0.04818158, "qsc_code_frac_chars_top_3grams": 0.00816299, "qsc_code_frac_chars_top_4grams": 0.0100876, "qsc_code_frac_chars_dupe_5grams": 0.4301168, "qsc_code_frac_chars_dupe_6grams": 0.35147332, "qsc_code_frac_chars_dupe_7grams": 0.32041412, "qsc_code_frac_chars_dupe_8grams": 0.26931245, "qsc_code_frac_chars_dupe_9grams": 0.22086541, "qsc_code_frac_chars_dupe_10grams": 0.20427396, "qsc_code_frac_chars_replacement_symbols": 0.0, "qsc_code_frac_chars_digital": 0.03336088, "qsc_code_frac_chars_whitespace": 0.27953269, "qsc_code_size_file_byte": 26877.0, "qsc_code_num_lines": 710.0, "qsc_code_num_chars_line_max": 182.0, "qsc_code_num_chars_line_mean": 37.85492958, "qsc_code_frac_chars_alphabet": 0.74478414, "qsc_code_frac_chars_comments": 0.20344532, "qsc_code_cate_xml_start": 0.0, "qsc_code_frac_lines_dupe_lines": 0.35355649, "qsc_code_cate_autogen": 0.0, "qsc_code_frac_lines_long_string": 0.0, "qsc_code_frac_chars_string_length": 0.01429305, "qsc_code_frac_chars_long_word_length": 0.0, "qsc_code_frac_lines_string_concat": 0.0, "qsc_code_cate_encoded_data": 0.0, "qsc_code_frac_chars_hex_words": 0.00644589, "qsc_code_frac_lines_prompt_comments": 0.0, "qsc_code_frac_lines_assert": 0.0209205, "qsc_codec_frac_lines_func_ratio": 0.17573222, "qsc_codec_cate_bitsstdc": 0.0, "qsc_codec_nums_lines_main": 0, "qsc_codec_frac_lines_goto": 0.0, "qsc_codec_cate_var_zero": 0.0, "qsc_codec_score_lines_no_logic": 0.26778243, "qsc_codec_frac_lines_print": 0.0, "qsc_codec_frac_lines_preprocessor_directives": null}
1
{"qsc_code_frac_chars_replacement_symbols": 0, "qsc_code_num_words": 0, "qsc_code_num_chars": 0, "qsc_code_mean_word_length": 0, "qsc_code_frac_chars_top_2grams": 0, "qsc_code_frac_chars_top_3grams": 0, "qsc_code_frac_chars_top_4grams": 0, "qsc_code_frac_chars_dupe_5grams": 0, "qsc_code_frac_chars_dupe_6grams": 0, "qsc_code_frac_chars_dupe_7grams": 0, "qsc_code_frac_chars_dupe_8grams": 0, "qsc_code_frac_chars_dupe_9grams": 0, "qsc_code_frac_chars_dupe_10grams": 0, "qsc_code_size_file_byte": 0, "qsc_code_num_lines": 0, "qsc_code_num_chars_line_max": 0, "qsc_code_num_chars_line_mean": 0, "qsc_code_frac_chars_alphabet": 0, "qsc_code_frac_chars_digital": 0, "qsc_code_frac_chars_whitespace": 0, "qsc_code_frac_chars_comments": 0, "qsc_code_cate_xml_start": 0, "qsc_code_frac_lines_dupe_lines": 0, "qsc_code_cate_autogen": 0, "qsc_code_frac_lines_long_string": 0, "qsc_code_frac_chars_string_length": 0, "qsc_code_frac_chars_long_word_length": 0, "qsc_code_cate_encoded_data": 0, "qsc_code_frac_chars_hex_words": 0, "qsc_code_frac_lines_prompt_comments": 0, "qsc_code_frac_lines_assert": 0, "qsc_codec_frac_lines_func_ratio": 0, "qsc_codec_nums_lines_main": 0, "qsc_codec_score_lines_no_logic": 0, "qsc_codec_frac_lines_preprocessor_directives": 0, "qsc_codec_frac_lines_print": 0}
0015/TP_Arduino_DigitalRain_Anim
README.md
# Digital Rain Animation(A.K.A Matrix Effect) for ESP32 Displays <div align="center"> [![Matrix Prism](./misc/matrix_prism.gif)](https://youtu.be/49H7vtQmagQ) </div> Bring the iconic Matrix-style digital rain animation to life on your ESP32-powered display! This library supports popular graphics drivers like **TFT_eSPI**, **LovyanGFX**, and **Arduino_GFX** (Adafruit GFX), making it easy to integrate with a wide range of displays. --- ## Demo Videos Click the thumbnails below to see the animation in action: [![v2.0 demo](https://github.com/0015/TP_Arduino_DigitalRain_Anim/blob/main/misc/v2.0.jpg)](https://youtu.be/1qTgspF4SPc) [![video preview](https://github.com/0015/TP_Arduino_DigitalRain_Anim/blob/main/misc/image.jpg)](https://youtu.be/i6gGK4L4Yv8) [![TTGO demo](https://github.com/0015/TP_Arduino_DigitalRain_Anim/blob/main/misc/ttgo.jpg)](https://youtu.be/uexWyEWtVzg) --- ## Features - Matrix-style rain effect on various displays - Supports: - **TFT_eSPI** - **LovyanGFX** - **Arduino_GFX (Adafruit GFX)** - Customizable: - Text and background colors - Character size - Falling speed and effect intensity - Random key generation with color-switching animation - Minimal resource usage for smooth rendering --- ## Installation ### From Arduino Library Manager 1. Open **Arduino IDE** 2. Go to **Sketch → Include Library → Manage Libraries…** 3. Search for **Digital Rain Animation** 4. Click **Install** ### Manual Installation ```bash git clone https://github.com/0015/TP_Arduino_DigitalRain_Anim.git ``` ## Update Log - v2.0.2 * Fixed bug where one more line would be displayed - v2.0.1 * Added support for TFT_eSPI, LovyanGFX, Arduino_GFX * Example added for Japanese characters - v1.2.1 * Added color customization: * Background * Text * Header character - v1.1.x * Added random key generator * Red animation mode when key is active * Examples added for key features ## License This project is licensed under the MIT License. See the [LICENSE](./LICENSE) file for more information.
2,074
README
md
en
markdown
text
{"qsc_doc_frac_chars_curly_bracket": 0.0, "qsc_doc_frac_words_redpajama_stop": 0.11590909, "qsc_doc_num_sentences": 39.0, "qsc_doc_num_words": 297, "qsc_doc_num_chars": 2074.0, "qsc_doc_num_lines": 75.0, "qsc_doc_mean_word_length": 5.02693603, "qsc_doc_frac_words_full_bracket": 0.0, "qsc_doc_frac_lines_end_with_readmore": 0.0, "qsc_doc_frac_lines_start_with_bullet": 0.0, "qsc_doc_frac_words_unique": 0.51851852, "qsc_doc_entropy_unigram": 4.80616018, "qsc_doc_frac_words_all_caps": 0.02727273, "qsc_doc_frac_lines_dupe_lines": 0.05660377, "qsc_doc_frac_chars_dupe_lines": 0.00461775, "qsc_doc_frac_chars_top_2grams": 0.02679169, "qsc_doc_frac_chars_top_3grams": 0.03215003, "qsc_doc_frac_chars_top_4grams": 0.04822505, "qsc_doc_frac_chars_dupe_5grams": 0.17682518, "qsc_doc_frac_chars_dupe_6grams": 0.14199598, "qsc_doc_frac_chars_dupe_7grams": 0.14199598, "qsc_doc_frac_chars_dupe_8grams": 0.14199598, "qsc_doc_frac_chars_dupe_9grams": 0.1138647, "qsc_doc_frac_chars_dupe_10grams": 0.1138647, "qsc_doc_frac_chars_replacement_symbols": 0.0, "qsc_doc_cate_code_related_file_name": 1.0, "qsc_doc_num_chars_sentence_length_mean": 17.20175439, "qsc_doc_frac_chars_hyperlink_html_tag": 0.18370299, "qsc_doc_frac_chars_alphabet": 0.81818182, "qsc_doc_frac_chars_digital": 0.02727273, "qsc_doc_frac_chars_whitespace": 0.15139826, "qsc_doc_frac_chars_hex_words": 0.0}
1
{"qsc_doc_frac_chars_replacement_symbols": 0, "qsc_doc_entropy_unigram": 0, "qsc_doc_frac_chars_top_2grams": 0, "qsc_doc_frac_chars_top_3grams": 0, "qsc_doc_frac_chars_top_4grams": 0, "qsc_doc_frac_chars_dupe_5grams": 0, "qsc_doc_frac_chars_dupe_6grams": 0, "qsc_doc_frac_chars_dupe_7grams": 0, "qsc_doc_frac_chars_dupe_8grams": 0, "qsc_doc_frac_chars_dupe_9grams": 0, "qsc_doc_frac_chars_dupe_10grams": 0, "qsc_doc_frac_chars_dupe_lines": 0, "qsc_doc_frac_lines_dupe_lines": 0, "qsc_doc_frac_lines_end_with_readmore": 0, "qsc_doc_frac_lines_start_with_bullet": 0, "qsc_doc_frac_words_all_caps": 0, "qsc_doc_mean_word_length": 0, "qsc_doc_num_chars": 0, "qsc_doc_num_lines": 0, "qsc_doc_num_sentences": 0, "qsc_doc_num_words": 0, "qsc_doc_frac_chars_hex_words": 0, "qsc_doc_frac_chars_hyperlink_html_tag": 0, "qsc_doc_frac_chars_alphabet": 0, "qsc_doc_frac_chars_digital": 0, "qsc_doc_frac_chars_whitespace": 0}
0015/esp_rlottie
rlottie/src/lottie/rapidjson/document.h
// Tencent is pleased to support the open source community by making RapidJSON available. // // Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip. All rights reserved. // // Licensed under the MIT License (the "License"); you may not use this file except // in compliance with the License. You may obtain a copy of the License at // // http://opensource.org/licenses/MIT // // Unless required by applicable law or agreed to in writing, software distributed // under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR // CONDITIONS OF ANY KIND, either express or implied. See the License for the // specific language governing permissions and limitations under the License. #ifndef RAPIDJSON_DOCUMENT_H_ #define RAPIDJSON_DOCUMENT_H_ /*! \file document.h */ #include "reader.h" #include "internal/meta.h" #include "internal/strfunc.h" #include "memorystream.h" #include "encodedstream.h" #include <new> // placement new #include <limits> #ifdef __cpp_lib_three_way_comparison #include <compare> #endif RAPIDJSON_DIAG_PUSH #ifdef __clang__ RAPIDJSON_DIAG_OFF(padded) RAPIDJSON_DIAG_OFF(switch-enum) RAPIDJSON_DIAG_OFF(c++98-compat) #elif defined(_MSC_VER) RAPIDJSON_DIAG_OFF(4127) // conditional expression is constant RAPIDJSON_DIAG_OFF(4244) // conversion from kXxxFlags to 'uint16_t', possible loss of data #endif #ifdef __GNUC__ RAPIDJSON_DIAG_OFF(effc++) #endif // __GNUC__ #ifndef RAPIDJSON_NOMEMBERITERATORCLASS #include <iterator> // std::random_access_iterator_tag #endif #if RAPIDJSON_HAS_CXX11_RVALUE_REFS #include <utility> // std::move #endif RAPIDJSON_NAMESPACE_BEGIN // Forward declaration. template <typename Encoding, typename Allocator> class GenericValue; template <typename Encoding, typename Allocator, typename StackAllocator> class GenericDocument; /*! \def RAPIDJSON_DEFAULT_ALLOCATOR \ingroup RAPIDJSON_CONFIG \brief Allows to choose default allocator. User can define this to use CrtAllocator or MemoryPoolAllocator. */ #ifndef RAPIDJSON_DEFAULT_ALLOCATOR #define RAPIDJSON_DEFAULT_ALLOCATOR MemoryPoolAllocator<CrtAllocator> #endif /*! \def RAPIDJSON_DEFAULT_STACK_ALLOCATOR \ingroup RAPIDJSON_CONFIG \brief Allows to choose default stack allocator for Document. User can define this to use CrtAllocator or MemoryPoolAllocator. */ #ifndef RAPIDJSON_DEFAULT_STACK_ALLOCATOR #define RAPIDJSON_DEFAULT_STACK_ALLOCATOR CrtAllocator #endif /*! \def RAPIDJSON_VALUE_DEFAULT_OBJECT_CAPACITY \ingroup RAPIDJSON_CONFIG \brief User defined kDefaultObjectCapacity value. User can define this as any natural number. */ #ifndef RAPIDJSON_VALUE_DEFAULT_OBJECT_CAPACITY // number of objects that rapidjson::Value allocates memory for by default #define RAPIDJSON_VALUE_DEFAULT_OBJECT_CAPACITY 16 #endif /*! \def RAPIDJSON_VALUE_DEFAULT_ARRAY_CAPACITY \ingroup RAPIDJSON_CONFIG \brief User defined kDefaultArrayCapacity value. User can define this as any natural number. */ #ifndef RAPIDJSON_VALUE_DEFAULT_ARRAY_CAPACITY // number of array elements that rapidjson::Value allocates memory for by default #define RAPIDJSON_VALUE_DEFAULT_ARRAY_CAPACITY 16 #endif //! Name-value pair in a JSON object value. /*! This class was internal to GenericValue. It used to be a inner struct. But a compiler (IBM XL C/C++ for AIX) have reported to have problem with that so it moved as a namespace scope struct. https://code.google.com/p/rapidjson/issues/detail?id=64 */ template <typename Encoding, typename Allocator> class GenericMember { public: GenericValue<Encoding, Allocator> name; //!< name of member (must be a string) GenericValue<Encoding, Allocator> value; //!< value of member. #if RAPIDJSON_HAS_CXX11_RVALUE_REFS //! Move constructor in C++11 GenericMember(GenericMember&& rhs) RAPIDJSON_NOEXCEPT : name(std::move(rhs.name)), value(std::move(rhs.value)) { } //! Move assignment in C++11 GenericMember& operator=(GenericMember&& rhs) RAPIDJSON_NOEXCEPT { return *this = static_cast<GenericMember&>(rhs); } #endif //! Assignment with move semantics. /*! \param rhs Source of the assignment. Its name and value will become a null value after assignment. */ GenericMember& operator=(GenericMember& rhs) RAPIDJSON_NOEXCEPT { if (RAPIDJSON_LIKELY(this != &rhs)) { name = rhs.name; value = rhs.value; } return *this; } // swap() for std::sort() and other potential use in STL. friend inline void swap(GenericMember& a, GenericMember& b) RAPIDJSON_NOEXCEPT { a.name.Swap(b.name); a.value.Swap(b.value); } private: //! Copy constructor is not permitted. GenericMember(const GenericMember& rhs); }; /////////////////////////////////////////////////////////////////////////////// // GenericMemberIterator #ifndef RAPIDJSON_NOMEMBERITERATORCLASS //! (Constant) member iterator for a JSON object value /*! \tparam Const Is this a constant iterator? \tparam Encoding Encoding of the value. (Even non-string values need to have the same encoding in a document) \tparam Allocator Allocator type for allocating memory of object, array and string. This class implements a Random Access Iterator for GenericMember elements of a GenericValue, see ISO/IEC 14882:2003(E) C++ standard, 24.1 [lib.iterator.requirements]. \note This iterator implementation is mainly intended to avoid implicit conversions from iterator values to \c NULL, e.g. from GenericValue::FindMember. \note Define \c RAPIDJSON_NOMEMBERITERATORCLASS to fall back to a pointer-based implementation, if your platform doesn't provide the C++ <iterator> header. \see GenericMember, GenericValue::MemberIterator, GenericValue::ConstMemberIterator */ template <bool Const, typename Encoding, typename Allocator> class GenericMemberIterator { friend class GenericValue<Encoding,Allocator>; template <bool, typename, typename> friend class GenericMemberIterator; typedef GenericMember<Encoding,Allocator> PlainType; typedef typename internal::MaybeAddConst<Const,PlainType>::Type ValueType; public: //! Iterator type itself typedef GenericMemberIterator Iterator; //! Constant iterator type typedef GenericMemberIterator<true,Encoding,Allocator> ConstIterator; //! Non-constant iterator type typedef GenericMemberIterator<false,Encoding,Allocator> NonConstIterator; /** \name std::iterator_traits support */ //@{ typedef ValueType value_type; typedef ValueType * pointer; typedef ValueType & reference; typedef std::ptrdiff_t difference_type; typedef std::random_access_iterator_tag iterator_category; //@} //! Pointer to (const) GenericMember typedef pointer Pointer; //! Reference to (const) GenericMember typedef reference Reference; //! Signed integer type (e.g. \c ptrdiff_t) typedef difference_type DifferenceType; //! Default constructor (singular value) /*! Creates an iterator pointing to no element. \note All operations, except for comparisons, are undefined on such values. */ GenericMemberIterator() : ptr_() {} //! Iterator conversions to more const /*! \param it (Non-const) iterator to copy from Allows the creation of an iterator from another GenericMemberIterator that is "less const". Especially, creating a non-constant iterator from a constant iterator are disabled: \li const -> non-const (not ok) \li const -> const (ok) \li non-const -> const (ok) \li non-const -> non-const (ok) \note If the \c Const template parameter is already \c false, this constructor effectively defines a regular copy-constructor. Otherwise, the copy constructor is implicitly defined. */ GenericMemberIterator(const NonConstIterator & it) : ptr_(it.ptr_) {} Iterator& operator=(const NonConstIterator & it) { ptr_ = it.ptr_; return *this; } //! @name stepping //@{ Iterator& operator++(){ ++ptr_; return *this; } Iterator& operator--(){ --ptr_; return *this; } Iterator operator++(int){ Iterator old(*this); ++ptr_; return old; } Iterator operator--(int){ Iterator old(*this); --ptr_; return old; } //@} //! @name increment/decrement //@{ Iterator operator+(DifferenceType n) const { return Iterator(ptr_+n); } Iterator operator-(DifferenceType n) const { return Iterator(ptr_-n); } Iterator& operator+=(DifferenceType n) { ptr_+=n; return *this; } Iterator& operator-=(DifferenceType n) { ptr_-=n; return *this; } //@} //! @name relations //@{ template <bool Const_> bool operator==(const GenericMemberIterator<Const_, Encoding, Allocator>& that) const { return ptr_ == that.ptr_; } template <bool Const_> bool operator!=(const GenericMemberIterator<Const_, Encoding, Allocator>& that) const { return ptr_ != that.ptr_; } template <bool Const_> bool operator<=(const GenericMemberIterator<Const_, Encoding, Allocator>& that) const { return ptr_ <= that.ptr_; } template <bool Const_> bool operator>=(const GenericMemberIterator<Const_, Encoding, Allocator>& that) const { return ptr_ >= that.ptr_; } template <bool Const_> bool operator< (const GenericMemberIterator<Const_, Encoding, Allocator>& that) const { return ptr_ < that.ptr_; } template <bool Const_> bool operator> (const GenericMemberIterator<Const_, Encoding, Allocator>& that) const { return ptr_ > that.ptr_; } #ifdef __cpp_lib_three_way_comparison template <bool Const_> std::strong_ordering operator<=>(const GenericMemberIterator<Const_, Encoding, Allocator>& that) const { return ptr_ <=> that.ptr_; } #endif //@} //! @name dereference //@{ Reference operator*() const { return *ptr_; } Pointer operator->() const { return ptr_; } Reference operator[](DifferenceType n) const { return ptr_[n]; } //@} //! Distance DifferenceType operator-(ConstIterator that) const { return ptr_-that.ptr_; } private: //! Internal constructor from plain pointer explicit GenericMemberIterator(Pointer p) : ptr_(p) {} Pointer ptr_; //!< raw pointer }; #else // RAPIDJSON_NOMEMBERITERATORCLASS // class-based member iterator implementation disabled, use plain pointers template <bool Const, typename Encoding, typename Allocator> class GenericMemberIterator; //! non-const GenericMemberIterator template <typename Encoding, typename Allocator> class GenericMemberIterator<false,Encoding,Allocator> { //! use plain pointer as iterator type typedef GenericMember<Encoding,Allocator>* Iterator; }; //! const GenericMemberIterator template <typename Encoding, typename Allocator> class GenericMemberIterator<true,Encoding,Allocator> { //! use plain const pointer as iterator type typedef const GenericMember<Encoding,Allocator>* Iterator; }; #endif // RAPIDJSON_NOMEMBERITERATORCLASS /////////////////////////////////////////////////////////////////////////////// // GenericStringRef //! Reference to a constant string (not taking a copy) /*! \tparam CharType character type of the string This helper class is used to automatically infer constant string references for string literals, especially from \c const \b (!) character arrays. The main use is for creating JSON string values without copying the source string via an \ref Allocator. This requires that the referenced string pointers have a sufficient lifetime, which exceeds the lifetime of the associated GenericValue. \b Example \code Value v("foo"); // ok, no need to copy & calculate length const char foo[] = "foo"; v.SetString(foo); // ok const char* bar = foo; // Value x(bar); // not ok, can't rely on bar's lifetime Value x(StringRef(bar)); // lifetime explicitly guaranteed by user Value y(StringRef(bar, 3)); // ok, explicitly pass length \endcode \see StringRef, GenericValue::SetString */ template<typename CharType> struct GenericStringRef { typedef CharType Ch; //!< character type of the string //! Create string reference from \c const character array #ifndef __clang__ // -Wdocumentation /*! This constructor implicitly creates a constant string reference from a \c const character array. It has better performance than \ref StringRef(const CharType*) by inferring the string \ref length from the array length, and also supports strings containing null characters. \tparam N length of the string, automatically inferred \param str Constant character array, lifetime assumed to be longer than the use of the string in e.g. a GenericValue \post \ref s == str \note Constant complexity. \note There is a hidden, private overload to disallow references to non-const character arrays to be created via this constructor. By this, e.g. function-scope arrays used to be filled via \c snprintf are excluded from consideration. In such cases, the referenced string should be \b copied to the GenericValue instead. */ #endif template<SizeType N> GenericStringRef(const CharType (&str)[N]) RAPIDJSON_NOEXCEPT : s(str), length(N-1) {} //! Explicitly create string reference from \c const character pointer #ifndef __clang__ // -Wdocumentation /*! This constructor can be used to \b explicitly create a reference to a constant string pointer. \see StringRef(const CharType*) \param str Constant character pointer, lifetime assumed to be longer than the use of the string in e.g. a GenericValue \post \ref s == str \note There is a hidden, private overload to disallow references to non-const character arrays to be created via this constructor. By this, e.g. function-scope arrays used to be filled via \c snprintf are excluded from consideration. In such cases, the referenced string should be \b copied to the GenericValue instead. */ #endif explicit GenericStringRef(const CharType* str) : s(str), length(NotNullStrLen(str)) {} //! Create constant string reference from pointer and length #ifndef __clang__ // -Wdocumentation /*! \param str constant string, lifetime assumed to be longer than the use of the string in e.g. a GenericValue \param len length of the string, excluding the trailing NULL terminator \post \ref s == str && \ref length == len \note Constant complexity. */ #endif GenericStringRef(const CharType* str, SizeType len) : s(RAPIDJSON_LIKELY(str) ? str : emptyString), length(len) { RAPIDJSON_ASSERT(str != 0 || len == 0u); } GenericStringRef(const GenericStringRef& rhs) : s(rhs.s), length(rhs.length) {} //! implicit conversion to plain CharType pointer operator const Ch *() const { return s; } const Ch* const s; //!< plain CharType pointer const SizeType length; //!< length of the string (excluding the trailing NULL terminator) private: SizeType NotNullStrLen(const CharType* str) { RAPIDJSON_ASSERT(str != 0); return internal::StrLen(str); } /// Empty string - used when passing in a NULL pointer static const Ch emptyString[]; //! Disallow construction from non-const array template<SizeType N> GenericStringRef(CharType (&str)[N]) /* = delete */; //! Copy assignment operator not permitted - immutable type GenericStringRef& operator=(const GenericStringRef& rhs) /* = delete */; }; template<typename CharType> const CharType GenericStringRef<CharType>::emptyString[] = { CharType() }; //! Mark a character pointer as constant string /*! Mark a plain character pointer as a "string literal". This function can be used to avoid copying a character string to be referenced as a value in a JSON GenericValue object, if the string's lifetime is known to be valid long enough. \tparam CharType Character type of the string \param str Constant string, lifetime assumed to be longer than the use of the string in e.g. a GenericValue \return GenericStringRef string reference object \relatesalso GenericStringRef \see GenericValue::GenericValue(StringRefType), GenericValue::operator=(StringRefType), GenericValue::SetString(StringRefType), GenericValue::PushBack(StringRefType, Allocator&), GenericValue::AddMember */ template<typename CharType> inline GenericStringRef<CharType> StringRef(const CharType* str) { return GenericStringRef<CharType>(str); } //! Mark a character pointer as constant string /*! Mark a plain character pointer as a "string literal". This function can be used to avoid copying a character string to be referenced as a value in a JSON GenericValue object, if the string's lifetime is known to be valid long enough. This version has better performance with supplied length, and also supports string containing null characters. \tparam CharType character type of the string \param str Constant string, lifetime assumed to be longer than the use of the string in e.g. a GenericValue \param length The length of source string. \return GenericStringRef string reference object \relatesalso GenericStringRef */ template<typename CharType> inline GenericStringRef<CharType> StringRef(const CharType* str, size_t length) { return GenericStringRef<CharType>(str, SizeType(length)); } #if RAPIDJSON_HAS_STDSTRING //! Mark a string object as constant string /*! Mark a string object (e.g. \c std::string) as a "string literal". This function can be used to avoid copying a string to be referenced as a value in a JSON GenericValue object, if the string's lifetime is known to be valid long enough. \tparam CharType character type of the string \param str Constant string, lifetime assumed to be longer than the use of the string in e.g. a GenericValue \return GenericStringRef string reference object \relatesalso GenericStringRef \note Requires the definition of the preprocessor symbol \ref RAPIDJSON_HAS_STDSTRING. */ template<typename CharType> inline GenericStringRef<CharType> StringRef(const std::basic_string<CharType>& str) { return GenericStringRef<CharType>(str.data(), SizeType(str.size())); } #endif /////////////////////////////////////////////////////////////////////////////// // GenericValue type traits namespace internal { template <typename T, typename Encoding = void, typename Allocator = void> struct IsGenericValueImpl : FalseType {}; // select candidates according to nested encoding and allocator types template <typename T> struct IsGenericValueImpl<T, typename Void<typename T::EncodingType>::Type, typename Void<typename T::AllocatorType>::Type> : IsBaseOf<GenericValue<typename T::EncodingType, typename T::AllocatorType>, T>::Type {}; // helper to match arbitrary GenericValue instantiations, including derived classes template <typename T> struct IsGenericValue : IsGenericValueImpl<T>::Type {}; } // namespace internal /////////////////////////////////////////////////////////////////////////////// // TypeHelper namespace internal { template <typename ValueType, typename T> struct TypeHelper {}; template<typename ValueType> struct TypeHelper<ValueType, bool> { static bool Is(const ValueType& v) { return v.IsBool(); } static bool Get(const ValueType& v) { return v.GetBool(); } static ValueType& Set(ValueType& v, bool data) { return v.SetBool(data); } static ValueType& Set(ValueType& v, bool data, typename ValueType::AllocatorType&) { return v.SetBool(data); } }; template<typename ValueType> struct TypeHelper<ValueType, int> { static bool Is(const ValueType& v) { return v.IsInt(); } static int Get(const ValueType& v) { return v.GetInt(); } static ValueType& Set(ValueType& v, int data) { return v.SetInt(data); } static ValueType& Set(ValueType& v, int data, typename ValueType::AllocatorType&) { return v.SetInt(data); } }; template<typename ValueType> struct TypeHelper<ValueType, unsigned> { static bool Is(const ValueType& v) { return v.IsUint(); } static unsigned Get(const ValueType& v) { return v.GetUint(); } static ValueType& Set(ValueType& v, unsigned data) { return v.SetUint(data); } static ValueType& Set(ValueType& v, unsigned data, typename ValueType::AllocatorType&) { return v.SetUint(data); } }; #ifdef _MSC_VER RAPIDJSON_STATIC_ASSERT(sizeof(long) == sizeof(int)); template<typename ValueType> struct TypeHelper<ValueType, long> { static bool Is(const ValueType& v) { return v.IsInt(); } static long Get(const ValueType& v) { return v.GetInt(); } static ValueType& Set(ValueType& v, long data) { return v.SetInt(data); } static ValueType& Set(ValueType& v, long data, typename ValueType::AllocatorType&) { return v.SetInt(data); } }; RAPIDJSON_STATIC_ASSERT(sizeof(unsigned long) == sizeof(unsigned)); template<typename ValueType> struct TypeHelper<ValueType, unsigned long> { static bool Is(const ValueType& v) { return v.IsUint(); } static unsigned long Get(const ValueType& v) { return v.GetUint(); } static ValueType& Set(ValueType& v, unsigned long data) { return v.SetUint(data); } static ValueType& Set(ValueType& v, unsigned long data, typename ValueType::AllocatorType&) { return v.SetUint(data); } }; #endif template<typename ValueType> struct TypeHelper<ValueType, int64_t> { static bool Is(const ValueType& v) { return v.IsInt64(); } static int64_t Get(const ValueType& v) { return v.GetInt64(); } static ValueType& Set(ValueType& v, int64_t data) { return v.SetInt64(data); } static ValueType& Set(ValueType& v, int64_t data, typename ValueType::AllocatorType&) { return v.SetInt64(data); } }; template<typename ValueType> struct TypeHelper<ValueType, uint64_t> { static bool Is(const ValueType& v) { return v.IsUint64(); } static uint64_t Get(const ValueType& v) { return v.GetUint64(); } static ValueType& Set(ValueType& v, uint64_t data) { return v.SetUint64(data); } static ValueType& Set(ValueType& v, uint64_t data, typename ValueType::AllocatorType&) { return v.SetUint64(data); } }; template<typename ValueType> struct TypeHelper<ValueType, double> { static bool Is(const ValueType& v) { return v.IsDouble(); } static double Get(const ValueType& v) { return v.GetDouble(); } static ValueType& Set(ValueType& v, double data) { return v.SetDouble(data); } static ValueType& Set(ValueType& v, double data, typename ValueType::AllocatorType&) { return v.SetDouble(data); } }; template<typename ValueType> struct TypeHelper<ValueType, float> { static bool Is(const ValueType& v) { return v.IsFloat(); } static float Get(const ValueType& v) { return v.GetFloat(); } static ValueType& Set(ValueType& v, float data) { return v.SetFloat(data); } static ValueType& Set(ValueType& v, float data, typename ValueType::AllocatorType&) { return v.SetFloat(data); } }; template<typename ValueType> struct TypeHelper<ValueType, const typename ValueType::Ch*> { typedef const typename ValueType::Ch* StringType; static bool Is(const ValueType& v) { return v.IsString(); } static StringType Get(const ValueType& v) { return v.GetString(); } static ValueType& Set(ValueType& v, const StringType data) { return v.SetString(typename ValueType::StringRefType(data)); } static ValueType& Set(ValueType& v, const StringType data, typename ValueType::AllocatorType& a) { return v.SetString(data, a); } }; #if RAPIDJSON_HAS_STDSTRING template<typename ValueType> struct TypeHelper<ValueType, std::basic_string<typename ValueType::Ch> > { typedef std::basic_string<typename ValueType::Ch> StringType; static bool Is(const ValueType& v) { return v.IsString(); } static StringType Get(const ValueType& v) { return StringType(v.GetString(), v.GetStringLength()); } static ValueType& Set(ValueType& v, const StringType& data, typename ValueType::AllocatorType& a) { return v.SetString(data, a); } }; #endif template<typename ValueType> struct TypeHelper<ValueType, typename ValueType::Array> { typedef typename ValueType::Array ArrayType; static bool Is(const ValueType& v) { return v.IsArray(); } static ArrayType Get(ValueType& v) { return v.GetArray(); } static ValueType& Set(ValueType& v, ArrayType data) { return v = data; } static ValueType& Set(ValueType& v, ArrayType data, typename ValueType::AllocatorType&) { return v = data; } }; template<typename ValueType> struct TypeHelper<ValueType, typename ValueType::ConstArray> { typedef typename ValueType::ConstArray ArrayType; static bool Is(const ValueType& v) { return v.IsArray(); } static ArrayType Get(const ValueType& v) { return v.GetArray(); } }; template<typename ValueType> struct TypeHelper<ValueType, typename ValueType::Object> { typedef typename ValueType::Object ObjectType; static bool Is(const ValueType& v) { return v.IsObject(); } static ObjectType Get(ValueType& v) { return v.GetObject(); } static ValueType& Set(ValueType& v, ObjectType data) { return v = data; } static ValueType& Set(ValueType& v, ObjectType data, typename ValueType::AllocatorType&) { return v = data; } }; template<typename ValueType> struct TypeHelper<ValueType, typename ValueType::ConstObject> { typedef typename ValueType::ConstObject ObjectType; static bool Is(const ValueType& v) { return v.IsObject(); } static ObjectType Get(const ValueType& v) { return v.GetObject(); } }; } // namespace internal // Forward declarations template <bool, typename> class GenericArray; template <bool, typename> class GenericObject; /////////////////////////////////////////////////////////////////////////////// // GenericValue //! Represents a JSON value. Use Value for UTF8 encoding and default allocator. /*! A JSON value can be one of 7 types. This class is a variant type supporting these types. Use the Value if UTF8 and default allocator \tparam Encoding Encoding of the value. (Even non-string values need to have the same encoding in a document) \tparam Allocator Allocator type for allocating memory of object, array and string. */ template <typename Encoding, typename Allocator = RAPIDJSON_DEFAULT_ALLOCATOR > class GenericValue { public: //! Name-value pair in an object. typedef GenericMember<Encoding, Allocator> Member; typedef Encoding EncodingType; //!< Encoding type from template parameter. typedef Allocator AllocatorType; //!< Allocator type from template parameter. typedef typename Encoding::Ch Ch; //!< Character type derived from Encoding. typedef GenericStringRef<Ch> StringRefType; //!< Reference to a constant string typedef typename GenericMemberIterator<false,Encoding,Allocator>::Iterator MemberIterator; //!< Member iterator for iterating in object. typedef typename GenericMemberIterator<true,Encoding,Allocator>::Iterator ConstMemberIterator; //!< Constant member iterator for iterating in object. typedef GenericValue* ValueIterator; //!< Value iterator for iterating in array. typedef const GenericValue* ConstValueIterator; //!< Constant value iterator for iterating in array. typedef GenericValue<Encoding, Allocator> ValueType; //!< Value type of itself. typedef GenericArray<false, ValueType> Array; typedef GenericArray<true, ValueType> ConstArray; typedef GenericObject<false, ValueType> Object; typedef GenericObject<true, ValueType> ConstObject; //!@name Constructors and destructor. //@{ //! Default constructor creates a null value. GenericValue() RAPIDJSON_NOEXCEPT : data_() { data_.f.flags = kNullFlag; } #if RAPIDJSON_HAS_CXX11_RVALUE_REFS //! Move constructor in C++11 GenericValue(GenericValue&& rhs) RAPIDJSON_NOEXCEPT : data_(rhs.data_) { rhs.data_.f.flags = kNullFlag; // give up contents } #endif private: //! Copy constructor is not permitted. GenericValue(const GenericValue& rhs); #if RAPIDJSON_HAS_CXX11_RVALUE_REFS //! Moving from a GenericDocument is not permitted. template <typename StackAllocator> GenericValue(GenericDocument<Encoding,Allocator,StackAllocator>&& rhs); //! Move assignment from a GenericDocument is not permitted. template <typename StackAllocator> GenericValue& operator=(GenericDocument<Encoding,Allocator,StackAllocator>&& rhs); #endif public: //! Constructor with JSON value type. /*! This creates a Value of specified type with default content. \param type Type of the value. \note Default content for number is zero. */ explicit GenericValue(Type type) RAPIDJSON_NOEXCEPT : data_() { static const uint16_t defaultFlags[] = { kNullFlag, kFalseFlag, kTrueFlag, kObjectFlag, kArrayFlag, kShortStringFlag, kNumberAnyFlag }; RAPIDJSON_NOEXCEPT_ASSERT(type >= kNullType && type <= kNumberType); data_.f.flags = defaultFlags[type]; // Use ShortString to store empty string. if (type == kStringType) data_.ss.SetLength(0); } //! Explicit copy constructor (with allocator) /*! Creates a copy of a Value by using the given Allocator \tparam SourceAllocator allocator of \c rhs \param rhs Value to copy from (read-only) \param allocator Allocator for allocating copied elements and buffers. Commonly use GenericDocument::GetAllocator(). \param copyConstStrings Force copying of constant strings (e.g. referencing an in-situ buffer) \see CopyFrom() */ template <typename SourceAllocator> GenericValue(const GenericValue<Encoding,SourceAllocator>& rhs, Allocator& allocator, bool copyConstStrings = false) { switch (rhs.GetType()) { case kObjectType: { SizeType count = rhs.data_.o.size; Member* lm = reinterpret_cast<Member*>(allocator.Malloc(count * sizeof(Member))); const typename GenericValue<Encoding,SourceAllocator>::Member* rm = rhs.GetMembersPointer(); for (SizeType i = 0; i < count; i++) { new (&lm[i].name) GenericValue(rm[i].name, allocator, copyConstStrings); new (&lm[i].value) GenericValue(rm[i].value, allocator, copyConstStrings); } data_.f.flags = kObjectFlag; data_.o.size = data_.o.capacity = count; SetMembersPointer(lm); } break; case kArrayType: { SizeType count = rhs.data_.a.size; GenericValue* le = reinterpret_cast<GenericValue*>(allocator.Malloc(count * sizeof(GenericValue))); const GenericValue<Encoding,SourceAllocator>* re = rhs.GetElementsPointer(); for (SizeType i = 0; i < count; i++) new (&le[i]) GenericValue(re[i], allocator, copyConstStrings); data_.f.flags = kArrayFlag; data_.a.size = data_.a.capacity = count; SetElementsPointer(le); } break; case kStringType: if (rhs.data_.f.flags == kConstStringFlag && !copyConstStrings) { data_.f.flags = rhs.data_.f.flags; data_ = *reinterpret_cast<const Data*>(&rhs.data_); } else SetStringRaw(StringRef(rhs.GetString(), rhs.GetStringLength()), allocator); break; default: data_.f.flags = rhs.data_.f.flags; data_ = *reinterpret_cast<const Data*>(&rhs.data_); break; } } //! Constructor for boolean value. /*! \param b Boolean value \note This constructor is limited to \em real boolean values and rejects implicitly converted types like arbitrary pointers. Use an explicit cast to \c bool, if you want to construct a boolean JSON value in such cases. */ #ifndef RAPIDJSON_DOXYGEN_RUNNING // hide SFINAE from Doxygen template <typename T> explicit GenericValue(T b, RAPIDJSON_ENABLEIF((internal::IsSame<bool, T>))) RAPIDJSON_NOEXCEPT // See #472 #else explicit GenericValue(bool b) RAPIDJSON_NOEXCEPT #endif : data_() { // safe-guard against failing SFINAE RAPIDJSON_STATIC_ASSERT((internal::IsSame<bool,T>::Value)); data_.f.flags = b ? kTrueFlag : kFalseFlag; } //! Constructor for int value. explicit GenericValue(int i) RAPIDJSON_NOEXCEPT : data_() { data_.n.i64 = i; data_.f.flags = (i >= 0) ? (kNumberIntFlag | kUintFlag | kUint64Flag) : kNumberIntFlag; } //! Constructor for unsigned value. explicit GenericValue(unsigned u) RAPIDJSON_NOEXCEPT : data_() { data_.n.u64 = u; data_.f.flags = (u & 0x80000000) ? kNumberUintFlag : (kNumberUintFlag | kIntFlag | kInt64Flag); } //! Constructor for int64_t value. explicit GenericValue(int64_t i64) RAPIDJSON_NOEXCEPT : data_() { data_.n.i64 = i64; data_.f.flags = kNumberInt64Flag; if (i64 >= 0) { data_.f.flags |= kNumberUint64Flag; if (!(static_cast<uint64_t>(i64) & RAPIDJSON_UINT64_C2(0xFFFFFFFF, 0x00000000))) data_.f.flags |= kUintFlag; if (!(static_cast<uint64_t>(i64) & RAPIDJSON_UINT64_C2(0xFFFFFFFF, 0x80000000))) data_.f.flags |= kIntFlag; } else if (i64 >= static_cast<int64_t>(RAPIDJSON_UINT64_C2(0xFFFFFFFF, 0x80000000))) data_.f.flags |= kIntFlag; } //! Constructor for uint64_t value. explicit GenericValue(uint64_t u64) RAPIDJSON_NOEXCEPT : data_() { data_.n.u64 = u64; data_.f.flags = kNumberUint64Flag; if (!(u64 & RAPIDJSON_UINT64_C2(0x80000000, 0x00000000))) data_.f.flags |= kInt64Flag; if (!(u64 & RAPIDJSON_UINT64_C2(0xFFFFFFFF, 0x00000000))) data_.f.flags |= kUintFlag; if (!(u64 & RAPIDJSON_UINT64_C2(0xFFFFFFFF, 0x80000000))) data_.f.flags |= kIntFlag; } //! Constructor for double value. explicit GenericValue(double d) RAPIDJSON_NOEXCEPT : data_() { data_.n.d = d; data_.f.flags = kNumberDoubleFlag; } //! Constructor for float value. explicit GenericValue(float f) RAPIDJSON_NOEXCEPT : data_() { data_.n.d = static_cast<double>(f); data_.f.flags = kNumberDoubleFlag; } //! Constructor for constant string (i.e. do not make a copy of string) GenericValue(const Ch* s, SizeType length) RAPIDJSON_NOEXCEPT : data_() { SetStringRaw(StringRef(s, length)); } //! Constructor for constant string (i.e. do not make a copy of string) explicit GenericValue(StringRefType s) RAPIDJSON_NOEXCEPT : data_() { SetStringRaw(s); } //! Constructor for copy-string (i.e. do make a copy of string) GenericValue(const Ch* s, SizeType length, Allocator& allocator) : data_() { SetStringRaw(StringRef(s, length), allocator); } //! Constructor for copy-string (i.e. do make a copy of string) GenericValue(const Ch*s, Allocator& allocator) : data_() { SetStringRaw(StringRef(s), allocator); } #if RAPIDJSON_HAS_STDSTRING //! Constructor for copy-string from a string object (i.e. do make a copy of string) /*! \note Requires the definition of the preprocessor symbol \ref RAPIDJSON_HAS_STDSTRING. */ GenericValue(const std::basic_string<Ch>& s, Allocator& allocator) : data_() { SetStringRaw(StringRef(s), allocator); } #endif //! Constructor for Array. /*! \param a An array obtained by \c GetArray(). \note \c Array is always pass-by-value. \note the source array is moved into this value and the sourec array becomes empty. */ GenericValue(Array a) RAPIDJSON_NOEXCEPT : data_(a.value_.data_) { a.value_.data_ = Data(); a.value_.data_.f.flags = kArrayFlag; } //! Constructor for Object. /*! \param o An object obtained by \c GetObject(). \note \c Object is always pass-by-value. \note the source object is moved into this value and the sourec object becomes empty. */ GenericValue(Object o) RAPIDJSON_NOEXCEPT : data_(o.value_.data_) { o.value_.data_ = Data(); o.value_.data_.f.flags = kObjectFlag; } //! Destructor. /*! Need to destruct elements of array, members of object, or copy-string. */ ~GenericValue() { if (Allocator::kNeedFree) { // Shortcut by Allocator's trait switch(data_.f.flags) { case kArrayFlag: { GenericValue* e = GetElementsPointer(); for (GenericValue* v = e; v != e + data_.a.size; ++v) v->~GenericValue(); Allocator::Free(e); } break; case kObjectFlag: for (MemberIterator m = MemberBegin(); m != MemberEnd(); ++m) m->~Member(); Allocator::Free(GetMembersPointer()); break; case kCopyStringFlag: Allocator::Free(const_cast<Ch*>(GetStringPointer())); break; default: break; // Do nothing for other types. } } } //@} //!@name Assignment operators //@{ //! Assignment with move semantics. /*! \param rhs Source of the assignment. It will become a null value after assignment. */ GenericValue& operator=(GenericValue& rhs) RAPIDJSON_NOEXCEPT { if (RAPIDJSON_LIKELY(this != &rhs)) { this->~GenericValue(); RawAssign(rhs); } return *this; } #if RAPIDJSON_HAS_CXX11_RVALUE_REFS //! Move assignment in C++11 GenericValue& operator=(GenericValue&& rhs) RAPIDJSON_NOEXCEPT { return *this = rhs.Move(); } #endif //! Assignment of constant string reference (no copy) /*! \param str Constant string reference to be assigned \note This overload is needed to avoid clashes with the generic primitive type assignment overload below. \see GenericStringRef, operator=(T) */ GenericValue& operator=(StringRefType str) RAPIDJSON_NOEXCEPT { GenericValue s(str); return *this = s; } //! Assignment with primitive types. /*! \tparam T Either \ref Type, \c int, \c unsigned, \c int64_t, \c uint64_t \param value The value to be assigned. \note The source type \c T explicitly disallows all pointer types, especially (\c const) \ref Ch*. This helps avoiding implicitly referencing character strings with insufficient lifetime, use \ref SetString(const Ch*, Allocator&) (for copying) or \ref StringRef() (to explicitly mark the pointer as constant) instead. All other pointer types would implicitly convert to \c bool, use \ref SetBool() instead. */ template <typename T> RAPIDJSON_DISABLEIF_RETURN((internal::IsPointer<T>), (GenericValue&)) operator=(T value) { GenericValue v(value); return *this = v; } //! Deep-copy assignment from Value /*! Assigns a \b copy of the Value to the current Value object \tparam SourceAllocator Allocator type of \c rhs \param rhs Value to copy from (read-only) \param allocator Allocator to use for copying \param copyConstStrings Force copying of constant strings (e.g. referencing an in-situ buffer) */ template <typename SourceAllocator> GenericValue& CopyFrom(const GenericValue<Encoding, SourceAllocator>& rhs, Allocator& allocator, bool copyConstStrings = false) { RAPIDJSON_ASSERT(static_cast<void*>(this) != static_cast<void const*>(&rhs)); this->~GenericValue(); new (this) GenericValue(rhs, allocator, copyConstStrings); return *this; } //! Exchange the contents of this value with those of other. /*! \param other Another value. \note Constant complexity. */ GenericValue& Swap(GenericValue& other) RAPIDJSON_NOEXCEPT { GenericValue temp; temp.RawAssign(*this); RawAssign(other); other.RawAssign(temp); return *this; } //! free-standing swap function helper /*! Helper function to enable support for common swap implementation pattern based on \c std::swap: \code void swap(MyClass& a, MyClass& b) { using std::swap; swap(a.value, b.value); // ... } \endcode \see Swap() */ friend inline void swap(GenericValue& a, GenericValue& b) RAPIDJSON_NOEXCEPT { a.Swap(b); } //! Prepare Value for move semantics /*! \return *this */ GenericValue& Move() RAPIDJSON_NOEXCEPT { return *this; } //@} //!@name Equal-to and not-equal-to operators //@{ //! Equal-to operator /*! \note If an object contains duplicated named member, comparing equality with any object is always \c false. \note Complexity is quadratic in Object's member number and linear for the rest (number of all values in the subtree and total lengths of all strings). */ template <typename SourceAllocator> bool operator==(const GenericValue<Encoding, SourceAllocator>& rhs) const { typedef GenericValue<Encoding, SourceAllocator> RhsType; if (GetType() != rhs.GetType()) return false; switch (GetType()) { case kObjectType: // Warning: O(n^2) inner-loop if (data_.o.size != rhs.data_.o.size) return false; for (ConstMemberIterator lhsMemberItr = MemberBegin(); lhsMemberItr != MemberEnd(); ++lhsMemberItr) { typename RhsType::ConstMemberIterator rhsMemberItr = rhs.FindMember(lhsMemberItr->name); if (rhsMemberItr == rhs.MemberEnd() || lhsMemberItr->value != rhsMemberItr->value) return false; } return true; case kArrayType: if (data_.a.size != rhs.data_.a.size) return false; for (SizeType i = 0; i < data_.a.size; i++) if ((*this)[i] != rhs[i]) return false; return true; case kStringType: return StringEqual(rhs); case kNumberType: if (IsDouble() || rhs.IsDouble()) { double a = GetDouble(); // May convert from integer to double. double b = rhs.GetDouble(); // Ditto return a >= b && a <= b; // Prevent -Wfloat-equal } else return data_.n.u64 == rhs.data_.n.u64; default: return true; } } //! Equal-to operator with const C-string pointer bool operator==(const Ch* rhs) const { return *this == GenericValue(StringRef(rhs)); } #if RAPIDJSON_HAS_STDSTRING //! Equal-to operator with string object /*! \note Requires the definition of the preprocessor symbol \ref RAPIDJSON_HAS_STDSTRING. */ bool operator==(const std::basic_string<Ch>& rhs) const { return *this == GenericValue(StringRef(rhs)); } #endif //! Equal-to operator with primitive types /*! \tparam T Either \ref Type, \c int, \c unsigned, \c int64_t, \c uint64_t, \c double, \c true, \c false */ template <typename T> RAPIDJSON_DISABLEIF_RETURN((internal::OrExpr<internal::IsPointer<T>,internal::IsGenericValue<T> >), (bool)) operator==(const T& rhs) const { return *this == GenericValue(rhs); } //! Not-equal-to operator /*! \return !(*this == rhs) */ template <typename SourceAllocator> bool operator!=(const GenericValue<Encoding, SourceAllocator>& rhs) const { return !(*this == rhs); } //! Not-equal-to operator with const C-string pointer bool operator!=(const Ch* rhs) const { return !(*this == rhs); } //! Not-equal-to operator with arbitrary types /*! \return !(*this == rhs) */ template <typename T> RAPIDJSON_DISABLEIF_RETURN((internal::IsGenericValue<T>), (bool)) operator!=(const T& rhs) const { return !(*this == rhs); } //! Equal-to operator with arbitrary types (symmetric version) /*! \return (rhs == lhs) */ template <typename T> friend RAPIDJSON_DISABLEIF_RETURN((internal::IsGenericValue<T>), (bool)) operator==(const T& lhs, const GenericValue& rhs) { return rhs == lhs; } //! Not-Equal-to operator with arbitrary types (symmetric version) /*! \return !(rhs == lhs) */ template <typename T> friend RAPIDJSON_DISABLEIF_RETURN((internal::IsGenericValue<T>), (bool)) operator!=(const T& lhs, const GenericValue& rhs) { return !(rhs == lhs); } //@} //!@name Type //@{ Type GetType() const { return static_cast<Type>(data_.f.flags & kTypeMask); } bool IsNull() const { return data_.f.flags == kNullFlag; } bool IsFalse() const { return data_.f.flags == kFalseFlag; } bool IsTrue() const { return data_.f.flags == kTrueFlag; } bool IsBool() const { return (data_.f.flags & kBoolFlag) != 0; } bool IsObject() const { return data_.f.flags == kObjectFlag; } bool IsArray() const { return data_.f.flags == kArrayFlag; } bool IsNumber() const { return (data_.f.flags & kNumberFlag) != 0; } bool IsInt() const { return (data_.f.flags & kIntFlag) != 0; } bool IsUint() const { return (data_.f.flags & kUintFlag) != 0; } bool IsInt64() const { return (data_.f.flags & kInt64Flag) != 0; } bool IsUint64() const { return (data_.f.flags & kUint64Flag) != 0; } bool IsDouble() const { return (data_.f.flags & kDoubleFlag) != 0; } bool IsString() const { return (data_.f.flags & kStringFlag) != 0; } // Checks whether a number can be losslessly converted to a double. bool IsLosslessDouble() const { if (!IsNumber()) return false; if (IsUint64()) { uint64_t u = GetUint64(); volatile double d = static_cast<double>(u); return (d >= 0.0) && (d < static_cast<double>((std::numeric_limits<uint64_t>::max)())) && (u == static_cast<uint64_t>(d)); } if (IsInt64()) { int64_t i = GetInt64(); volatile double d = static_cast<double>(i); return (d >= static_cast<double>((std::numeric_limits<int64_t>::min)())) && (d < static_cast<double>((std::numeric_limits<int64_t>::max)())) && (i == static_cast<int64_t>(d)); } return true; // double, int, uint are always lossless } // Checks whether a number is a float (possible lossy). bool IsFloat() const { if ((data_.f.flags & kDoubleFlag) == 0) return false; double d = GetDouble(); return d >= -3.4028234e38 && d <= 3.4028234e38; } // Checks whether a number can be losslessly converted to a float. bool IsLosslessFloat() const { if (!IsNumber()) return false; double a = GetDouble(); if (a < static_cast<double>(-(std::numeric_limits<float>::max)()) || a > static_cast<double>((std::numeric_limits<float>::max)())) return false; double b = static_cast<double>(static_cast<float>(a)); return a >= b && a <= b; // Prevent -Wfloat-equal } //@} //!@name Null //@{ GenericValue& SetNull() { this->~GenericValue(); new (this) GenericValue(); return *this; } //@} //!@name Bool //@{ bool GetBool() const { RAPIDJSON_ASSERT(IsBool()); return data_.f.flags == kTrueFlag; } //!< Set boolean value /*! \post IsBool() == true */ GenericValue& SetBool(bool b) { this->~GenericValue(); new (this) GenericValue(b); return *this; } //@} //!@name Object //@{ //! Set this value as an empty object. /*! \post IsObject() == true */ GenericValue& SetObject() { this->~GenericValue(); new (this) GenericValue(kObjectType); return *this; } //! Get the number of members in the object. SizeType MemberCount() const { RAPIDJSON_ASSERT(IsObject()); return data_.o.size; } //! Get the capacity of object. SizeType MemberCapacity() const { RAPIDJSON_ASSERT(IsObject()); return data_.o.capacity; } //! Check whether the object is empty. bool ObjectEmpty() const { RAPIDJSON_ASSERT(IsObject()); return data_.o.size == 0; } //! Get a value from an object associated with the name. /*! \pre IsObject() == true \tparam T Either \c Ch or \c const \c Ch (template used for disambiguation with \ref operator[](SizeType)) \note In version 0.1x, if the member is not found, this function returns a null value. This makes issue 7. Since 0.2, if the name is not correct, it will assert. If user is unsure whether a member exists, user should use HasMember() first. A better approach is to use FindMember(). \note Linear time complexity. */ template <typename T> RAPIDJSON_DISABLEIF_RETURN((internal::NotExpr<internal::IsSame<typename internal::RemoveConst<T>::Type, Ch> >),(GenericValue&)) operator[](T* name) { GenericValue n(StringRef(name)); return (*this)[n]; } template <typename T> RAPIDJSON_DISABLEIF_RETURN((internal::NotExpr<internal::IsSame<typename internal::RemoveConst<T>::Type, Ch> >),(const GenericValue&)) operator[](T* name) const { return const_cast<GenericValue&>(*this)[name]; } //! Get a value from an object associated with the name. /*! \pre IsObject() == true \tparam SourceAllocator Allocator of the \c name value \note Compared to \ref operator[](T*), this version is faster because it does not need a StrLen(). And it can also handle strings with embedded null characters. \note Linear time complexity. */ template <typename SourceAllocator> GenericValue& operator[](const GenericValue<Encoding, SourceAllocator>& name) { MemberIterator member = FindMember(name); if (member != MemberEnd()) return member->value; else { RAPIDJSON_ASSERT(false); // see above note // This will generate -Wexit-time-destructors in clang // static GenericValue NullValue; // return NullValue; // Use static buffer and placement-new to prevent destruction static char buffer[sizeof(GenericValue)]; return *new (buffer) GenericValue(); } } template <typename SourceAllocator> const GenericValue& operator[](const GenericValue<Encoding, SourceAllocator>& name) const { return const_cast<GenericValue&>(*this)[name]; } #if RAPIDJSON_HAS_STDSTRING //! Get a value from an object associated with name (string object). GenericValue& operator[](const std::basic_string<Ch>& name) { return (*this)[GenericValue(StringRef(name))]; } const GenericValue& operator[](const std::basic_string<Ch>& name) const { return (*this)[GenericValue(StringRef(name))]; } #endif //! Const member iterator /*! \pre IsObject() == true */ ConstMemberIterator MemberBegin() const { RAPIDJSON_ASSERT(IsObject()); return ConstMemberIterator(GetMembersPointer()); } //! Const \em past-the-end member iterator /*! \pre IsObject() == true */ ConstMemberIterator MemberEnd() const { RAPIDJSON_ASSERT(IsObject()); return ConstMemberIterator(GetMembersPointer() + data_.o.size); } //! Member iterator /*! \pre IsObject() == true */ MemberIterator MemberBegin() { RAPIDJSON_ASSERT(IsObject()); return MemberIterator(GetMembersPointer()); } //! \em Past-the-end member iterator /*! \pre IsObject() == true */ MemberIterator MemberEnd() { RAPIDJSON_ASSERT(IsObject()); return MemberIterator(GetMembersPointer() + data_.o.size); } //! Request the object to have enough capacity to store members. /*! \param newCapacity The capacity that the object at least need to have. \param allocator Allocator for reallocating memory. It must be the same one as used before. Commonly use GenericDocument::GetAllocator(). \return The value itself for fluent API. \note Linear time complexity. */ GenericValue& MemberReserve(SizeType newCapacity, Allocator &allocator) { RAPIDJSON_ASSERT(IsObject()); if (newCapacity > data_.o.capacity) { SetMembersPointer(reinterpret_cast<Member*>(allocator.Realloc(GetMembersPointer(), data_.o.capacity * sizeof(Member), newCapacity * sizeof(Member)))); data_.o.capacity = newCapacity; } return *this; } //! Check whether a member exists in the object. /*! \param name Member name to be searched. \pre IsObject() == true \return Whether a member with that name exists. \note It is better to use FindMember() directly if you need the obtain the value as well. \note Linear time complexity. */ bool HasMember(const Ch* name) const { return FindMember(name) != MemberEnd(); } #if RAPIDJSON_HAS_STDSTRING //! Check whether a member exists in the object with string object. /*! \param name Member name to be searched. \pre IsObject() == true \return Whether a member with that name exists. \note It is better to use FindMember() directly if you need the obtain the value as well. \note Linear time complexity. */ bool HasMember(const std::basic_string<Ch>& name) const { return FindMember(name) != MemberEnd(); } #endif //! Check whether a member exists in the object with GenericValue name. /*! This version is faster because it does not need a StrLen(). It can also handle string with null character. \param name Member name to be searched. \pre IsObject() == true \return Whether a member with that name exists. \note It is better to use FindMember() directly if you need the obtain the value as well. \note Linear time complexity. */ template <typename SourceAllocator> bool HasMember(const GenericValue<Encoding, SourceAllocator>& name) const { return FindMember(name) != MemberEnd(); } //! Find member by name. /*! \param name Member name to be searched. \pre IsObject() == true \return Iterator to member, if it exists. Otherwise returns \ref MemberEnd(). \note Earlier versions of Rapidjson returned a \c NULL pointer, in case the requested member doesn't exist. For consistency with e.g. \c std::map, this has been changed to MemberEnd() now. \note Linear time complexity. */ MemberIterator FindMember(const Ch* name) { GenericValue n(StringRef(name)); return FindMember(n); } ConstMemberIterator FindMember(const Ch* name) const { return const_cast<GenericValue&>(*this).FindMember(name); } //! Find member by name. /*! This version is faster because it does not need a StrLen(). It can also handle string with null character. \param name Member name to be searched. \pre IsObject() == true \return Iterator to member, if it exists. Otherwise returns \ref MemberEnd(). \note Earlier versions of Rapidjson returned a \c NULL pointer, in case the requested member doesn't exist. For consistency with e.g. \c std::map, this has been changed to MemberEnd() now. \note Linear time complexity. */ template <typename SourceAllocator> MemberIterator FindMember(const GenericValue<Encoding, SourceAllocator>& name) { RAPIDJSON_ASSERT(IsObject()); RAPIDJSON_ASSERT(name.IsString()); MemberIterator member = MemberBegin(); for ( ; member != MemberEnd(); ++member) if (name.StringEqual(member->name)) break; return member; } template <typename SourceAllocator> ConstMemberIterator FindMember(const GenericValue<Encoding, SourceAllocator>& name) const { return const_cast<GenericValue&>(*this).FindMember(name); } #if RAPIDJSON_HAS_STDSTRING //! Find member by string object name. /*! \param name Member name to be searched. \pre IsObject() == true \return Iterator to member, if it exists. Otherwise returns \ref MemberEnd(). */ MemberIterator FindMember(const std::basic_string<Ch>& name) { return FindMember(GenericValue(StringRef(name))); } ConstMemberIterator FindMember(const std::basic_string<Ch>& name) const { return FindMember(GenericValue(StringRef(name))); } #endif //! Add a member (name-value pair) to the object. /*! \param name A string value as name of member. \param value Value of any type. \param allocator Allocator for reallocating memory. It must be the same one as used before. Commonly use GenericDocument::GetAllocator(). \return The value itself for fluent API. \note The ownership of \c name and \c value will be transferred to this object on success. \pre IsObject() && name.IsString() \post name.IsNull() && value.IsNull() \note Amortized Constant time complexity. */ GenericValue& AddMember(GenericValue& name, GenericValue& value, Allocator& allocator) { RAPIDJSON_ASSERT(IsObject()); RAPIDJSON_ASSERT(name.IsString()); ObjectData& o = data_.o; if (o.size >= o.capacity) MemberReserve(o.capacity == 0 ? kDefaultObjectCapacity : (o.capacity + (o.capacity + 1) / 2), allocator); Member* members = GetMembersPointer(); members[o.size].name.RawAssign(name); members[o.size].value.RawAssign(value); o.size++; return *this; } //! Add a constant string value as member (name-value pair) to the object. /*! \param name A string value as name of member. \param value constant string reference as value of member. \param allocator Allocator for reallocating memory. It must be the same one as used before. Commonly use GenericDocument::GetAllocator(). \return The value itself for fluent API. \pre IsObject() \note This overload is needed to avoid clashes with the generic primitive type AddMember(GenericValue&,T,Allocator&) overload below. \note Amortized Constant time complexity. */ GenericValue& AddMember(GenericValue& name, StringRefType value, Allocator& allocator) { GenericValue v(value); return AddMember(name, v, allocator); } #if RAPIDJSON_HAS_STDSTRING //! Add a string object as member (name-value pair) to the object. /*! \param name A string value as name of member. \param value constant string reference as value of member. \param allocator Allocator for reallocating memory. It must be the same one as used before. Commonly use GenericDocument::GetAllocator(). \return The value itself for fluent API. \pre IsObject() \note This overload is needed to avoid clashes with the generic primitive type AddMember(GenericValue&,T,Allocator&) overload below. \note Amortized Constant time complexity. */ GenericValue& AddMember(GenericValue& name, std::basic_string<Ch>& value, Allocator& allocator) { GenericValue v(value, allocator); return AddMember(name, v, allocator); } #endif //! Add any primitive value as member (name-value pair) to the object. /*! \tparam T Either \ref Type, \c int, \c unsigned, \c int64_t, \c uint64_t \param name A string value as name of member. \param value Value of primitive type \c T as value of member \param allocator Allocator for reallocating memory. Commonly use GenericDocument::GetAllocator(). \return The value itself for fluent API. \pre IsObject() \note The source type \c T explicitly disallows all pointer types, especially (\c const) \ref Ch*. This helps avoiding implicitly referencing character strings with insufficient lifetime, use \ref AddMember(StringRefType, GenericValue&, Allocator&) or \ref AddMember(StringRefType, StringRefType, Allocator&). All other pointer types would implicitly convert to \c bool, use an explicit cast instead, if needed. \note Amortized Constant time complexity. */ template <typename T> RAPIDJSON_DISABLEIF_RETURN((internal::OrExpr<internal::IsPointer<T>, internal::IsGenericValue<T> >), (GenericValue&)) AddMember(GenericValue& name, T value, Allocator& allocator) { GenericValue v(value); return AddMember(name, v, allocator); } #if RAPIDJSON_HAS_CXX11_RVALUE_REFS GenericValue& AddMember(GenericValue&& name, GenericValue&& value, Allocator& allocator) { return AddMember(name, value, allocator); } GenericValue& AddMember(GenericValue&& name, GenericValue& value, Allocator& allocator) { return AddMember(name, value, allocator); } GenericValue& AddMember(GenericValue& name, GenericValue&& value, Allocator& allocator) { return AddMember(name, value, allocator); } GenericValue& AddMember(StringRefType name, GenericValue&& value, Allocator& allocator) { GenericValue n(name); return AddMember(n, value, allocator); } #endif // RAPIDJSON_HAS_CXX11_RVALUE_REFS //! Add a member (name-value pair) to the object. /*! \param name A constant string reference as name of member. \param value Value of any type. \param allocator Allocator for reallocating memory. It must be the same one as used before. Commonly use GenericDocument::GetAllocator(). \return The value itself for fluent API. \note The ownership of \c value will be transferred to this object on success. \pre IsObject() \post value.IsNull() \note Amortized Constant time complexity. */ GenericValue& AddMember(StringRefType name, GenericValue& value, Allocator& allocator) { GenericValue n(name); return AddMember(n, value, allocator); } //! Add a constant string value as member (name-value pair) to the object. /*! \param name A constant string reference as name of member. \param value constant string reference as value of member. \param allocator Allocator for reallocating memory. It must be the same one as used before. Commonly use GenericDocument::GetAllocator(). \return The value itself for fluent API. \pre IsObject() \note This overload is needed to avoid clashes with the generic primitive type AddMember(StringRefType,T,Allocator&) overload below. \note Amortized Constant time complexity. */ GenericValue& AddMember(StringRefType name, StringRefType value, Allocator& allocator) { GenericValue v(value); return AddMember(name, v, allocator); } //! Add any primitive value as member (name-value pair) to the object. /*! \tparam T Either \ref Type, \c int, \c unsigned, \c int64_t, \c uint64_t \param name A constant string reference as name of member. \param value Value of primitive type \c T as value of member \param allocator Allocator for reallocating memory. Commonly use GenericDocument::GetAllocator(). \return The value itself for fluent API. \pre IsObject() \note The source type \c T explicitly disallows all pointer types, especially (\c const) \ref Ch*. This helps avoiding implicitly referencing character strings with insufficient lifetime, use \ref AddMember(StringRefType, GenericValue&, Allocator&) or \ref AddMember(StringRefType, StringRefType, Allocator&). All other pointer types would implicitly convert to \c bool, use an explicit cast instead, if needed. \note Amortized Constant time complexity. */ template <typename T> RAPIDJSON_DISABLEIF_RETURN((internal::OrExpr<internal::IsPointer<T>, internal::IsGenericValue<T> >), (GenericValue&)) AddMember(StringRefType name, T value, Allocator& allocator) { GenericValue n(name); return AddMember(n, value, allocator); } //! Remove all members in the object. /*! This function do not deallocate memory in the object, i.e. the capacity is unchanged. \note Linear time complexity. */ void RemoveAllMembers() { RAPIDJSON_ASSERT(IsObject()); for (MemberIterator m = MemberBegin(); m != MemberEnd(); ++m) m->~Member(); data_.o.size = 0; } //! Remove a member in object by its name. /*! \param name Name of member to be removed. \return Whether the member existed. \note This function may reorder the object members. Use \ref EraseMember(ConstMemberIterator) if you need to preserve the relative order of the remaining members. \note Linear time complexity. */ bool RemoveMember(const Ch* name) { GenericValue n(StringRef(name)); return RemoveMember(n); } #if RAPIDJSON_HAS_STDSTRING bool RemoveMember(const std::basic_string<Ch>& name) { return RemoveMember(GenericValue(StringRef(name))); } #endif template <typename SourceAllocator> bool RemoveMember(const GenericValue<Encoding, SourceAllocator>& name) { MemberIterator m = FindMember(name); if (m != MemberEnd()) { RemoveMember(m); return true; } else return false; } //! Remove a member in object by iterator. /*! \param m member iterator (obtained by FindMember() or MemberBegin()). \return the new iterator after removal. \note This function may reorder the object members. Use \ref EraseMember(ConstMemberIterator) if you need to preserve the relative order of the remaining members. \note Constant time complexity. */ MemberIterator RemoveMember(MemberIterator m) { RAPIDJSON_ASSERT(IsObject()); RAPIDJSON_ASSERT(data_.o.size > 0); RAPIDJSON_ASSERT(GetMembersPointer() != 0); RAPIDJSON_ASSERT(m >= MemberBegin() && m < MemberEnd()); MemberIterator last(GetMembersPointer() + (data_.o.size - 1)); if (data_.o.size > 1 && m != last) *m = *last; // Move the last one to this place else m->~Member(); // Only one left, just destroy --data_.o.size; return m; } //! Remove a member from an object by iterator. /*! \param pos iterator to the member to remove \pre IsObject() == true && \ref MemberBegin() <= \c pos < \ref MemberEnd() \return Iterator following the removed element. If the iterator \c pos refers to the last element, the \ref MemberEnd() iterator is returned. \note This function preserves the relative order of the remaining object members. If you do not need this, use the more efficient \ref RemoveMember(MemberIterator). \note Linear time complexity. */ MemberIterator EraseMember(ConstMemberIterator pos) { return EraseMember(pos, pos +1); } //! Remove members in the range [first, last) from an object. /*! \param first iterator to the first member to remove \param last iterator following the last member to remove \pre IsObject() == true && \ref MemberBegin() <= \c first <= \c last <= \ref MemberEnd() \return Iterator following the last removed element. \note This function preserves the relative order of the remaining object members. \note Linear time complexity. */ MemberIterator EraseMember(ConstMemberIterator first, ConstMemberIterator last) { RAPIDJSON_ASSERT(IsObject()); RAPIDJSON_ASSERT(data_.o.size > 0); RAPIDJSON_ASSERT(GetMembersPointer() != 0); RAPIDJSON_ASSERT(first >= MemberBegin()); RAPIDJSON_ASSERT(first <= last); RAPIDJSON_ASSERT(last <= MemberEnd()); MemberIterator pos = MemberBegin() + (first - MemberBegin()); for (MemberIterator itr = pos; itr != last; ++itr) itr->~Member(); std::memmove(static_cast<void*>(&*pos), &*last, static_cast<size_t>(MemberEnd() - last) * sizeof(Member)); data_.o.size -= static_cast<SizeType>(last - first); return pos; } //! Erase a member in object by its name. /*! \param name Name of member to be removed. \return Whether the member existed. \note Linear time complexity. */ bool EraseMember(const Ch* name) { GenericValue n(StringRef(name)); return EraseMember(n); } #if RAPIDJSON_HAS_STDSTRING bool EraseMember(const std::basic_string<Ch>& name) { return EraseMember(GenericValue(StringRef(name))); } #endif template <typename SourceAllocator> bool EraseMember(const GenericValue<Encoding, SourceAllocator>& name) { MemberIterator m = FindMember(name); if (m != MemberEnd()) { EraseMember(m); return true; } else return false; } Object GetObject() { RAPIDJSON_ASSERT(IsObject()); return Object(*this); } ConstObject GetObject() const { RAPIDJSON_ASSERT(IsObject()); return ConstObject(*this); } //@} //!@name Array //@{ //! Set this value as an empty array. /*! \post IsArray == true */ GenericValue& SetArray() { this->~GenericValue(); new (this) GenericValue(kArrayType); return *this; } //! Get the number of elements in array. SizeType Size() const { RAPIDJSON_ASSERT(IsArray()); return data_.a.size; } //! Get the capacity of array. SizeType Capacity() const { RAPIDJSON_ASSERT(IsArray()); return data_.a.capacity; } //! Check whether the array is empty. bool Empty() const { RAPIDJSON_ASSERT(IsArray()); return data_.a.size == 0; } //! Remove all elements in the array. /*! This function do not deallocate memory in the array, i.e. the capacity is unchanged. \note Linear time complexity. */ void Clear() { RAPIDJSON_ASSERT(IsArray()); GenericValue* e = GetElementsPointer(); for (GenericValue* v = e; v != e + data_.a.size; ++v) v->~GenericValue(); data_.a.size = 0; } //! Get an element from array by index. /*! \pre IsArray() == true \param index Zero-based index of element. \see operator[](T*) */ GenericValue& operator[](SizeType index) { RAPIDJSON_ASSERT(IsArray()); RAPIDJSON_ASSERT(index < data_.a.size); return GetElementsPointer()[index]; } const GenericValue& operator[](SizeType index) const { return const_cast<GenericValue&>(*this)[index]; } //! Element iterator /*! \pre IsArray() == true */ ValueIterator Begin() { RAPIDJSON_ASSERT(IsArray()); return GetElementsPointer(); } //! \em Past-the-end element iterator /*! \pre IsArray() == true */ ValueIterator End() { RAPIDJSON_ASSERT(IsArray()); return GetElementsPointer() + data_.a.size; } //! Constant element iterator /*! \pre IsArray() == true */ ConstValueIterator Begin() const { return const_cast<GenericValue&>(*this).Begin(); } //! Constant \em past-the-end element iterator /*! \pre IsArray() == true */ ConstValueIterator End() const { return const_cast<GenericValue&>(*this).End(); } //! Request the array to have enough capacity to store elements. /*! \param newCapacity The capacity that the array at least need to have. \param allocator Allocator for reallocating memory. It must be the same one as used before. Commonly use GenericDocument::GetAllocator(). \return The value itself for fluent API. \note Linear time complexity. */ GenericValue& Reserve(SizeType newCapacity, Allocator &allocator) { RAPIDJSON_ASSERT(IsArray()); if (newCapacity > data_.a.capacity) { SetElementsPointer(reinterpret_cast<GenericValue*>(allocator.Realloc(GetElementsPointer(), data_.a.capacity * sizeof(GenericValue), newCapacity * sizeof(GenericValue)))); data_.a.capacity = newCapacity; } return *this; } //! Append a GenericValue at the end of the array. /*! \param value Value to be appended. \param allocator Allocator for reallocating memory. It must be the same one as used before. Commonly use GenericDocument::GetAllocator(). \pre IsArray() == true \post value.IsNull() == true \return The value itself for fluent API. \note The ownership of \c value will be transferred to this array on success. \note If the number of elements to be appended is known, calls Reserve() once first may be more efficient. \note Amortized constant time complexity. */ GenericValue& PushBack(GenericValue& value, Allocator& allocator) { RAPIDJSON_ASSERT(IsArray()); if (data_.a.size >= data_.a.capacity) Reserve(data_.a.capacity == 0 ? kDefaultArrayCapacity : (data_.a.capacity + (data_.a.capacity + 1) / 2), allocator); GetElementsPointer()[data_.a.size++].RawAssign(value); return *this; } #if RAPIDJSON_HAS_CXX11_RVALUE_REFS GenericValue& PushBack(GenericValue&& value, Allocator& allocator) { return PushBack(value, allocator); } #endif // RAPIDJSON_HAS_CXX11_RVALUE_REFS //! Append a constant string reference at the end of the array. /*! \param value Constant string reference to be appended. \param allocator Allocator for reallocating memory. It must be the same one used previously. Commonly use GenericDocument::GetAllocator(). \pre IsArray() == true \return The value itself for fluent API. \note If the number of elements to be appended is known, calls Reserve() once first may be more efficient. \note Amortized constant time complexity. \see GenericStringRef */ GenericValue& PushBack(StringRefType value, Allocator& allocator) { return (*this).template PushBack<StringRefType>(value, allocator); } //! Append a primitive value at the end of the array. /*! \tparam T Either \ref Type, \c int, \c unsigned, \c int64_t, \c uint64_t \param value Value of primitive type T to be appended. \param allocator Allocator for reallocating memory. It must be the same one as used before. Commonly use GenericDocument::GetAllocator(). \pre IsArray() == true \return The value itself for fluent API. \note If the number of elements to be appended is known, calls Reserve() once first may be more efficient. \note The source type \c T explicitly disallows all pointer types, especially (\c const) \ref Ch*. This helps avoiding implicitly referencing character strings with insufficient lifetime, use \ref PushBack(GenericValue&, Allocator&) or \ref PushBack(StringRefType, Allocator&). All other pointer types would implicitly convert to \c bool, use an explicit cast instead, if needed. \note Amortized constant time complexity. */ template <typename T> RAPIDJSON_DISABLEIF_RETURN((internal::OrExpr<internal::IsPointer<T>, internal::IsGenericValue<T> >), (GenericValue&)) PushBack(T value, Allocator& allocator) { GenericValue v(value); return PushBack(v, allocator); } //! Remove the last element in the array. /*! \note Constant time complexity. */ GenericValue& PopBack() { RAPIDJSON_ASSERT(IsArray()); RAPIDJSON_ASSERT(!Empty()); GetElementsPointer()[--data_.a.size].~GenericValue(); return *this; } //! Remove an element of array by iterator. /*! \param pos iterator to the element to remove \pre IsArray() == true && \ref Begin() <= \c pos < \ref End() \return Iterator following the removed element. If the iterator pos refers to the last element, the End() iterator is returned. \note Linear time complexity. */ ValueIterator Erase(ConstValueIterator pos) { return Erase(pos, pos + 1); } //! Remove elements in the range [first, last) of the array. /*! \param first iterator to the first element to remove \param last iterator following the last element to remove \pre IsArray() == true && \ref Begin() <= \c first <= \c last <= \ref End() \return Iterator following the last removed element. \note Linear time complexity. */ ValueIterator Erase(ConstValueIterator first, ConstValueIterator last) { RAPIDJSON_ASSERT(IsArray()); RAPIDJSON_ASSERT(data_.a.size > 0); RAPIDJSON_ASSERT(GetElementsPointer() != 0); RAPIDJSON_ASSERT(first >= Begin()); RAPIDJSON_ASSERT(first <= last); RAPIDJSON_ASSERT(last <= End()); ValueIterator pos = Begin() + (first - Begin()); for (ValueIterator itr = pos; itr != last; ++itr) itr->~GenericValue(); std::memmove(static_cast<void*>(pos), last, static_cast<size_t>(End() - last) * sizeof(GenericValue)); data_.a.size -= static_cast<SizeType>(last - first); return pos; } Array GetArray() { RAPIDJSON_ASSERT(IsArray()); return Array(*this); } ConstArray GetArray() const { RAPIDJSON_ASSERT(IsArray()); return ConstArray(*this); } //@} //!@name Number //@{ int GetInt() const { RAPIDJSON_ASSERT(data_.f.flags & kIntFlag); return data_.n.i.i; } unsigned GetUint() const { RAPIDJSON_ASSERT(data_.f.flags & kUintFlag); return data_.n.u.u; } int64_t GetInt64() const { RAPIDJSON_ASSERT(data_.f.flags & kInt64Flag); return data_.n.i64; } uint64_t GetUint64() const { RAPIDJSON_ASSERT(data_.f.flags & kUint64Flag); return data_.n.u64; } //! Get the value as double type. /*! \note If the value is 64-bit integer type, it may lose precision. Use \c IsLosslessDouble() to check whether the converison is lossless. */ double GetDouble() const { RAPIDJSON_ASSERT(IsNumber()); if ((data_.f.flags & kDoubleFlag) != 0) return data_.n.d; // exact type, no conversion. if ((data_.f.flags & kIntFlag) != 0) return data_.n.i.i; // int -> double if ((data_.f.flags & kUintFlag) != 0) return data_.n.u.u; // unsigned -> double if ((data_.f.flags & kInt64Flag) != 0) return static_cast<double>(data_.n.i64); // int64_t -> double (may lose precision) RAPIDJSON_ASSERT((data_.f.flags & kUint64Flag) != 0); return static_cast<double>(data_.n.u64); // uint64_t -> double (may lose precision) } //! Get the value as float type. /*! \note If the value is 64-bit integer type, it may lose precision. Use \c IsLosslessFloat() to check whether the converison is lossless. */ float GetFloat() const { return static_cast<float>(GetDouble()); } GenericValue& SetInt(int i) { this->~GenericValue(); new (this) GenericValue(i); return *this; } GenericValue& SetUint(unsigned u) { this->~GenericValue(); new (this) GenericValue(u); return *this; } GenericValue& SetInt64(int64_t i64) { this->~GenericValue(); new (this) GenericValue(i64); return *this; } GenericValue& SetUint64(uint64_t u64) { this->~GenericValue(); new (this) GenericValue(u64); return *this; } GenericValue& SetDouble(double d) { this->~GenericValue(); new (this) GenericValue(d); return *this; } GenericValue& SetFloat(float f) { this->~GenericValue(); new (this) GenericValue(static_cast<double>(f)); return *this; } //@} //!@name String //@{ const Ch* GetString() const { RAPIDJSON_ASSERT(IsString()); return (data_.f.flags & kInlineStrFlag) ? data_.ss.str : GetStringPointer(); } //! Get the length of string. /*! Since rapidjson permits "\\u0000" in the json string, strlen(v.GetString()) may not equal to v.GetStringLength(). */ SizeType GetStringLength() const { RAPIDJSON_ASSERT(IsString()); return ((data_.f.flags & kInlineStrFlag) ? (data_.ss.GetLength()) : data_.s.length); } //! Set this value as a string without copying source string. /*! This version has better performance with supplied length, and also support string containing null character. \param s source string pointer. \param length The length of source string, excluding the trailing null terminator. \return The value itself for fluent API. \post IsString() == true && GetString() == s && GetStringLength() == length \see SetString(StringRefType) */ GenericValue& SetString(const Ch* s, SizeType length) { return SetString(StringRef(s, length)); } //! Set this value as a string without copying source string. /*! \param s source string reference \return The value itself for fluent API. \post IsString() == true && GetString() == s && GetStringLength() == s.length */ GenericValue& SetString(StringRefType s) { this->~GenericValue(); SetStringRaw(s); return *this; } //! Set this value as a string by copying from source string. /*! This version has better performance with supplied length, and also support string containing null character. \param s source string. \param length The length of source string, excluding the trailing null terminator. \param allocator Allocator for allocating copied buffer. Commonly use GenericDocument::GetAllocator(). \return The value itself for fluent API. \post IsString() == true && GetString() != s && strcmp(GetString(),s) == 0 && GetStringLength() == length */ GenericValue& SetString(const Ch* s, SizeType length, Allocator& allocator) { return SetString(StringRef(s, length), allocator); } //! Set this value as a string by copying from source string. /*! \param s source string. \param allocator Allocator for allocating copied buffer. Commonly use GenericDocument::GetAllocator(). \return The value itself for fluent API. \post IsString() == true && GetString() != s && strcmp(GetString(),s) == 0 && GetStringLength() == length */ GenericValue& SetString(const Ch* s, Allocator& allocator) { return SetString(StringRef(s), allocator); } //! Set this value as a string by copying from source string. /*! \param s source string reference \param allocator Allocator for allocating copied buffer. Commonly use GenericDocument::GetAllocator(). \return The value itself for fluent API. \post IsString() == true && GetString() != s.s && strcmp(GetString(),s) == 0 && GetStringLength() == length */ GenericValue& SetString(StringRefType s, Allocator& allocator) { this->~GenericValue(); SetStringRaw(s, allocator); return *this; } #if RAPIDJSON_HAS_STDSTRING //! Set this value as a string by copying from source string. /*! \param s source string. \param allocator Allocator for allocating copied buffer. Commonly use GenericDocument::GetAllocator(). \return The value itself for fluent API. \post IsString() == true && GetString() != s.data() && strcmp(GetString(),s.data() == 0 && GetStringLength() == s.size() \note Requires the definition of the preprocessor symbol \ref RAPIDJSON_HAS_STDSTRING. */ GenericValue& SetString(const std::basic_string<Ch>& s, Allocator& allocator) { return SetString(StringRef(s), allocator); } #endif //@} //!@name Array //@{ //! Templated version for checking whether this value is type T. /*! \tparam T Either \c bool, \c int, \c unsigned, \c int64_t, \c uint64_t, \c double, \c float, \c const \c char*, \c std::basic_string<Ch> */ template <typename T> bool Is() const { return internal::TypeHelper<ValueType, T>::Is(*this); } template <typename T> T Get() const { return internal::TypeHelper<ValueType, T>::Get(*this); } template <typename T> T Get() { return internal::TypeHelper<ValueType, T>::Get(*this); } template<typename T> ValueType& Set(const T& data) { return internal::TypeHelper<ValueType, T>::Set(*this, data); } template<typename T> ValueType& Set(const T& data, AllocatorType& allocator) { return internal::TypeHelper<ValueType, T>::Set(*this, data, allocator); } //@} //! Generate events of this value to a Handler. /*! This function adopts the GoF visitor pattern. Typical usage is to output this JSON value as JSON text via Writer, which is a Handler. It can also be used to deep clone this value via GenericDocument, which is also a Handler. \tparam Handler type of handler. \param handler An object implementing concept Handler. */ template <typename Handler> bool Accept(Handler& handler) const { switch(GetType()) { case kNullType: return handler.Null(); case kFalseType: return handler.Bool(false); case kTrueType: return handler.Bool(true); case kObjectType: if (RAPIDJSON_UNLIKELY(!handler.StartObject())) return false; for (ConstMemberIterator m = MemberBegin(); m != MemberEnd(); ++m) { RAPIDJSON_ASSERT(m->name.IsString()); // User may change the type of name by MemberIterator. if (RAPIDJSON_UNLIKELY(!handler.Key(m->name.GetString(), m->name.GetStringLength(), (m->name.data_.f.flags & kCopyFlag) != 0))) return false; if (RAPIDJSON_UNLIKELY(!m->value.Accept(handler))) return false; } return handler.EndObject(data_.o.size); case kArrayType: if (RAPIDJSON_UNLIKELY(!handler.StartArray())) return false; for (const GenericValue* v = Begin(); v != End(); ++v) if (RAPIDJSON_UNLIKELY(!v->Accept(handler))) return false; return handler.EndArray(data_.a.size); case kStringType: return handler.String(GetString(), GetStringLength(), (data_.f.flags & kCopyFlag) != 0); default: RAPIDJSON_ASSERT(GetType() == kNumberType); if (IsDouble()) return handler.Double(data_.n.d); else if (IsInt()) return handler.Int(data_.n.i.i); else if (IsUint()) return handler.Uint(data_.n.u.u); else if (IsInt64()) return handler.Int64(data_.n.i64); else return handler.Uint64(data_.n.u64); } } private: template <typename, typename> friend class GenericValue; template <typename, typename, typename> friend class GenericDocument; enum { kBoolFlag = 0x0008, kNumberFlag = 0x0010, kIntFlag = 0x0020, kUintFlag = 0x0040, kInt64Flag = 0x0080, kUint64Flag = 0x0100, kDoubleFlag = 0x0200, kStringFlag = 0x0400, kCopyFlag = 0x0800, kInlineStrFlag = 0x1000, // Initial flags of different types. kNullFlag = kNullType, kTrueFlag = kTrueType | kBoolFlag, kFalseFlag = kFalseType | kBoolFlag, kNumberIntFlag = kNumberType | kNumberFlag | kIntFlag | kInt64Flag, kNumberUintFlag = kNumberType | kNumberFlag | kUintFlag | kUint64Flag | kInt64Flag, kNumberInt64Flag = kNumberType | kNumberFlag | kInt64Flag, kNumberUint64Flag = kNumberType | kNumberFlag | kUint64Flag, kNumberDoubleFlag = kNumberType | kNumberFlag | kDoubleFlag, kNumberAnyFlag = kNumberType | kNumberFlag | kIntFlag | kInt64Flag | kUintFlag | kUint64Flag | kDoubleFlag, kConstStringFlag = kStringType | kStringFlag, kCopyStringFlag = kStringType | kStringFlag | kCopyFlag, kShortStringFlag = kStringType | kStringFlag | kCopyFlag | kInlineStrFlag, kObjectFlag = kObjectType, kArrayFlag = kArrayType, kTypeMask = 0x07 }; static const SizeType kDefaultArrayCapacity = RAPIDJSON_VALUE_DEFAULT_ARRAY_CAPACITY; static const SizeType kDefaultObjectCapacity = RAPIDJSON_VALUE_DEFAULT_OBJECT_CAPACITY; struct Flag { #if RAPIDJSON_48BITPOINTER_OPTIMIZATION char payload[sizeof(SizeType) * 2 + 6]; // 2 x SizeType + lower 48-bit pointer #elif RAPIDJSON_64BIT char payload[sizeof(SizeType) * 2 + sizeof(void*) + 6]; // 6 padding bytes #else char payload[sizeof(SizeType) * 2 + sizeof(void*) + 2]; // 2 padding bytes #endif uint16_t flags; }; struct String { SizeType length; SizeType hashcode; //!< reserved const Ch* str; }; // 12 bytes in 32-bit mode, 16 bytes in 64-bit mode // implementation detail: ShortString can represent zero-terminated strings up to MaxSize chars // (excluding the terminating zero) and store a value to determine the length of the contained // string in the last character str[LenPos] by storing "MaxSize - length" there. If the string // to store has the maximal length of MaxSize then str[LenPos] will be 0 and therefore act as // the string terminator as well. For getting the string length back from that value just use // "MaxSize - str[LenPos]". // This allows to store 13-chars strings in 32-bit mode, 21-chars strings in 64-bit mode, // 13-chars strings for RAPIDJSON_48BITPOINTER_OPTIMIZATION=1 inline (for `UTF8`-encoded strings). struct ShortString { enum { MaxChars = sizeof(static_cast<Flag*>(0)->payload) / sizeof(Ch), MaxSize = MaxChars - 1, LenPos = MaxSize }; Ch str[MaxChars]; inline static bool Usable(SizeType len) { return (MaxSize >= len); } inline void SetLength(SizeType len) { str[LenPos] = static_cast<Ch>(MaxSize - len); } inline SizeType GetLength() const { return static_cast<SizeType>(MaxSize - str[LenPos]); } }; // at most as many bytes as "String" above => 12 bytes in 32-bit mode, 16 bytes in 64-bit mode // By using proper binary layout, retrieval of different integer types do not need conversions. union Number { #if RAPIDJSON_ENDIAN == RAPIDJSON_LITTLEENDIAN struct I { int i; char padding[4]; }i; struct U { unsigned u; char padding2[4]; }u; #else struct I { char padding[4]; int i; }i; struct U { char padding2[4]; unsigned u; }u; #endif int64_t i64; uint64_t u64; double d; }; // 8 bytes struct ObjectData { SizeType size; SizeType capacity; Member* members; }; // 12 bytes in 32-bit mode, 16 bytes in 64-bit mode struct ArrayData { SizeType size; SizeType capacity; GenericValue* elements; }; // 12 bytes in 32-bit mode, 16 bytes in 64-bit mode union Data { String s; ShortString ss; Number n; ObjectData o; ArrayData a; Flag f; }; // 16 bytes in 32-bit mode, 24 bytes in 64-bit mode, 16 bytes in 64-bit with RAPIDJSON_48BITPOINTER_OPTIMIZATION RAPIDJSON_FORCEINLINE const Ch* GetStringPointer() const { return RAPIDJSON_GETPOINTER(Ch, data_.s.str); } RAPIDJSON_FORCEINLINE const Ch* SetStringPointer(const Ch* str) { return RAPIDJSON_SETPOINTER(Ch, data_.s.str, str); } RAPIDJSON_FORCEINLINE GenericValue* GetElementsPointer() const { return RAPIDJSON_GETPOINTER(GenericValue, data_.a.elements); } RAPIDJSON_FORCEINLINE GenericValue* SetElementsPointer(GenericValue* elements) { return RAPIDJSON_SETPOINTER(GenericValue, data_.a.elements, elements); } RAPIDJSON_FORCEINLINE Member* GetMembersPointer() const { return RAPIDJSON_GETPOINTER(Member, data_.o.members); } RAPIDJSON_FORCEINLINE Member* SetMembersPointer(Member* members) { return RAPIDJSON_SETPOINTER(Member, data_.o.members, members); } // Initialize this value as array with initial data, without calling destructor. void SetArrayRaw(GenericValue* values, SizeType count, Allocator& allocator) { data_.f.flags = kArrayFlag; if (count) { GenericValue* e = static_cast<GenericValue*>(allocator.Malloc(count * sizeof(GenericValue))); SetElementsPointer(e); std::memcpy(static_cast<void*>(e), values, count * sizeof(GenericValue)); } else SetElementsPointer(0); data_.a.size = data_.a.capacity = count; } //! Initialize this value as object with initial data, without calling destructor. void SetObjectRaw(Member* members, SizeType count, Allocator& allocator) { data_.f.flags = kObjectFlag; if (count) { Member* m = static_cast<Member*>(allocator.Malloc(count * sizeof(Member))); SetMembersPointer(m); std::memcpy(static_cast<void*>(m), members, count * sizeof(Member)); } else SetMembersPointer(0); data_.o.size = data_.o.capacity = count; } //! Initialize this value as constant string, without calling destructor. void SetStringRaw(StringRefType s) RAPIDJSON_NOEXCEPT { data_.f.flags = kConstStringFlag; SetStringPointer(s); data_.s.length = s.length; } //! Initialize this value as copy string with initial data, without calling destructor. void SetStringRaw(StringRefType s, Allocator& allocator) { Ch* str = 0; if (ShortString::Usable(s.length)) { data_.f.flags = kShortStringFlag; data_.ss.SetLength(s.length); str = data_.ss.str; } else { data_.f.flags = kCopyStringFlag; data_.s.length = s.length; str = static_cast<Ch *>(allocator.Malloc((s.length + 1) * sizeof(Ch))); SetStringPointer(str); } std::memcpy(str, s, s.length * sizeof(Ch)); str[s.length] = '\0'; } //! Assignment without calling destructor void RawAssign(GenericValue& rhs) RAPIDJSON_NOEXCEPT { data_ = rhs.data_; // data_.f.flags = rhs.data_.f.flags; rhs.data_.f.flags = kNullFlag; } template <typename SourceAllocator> bool StringEqual(const GenericValue<Encoding, SourceAllocator>& rhs) const { RAPIDJSON_ASSERT(IsString()); RAPIDJSON_ASSERT(rhs.IsString()); const SizeType len1 = GetStringLength(); const SizeType len2 = rhs.GetStringLength(); if(len1 != len2) { return false; } const Ch* const str1 = GetString(); const Ch* const str2 = rhs.GetString(); if(str1 == str2) { return true; } // fast path for constant string return (std::memcmp(str1, str2, sizeof(Ch) * len1) == 0); } Data data_; }; //! GenericValue with UTF8 encoding typedef GenericValue<UTF8<> > Value; /////////////////////////////////////////////////////////////////////////////// // GenericDocument //! A document for parsing JSON text as DOM. /*! \note implements Handler concept \tparam Encoding Encoding for both parsing and string storage. \tparam Allocator Allocator for allocating memory for the DOM \tparam StackAllocator Allocator for allocating memory for stack during parsing. \warning Although GenericDocument inherits from GenericValue, the API does \b not provide any virtual functions, especially no virtual destructor. To avoid memory leaks, do not \c delete a GenericDocument object via a pointer to a GenericValue. */ template <typename Encoding, typename Allocator = RAPIDJSON_DEFAULT_ALLOCATOR, typename StackAllocator = RAPIDJSON_DEFAULT_STACK_ALLOCATOR > class GenericDocument : public GenericValue<Encoding, Allocator> { public: typedef typename Encoding::Ch Ch; //!< Character type derived from Encoding. typedef GenericValue<Encoding, Allocator> ValueType; //!< Value type of the document. typedef Allocator AllocatorType; //!< Allocator type from template parameter. //! Constructor /*! Creates an empty document of specified type. \param type Mandatory type of object to create. \param allocator Optional allocator for allocating memory. \param stackCapacity Optional initial capacity of stack in bytes. \param stackAllocator Optional allocator for allocating memory for stack. */ explicit GenericDocument(Type type, Allocator* allocator = 0, size_t stackCapacity = kDefaultStackCapacity, StackAllocator* stackAllocator = 0) : GenericValue<Encoding, Allocator>(type), allocator_(allocator), ownAllocator_(0), stack_(stackAllocator, stackCapacity), parseResult_() { if (!allocator_) ownAllocator_ = allocator_ = RAPIDJSON_NEW(Allocator)(); } //! Constructor /*! Creates an empty document which type is Null. \param allocator Optional allocator for allocating memory. \param stackCapacity Optional initial capacity of stack in bytes. \param stackAllocator Optional allocator for allocating memory for stack. */ GenericDocument(Allocator* allocator = 0, size_t stackCapacity = kDefaultStackCapacity, StackAllocator* stackAllocator = 0) : allocator_(allocator), ownAllocator_(0), stack_(stackAllocator, stackCapacity), parseResult_() { if (!allocator_) ownAllocator_ = allocator_ = RAPIDJSON_NEW(Allocator)(); } #if RAPIDJSON_HAS_CXX11_RVALUE_REFS //! Move constructor in C++11 GenericDocument(GenericDocument&& rhs) RAPIDJSON_NOEXCEPT : ValueType(std::forward<ValueType>(rhs)), // explicit cast to avoid prohibited move from Document allocator_(rhs.allocator_), ownAllocator_(rhs.ownAllocator_), stack_(std::move(rhs.stack_)), parseResult_(rhs.parseResult_) { rhs.allocator_ = 0; rhs.ownAllocator_ = 0; rhs.parseResult_ = ParseResult(); } #endif ~GenericDocument() { Destroy(); } #if RAPIDJSON_HAS_CXX11_RVALUE_REFS //! Move assignment in C++11 GenericDocument& operator=(GenericDocument&& rhs) RAPIDJSON_NOEXCEPT { // The cast to ValueType is necessary here, because otherwise it would // attempt to call GenericValue's templated assignment operator. ValueType::operator=(std::forward<ValueType>(rhs)); // Calling the destructor here would prematurely call stack_'s destructor Destroy(); allocator_ = rhs.allocator_; ownAllocator_ = rhs.ownAllocator_; stack_ = std::move(rhs.stack_); parseResult_ = rhs.parseResult_; rhs.allocator_ = 0; rhs.ownAllocator_ = 0; rhs.parseResult_ = ParseResult(); return *this; } #endif //! Exchange the contents of this document with those of another. /*! \param rhs Another document. \note Constant complexity. \see GenericValue::Swap */ GenericDocument& Swap(GenericDocument& rhs) RAPIDJSON_NOEXCEPT { ValueType::Swap(rhs); stack_.Swap(rhs.stack_); internal::Swap(allocator_, rhs.allocator_); internal::Swap(ownAllocator_, rhs.ownAllocator_); internal::Swap(parseResult_, rhs.parseResult_); return *this; } // Allow Swap with ValueType. // Refer to Effective C++ 3rd Edition/Item 33: Avoid hiding inherited names. using ValueType::Swap; //! free-standing swap function helper /*! Helper function to enable support for common swap implementation pattern based on \c std::swap: \code void swap(MyClass& a, MyClass& b) { using std::swap; swap(a.doc, b.doc); // ... } \endcode \see Swap() */ friend inline void swap(GenericDocument& a, GenericDocument& b) RAPIDJSON_NOEXCEPT { a.Swap(b); } //! Populate this document by a generator which produces SAX events. /*! \tparam Generator A functor with <tt>bool f(Handler)</tt> prototype. \param g Generator functor which sends SAX events to the parameter. \return The document itself for fluent API. */ template <typename Generator> GenericDocument& Populate(Generator& g) { ClearStackOnExit scope(*this); if (g(*this)) { RAPIDJSON_ASSERT(stack_.GetSize() == sizeof(ValueType)); // Got one and only one root object ValueType::operator=(*stack_.template Pop<ValueType>(1));// Move value from stack to document } return *this; } //!@name Parse from stream //!@{ //! Parse JSON text from an input stream (with Encoding conversion) /*! \tparam parseFlags Combination of \ref ParseFlag. \tparam SourceEncoding Encoding of input stream \tparam InputStream Type of input stream, implementing Stream concept \param is Input stream to be parsed. \return The document itself for fluent API. */ template <unsigned parseFlags, typename SourceEncoding, typename InputStream> GenericDocument& ParseStream(InputStream& is) { GenericReader<SourceEncoding, Encoding, StackAllocator> reader( stack_.HasAllocator() ? &stack_.GetAllocator() : 0); ClearStackOnExit scope(*this); parseResult_ = reader.template Parse<parseFlags>(is, *this); if (parseResult_) { RAPIDJSON_ASSERT(stack_.GetSize() == sizeof(ValueType)); // Got one and only one root object ValueType::operator=(*stack_.template Pop<ValueType>(1));// Move value from stack to document } return *this; } //! Parse JSON text from an input stream /*! \tparam parseFlags Combination of \ref ParseFlag. \tparam InputStream Type of input stream, implementing Stream concept \param is Input stream to be parsed. \return The document itself for fluent API. */ template <unsigned parseFlags, typename InputStream> GenericDocument& ParseStream(InputStream& is) { return ParseStream<parseFlags, Encoding, InputStream>(is); } //! Parse JSON text from an input stream (with \ref kParseDefaultFlags) /*! \tparam InputStream Type of input stream, implementing Stream concept \param is Input stream to be parsed. \return The document itself for fluent API. */ template <typename InputStream> GenericDocument& ParseStream(InputStream& is) { return ParseStream<kParseDefaultFlags, Encoding, InputStream>(is); } //!@} //!@name Parse in-place from mutable string //!@{ //! Parse JSON text from a mutable string /*! \tparam parseFlags Combination of \ref ParseFlag. \param str Mutable zero-terminated string to be parsed. \return The document itself for fluent API. */ template <unsigned parseFlags> GenericDocument& ParseInsitu(Ch* str) { GenericInsituStringStream<Encoding> s(str); return ParseStream<parseFlags | kParseInsituFlag>(s); } //! Parse JSON text from a mutable string (with \ref kParseDefaultFlags) /*! \param str Mutable zero-terminated string to be parsed. \return The document itself for fluent API. */ GenericDocument& ParseInsitu(Ch* str) { return ParseInsitu<kParseDefaultFlags>(str); } //!@} //!@name Parse from read-only string //!@{ //! Parse JSON text from a read-only string (with Encoding conversion) /*! \tparam parseFlags Combination of \ref ParseFlag (must not contain \ref kParseInsituFlag). \tparam SourceEncoding Transcoding from input Encoding \param str Read-only zero-terminated string to be parsed. */ template <unsigned parseFlags, typename SourceEncoding> GenericDocument& Parse(const typename SourceEncoding::Ch* str) { RAPIDJSON_ASSERT(!(parseFlags & kParseInsituFlag)); GenericStringStream<SourceEncoding> s(str); return ParseStream<parseFlags, SourceEncoding>(s); } //! Parse JSON text from a read-only string /*! \tparam parseFlags Combination of \ref ParseFlag (must not contain \ref kParseInsituFlag). \param str Read-only zero-terminated string to be parsed. */ template <unsigned parseFlags> GenericDocument& Parse(const Ch* str) { return Parse<parseFlags, Encoding>(str); } //! Parse JSON text from a read-only string (with \ref kParseDefaultFlags) /*! \param str Read-only zero-terminated string to be parsed. */ GenericDocument& Parse(const Ch* str) { return Parse<kParseDefaultFlags>(str); } template <unsigned parseFlags, typename SourceEncoding> GenericDocument& Parse(const typename SourceEncoding::Ch* str, size_t length) { RAPIDJSON_ASSERT(!(parseFlags & kParseInsituFlag)); MemoryStream ms(reinterpret_cast<const char*>(str), length * sizeof(typename SourceEncoding::Ch)); EncodedInputStream<SourceEncoding, MemoryStream> is(ms); ParseStream<parseFlags, SourceEncoding>(is); return *this; } template <unsigned parseFlags> GenericDocument& Parse(const Ch* str, size_t length) { return Parse<parseFlags, Encoding>(str, length); } GenericDocument& Parse(const Ch* str, size_t length) { return Parse<kParseDefaultFlags>(str, length); } #if RAPIDJSON_HAS_STDSTRING template <unsigned parseFlags, typename SourceEncoding> GenericDocument& Parse(const std::basic_string<typename SourceEncoding::Ch>& str) { // c_str() is constant complexity according to standard. Should be faster than Parse(const char*, size_t) return Parse<parseFlags, SourceEncoding>(str.c_str()); } template <unsigned parseFlags> GenericDocument& Parse(const std::basic_string<Ch>& str) { return Parse<parseFlags, Encoding>(str.c_str()); } GenericDocument& Parse(const std::basic_string<Ch>& str) { return Parse<kParseDefaultFlags>(str); } #endif // RAPIDJSON_HAS_STDSTRING //!@} //!@name Handling parse errors //!@{ //! Whether a parse error has occurred in the last parsing. bool HasParseError() const { return parseResult_.IsError(); } //! Get the \ref ParseErrorCode of last parsing. ParseErrorCode GetParseError() const { return parseResult_.Code(); } //! Get the position of last parsing error in input, 0 otherwise. size_t GetErrorOffset() const { return parseResult_.Offset(); } //! Implicit conversion to get the last parse result #ifndef __clang // -Wdocumentation /*! \return \ref ParseResult of the last parse operation \code Document doc; ParseResult ok = doc.Parse(json); if (!ok) printf( "JSON parse error: %s (%u)\n", GetParseError_En(ok.Code()), ok.Offset()); \endcode */ #endif operator ParseResult() const { return parseResult_; } //!@} //! Get the allocator of this document. Allocator& GetAllocator() { RAPIDJSON_ASSERT(allocator_); return *allocator_; } //! Get the capacity of stack in bytes. size_t GetStackCapacity() const { return stack_.GetCapacity(); } private: // clear stack on any exit from ParseStream, e.g. due to exception struct ClearStackOnExit { explicit ClearStackOnExit(GenericDocument& d) : d_(d) {} ~ClearStackOnExit() { d_.ClearStack(); } private: ClearStackOnExit(const ClearStackOnExit&); ClearStackOnExit& operator=(const ClearStackOnExit&); GenericDocument& d_; }; // callers of the following private Handler functions // template <typename,typename,typename> friend class GenericReader; // for parsing template <typename, typename> friend class GenericValue; // for deep copying public: // Implementation of Handler bool Null() { new (stack_.template Push<ValueType>()) ValueType(); return true; } bool Bool(bool b) { new (stack_.template Push<ValueType>()) ValueType(b); return true; } bool Int(int i) { new (stack_.template Push<ValueType>()) ValueType(i); return true; } bool Uint(unsigned i) { new (stack_.template Push<ValueType>()) ValueType(i); return true; } bool Int64(int64_t i) { new (stack_.template Push<ValueType>()) ValueType(i); return true; } bool Uint64(uint64_t i) { new (stack_.template Push<ValueType>()) ValueType(i); return true; } bool Double(double d) { new (stack_.template Push<ValueType>()) ValueType(d); return true; } bool RawNumber(const Ch* str, SizeType length, bool copy) { if (copy) new (stack_.template Push<ValueType>()) ValueType(str, length, GetAllocator()); else new (stack_.template Push<ValueType>()) ValueType(str, length); return true; } bool String(const Ch* str, SizeType length, bool copy) { if (copy) new (stack_.template Push<ValueType>()) ValueType(str, length, GetAllocator()); else new (stack_.template Push<ValueType>()) ValueType(str, length); return true; } bool StartObject() { new (stack_.template Push<ValueType>()) ValueType(kObjectType); return true; } bool Key(const Ch* str, SizeType length, bool copy) { return String(str, length, copy); } bool EndObject(SizeType memberCount) { typename ValueType::Member* members = stack_.template Pop<typename ValueType::Member>(memberCount); stack_.template Top<ValueType>()->SetObjectRaw(members, memberCount, GetAllocator()); return true; } bool StartArray() { new (stack_.template Push<ValueType>()) ValueType(kArrayType); return true; } bool EndArray(SizeType elementCount) { ValueType* elements = stack_.template Pop<ValueType>(elementCount); stack_.template Top<ValueType>()->SetArrayRaw(elements, elementCount, GetAllocator()); return true; } private: //! Prohibit copying GenericDocument(const GenericDocument&); //! Prohibit assignment GenericDocument& operator=(const GenericDocument&); void ClearStack() { if (Allocator::kNeedFree) while (stack_.GetSize() > 0) // Here assumes all elements in stack array are GenericValue (Member is actually 2 GenericValue objects) (stack_.template Pop<ValueType>(1))->~ValueType(); else stack_.Clear(); stack_.ShrinkToFit(); } void Destroy() { RAPIDJSON_DELETE(ownAllocator_); } static const size_t kDefaultStackCapacity = 1024; Allocator* allocator_; Allocator* ownAllocator_; internal::Stack<StackAllocator> stack_; ParseResult parseResult_; }; //! GenericDocument with UTF8 encoding typedef GenericDocument<UTF8<> > Document; //! Helper class for accessing Value of array type. /*! Instance of this helper class is obtained by \c GenericValue::GetArray(). In addition to all APIs for array type, it provides range-based for loop if \c RAPIDJSON_HAS_CXX11_RANGE_FOR=1. */ template <bool Const, typename ValueT> class GenericArray { public: typedef GenericArray<true, ValueT> ConstArray; typedef GenericArray<false, ValueT> Array; typedef ValueT PlainType; typedef typename internal::MaybeAddConst<Const,PlainType>::Type ValueType; typedef ValueType* ValueIterator; // This may be const or non-const iterator typedef const ValueT* ConstValueIterator; typedef typename ValueType::AllocatorType AllocatorType; typedef typename ValueType::StringRefType StringRefType; template <typename, typename> friend class GenericValue; GenericArray(const GenericArray& rhs) : value_(rhs.value_) {} GenericArray& operator=(const GenericArray& rhs) { value_ = rhs.value_; return *this; } ~GenericArray() {} SizeType Size() const { return value_.Size(); } SizeType Capacity() const { return value_.Capacity(); } bool Empty() const { return value_.Empty(); } void Clear() const { value_.Clear(); } ValueType& operator[](SizeType index) const { return value_[index]; } ValueIterator Begin() const { return value_.Begin(); } ValueIterator End() const { return value_.End(); } GenericArray Reserve(SizeType newCapacity, AllocatorType &allocator) const { value_.Reserve(newCapacity, allocator); return *this; } GenericArray PushBack(ValueType& value, AllocatorType& allocator) const { value_.PushBack(value, allocator); return *this; } #if RAPIDJSON_HAS_CXX11_RVALUE_REFS GenericArray PushBack(ValueType&& value, AllocatorType& allocator) const { value_.PushBack(value, allocator); return *this; } #endif // RAPIDJSON_HAS_CXX11_RVALUE_REFS GenericArray PushBack(StringRefType value, AllocatorType& allocator) const { value_.PushBack(value, allocator); return *this; } template <typename T> RAPIDJSON_DISABLEIF_RETURN((internal::OrExpr<internal::IsPointer<T>, internal::IsGenericValue<T> >), (const GenericArray&)) PushBack(T value, AllocatorType& allocator) const { value_.PushBack(value, allocator); return *this; } GenericArray PopBack() const { value_.PopBack(); return *this; } ValueIterator Erase(ConstValueIterator pos) const { return value_.Erase(pos); } ValueIterator Erase(ConstValueIterator first, ConstValueIterator last) const { return value_.Erase(first, last); } #if RAPIDJSON_HAS_CXX11_RANGE_FOR ValueIterator begin() const { return value_.Begin(); } ValueIterator end() const { return value_.End(); } #endif private: GenericArray(); GenericArray(ValueType& value) : value_(value) {} ValueType& value_; }; //! Helper class for accessing Value of object type. /*! Instance of this helper class is obtained by \c GenericValue::GetObject(). In addition to all APIs for array type, it provides range-based for loop if \c RAPIDJSON_HAS_CXX11_RANGE_FOR=1. */ template <bool Const, typename ValueT> class GenericObject { public: typedef GenericObject<true, ValueT> ConstObject; typedef GenericObject<false, ValueT> Object; typedef ValueT PlainType; typedef typename internal::MaybeAddConst<Const,PlainType>::Type ValueType; typedef GenericMemberIterator<Const, typename ValueT::EncodingType, typename ValueT::AllocatorType> MemberIterator; // This may be const or non-const iterator typedef GenericMemberIterator<true, typename ValueT::EncodingType, typename ValueT::AllocatorType> ConstMemberIterator; typedef typename ValueType::AllocatorType AllocatorType; typedef typename ValueType::StringRefType StringRefType; typedef typename ValueType::EncodingType EncodingType; typedef typename ValueType::Ch Ch; template <typename, typename> friend class GenericValue; GenericObject(const GenericObject& rhs) : value_(rhs.value_) {} GenericObject& operator=(const GenericObject& rhs) { value_ = rhs.value_; return *this; } ~GenericObject() {} SizeType MemberCount() const { return value_.MemberCount(); } SizeType MemberCapacity() const { return value_.MemberCapacity(); } bool ObjectEmpty() const { return value_.ObjectEmpty(); } template <typename T> ValueType& operator[](T* name) const { return value_[name]; } template <typename SourceAllocator> ValueType& operator[](const GenericValue<EncodingType, SourceAllocator>& name) const { return value_[name]; } #if RAPIDJSON_HAS_STDSTRING ValueType& operator[](const std::basic_string<Ch>& name) const { return value_[name]; } #endif MemberIterator MemberBegin() const { return value_.MemberBegin(); } MemberIterator MemberEnd() const { return value_.MemberEnd(); } GenericObject MemberReserve(SizeType newCapacity, AllocatorType &allocator) const { value_.MemberReserve(newCapacity, allocator); return *this; } bool HasMember(const Ch* name) const { return value_.HasMember(name); } #if RAPIDJSON_HAS_STDSTRING bool HasMember(const std::basic_string<Ch>& name) const { return value_.HasMember(name); } #endif template <typename SourceAllocator> bool HasMember(const GenericValue<EncodingType, SourceAllocator>& name) const { return value_.HasMember(name); } MemberIterator FindMember(const Ch* name) const { return value_.FindMember(name); } template <typename SourceAllocator> MemberIterator FindMember(const GenericValue<EncodingType, SourceAllocator>& name) const { return value_.FindMember(name); } #if RAPIDJSON_HAS_STDSTRING MemberIterator FindMember(const std::basic_string<Ch>& name) const { return value_.FindMember(name); } #endif GenericObject AddMember(ValueType& name, ValueType& value, AllocatorType& allocator) const { value_.AddMember(name, value, allocator); return *this; } GenericObject AddMember(ValueType& name, StringRefType value, AllocatorType& allocator) const { value_.AddMember(name, value, allocator); return *this; } #if RAPIDJSON_HAS_STDSTRING GenericObject AddMember(ValueType& name, std::basic_string<Ch>& value, AllocatorType& allocator) const { value_.AddMember(name, value, allocator); return *this; } #endif template <typename T> RAPIDJSON_DISABLEIF_RETURN((internal::OrExpr<internal::IsPointer<T>, internal::IsGenericValue<T> >), (ValueType&)) AddMember(ValueType& name, T value, AllocatorType& allocator) const { value_.AddMember(name, value, allocator); return *this; } #if RAPIDJSON_HAS_CXX11_RVALUE_REFS GenericObject AddMember(ValueType&& name, ValueType&& value, AllocatorType& allocator) const { value_.AddMember(name, value, allocator); return *this; } GenericObject AddMember(ValueType&& name, ValueType& value, AllocatorType& allocator) const { value_.AddMember(name, value, allocator); return *this; } GenericObject AddMember(ValueType& name, ValueType&& value, AllocatorType& allocator) const { value_.AddMember(name, value, allocator); return *this; } GenericObject AddMember(StringRefType name, ValueType&& value, AllocatorType& allocator) const { value_.AddMember(name, value, allocator); return *this; } #endif // RAPIDJSON_HAS_CXX11_RVALUE_REFS GenericObject AddMember(StringRefType name, ValueType& value, AllocatorType& allocator) const { value_.AddMember(name, value, allocator); return *this; } GenericObject AddMember(StringRefType name, StringRefType value, AllocatorType& allocator) const { value_.AddMember(name, value, allocator); return *this; } template <typename T> RAPIDJSON_DISABLEIF_RETURN((internal::OrExpr<internal::IsPointer<T>, internal::IsGenericValue<T> >), (GenericObject)) AddMember(StringRefType name, T value, AllocatorType& allocator) const { value_.AddMember(name, value, allocator); return *this; } void RemoveAllMembers() { value_.RemoveAllMembers(); } bool RemoveMember(const Ch* name) const { return value_.RemoveMember(name); } #if RAPIDJSON_HAS_STDSTRING bool RemoveMember(const std::basic_string<Ch>& name) const { return value_.RemoveMember(name); } #endif template <typename SourceAllocator> bool RemoveMember(const GenericValue<EncodingType, SourceAllocator>& name) const { return value_.RemoveMember(name); } MemberIterator RemoveMember(MemberIterator m) const { return value_.RemoveMember(m); } MemberIterator EraseMember(ConstMemberIterator pos) const { return value_.EraseMember(pos); } MemberIterator EraseMember(ConstMemberIterator first, ConstMemberIterator last) const { return value_.EraseMember(first, last); } bool EraseMember(const Ch* name) const { return value_.EraseMember(name); } #if RAPIDJSON_HAS_STDSTRING bool EraseMember(const std::basic_string<Ch>& name) const { return EraseMember(ValueType(StringRef(name))); } #endif template <typename SourceAllocator> bool EraseMember(const GenericValue<EncodingType, SourceAllocator>& name) const { return value_.EraseMember(name); } #if RAPIDJSON_HAS_CXX11_RANGE_FOR MemberIterator begin() const { return value_.MemberBegin(); } MemberIterator end() const { return value_.MemberEnd(); } #endif private: GenericObject(); GenericObject(ValueType& value) : value_(value) {} ValueType& value_; }; RAPIDJSON_NAMESPACE_END RAPIDJSON_DIAG_POP #endif // RAPIDJSON_DOCUMENT_H_
121,069
document
h
en
c
code
{"qsc_code_num_words": 13727, "qsc_code_num_chars": 121069.0, "qsc_code_mean_word_length": 5.82472499, "qsc_code_frac_words_unique": 0.07496175, "qsc_code_frac_chars_top_2grams": 0.01279454, "qsc_code_frac_chars_top_3grams": 0.0080044, "qsc_code_frac_chars_top_4grams": 0.00616589, "qsc_code_frac_chars_dupe_5grams": 0.59421432, "qsc_code_frac_chars_dupe_6grams": 0.54312372, "qsc_code_frac_chars_dupe_7grams": 0.48021412, "qsc_code_frac_chars_dupe_8grams": 0.42220721, "qsc_code_frac_chars_dupe_9grams": 0.3779954, "qsc_code_frac_chars_dupe_10grams": 0.3416379, "qsc_code_frac_chars_replacement_symbols": 0.0, "qsc_code_frac_chars_digital": 0.00746992, "qsc_code_frac_chars_whitespace": 0.22488003, "qsc_code_size_file_byte": 121069.0, "qsc_code_num_lines": 2732.0, "qsc_code_num_chars_line_max": 275.0, "qsc_code_num_chars_line_mean": 44.31515373, "qsc_code_frac_chars_alphabet": 0.84454887, "qsc_code_frac_chars_comments": 0.38990989, "qsc_code_cate_xml_start": 0.0, "qsc_code_frac_lines_dupe_lines": 0.31169757, "qsc_code_cate_autogen": 0.0, "qsc_code_frac_lines_long_string": 0.0, "qsc_code_frac_chars_string_length": 0.00097478, "qsc_code_frac_chars_long_word_length": 0.0, "qsc_code_frac_lines_string_concat": 0.0, "qsc_code_cate_encoded_data": 0.0, "qsc_code_frac_chars_hex_words": 0.00262648, "qsc_code_frac_lines_prompt_comments": 0.0, "qsc_code_frac_lines_assert": 0.05064194, "qsc_codec_frac_lines_func_ratio": 0.21398003, "qsc_codec_cate_bitsstdc": 0.0, "qsc_codec_nums_lines_main": 0, "qsc_codec_frac_lines_goto": 0.0, "qsc_codec_cate_var_zero": 0.0, "qsc_codec_score_lines_no_logic": 0.2467903, "qsc_codec_frac_lines_print": 0.0, "qsc_codec_frac_lines_preprocessor_directives": null}
0
{"qsc_code_frac_chars_replacement_symbols": 0, "qsc_code_num_words": 0, "qsc_code_num_chars": 0, "qsc_code_mean_word_length": 0, "qsc_code_frac_chars_top_2grams": 0, "qsc_code_frac_chars_top_3grams": 0, "qsc_code_frac_chars_top_4grams": 0, "qsc_code_frac_chars_dupe_5grams": 0, "qsc_code_frac_chars_dupe_6grams": 0, "qsc_code_frac_chars_dupe_7grams": 0, "qsc_code_frac_chars_dupe_8grams": 0, "qsc_code_frac_chars_dupe_9grams": 0, "qsc_code_frac_chars_dupe_10grams": 0, "qsc_code_size_file_byte": 0, "qsc_code_num_lines": 0, "qsc_code_num_chars_line_max": 0, "qsc_code_num_chars_line_mean": 0, "qsc_code_frac_chars_alphabet": 0, "qsc_code_frac_chars_digital": 0, "qsc_code_frac_chars_whitespace": 0, "qsc_code_frac_chars_comments": 0, "qsc_code_cate_xml_start": 0, "qsc_code_frac_lines_dupe_lines": 0, "qsc_code_cate_autogen": 0, "qsc_code_frac_lines_long_string": 0, "qsc_code_frac_chars_string_length": 0, "qsc_code_frac_chars_long_word_length": 0, "qsc_code_cate_encoded_data": 0, "qsc_code_frac_chars_hex_words": 0, "qsc_code_frac_lines_prompt_comments": 0, "qsc_code_frac_lines_assert": 0, "qsc_codec_frac_lines_func_ratio": 1, "qsc_codec_nums_lines_main": 0, "qsc_codec_score_lines_no_logic": 0, "qsc_codec_frac_lines_preprocessor_directives": 0, "qsc_codec_frac_lines_print": 0}
0015/esp_rlottie
rlottie/src/lottie/rapidjson/stringbuffer.h
// Tencent is pleased to support the open source community by making RapidJSON available. // // Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip. All rights reserved. // // Licensed under the MIT License (the "License"); you may not use this file except // in compliance with the License. You may obtain a copy of the License at // // http://opensource.org/licenses/MIT // // Unless required by applicable law or agreed to in writing, software distributed // under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR // CONDITIONS OF ANY KIND, either express or implied. See the License for the // specific language governing permissions and limitations under the License. #ifndef RAPIDJSON_STRINGBUFFER_H_ #define RAPIDJSON_STRINGBUFFER_H_ #include "stream.h" #include "internal/stack.h" #if RAPIDJSON_HAS_CXX11_RVALUE_REFS #include <utility> // std::move #endif #include "internal/stack.h" #if defined(__clang__) RAPIDJSON_DIAG_PUSH RAPIDJSON_DIAG_OFF(c++98-compat) #endif RAPIDJSON_NAMESPACE_BEGIN //! Represents an in-memory output stream. /*! \tparam Encoding Encoding of the stream. \tparam Allocator type for allocating memory buffer. \note implements Stream concept */ template <typename Encoding, typename Allocator = CrtAllocator> class GenericStringBuffer { public: typedef typename Encoding::Ch Ch; GenericStringBuffer(Allocator* allocator = 0, size_t capacity = kDefaultCapacity) : stack_(allocator, capacity) {} #if RAPIDJSON_HAS_CXX11_RVALUE_REFS GenericStringBuffer(GenericStringBuffer&& rhs) : stack_(std::move(rhs.stack_)) {} GenericStringBuffer& operator=(GenericStringBuffer&& rhs) { if (&rhs != this) stack_ = std::move(rhs.stack_); return *this; } #endif void Put(Ch c) { *stack_.template Push<Ch>() = c; } void PutUnsafe(Ch c) { *stack_.template PushUnsafe<Ch>() = c; } void Flush() {} void Clear() { stack_.Clear(); } void ShrinkToFit() { // Push and pop a null terminator. This is safe. *stack_.template Push<Ch>() = '\0'; stack_.ShrinkToFit(); stack_.template Pop<Ch>(1); } void Reserve(size_t count) { stack_.template Reserve<Ch>(count); } Ch* Push(size_t count) { return stack_.template Push<Ch>(count); } Ch* PushUnsafe(size_t count) { return stack_.template PushUnsafe<Ch>(count); } void Pop(size_t count) { stack_.template Pop<Ch>(count); } const Ch* GetString() const { // Push and pop a null terminator. This is safe. *stack_.template Push<Ch>() = '\0'; stack_.template Pop<Ch>(1); return stack_.template Bottom<Ch>(); } //! Get the size of string in bytes in the string buffer. size_t GetSize() const { return stack_.GetSize(); } //! Get the length of string in Ch in the string buffer. size_t GetLength() const { return stack_.GetSize() / sizeof(Ch); } static const size_t kDefaultCapacity = 256; mutable internal::Stack<Allocator> stack_; private: // Prohibit copy constructor & assignment operator. GenericStringBuffer(const GenericStringBuffer&); GenericStringBuffer& operator=(const GenericStringBuffer&); }; //! String buffer with UTF8 encoding typedef GenericStringBuffer<UTF8<> > StringBuffer; template<typename Encoding, typename Allocator> inline void PutReserve(GenericStringBuffer<Encoding, Allocator>& stream, size_t count) { stream.Reserve(count); } template<typename Encoding, typename Allocator> inline void PutUnsafe(GenericStringBuffer<Encoding, Allocator>& stream, typename Encoding::Ch c) { stream.PutUnsafe(c); } //! Implement specialized version of PutN() with memset() for better performance. template<> inline void PutN(GenericStringBuffer<UTF8<> >& stream, char c, size_t n) { std::memset(stream.stack_.Push<char>(n), c, n * sizeof(c)); } RAPIDJSON_NAMESPACE_END #if defined(__clang__) RAPIDJSON_DIAG_POP #endif #endif // RAPIDJSON_STRINGBUFFER_H_
3,993
stringbuffer
h
en
c
code
{"qsc_code_num_words": 503, "qsc_code_num_chars": 3993.0, "qsc_code_mean_word_length": 5.54075547, "qsc_code_frac_words_unique": 0.34791252, "qsc_code_frac_chars_top_2grams": 0.05130965, "qsc_code_frac_chars_top_3grams": 0.01794044, "qsc_code_frac_chars_top_4grams": 0.02726947, "qsc_code_frac_chars_dupe_5grams": 0.22891999, "qsc_code_frac_chars_dupe_6grams": 0.13706494, "qsc_code_frac_chars_dupe_7grams": 0.07965554, "qsc_code_frac_chars_dupe_8grams": 0.04305705, "qsc_code_frac_chars_dupe_9grams": 0.04305705, "qsc_code_frac_chars_dupe_10grams": 0.04305705, "qsc_code_frac_chars_replacement_symbols": 0.0, "qsc_code_frac_chars_digital": 0.00699088, "qsc_code_frac_chars_whitespace": 0.1760581, "qsc_code_size_file_byte": 3993.0, "qsc_code_num_lines": 121.0, "qsc_code_num_chars_line_max": 119.0, "qsc_code_num_chars_line_mean": 33.0, "qsc_code_frac_chars_alphabet": 0.84012158, "qsc_code_frac_chars_comments": 0.33233158, "qsc_code_cate_xml_start": 0.0, "qsc_code_frac_lines_dupe_lines": 0.24285714, "qsc_code_cate_autogen": 0.0, "qsc_code_frac_lines_long_string": 0.0, "qsc_code_frac_chars_string_length": 0.01650413, "qsc_code_frac_chars_long_word_length": 0.0, "qsc_code_frac_lines_string_concat": 0.0, "qsc_code_cate_encoded_data": 0.0, "qsc_code_frac_chars_hex_words": 0.0, "qsc_code_frac_lines_prompt_comments": 0.0, "qsc_code_frac_lines_assert": 0.0, "qsc_codec_frac_lines_func_ratio": 0.28571429, "qsc_codec_cate_bitsstdc": 0.0, "qsc_codec_nums_lines_main": 0, "qsc_codec_frac_lines_goto": 0.0, "qsc_codec_cate_var_zero": 0.0, "qsc_codec_score_lines_no_logic": 0.35714286, "qsc_codec_frac_lines_print": 0.0, "qsc_codec_frac_lines_preprocessor_directives": null}
0
{"qsc_code_frac_chars_replacement_symbols": 0, "qsc_code_num_words": 0, "qsc_code_num_chars": 0, "qsc_code_mean_word_length": 0, "qsc_code_frac_chars_top_2grams": 0, "qsc_code_frac_chars_top_3grams": 0, "qsc_code_frac_chars_top_4grams": 0, "qsc_code_frac_chars_dupe_5grams": 0, "qsc_code_frac_chars_dupe_6grams": 0, "qsc_code_frac_chars_dupe_7grams": 0, "qsc_code_frac_chars_dupe_8grams": 0, "qsc_code_frac_chars_dupe_9grams": 0, "qsc_code_frac_chars_dupe_10grams": 0, "qsc_code_size_file_byte": 0, "qsc_code_num_lines": 0, "qsc_code_num_chars_line_max": 0, "qsc_code_num_chars_line_mean": 0, "qsc_code_frac_chars_alphabet": 0, "qsc_code_frac_chars_digital": 0, "qsc_code_frac_chars_whitespace": 0, "qsc_code_frac_chars_comments": 0, "qsc_code_cate_xml_start": 0, "qsc_code_frac_lines_dupe_lines": 0, "qsc_code_cate_autogen": 0, "qsc_code_frac_lines_long_string": 0, "qsc_code_frac_chars_string_length": 0, "qsc_code_frac_chars_long_word_length": 0, "qsc_code_cate_encoded_data": 0, "qsc_code_frac_chars_hex_words": 0, "qsc_code_frac_lines_prompt_comments": 0, "qsc_code_frac_lines_assert": 0, "qsc_codec_frac_lines_func_ratio": 1, "qsc_codec_nums_lines_main": 0, "qsc_codec_score_lines_no_logic": 0, "qsc_codec_frac_lines_preprocessor_directives": 0, "qsc_codec_frac_lines_print": 0}
0015/TP_Arduino_DigitalRain_Anim
src/DigitalRainAnimation.hpp
/* DigitalRainAnimation.hpp - Library for Digital Rain Animation(MATRIX EFFECT). Created by Eric Nam, November 08, 2021. Released into the public domain. */ #pragma once #include <vector> #include <string> #define DEFAULT_FONT_SIZE 2 #define DEFAULT_LINE_WIDTH 12 #define DEFAULT_LETTER_HEIGHT 14 #define KEY_RESET_TIME 60000 // 60 seconds #define ASCII_RANGE_1_START 33 #define ASCII_RANGE_1_END 65 #define ASCII_RANGE_2_START 91 #define ASCII_RANGE_2_END 126 enum AnimMode { SHOWCASE, MATRIX, TEXT }; template<class T> class DigitalRainAnimation { private: T* _gfx = nullptr; AnimMode _animMode; // Display dimensions int width = 0, height = 0; // Matrix settings int line_len_min = 3; int line_len_max = 20; int line_speed_min = 3; int line_speed_max = 15; int numOfline = 0; int matrixTimeFrame = 100; // Text settings int textTimeFrame = 400; int timeFrame = 100; int textStartX = 60, textStartY = 60; std::string textMessage; size_t textIndex = 0; // Font settings uint8_t fontSize = DEFAULT_FONT_SIZE; uint8_t lineWidth = DEFAULT_LINE_WIDTH; uint8_t letterHeight = DEFAULT_LETTER_HEIGHT; // Flags bool isPlaying = true; bool isAlphabetOnly = false; // Time tracking uint32_t lastDrawTime = 0; uint32_t lastUpdatedKeyTime = 0; // Colors uint16_t headCharColor; uint16_t textColor; uint16_t bgColor; // Data buffers std::vector<int> line_length; std::vector<int> line_pos; std::vector<int> line_speed; // Key animation std::string keyString; // Helper: generate random ASCII character String getASCIIChar() { return String((char)(random(0, 2) == 0 ? random(ASCII_RANGE_1_START, ASCII_RANGE_1_END) : random(ASCII_RANGE_2_START, ASCII_RANGE_2_END))); } String getAbcASCIIChar() { return String((char)(random(0, 2) == 0 ? random('A', 'Z' + 1) : random('a', 'z' + 1))); } int setYPos(int lineLen) { return lineLen * -20; } int getRandomNum(int min, int max) { return random(min, max + 1); } void resetKey() { keyString.clear(); lastUpdatedKeyTime = millis(); } std::string getKey(int key_length) { resetKey(); int maxKeyLength = std::min(key_length > 0 ? key_length : numOfline, numOfline); for (int i = 0; i < maxKeyLength; ++i) keyString += getAbcASCIIChar().c_str(); return keyString; } void prepareAnim() { if (!_gfx) return; setHeadCharColor(255, 255, 255); setTextColor(0, 255, 0); setBGColor(0, 0, 0); width = _gfx->width(); height = _gfx->height(); numOfline = (width + lineWidth - 1) / lineWidth; _gfx->fillRect(0, 0, width, height, bgColor); _gfx->setTextColor(textColor, bgColor); line_length.clear(); line_pos.clear(); line_speed.clear(); for (int i = 0; i < numOfline; ++i) { line_length.push_back(getRandomNum(line_len_min, line_len_max)); line_pos.push_back(setYPos(line_length[i]) - letterHeight); line_speed.push_back(getRandomNum(line_speed_min, line_speed_max)); } lastDrawTime = millis() - timeFrame; lastUpdatedKeyTime = millis() - timeFrame; isPlaying = true; } void lineUpdate(int i) { line_length[i] = getRandomNum(line_len_min, line_len_max); line_pos[i] = setYPos(line_length[i]); line_speed[i] = getRandomNum(line_speed_min, line_speed_max); } void lineAnimation(int i) { int startX = i * lineWidth; int currentY = -letterHeight; bool isKeyMode = !keyString.empty(); _gfx->fillRect(startX, 0, lineWidth, height, bgColor); _gfx->setTextSize(fontSize); for (int j = 0; j < line_length[i]; ++j) { int colorVal = map(j, 0, line_length[i], 10, 255); uint16_t lumColor = luminance(textColor, colorVal); _gfx->setTextColor(isKeyMode ? _gfx->color565(colorVal, 0, 0) : lumColor, bgColor); _gfx->setCursor(startX, line_pos[i] + currentY); _gfx->print(isAlphabetOnly ? getAbcASCIIChar() : getASCIIChar()); currentY = j * letterHeight; } _gfx->setTextColor(headCharColor, bgColor); _gfx->setCursor(startX, line_pos[i] + currentY); _gfx->print( isKeyMode && keyString.length() > i ? String(keyString[i]) : (isAlphabetOnly ? getAbcASCIIChar() : getASCIIChar()) ); line_pos[i] += line_speed[i]; if (line_pos[i] >= height) lineUpdate(i); } uint16_t luminance(uint16_t color, uint8_t lum) { uint16_t r = (color & 0xF800) >> 8; r |= (r >> 5); uint16_t g = (color & 0x07E0) >> 3; g |= (g >> 6); uint16_t b = (color & 0x001F) << 3; b |= (b >> 5); b = ((b * lum + 255) >> 8) & 0x00F8; g = ((g * lum + 255) >> 8) & 0x00FC; r = ((r * lum + 255) >> 8) & 0x00F8; return (r << 8) | (g << 3) | (b >> 3); } void textAnimation() { if (textIndex >= textMessage.length()) { _gfx->fillRect(0, 0, width, height, bgColor); textIndex = 0; if (_animMode == TEXT) { _gfx->setCursor(textStartX, textStartY); } else { _animMode = MATRIX; timeFrame = matrixTimeFrame; } return; } _gfx->setTextSize(fontSize); char letter = textMessage[textIndex++]; if (letter == '\n') { _gfx->fillRect(0, 0, width, height, bgColor); _gfx->setCursor(textStartX, textStartY); } else { _gfx->print(letter); } } public: DigitalRainAnimation() {} void init(T* gfx, bool biggerText = false, bool alphabetOnly = false) { _gfx = gfx; isAlphabetOnly = alphabetOnly; setBigText(biggerText); prepareAnim(); } void setup(int len_min, int len_max, int spd_min, int spd_max, int frame) { line_len_min = len_min; line_len_max = len_max; line_speed_min = spd_min; line_speed_max = spd_max; matrixTimeFrame = frame; timeFrame = matrixTimeFrame; prepareAnim(); } void setTextAnimMode(AnimMode mode, const std::string& msg, int startX = 60, int startY = 60, int frame = 400) { _animMode = mode; textMessage = msg; textIndex = 0; textStartX = startX; textStartY = startY; textTimeFrame = frame; timeFrame = frame; } void setAnimText(const std::string& msg) { textMessage = msg; textIndex = 0; } void setBigText(bool on) { fontSize = on ? DEFAULT_FONT_SIZE * 2 : DEFAULT_FONT_SIZE; lineWidth = on ? DEFAULT_LINE_WIDTH * 2 : DEFAULT_LINE_WIDTH; letterHeight = on ? DEFAULT_LETTER_HEIGHT * 1.6 : DEFAULT_LETTER_HEIGHT; } void setHeadCharColor(uint8_t r, uint8_t g, uint8_t b) { headCharColor = _gfx->color565(r, g, b); } void setTextColor(uint8_t r, uint8_t g, uint8_t b) { textColor = _gfx->color565(r, g, b); } void setBGColor(uint8_t r, uint8_t g, uint8_t b) { bgColor = _gfx->color565(r, g, b); } void pause() { isPlaying = false; } void resume() { isPlaying = true; } void loop() { if (!_gfx) return; uint32_t now = millis(); if (now - lastUpdatedKeyTime > KEY_RESET_TIME) resetKey(); if (now - lastDrawTime < timeFrame) return; if (!isPlaying) return; switch (_animMode) { case MATRIX: for (int i = 0; i < numOfline; ++i) lineAnimation(i); break; case TEXT: case SHOWCASE: textAnimation(); break; } lastDrawTime = now; } };
7,300
DigitalRainAnimation
hpp
en
cpp
code
{"qsc_code_num_words": 905, "qsc_code_num_chars": 7300.0, "qsc_code_mean_word_length": 4.9558011, "qsc_code_frac_words_unique": 0.21325967, "qsc_code_frac_chars_top_2grams": 0.02608696, "qsc_code_frac_chars_top_3grams": 0.0122631, "qsc_code_frac_chars_top_4grams": 0.01070234, "qsc_code_frac_chars_dupe_5grams": 0.14671126, "qsc_code_frac_chars_dupe_6grams": 0.12575251, "qsc_code_frac_chars_dupe_7grams": 0.11371237, "qsc_code_frac_chars_dupe_8grams": 0.08227425, "qsc_code_frac_chars_dupe_9grams": 0.05328874, "qsc_code_frac_chars_dupe_10grams": 0.02185061, "qsc_code_frac_chars_replacement_symbols": 0.0, "qsc_code_frac_chars_digital": 0.03858521, "qsc_code_frac_chars_whitespace": 0.23315068, "qsc_code_size_file_byte": 7300.0, "qsc_code_num_lines": 286.0, "qsc_code_num_chars_line_max": 144.0, "qsc_code_num_chars_line_mean": 25.52447552, "qsc_code_frac_chars_alphabet": 0.76259378, "qsc_code_frac_chars_comments": 0.04972603, "qsc_code_cate_xml_start": 0.0, "qsc_code_frac_lines_dupe_lines": 0.12962963, "qsc_code_cate_autogen": 0.0, "qsc_code_frac_lines_long_string": 0.0, "qsc_code_frac_chars_string_length": 0.0008648, "qsc_code_frac_chars_long_word_length": 0.0, "qsc_code_frac_lines_string_concat": 0.0, "qsc_code_cate_encoded_data": 0.0, "qsc_code_frac_chars_hex_words": 0.00518882, "qsc_code_frac_lines_prompt_comments": 0.0, "qsc_code_frac_lines_assert": 0.0, "qsc_codecpp_frac_lines_preprocessor_directives": null, "qsc_codecpp_frac_lines_func_ratio": 0.11574074, "qsc_codecpp_cate_bitsstdc": 0.0, "qsc_codecpp_nums_lines_main": 0.0, "qsc_codecpp_frac_lines_goto": 0.0, "qsc_codecpp_cate_var_zero": 0.0, "qsc_codecpp_score_lines_no_logic": 0.15277778, "qsc_codecpp_frac_lines_print": 0.0}
1
{"qsc_code_frac_chars_replacement_symbols": 0, "qsc_code_num_words": 0, "qsc_code_num_chars": 0, "qsc_code_mean_word_length": 0, "qsc_code_frac_chars_top_2grams": 0, "qsc_code_frac_chars_top_3grams": 0, "qsc_code_frac_chars_top_4grams": 0, "qsc_code_frac_chars_dupe_5grams": 0, "qsc_code_frac_chars_dupe_6grams": 0, "qsc_code_frac_chars_dupe_7grams": 0, "qsc_code_frac_chars_dupe_8grams": 0, "qsc_code_frac_chars_dupe_9grams": 0, "qsc_code_frac_chars_dupe_10grams": 0, "qsc_code_frac_lines_dupe_lines": 0, "qsc_code_size_file_byte": 0, "qsc_code_num_lines": 0, "qsc_code_num_chars_line_max": 0, "qsc_code_num_chars_line_mean": 0, "qsc_code_frac_chars_alphabet": 0, "qsc_code_frac_chars_digital": 0, "qsc_code_frac_chars_whitespace": 0, "qsc_code_frac_chars_comments": 0, "qsc_code_cate_xml_start": 0, "qsc_code_cate_autogen": 0, "qsc_code_frac_lines_long_string": 0, "qsc_code_frac_chars_string_length": 0, "qsc_code_frac_chars_long_word_length": 0, "qsc_code_cate_encoded_data": 0, "qsc_code_frac_chars_hex_words": 0, "qsc_code_frac_lines_prompt_comments": 0, "qsc_code_frac_lines_assert": 0, "qsc_codecpp_frac_lines_func_ratio": 0, "qsc_codecpp_nums_lines_main": 0, "qsc_codecpp_score_lines_no_logic": 0, "qsc_codecpp_frac_lines_preprocessor_directives": 0, "qsc_codecpp_frac_lines_print": 0}
0015/esp_rlottie
rlottie/src/lottie/rapidjson/pointer.h
// Tencent is pleased to support the open source community by making RapidJSON available. // // Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip. All rights reserved. // // Licensed under the MIT License (the "License"); you may not use this file except // in compliance with the License. You may obtain a copy of the License at // // http://opensource.org/licenses/MIT // // Unless required by applicable law or agreed to in writing, software distributed // under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR // CONDITIONS OF ANY KIND, either express or implied. See the License for the // specific language governing permissions and limitations under the License. #ifndef RAPIDJSON_POINTER_H_ #define RAPIDJSON_POINTER_H_ #include "document.h" #include "internal/itoa.h" #ifdef __clang__ RAPIDJSON_DIAG_PUSH RAPIDJSON_DIAG_OFF(switch-enum) #elif defined(_MSC_VER) RAPIDJSON_DIAG_PUSH RAPIDJSON_DIAG_OFF(4512) // assignment operator could not be generated #endif RAPIDJSON_NAMESPACE_BEGIN static const SizeType kPointerInvalidIndex = ~SizeType(0); //!< Represents an invalid index in GenericPointer::Token //! Error code of parsing. /*! \ingroup RAPIDJSON_ERRORS \see GenericPointer::GenericPointer, GenericPointer::GetParseErrorCode */ enum PointerParseErrorCode { kPointerParseErrorNone = 0, //!< The parse is successful kPointerParseErrorTokenMustBeginWithSolidus, //!< A token must begin with a '/' kPointerParseErrorInvalidEscape, //!< Invalid escape kPointerParseErrorInvalidPercentEncoding, //!< Invalid percent encoding in URI fragment kPointerParseErrorCharacterMustPercentEncode //!< A character must percent encoded in URI fragment }; /////////////////////////////////////////////////////////////////////////////// // GenericPointer //! Represents a JSON Pointer. Use Pointer for UTF8 encoding and default allocator. /*! This class implements RFC 6901 "JavaScript Object Notation (JSON) Pointer" (https://tools.ietf.org/html/rfc6901). A JSON pointer is for identifying a specific value in a JSON document (GenericDocument). It can simplify coding of DOM tree manipulation, because it can access multiple-level depth of DOM tree with single API call. After it parses a string representation (e.g. "/foo/0" or URI fragment representation (e.g. "#/foo/0") into its internal representation (tokens), it can be used to resolve a specific value in multiple documents, or sub-tree of documents. Contrary to GenericValue, Pointer can be copy constructed and copy assigned. Apart from assignment, a Pointer cannot be modified after construction. Although Pointer is very convenient, please aware that constructing Pointer involves parsing and dynamic memory allocation. A special constructor with user- supplied tokens eliminates these. GenericPointer depends on GenericDocument and GenericValue. \tparam ValueType The value type of the DOM tree. E.g. GenericValue<UTF8<> > \tparam Allocator The allocator type for allocating memory for internal representation. \note GenericPointer uses same encoding of ValueType. However, Allocator of GenericPointer is independent of Allocator of Value. */ template <typename ValueType, typename Allocator = CrtAllocator> class GenericPointer { public: typedef typename ValueType::EncodingType EncodingType; //!< Encoding type from Value typedef typename ValueType::Ch Ch; //!< Character type from Value //! A token is the basic units of internal representation. /*! A JSON pointer string representation "/foo/123" is parsed to two tokens: "foo" and 123. 123 will be represented in both numeric form and string form. They are resolved according to the actual value type (object or array). For token that are not numbers, or the numeric value is out of bound (greater than limits of SizeType), they are only treated as string form (i.e. the token's index will be equal to kPointerInvalidIndex). This struct is public so that user can create a Pointer without parsing and allocation, using a special constructor. */ struct Token { const Ch* name; //!< Name of the token. It has null character at the end but it can contain null character. SizeType length; //!< Length of the name. SizeType index; //!< A valid array index, if it is not equal to kPointerInvalidIndex. }; //!@name Constructors and destructor. //@{ //! Default constructor. GenericPointer(Allocator* allocator = 0) : allocator_(allocator), ownAllocator_(), nameBuffer_(), tokens_(), tokenCount_(), parseErrorOffset_(), parseErrorCode_(kPointerParseErrorNone) {} //! Constructor that parses a string or URI fragment representation. /*! \param source A null-terminated, string or URI fragment representation of JSON pointer. \param allocator User supplied allocator for this pointer. If no allocator is provided, it creates a self-owned one. */ explicit GenericPointer(const Ch* source, Allocator* allocator = 0) : allocator_(allocator), ownAllocator_(), nameBuffer_(), tokens_(), tokenCount_(), parseErrorOffset_(), parseErrorCode_(kPointerParseErrorNone) { Parse(source, internal::StrLen(source)); } #if RAPIDJSON_HAS_STDSTRING //! Constructor that parses a string or URI fragment representation. /*! \param source A string or URI fragment representation of JSON pointer. \param allocator User supplied allocator for this pointer. If no allocator is provided, it creates a self-owned one. \note Requires the definition of the preprocessor symbol \ref RAPIDJSON_HAS_STDSTRING. */ explicit GenericPointer(const std::basic_string<Ch>& source, Allocator* allocator = 0) : allocator_(allocator), ownAllocator_(), nameBuffer_(), tokens_(), tokenCount_(), parseErrorOffset_(), parseErrorCode_(kPointerParseErrorNone) { Parse(source.c_str(), source.size()); } #endif //! Constructor that parses a string or URI fragment representation, with length of the source string. /*! \param source A string or URI fragment representation of JSON pointer. \param length Length of source. \param allocator User supplied allocator for this pointer. If no allocator is provided, it creates a self-owned one. \note Slightly faster than the overload without length. */ GenericPointer(const Ch* source, size_t length, Allocator* allocator = 0) : allocator_(allocator), ownAllocator_(), nameBuffer_(), tokens_(), tokenCount_(), parseErrorOffset_(), parseErrorCode_(kPointerParseErrorNone) { Parse(source, length); } //! Constructor with user-supplied tokens. /*! This constructor let user supplies const array of tokens. This prevents the parsing process and eliminates allocation. This is preferred for memory constrained environments. \param tokens An constant array of tokens representing the JSON pointer. \param tokenCount Number of tokens. \b Example \code #define NAME(s) { s, sizeof(s) / sizeof(s[0]) - 1, kPointerInvalidIndex } #define INDEX(i) { #i, sizeof(#i) - 1, i } static const Pointer::Token kTokens[] = { NAME("foo"), INDEX(123) }; static const Pointer p(kTokens, sizeof(kTokens) / sizeof(kTokens[0])); // Equivalent to static const Pointer p("/foo/123"); #undef NAME #undef INDEX \endcode */ GenericPointer(const Token* tokens, size_t tokenCount) : allocator_(), ownAllocator_(), nameBuffer_(), tokens_(const_cast<Token*>(tokens)), tokenCount_(tokenCount), parseErrorOffset_(), parseErrorCode_(kPointerParseErrorNone) {} //! Copy constructor. GenericPointer(const GenericPointer& rhs) : allocator_(rhs.allocator_), ownAllocator_(), nameBuffer_(), tokens_(), tokenCount_(), parseErrorOffset_(), parseErrorCode_(kPointerParseErrorNone) { *this = rhs; } //! Copy constructor. GenericPointer(const GenericPointer& rhs, Allocator* allocator) : allocator_(allocator), ownAllocator_(), nameBuffer_(), tokens_(), tokenCount_(), parseErrorOffset_(), parseErrorCode_(kPointerParseErrorNone) { *this = rhs; } //! Destructor. ~GenericPointer() { if (nameBuffer_) // If user-supplied tokens constructor is used, nameBuffer_ is nullptr and tokens_ are not deallocated. Allocator::Free(tokens_); RAPIDJSON_DELETE(ownAllocator_); } //! Assignment operator. GenericPointer& operator=(const GenericPointer& rhs) { if (this != &rhs) { // Do not delete ownAllcator if (nameBuffer_) Allocator::Free(tokens_); tokenCount_ = rhs.tokenCount_; parseErrorOffset_ = rhs.parseErrorOffset_; parseErrorCode_ = rhs.parseErrorCode_; if (rhs.nameBuffer_) CopyFromRaw(rhs); // Normally parsed tokens. else { tokens_ = rhs.tokens_; // User supplied const tokens. nameBuffer_ = 0; } } return *this; } //! Swap the content of this pointer with an other. /*! \param other The pointer to swap with. \note Constant complexity. */ GenericPointer& Swap(GenericPointer& other) RAPIDJSON_NOEXCEPT { internal::Swap(allocator_, other.allocator_); internal::Swap(ownAllocator_, other.ownAllocator_); internal::Swap(nameBuffer_, other.nameBuffer_); internal::Swap(tokens_, other.tokens_); internal::Swap(tokenCount_, other.tokenCount_); internal::Swap(parseErrorOffset_, other.parseErrorOffset_); internal::Swap(parseErrorCode_, other.parseErrorCode_); return *this; } //! free-standing swap function helper /*! Helper function to enable support for common swap implementation pattern based on \c std::swap: \code void swap(MyClass& a, MyClass& b) { using std::swap; swap(a.pointer, b.pointer); // ... } \endcode \see Swap() */ friend inline void swap(GenericPointer& a, GenericPointer& b) RAPIDJSON_NOEXCEPT { a.Swap(b); } //@} //!@name Append token //@{ //! Append a token and return a new Pointer /*! \param token Token to be appended. \param allocator Allocator for the newly return Pointer. \return A new Pointer with appended token. */ GenericPointer Append(const Token& token, Allocator* allocator = 0) const { GenericPointer r; r.allocator_ = allocator; Ch *p = r.CopyFromRaw(*this, 1, token.length + 1); std::memcpy(p, token.name, (token.length + 1) * sizeof(Ch)); r.tokens_[tokenCount_].name = p; r.tokens_[tokenCount_].length = token.length; r.tokens_[tokenCount_].index = token.index; return r; } //! Append a name token with length, and return a new Pointer /*! \param name Name to be appended. \param length Length of name. \param allocator Allocator for the newly return Pointer. \return A new Pointer with appended token. */ GenericPointer Append(const Ch* name, SizeType length, Allocator* allocator = 0) const { Token token = { name, length, kPointerInvalidIndex }; return Append(token, allocator); } //! Append a name token without length, and return a new Pointer /*! \param name Name (const Ch*) to be appended. \param allocator Allocator for the newly return Pointer. \return A new Pointer with appended token. */ template <typename T> RAPIDJSON_DISABLEIF_RETURN((internal::NotExpr<internal::IsSame<typename internal::RemoveConst<T>::Type, Ch> >), (GenericPointer)) Append(T* name, Allocator* allocator = 0) const { return Append(name, internal::StrLen(name), allocator); } #if RAPIDJSON_HAS_STDSTRING //! Append a name token, and return a new Pointer /*! \param name Name to be appended. \param allocator Allocator for the newly return Pointer. \return A new Pointer with appended token. */ GenericPointer Append(const std::basic_string<Ch>& name, Allocator* allocator = 0) const { return Append(name.c_str(), static_cast<SizeType>(name.size()), allocator); } #endif //! Append a index token, and return a new Pointer /*! \param index Index to be appended. \param allocator Allocator for the newly return Pointer. \return A new Pointer with appended token. */ GenericPointer Append(SizeType index, Allocator* allocator = 0) const { char buffer[21]; char* end = sizeof(SizeType) == 4 ? internal::u32toa(index, buffer) : internal::u64toa(index, buffer); SizeType length = static_cast<SizeType>(end - buffer); buffer[length] = '\0'; if (sizeof(Ch) == 1) { Token token = { reinterpret_cast<Ch*>(buffer), length, index }; return Append(token, allocator); } else { Ch name[21]; for (size_t i = 0; i <= length; i++) name[i] = static_cast<Ch>(buffer[i]); Token token = { name, length, index }; return Append(token, allocator); } } //! Append a token by value, and return a new Pointer /*! \param token token to be appended. \param allocator Allocator for the newly return Pointer. \return A new Pointer with appended token. */ GenericPointer Append(const ValueType& token, Allocator* allocator = 0) const { if (token.IsString()) return Append(token.GetString(), token.GetStringLength(), allocator); else { RAPIDJSON_ASSERT(token.IsUint64()); RAPIDJSON_ASSERT(token.GetUint64() <= SizeType(~0)); return Append(static_cast<SizeType>(token.GetUint64()), allocator); } } //!@name Handling Parse Error //@{ //! Check whether this is a valid pointer. bool IsValid() const { return parseErrorCode_ == kPointerParseErrorNone; } //! Get the parsing error offset in code unit. size_t GetParseErrorOffset() const { return parseErrorOffset_; } //! Get the parsing error code. PointerParseErrorCode GetParseErrorCode() const { return parseErrorCode_; } //@} //! Get the allocator of this pointer. Allocator& GetAllocator() { return *allocator_; } //!@name Tokens //@{ //! Get the token array (const version only). const Token* GetTokens() const { return tokens_; } //! Get the number of tokens. size_t GetTokenCount() const { return tokenCount_; } //@} //!@name Equality/inequality operators //@{ //! Equality operator. /*! \note When any pointers are invalid, always returns false. */ bool operator==(const GenericPointer& rhs) const { if (!IsValid() || !rhs.IsValid() || tokenCount_ != rhs.tokenCount_) return false; for (size_t i = 0; i < tokenCount_; i++) { if (tokens_[i].index != rhs.tokens_[i].index || tokens_[i].length != rhs.tokens_[i].length || (tokens_[i].length != 0 && std::memcmp(tokens_[i].name, rhs.tokens_[i].name, sizeof(Ch)* tokens_[i].length) != 0)) { return false; } } return true; } //! Inequality operator. /*! \note When any pointers are invalid, always returns true. */ bool operator!=(const GenericPointer& rhs) const { return !(*this == rhs); } //! Less than operator. /*! \note Invalid pointers are always greater than valid ones. */ bool operator<(const GenericPointer& rhs) const { if (!IsValid()) return false; if (!rhs.IsValid()) return true; if (tokenCount_ != rhs.tokenCount_) return tokenCount_ < rhs.tokenCount_; for (size_t i = 0; i < tokenCount_; i++) { if (tokens_[i].index != rhs.tokens_[i].index) return tokens_[i].index < rhs.tokens_[i].index; if (tokens_[i].length != rhs.tokens_[i].length) return tokens_[i].length < rhs.tokens_[i].length; if (int cmp = std::memcmp(tokens_[i].name, rhs.tokens_[i].name, sizeof(Ch) * tokens_[i].length)) return cmp < 0; } return false; } //@} //!@name Stringify //@{ //! Stringify the pointer into string representation. /*! \tparam OutputStream Type of output stream. \param os The output stream. */ template<typename OutputStream> bool Stringify(OutputStream& os) const { return Stringify<false, OutputStream>(os); } //! Stringify the pointer into URI fragment representation. /*! \tparam OutputStream Type of output stream. \param os The output stream. */ template<typename OutputStream> bool StringifyUriFragment(OutputStream& os) const { return Stringify<true, OutputStream>(os); } //@} //!@name Create value //@{ //! Create a value in a subtree. /*! If the value is not exist, it creates all parent values and a JSON Null value. So it always succeed and return the newly created or existing value. Remind that it may change types of parents according to tokens, so it potentially removes previously stored values. For example, if a document was an array, and "/foo" is used to create a value, then the document will be changed to an object, and all existing array elements are lost. \param root Root value of a DOM subtree to be resolved. It can be any value other than document root. \param allocator Allocator for creating the values if the specified value or its parents are not exist. \param alreadyExist If non-null, it stores whether the resolved value is already exist. \return The resolved newly created (a JSON Null value), or already exists value. */ ValueType& Create(ValueType& root, typename ValueType::AllocatorType& allocator, bool* alreadyExist = 0) const { RAPIDJSON_ASSERT(IsValid()); ValueType* v = &root; bool exist = true; for (const Token *t = tokens_; t != tokens_ + tokenCount_; ++t) { if (v->IsArray() && t->name[0] == '-' && t->length == 1) { v->PushBack(ValueType().Move(), allocator); v = &((*v)[v->Size() - 1]); exist = false; } else { if (t->index == kPointerInvalidIndex) { // must be object name if (!v->IsObject()) v->SetObject(); // Change to Object } else { // object name or array index if (!v->IsArray() && !v->IsObject()) v->SetArray(); // Change to Array } if (v->IsArray()) { if (t->index >= v->Size()) { v->Reserve(t->index + 1, allocator); while (t->index >= v->Size()) v->PushBack(ValueType().Move(), allocator); exist = false; } v = &((*v)[t->index]); } else { typename ValueType::MemberIterator m = v->FindMember(GenericValue<EncodingType>(GenericStringRef<Ch>(t->name, t->length))); if (m == v->MemberEnd()) { v->AddMember(ValueType(t->name, t->length, allocator).Move(), ValueType().Move(), allocator); m = v->MemberEnd(); v = &(--m)->value; // Assumes AddMember() appends at the end exist = false; } else v = &m->value; } } } if (alreadyExist) *alreadyExist = exist; return *v; } //! Creates a value in a document. /*! \param document A document to be resolved. \param alreadyExist If non-null, it stores whether the resolved value is already exist. \return The resolved newly created, or already exists value. */ template <typename stackAllocator> ValueType& Create(GenericDocument<EncodingType, typename ValueType::AllocatorType, stackAllocator>& document, bool* alreadyExist = 0) const { return Create(document, document.GetAllocator(), alreadyExist); } //@} //!@name Query value //@{ //! Query a value in a subtree. /*! \param root Root value of a DOM sub-tree to be resolved. It can be any value other than document root. \param unresolvedTokenIndex If the pointer cannot resolve a token in the pointer, this parameter can obtain the index of unresolved token. \return Pointer to the value if it can be resolved. Otherwise null. \note There are only 3 situations when a value cannot be resolved: 1. A value in the path is not an array nor object. 2. An object value does not contain the token. 3. A token is out of range of an array value. Use unresolvedTokenIndex to retrieve the token index. */ ValueType* Get(ValueType& root, size_t* unresolvedTokenIndex = 0) const { RAPIDJSON_ASSERT(IsValid()); ValueType* v = &root; for (const Token *t = tokens_; t != tokens_ + tokenCount_; ++t) { switch (v->GetType()) { case kObjectType: { typename ValueType::MemberIterator m = v->FindMember(GenericValue<EncodingType>(GenericStringRef<Ch>(t->name, t->length))); if (m == v->MemberEnd()) break; v = &m->value; } continue; case kArrayType: if (t->index == kPointerInvalidIndex || t->index >= v->Size()) break; v = &((*v)[t->index]); continue; default: break; } // Error: unresolved token if (unresolvedTokenIndex) *unresolvedTokenIndex = static_cast<size_t>(t - tokens_); return 0; } return v; } //! Query a const value in a const subtree. /*! \param root Root value of a DOM sub-tree to be resolved. It can be any value other than document root. \return Pointer to the value if it can be resolved. Otherwise null. */ const ValueType* Get(const ValueType& root, size_t* unresolvedTokenIndex = 0) const { return Get(const_cast<ValueType&>(root), unresolvedTokenIndex); } //@} //!@name Query a value with default //@{ //! Query a value in a subtree with default value. /*! Similar to Get(), but if the specified value do not exists, it creates all parents and clone the default value. So that this function always succeed. \param root Root value of a DOM sub-tree to be resolved. It can be any value other than document root. \param defaultValue Default value to be cloned if the value was not exists. \param allocator Allocator for creating the values if the specified value or its parents are not exist. \see Create() */ ValueType& GetWithDefault(ValueType& root, const ValueType& defaultValue, typename ValueType::AllocatorType& allocator) const { bool alreadyExist; ValueType& v = Create(root, allocator, &alreadyExist); return alreadyExist ? v : v.CopyFrom(defaultValue, allocator); } //! Query a value in a subtree with default null-terminated string. ValueType& GetWithDefault(ValueType& root, const Ch* defaultValue, typename ValueType::AllocatorType& allocator) const { bool alreadyExist; ValueType& v = Create(root, allocator, &alreadyExist); return alreadyExist ? v : v.SetString(defaultValue, allocator); } #if RAPIDJSON_HAS_STDSTRING //! Query a value in a subtree with default std::basic_string. ValueType& GetWithDefault(ValueType& root, const std::basic_string<Ch>& defaultValue, typename ValueType::AllocatorType& allocator) const { bool alreadyExist; ValueType& v = Create(root, allocator, &alreadyExist); return alreadyExist ? v : v.SetString(defaultValue, allocator); } #endif //! Query a value in a subtree with default primitive value. /*! \tparam T Either \ref Type, \c int, \c unsigned, \c int64_t, \c uint64_t, \c bool */ template <typename T> RAPIDJSON_DISABLEIF_RETURN((internal::OrExpr<internal::IsPointer<T>, internal::IsGenericValue<T> >), (ValueType&)) GetWithDefault(ValueType& root, T defaultValue, typename ValueType::AllocatorType& allocator) const { return GetWithDefault(root, ValueType(defaultValue).Move(), allocator); } //! Query a value in a document with default value. template <typename stackAllocator> ValueType& GetWithDefault(GenericDocument<EncodingType, typename ValueType::AllocatorType, stackAllocator>& document, const ValueType& defaultValue) const { return GetWithDefault(document, defaultValue, document.GetAllocator()); } //! Query a value in a document with default null-terminated string. template <typename stackAllocator> ValueType& GetWithDefault(GenericDocument<EncodingType, typename ValueType::AllocatorType, stackAllocator>& document, const Ch* defaultValue) const { return GetWithDefault(document, defaultValue, document.GetAllocator()); } #if RAPIDJSON_HAS_STDSTRING //! Query a value in a document with default std::basic_string. template <typename stackAllocator> ValueType& GetWithDefault(GenericDocument<EncodingType, typename ValueType::AllocatorType, stackAllocator>& document, const std::basic_string<Ch>& defaultValue) const { return GetWithDefault(document, defaultValue, document.GetAllocator()); } #endif //! Query a value in a document with default primitive value. /*! \tparam T Either \ref Type, \c int, \c unsigned, \c int64_t, \c uint64_t, \c bool */ template <typename T, typename stackAllocator> RAPIDJSON_DISABLEIF_RETURN((internal::OrExpr<internal::IsPointer<T>, internal::IsGenericValue<T> >), (ValueType&)) GetWithDefault(GenericDocument<EncodingType, typename ValueType::AllocatorType, stackAllocator>& document, T defaultValue) const { return GetWithDefault(document, defaultValue, document.GetAllocator()); } //@} //!@name Set a value //@{ //! Set a value in a subtree, with move semantics. /*! It creates all parents if they are not exist or types are different to the tokens. So this function always succeeds but potentially remove existing values. \param root Root value of a DOM sub-tree to be resolved. It can be any value other than document root. \param value Value to be set. \param allocator Allocator for creating the values if the specified value or its parents are not exist. \see Create() */ ValueType& Set(ValueType& root, ValueType& value, typename ValueType::AllocatorType& allocator) const { return Create(root, allocator) = value; } //! Set a value in a subtree, with copy semantics. ValueType& Set(ValueType& root, const ValueType& value, typename ValueType::AllocatorType& allocator) const { return Create(root, allocator).CopyFrom(value, allocator); } //! Set a null-terminated string in a subtree. ValueType& Set(ValueType& root, const Ch* value, typename ValueType::AllocatorType& allocator) const { return Create(root, allocator) = ValueType(value, allocator).Move(); } #if RAPIDJSON_HAS_STDSTRING //! Set a std::basic_string in a subtree. ValueType& Set(ValueType& root, const std::basic_string<Ch>& value, typename ValueType::AllocatorType& allocator) const { return Create(root, allocator) = ValueType(value, allocator).Move(); } #endif //! Set a primitive value in a subtree. /*! \tparam T Either \ref Type, \c int, \c unsigned, \c int64_t, \c uint64_t, \c bool */ template <typename T> RAPIDJSON_DISABLEIF_RETURN((internal::OrExpr<internal::IsPointer<T>, internal::IsGenericValue<T> >), (ValueType&)) Set(ValueType& root, T value, typename ValueType::AllocatorType& allocator) const { return Create(root, allocator) = ValueType(value).Move(); } //! Set a value in a document, with move semantics. template <typename stackAllocator> ValueType& Set(GenericDocument<EncodingType, typename ValueType::AllocatorType, stackAllocator>& document, ValueType& value) const { return Create(document) = value; } //! Set a value in a document, with copy semantics. template <typename stackAllocator> ValueType& Set(GenericDocument<EncodingType, typename ValueType::AllocatorType, stackAllocator>& document, const ValueType& value) const { return Create(document).CopyFrom(value, document.GetAllocator()); } //! Set a null-terminated string in a document. template <typename stackAllocator> ValueType& Set(GenericDocument<EncodingType, typename ValueType::AllocatorType, stackAllocator>& document, const Ch* value) const { return Create(document) = ValueType(value, document.GetAllocator()).Move(); } #if RAPIDJSON_HAS_STDSTRING //! Sets a std::basic_string in a document. template <typename stackAllocator> ValueType& Set(GenericDocument<EncodingType, typename ValueType::AllocatorType, stackAllocator>& document, const std::basic_string<Ch>& value) const { return Create(document) = ValueType(value, document.GetAllocator()).Move(); } #endif //! Set a primitive value in a document. /*! \tparam T Either \ref Type, \c int, \c unsigned, \c int64_t, \c uint64_t, \c bool */ template <typename T, typename stackAllocator> RAPIDJSON_DISABLEIF_RETURN((internal::OrExpr<internal::IsPointer<T>, internal::IsGenericValue<T> >), (ValueType&)) Set(GenericDocument<EncodingType, typename ValueType::AllocatorType, stackAllocator>& document, T value) const { return Create(document) = value; } //@} //!@name Swap a value //@{ //! Swap a value with a value in a subtree. /*! It creates all parents if they are not exist or types are different to the tokens. So this function always succeeds but potentially remove existing values. \param root Root value of a DOM sub-tree to be resolved. It can be any value other than document root. \param value Value to be swapped. \param allocator Allocator for creating the values if the specified value or its parents are not exist. \see Create() */ ValueType& Swap(ValueType& root, ValueType& value, typename ValueType::AllocatorType& allocator) const { return Create(root, allocator).Swap(value); } //! Swap a value with a value in a document. template <typename stackAllocator> ValueType& Swap(GenericDocument<EncodingType, typename ValueType::AllocatorType, stackAllocator>& document, ValueType& value) const { return Create(document).Swap(value); } //@} //! Erase a value in a subtree. /*! \param root Root value of a DOM sub-tree to be resolved. It can be any value other than document root. \return Whether the resolved value is found and erased. \note Erasing with an empty pointer \c Pointer(""), i.e. the root, always fail and return false. */ bool Erase(ValueType& root) const { RAPIDJSON_ASSERT(IsValid()); if (tokenCount_ == 0) // Cannot erase the root return false; ValueType* v = &root; const Token* last = tokens_ + (tokenCount_ - 1); for (const Token *t = tokens_; t != last; ++t) { switch (v->GetType()) { case kObjectType: { typename ValueType::MemberIterator m = v->FindMember(GenericValue<EncodingType>(GenericStringRef<Ch>(t->name, t->length))); if (m == v->MemberEnd()) return false; v = &m->value; } break; case kArrayType: if (t->index == kPointerInvalidIndex || t->index >= v->Size()) return false; v = &((*v)[t->index]); break; default: return false; } } switch (v->GetType()) { case kObjectType: return v->EraseMember(GenericStringRef<Ch>(last->name, last->length)); case kArrayType: if (last->index == kPointerInvalidIndex || last->index >= v->Size()) return false; v->Erase(v->Begin() + last->index); return true; default: return false; } } private: //! Clone the content from rhs to this. /*! \param rhs Source pointer. \param extraToken Extra tokens to be allocated. \param extraNameBufferSize Extra name buffer size (in number of Ch) to be allocated. \return Start of non-occupied name buffer, for storing extra names. */ Ch* CopyFromRaw(const GenericPointer& rhs, size_t extraToken = 0, size_t extraNameBufferSize = 0) { if (!allocator_) // allocator is independently owned. ownAllocator_ = allocator_ = RAPIDJSON_NEW(Allocator)(); size_t nameBufferSize = rhs.tokenCount_; // null terminators for tokens for (Token *t = rhs.tokens_; t != rhs.tokens_ + rhs.tokenCount_; ++t) nameBufferSize += t->length; tokenCount_ = rhs.tokenCount_ + extraToken; tokens_ = static_cast<Token *>(allocator_->Malloc(tokenCount_ * sizeof(Token) + (nameBufferSize + extraNameBufferSize) * sizeof(Ch))); nameBuffer_ = reinterpret_cast<Ch *>(tokens_ + tokenCount_); if (rhs.tokenCount_ > 0) { std::memcpy(tokens_, rhs.tokens_, rhs.tokenCount_ * sizeof(Token)); } if (nameBufferSize > 0) { std::memcpy(nameBuffer_, rhs.nameBuffer_, nameBufferSize * sizeof(Ch)); } // Adjust pointers to name buffer std::ptrdiff_t diff = nameBuffer_ - rhs.nameBuffer_; for (Token *t = tokens_; t != tokens_ + rhs.tokenCount_; ++t) t->name += diff; return nameBuffer_ + nameBufferSize; } //! Check whether a character should be percent-encoded. /*! According to RFC 3986 2.3 Unreserved Characters. \param c The character (code unit) to be tested. */ bool NeedPercentEncode(Ch c) const { return !((c >= '0' && c <= '9') || (c >= 'A' && c <='Z') || (c >= 'a' && c <= 'z') || c == '-' || c == '.' || c == '_' || c =='~'); } //! Parse a JSON String or its URI fragment representation into tokens. #ifndef __clang__ // -Wdocumentation /*! \param source Either a JSON Pointer string, or its URI fragment representation. Not need to be null terminated. \param length Length of the source string. \note Source cannot be JSON String Representation of JSON Pointer, e.g. In "/\u0000", \u0000 will not be unescaped. */ #endif void Parse(const Ch* source, size_t length) { RAPIDJSON_ASSERT(source != NULL); RAPIDJSON_ASSERT(nameBuffer_ == 0); RAPIDJSON_ASSERT(tokens_ == 0); // Create own allocator if user did not supply. if (!allocator_) ownAllocator_ = allocator_ = RAPIDJSON_NEW(Allocator)(); // Count number of '/' as tokenCount tokenCount_ = 0; for (const Ch* s = source; s != source + length; s++) if (*s == '/') tokenCount_++; Token* token = tokens_ = static_cast<Token *>(allocator_->Malloc(tokenCount_ * sizeof(Token) + length * sizeof(Ch))); Ch* name = nameBuffer_ = reinterpret_cast<Ch *>(tokens_ + tokenCount_); size_t i = 0; // Detect if it is a URI fragment bool uriFragment = false; if (source[i] == '#') { uriFragment = true; i++; } if (i != length && source[i] != '/') { parseErrorCode_ = kPointerParseErrorTokenMustBeginWithSolidus; goto error; } while (i < length) { RAPIDJSON_ASSERT(source[i] == '/'); i++; // consumes '/' token->name = name; bool isNumber = true; while (i < length && source[i] != '/') { Ch c = source[i]; if (uriFragment) { // Decoding percent-encoding for URI fragment if (c == '%') { PercentDecodeStream is(&source[i], source + length); GenericInsituStringStream<EncodingType> os(name); Ch* begin = os.PutBegin(); if (!Transcoder<UTF8<>, EncodingType>().Validate(is, os) || !is.IsValid()) { parseErrorCode_ = kPointerParseErrorInvalidPercentEncoding; goto error; } size_t len = os.PutEnd(begin); i += is.Tell() - 1; if (len == 1) c = *name; else { name += len; isNumber = false; i++; continue; } } else if (NeedPercentEncode(c)) { parseErrorCode_ = kPointerParseErrorCharacterMustPercentEncode; goto error; } } i++; // Escaping "~0" -> '~', "~1" -> '/' if (c == '~') { if (i < length) { c = source[i]; if (c == '0') c = '~'; else if (c == '1') c = '/'; else { parseErrorCode_ = kPointerParseErrorInvalidEscape; goto error; } i++; } else { parseErrorCode_ = kPointerParseErrorInvalidEscape; goto error; } } // First check for index: all of characters are digit if (c < '0' || c > '9') isNumber = false; *name++ = c; } token->length = static_cast<SizeType>(name - token->name); if (token->length == 0) isNumber = false; *name++ = '\0'; // Null terminator // Second check for index: more than one digit cannot have leading zero if (isNumber && token->length > 1 && token->name[0] == '0') isNumber = false; // String to SizeType conversion SizeType n = 0; if (isNumber) { for (size_t j = 0; j < token->length; j++) { SizeType m = n * 10 + static_cast<SizeType>(token->name[j] - '0'); if (m < n) { // overflow detection isNumber = false; break; } n = m; } } token->index = isNumber ? n : kPointerInvalidIndex; token++; } RAPIDJSON_ASSERT(name <= nameBuffer_ + length); // Should not overflow buffer parseErrorCode_ = kPointerParseErrorNone; return; error: Allocator::Free(tokens_); nameBuffer_ = 0; tokens_ = 0; tokenCount_ = 0; parseErrorOffset_ = i; return; } //! Stringify to string or URI fragment representation. /*! \tparam uriFragment True for stringifying to URI fragment representation. False for string representation. \tparam OutputStream type of output stream. \param os The output stream. */ template<bool uriFragment, typename OutputStream> bool Stringify(OutputStream& os) const { RAPIDJSON_ASSERT(IsValid()); if (uriFragment) os.Put('#'); for (Token *t = tokens_; t != tokens_ + tokenCount_; ++t) { os.Put('/'); for (size_t j = 0; j < t->length; j++) { Ch c = t->name[j]; if (c == '~') { os.Put('~'); os.Put('0'); } else if (c == '/') { os.Put('~'); os.Put('1'); } else if (uriFragment && NeedPercentEncode(c)) { // Transcode to UTF8 sequence GenericStringStream<typename ValueType::EncodingType> source(&t->name[j]); PercentEncodeStream<OutputStream> target(os); if (!Transcoder<EncodingType, UTF8<> >().Validate(source, target)) return false; j += source.Tell() - 1; } else os.Put(c); } } return true; } //! A helper stream for decoding a percent-encoded sequence into code unit. /*! This stream decodes %XY triplet into code unit (0-255). If it encounters invalid characters, it sets output code unit as 0 and mark invalid, and to be checked by IsValid(). */ class PercentDecodeStream { public: typedef typename ValueType::Ch Ch; //! Constructor /*! \param source Start of the stream \param end Past-the-end of the stream. */ PercentDecodeStream(const Ch* source, const Ch* end) : src_(source), head_(source), end_(end), valid_(true) {} Ch Take() { if (*src_ != '%' || src_ + 3 > end_) { // %XY triplet valid_ = false; return 0; } src_++; Ch c = 0; for (int j = 0; j < 2; j++) { c = static_cast<Ch>(c << 4); Ch h = *src_; if (h >= '0' && h <= '9') c = static_cast<Ch>(c + h - '0'); else if (h >= 'A' && h <= 'F') c = static_cast<Ch>(c + h - 'A' + 10); else if (h >= 'a' && h <= 'f') c = static_cast<Ch>(c + h - 'a' + 10); else { valid_ = false; return 0; } src_++; } return c; } size_t Tell() const { return static_cast<size_t>(src_ - head_); } bool IsValid() const { return valid_; } private: const Ch* src_; //!< Current read position. const Ch* head_; //!< Original head of the string. const Ch* end_; //!< Past-the-end position. bool valid_; //!< Whether the parsing is valid. }; //! A helper stream to encode character (UTF-8 code unit) into percent-encoded sequence. template <typename OutputStream> class PercentEncodeStream { public: PercentEncodeStream(OutputStream& os) : os_(os) {} void Put(char c) { // UTF-8 must be byte unsigned char u = static_cast<unsigned char>(c); static const char hexDigits[16] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' }; os_.Put('%'); os_.Put(static_cast<typename OutputStream::Ch>(hexDigits[u >> 4])); os_.Put(static_cast<typename OutputStream::Ch>(hexDigits[u & 15])); } private: OutputStream& os_; }; Allocator* allocator_; //!< The current allocator. It is either user-supplied or equal to ownAllocator_. Allocator* ownAllocator_; //!< Allocator owned by this Pointer. Ch* nameBuffer_; //!< A buffer containing all names in tokens. Token* tokens_; //!< A list of tokens. size_t tokenCount_; //!< Number of tokens in tokens_. size_t parseErrorOffset_; //!< Offset in code unit when parsing fail. PointerParseErrorCode parseErrorCode_; //!< Parsing error code. }; //! GenericPointer for Value (UTF-8, default allocator). typedef GenericPointer<Value> Pointer; //!@name Helper functions for GenericPointer //@{ ////////////////////////////////////////////////////////////////////////////// template <typename T> typename T::ValueType& CreateValueByPointer(T& root, const GenericPointer<typename T::ValueType>& pointer, typename T::AllocatorType& a) { return pointer.Create(root, a); } template <typename T, typename CharType, size_t N> typename T::ValueType& CreateValueByPointer(T& root, const CharType(&source)[N], typename T::AllocatorType& a) { return GenericPointer<typename T::ValueType>(source, N - 1).Create(root, a); } // No allocator parameter template <typename DocumentType> typename DocumentType::ValueType& CreateValueByPointer(DocumentType& document, const GenericPointer<typename DocumentType::ValueType>& pointer) { return pointer.Create(document); } template <typename DocumentType, typename CharType, size_t N> typename DocumentType::ValueType& CreateValueByPointer(DocumentType& document, const CharType(&source)[N]) { return GenericPointer<typename DocumentType::ValueType>(source, N - 1).Create(document); } ////////////////////////////////////////////////////////////////////////////// template <typename T> typename T::ValueType* GetValueByPointer(T& root, const GenericPointer<typename T::ValueType>& pointer, size_t* unresolvedTokenIndex = 0) { return pointer.Get(root, unresolvedTokenIndex); } template <typename T> const typename T::ValueType* GetValueByPointer(const T& root, const GenericPointer<typename T::ValueType>& pointer, size_t* unresolvedTokenIndex = 0) { return pointer.Get(root, unresolvedTokenIndex); } template <typename T, typename CharType, size_t N> typename T::ValueType* GetValueByPointer(T& root, const CharType (&source)[N], size_t* unresolvedTokenIndex = 0) { return GenericPointer<typename T::ValueType>(source, N - 1).Get(root, unresolvedTokenIndex); } template <typename T, typename CharType, size_t N> const typename T::ValueType* GetValueByPointer(const T& root, const CharType(&source)[N], size_t* unresolvedTokenIndex = 0) { return GenericPointer<typename T::ValueType>(source, N - 1).Get(root, unresolvedTokenIndex); } ////////////////////////////////////////////////////////////////////////////// template <typename T> typename T::ValueType& GetValueByPointerWithDefault(T& root, const GenericPointer<typename T::ValueType>& pointer, const typename T::ValueType& defaultValue, typename T::AllocatorType& a) { return pointer.GetWithDefault(root, defaultValue, a); } template <typename T> typename T::ValueType& GetValueByPointerWithDefault(T& root, const GenericPointer<typename T::ValueType>& pointer, const typename T::Ch* defaultValue, typename T::AllocatorType& a) { return pointer.GetWithDefault(root, defaultValue, a); } #if RAPIDJSON_HAS_STDSTRING template <typename T> typename T::ValueType& GetValueByPointerWithDefault(T& root, const GenericPointer<typename T::ValueType>& pointer, const std::basic_string<typename T::Ch>& defaultValue, typename T::AllocatorType& a) { return pointer.GetWithDefault(root, defaultValue, a); } #endif template <typename T, typename T2> RAPIDJSON_DISABLEIF_RETURN((internal::OrExpr<internal::IsPointer<T2>, internal::IsGenericValue<T2> >), (typename T::ValueType&)) GetValueByPointerWithDefault(T& root, const GenericPointer<typename T::ValueType>& pointer, T2 defaultValue, typename T::AllocatorType& a) { return pointer.GetWithDefault(root, defaultValue, a); } template <typename T, typename CharType, size_t N> typename T::ValueType& GetValueByPointerWithDefault(T& root, const CharType(&source)[N], const typename T::ValueType& defaultValue, typename T::AllocatorType& a) { return GenericPointer<typename T::ValueType>(source, N - 1).GetWithDefault(root, defaultValue, a); } template <typename T, typename CharType, size_t N> typename T::ValueType& GetValueByPointerWithDefault(T& root, const CharType(&source)[N], const typename T::Ch* defaultValue, typename T::AllocatorType& a) { return GenericPointer<typename T::ValueType>(source, N - 1).GetWithDefault(root, defaultValue, a); } #if RAPIDJSON_HAS_STDSTRING template <typename T, typename CharType, size_t N> typename T::ValueType& GetValueByPointerWithDefault(T& root, const CharType(&source)[N], const std::basic_string<typename T::Ch>& defaultValue, typename T::AllocatorType& a) { return GenericPointer<typename T::ValueType>(source, N - 1).GetWithDefault(root, defaultValue, a); } #endif template <typename T, typename CharType, size_t N, typename T2> RAPIDJSON_DISABLEIF_RETURN((internal::OrExpr<internal::IsPointer<T2>, internal::IsGenericValue<T2> >), (typename T::ValueType&)) GetValueByPointerWithDefault(T& root, const CharType(&source)[N], T2 defaultValue, typename T::AllocatorType& a) { return GenericPointer<typename T::ValueType>(source, N - 1).GetWithDefault(root, defaultValue, a); } // No allocator parameter template <typename DocumentType> typename DocumentType::ValueType& GetValueByPointerWithDefault(DocumentType& document, const GenericPointer<typename DocumentType::ValueType>& pointer, const typename DocumentType::ValueType& defaultValue) { return pointer.GetWithDefault(document, defaultValue); } template <typename DocumentType> typename DocumentType::ValueType& GetValueByPointerWithDefault(DocumentType& document, const GenericPointer<typename DocumentType::ValueType>& pointer, const typename DocumentType::Ch* defaultValue) { return pointer.GetWithDefault(document, defaultValue); } #if RAPIDJSON_HAS_STDSTRING template <typename DocumentType> typename DocumentType::ValueType& GetValueByPointerWithDefault(DocumentType& document, const GenericPointer<typename DocumentType::ValueType>& pointer, const std::basic_string<typename DocumentType::Ch>& defaultValue) { return pointer.GetWithDefault(document, defaultValue); } #endif template <typename DocumentType, typename T2> RAPIDJSON_DISABLEIF_RETURN((internal::OrExpr<internal::IsPointer<T2>, internal::IsGenericValue<T2> >), (typename DocumentType::ValueType&)) GetValueByPointerWithDefault(DocumentType& document, const GenericPointer<typename DocumentType::ValueType>& pointer, T2 defaultValue) { return pointer.GetWithDefault(document, defaultValue); } template <typename DocumentType, typename CharType, size_t N> typename DocumentType::ValueType& GetValueByPointerWithDefault(DocumentType& document, const CharType(&source)[N], const typename DocumentType::ValueType& defaultValue) { return GenericPointer<typename DocumentType::ValueType>(source, N - 1).GetWithDefault(document, defaultValue); } template <typename DocumentType, typename CharType, size_t N> typename DocumentType::ValueType& GetValueByPointerWithDefault(DocumentType& document, const CharType(&source)[N], const typename DocumentType::Ch* defaultValue) { return GenericPointer<typename DocumentType::ValueType>(source, N - 1).GetWithDefault(document, defaultValue); } #if RAPIDJSON_HAS_STDSTRING template <typename DocumentType, typename CharType, size_t N> typename DocumentType::ValueType& GetValueByPointerWithDefault(DocumentType& document, const CharType(&source)[N], const std::basic_string<typename DocumentType::Ch>& defaultValue) { return GenericPointer<typename DocumentType::ValueType>(source, N - 1).GetWithDefault(document, defaultValue); } #endif template <typename DocumentType, typename CharType, size_t N, typename T2> RAPIDJSON_DISABLEIF_RETURN((internal::OrExpr<internal::IsPointer<T2>, internal::IsGenericValue<T2> >), (typename DocumentType::ValueType&)) GetValueByPointerWithDefault(DocumentType& document, const CharType(&source)[N], T2 defaultValue) { return GenericPointer<typename DocumentType::ValueType>(source, N - 1).GetWithDefault(document, defaultValue); } ////////////////////////////////////////////////////////////////////////////// template <typename T> typename T::ValueType& SetValueByPointer(T& root, const GenericPointer<typename T::ValueType>& pointer, typename T::ValueType& value, typename T::AllocatorType& a) { return pointer.Set(root, value, a); } template <typename T> typename T::ValueType& SetValueByPointer(T& root, const GenericPointer<typename T::ValueType>& pointer, const typename T::ValueType& value, typename T::AllocatorType& a) { return pointer.Set(root, value, a); } template <typename T> typename T::ValueType& SetValueByPointer(T& root, const GenericPointer<typename T::ValueType>& pointer, const typename T::Ch* value, typename T::AllocatorType& a) { return pointer.Set(root, value, a); } #if RAPIDJSON_HAS_STDSTRING template <typename T> typename T::ValueType& SetValueByPointer(T& root, const GenericPointer<typename T::ValueType>& pointer, const std::basic_string<typename T::Ch>& value, typename T::AllocatorType& a) { return pointer.Set(root, value, a); } #endif template <typename T, typename T2> RAPIDJSON_DISABLEIF_RETURN((internal::OrExpr<internal::IsPointer<T2>, internal::IsGenericValue<T2> >), (typename T::ValueType&)) SetValueByPointer(T& root, const GenericPointer<typename T::ValueType>& pointer, T2 value, typename T::AllocatorType& a) { return pointer.Set(root, value, a); } template <typename T, typename CharType, size_t N> typename T::ValueType& SetValueByPointer(T& root, const CharType(&source)[N], typename T::ValueType& value, typename T::AllocatorType& a) { return GenericPointer<typename T::ValueType>(source, N - 1).Set(root, value, a); } template <typename T, typename CharType, size_t N> typename T::ValueType& SetValueByPointer(T& root, const CharType(&source)[N], const typename T::ValueType& value, typename T::AllocatorType& a) { return GenericPointer<typename T::ValueType>(source, N - 1).Set(root, value, a); } template <typename T, typename CharType, size_t N> typename T::ValueType& SetValueByPointer(T& root, const CharType(&source)[N], const typename T::Ch* value, typename T::AllocatorType& a) { return GenericPointer<typename T::ValueType>(source, N - 1).Set(root, value, a); } #if RAPIDJSON_HAS_STDSTRING template <typename T, typename CharType, size_t N> typename T::ValueType& SetValueByPointer(T& root, const CharType(&source)[N], const std::basic_string<typename T::Ch>& value, typename T::AllocatorType& a) { return GenericPointer<typename T::ValueType>(source, N - 1).Set(root, value, a); } #endif template <typename T, typename CharType, size_t N, typename T2> RAPIDJSON_DISABLEIF_RETURN((internal::OrExpr<internal::IsPointer<T2>, internal::IsGenericValue<T2> >), (typename T::ValueType&)) SetValueByPointer(T& root, const CharType(&source)[N], T2 value, typename T::AllocatorType& a) { return GenericPointer<typename T::ValueType>(source, N - 1).Set(root, value, a); } // No allocator parameter template <typename DocumentType> typename DocumentType::ValueType& SetValueByPointer(DocumentType& document, const GenericPointer<typename DocumentType::ValueType>& pointer, typename DocumentType::ValueType& value) { return pointer.Set(document, value); } template <typename DocumentType> typename DocumentType::ValueType& SetValueByPointer(DocumentType& document, const GenericPointer<typename DocumentType::ValueType>& pointer, const typename DocumentType::ValueType& value) { return pointer.Set(document, value); } template <typename DocumentType> typename DocumentType::ValueType& SetValueByPointer(DocumentType& document, const GenericPointer<typename DocumentType::ValueType>& pointer, const typename DocumentType::Ch* value) { return pointer.Set(document, value); } #if RAPIDJSON_HAS_STDSTRING template <typename DocumentType> typename DocumentType::ValueType& SetValueByPointer(DocumentType& document, const GenericPointer<typename DocumentType::ValueType>& pointer, const std::basic_string<typename DocumentType::Ch>& value) { return pointer.Set(document, value); } #endif template <typename DocumentType, typename T2> RAPIDJSON_DISABLEIF_RETURN((internal::OrExpr<internal::IsPointer<T2>, internal::IsGenericValue<T2> >), (typename DocumentType::ValueType&)) SetValueByPointer(DocumentType& document, const GenericPointer<typename DocumentType::ValueType>& pointer, T2 value) { return pointer.Set(document, value); } template <typename DocumentType, typename CharType, size_t N> typename DocumentType::ValueType& SetValueByPointer(DocumentType& document, const CharType(&source)[N], typename DocumentType::ValueType& value) { return GenericPointer<typename DocumentType::ValueType>(source, N - 1).Set(document, value); } template <typename DocumentType, typename CharType, size_t N> typename DocumentType::ValueType& SetValueByPointer(DocumentType& document, const CharType(&source)[N], const typename DocumentType::ValueType& value) { return GenericPointer<typename DocumentType::ValueType>(source, N - 1).Set(document, value); } template <typename DocumentType, typename CharType, size_t N> typename DocumentType::ValueType& SetValueByPointer(DocumentType& document, const CharType(&source)[N], const typename DocumentType::Ch* value) { return GenericPointer<typename DocumentType::ValueType>(source, N - 1).Set(document, value); } #if RAPIDJSON_HAS_STDSTRING template <typename DocumentType, typename CharType, size_t N> typename DocumentType::ValueType& SetValueByPointer(DocumentType& document, const CharType(&source)[N], const std::basic_string<typename DocumentType::Ch>& value) { return GenericPointer<typename DocumentType::ValueType>(source, N - 1).Set(document, value); } #endif template <typename DocumentType, typename CharType, size_t N, typename T2> RAPIDJSON_DISABLEIF_RETURN((internal::OrExpr<internal::IsPointer<T2>, internal::IsGenericValue<T2> >), (typename DocumentType::ValueType&)) SetValueByPointer(DocumentType& document, const CharType(&source)[N], T2 value) { return GenericPointer<typename DocumentType::ValueType>(source, N - 1).Set(document, value); } ////////////////////////////////////////////////////////////////////////////// template <typename T> typename T::ValueType& SwapValueByPointer(T& root, const GenericPointer<typename T::ValueType>& pointer, typename T::ValueType& value, typename T::AllocatorType& a) { return pointer.Swap(root, value, a); } template <typename T, typename CharType, size_t N> typename T::ValueType& SwapValueByPointer(T& root, const CharType(&source)[N], typename T::ValueType& value, typename T::AllocatorType& a) { return GenericPointer<typename T::ValueType>(source, N - 1).Swap(root, value, a); } template <typename DocumentType> typename DocumentType::ValueType& SwapValueByPointer(DocumentType& document, const GenericPointer<typename DocumentType::ValueType>& pointer, typename DocumentType::ValueType& value) { return pointer.Swap(document, value); } template <typename DocumentType, typename CharType, size_t N> typename DocumentType::ValueType& SwapValueByPointer(DocumentType& document, const CharType(&source)[N], typename DocumentType::ValueType& value) { return GenericPointer<typename DocumentType::ValueType>(source, N - 1).Swap(document, value); } ////////////////////////////////////////////////////////////////////////////// template <typename T> bool EraseValueByPointer(T& root, const GenericPointer<typename T::ValueType>& pointer) { return pointer.Erase(root); } template <typename T, typename CharType, size_t N> bool EraseValueByPointer(T& root, const CharType(&source)[N]) { return GenericPointer<typename T::ValueType>(source, N - 1).Erase(root); } //@} RAPIDJSON_NAMESPACE_END #if defined(__clang__) || defined(_MSC_VER) RAPIDJSON_DIAG_POP #endif #endif // RAPIDJSON_POINTER_H_
60,889
pointer
h
en
c
code
{"qsc_code_num_words": 6581, "qsc_code_num_chars": 60889.0, "qsc_code_mean_word_length": 5.83649901, "qsc_code_frac_words_unique": 0.09223522, "qsc_code_frac_chars_top_2grams": 0.02928925, "qsc_code_frac_chars_top_3grams": 0.02905493, "qsc_code_frac_chars_top_4grams": 0.01822442, "qsc_code_frac_chars_dupe_5grams": 0.62481125, "qsc_code_frac_chars_dupe_6grams": 0.59185108, "qsc_code_frac_chars_dupe_7grams": 0.5670919, "qsc_code_frac_chars_dupe_8grams": 0.53762041, "qsc_code_frac_chars_dupe_9grams": 0.51072637, "qsc_code_frac_chars_dupe_10grams": 0.47740172, "qsc_code_frac_chars_replacement_symbols": 0.0, "qsc_code_frac_chars_digital": 0.00570943, "qsc_code_frac_chars_whitespace": 0.24634992, "qsc_code_size_file_byte": 60889.0, "qsc_code_num_lines": 1415.0, "qsc_code_num_chars_line_max": 237.0, "qsc_code_num_chars_line_mean": 43.03109541, "qsc_code_frac_chars_alphabet": 0.83131034, "qsc_code_frac_chars_comments": 0.29312355, "qsc_code_cate_xml_start": 0.0, "qsc_code_frac_lines_dupe_lines": 0.36397985, "qsc_code_cate_autogen": 0.0, "qsc_code_frac_lines_long_string": 0.0, "qsc_code_frac_chars_string_length": 0.00209103, "qsc_code_frac_chars_long_word_length": 0.0, "qsc_code_frac_lines_string_concat": 0.0, "qsc_code_cate_encoded_data": 0.0, "qsc_code_frac_chars_hex_words": 0.0, "qsc_code_frac_lines_prompt_comments": 0.0, "qsc_code_frac_lines_assert": 0.0138539, "qsc_codec_frac_lines_func_ratio": 0.11460957, "qsc_codec_cate_bitsstdc": 0.0, "qsc_codec_nums_lines_main": 0, "qsc_codec_frac_lines_goto": 0.00629723, "qsc_codec_cate_var_zero": 0.0, "qsc_codec_score_lines_no_logic": 0.15239295, "qsc_codec_frac_lines_print": 0.0, "qsc_codec_frac_lines_preprocessor_directives": null}
1
{"qsc_code_frac_chars_replacement_symbols": 0, "qsc_code_num_words": 0, "qsc_code_num_chars": 0, "qsc_code_mean_word_length": 0, "qsc_code_frac_chars_top_2grams": 0, "qsc_code_frac_chars_top_3grams": 0, "qsc_code_frac_chars_top_4grams": 0, "qsc_code_frac_chars_dupe_5grams": 0, "qsc_code_frac_chars_dupe_6grams": 0, "qsc_code_frac_chars_dupe_7grams": 0, "qsc_code_frac_chars_dupe_8grams": 0, "qsc_code_frac_chars_dupe_9grams": 0, "qsc_code_frac_chars_dupe_10grams": 0, "qsc_code_size_file_byte": 0, "qsc_code_num_lines": 0, "qsc_code_num_chars_line_max": 0, "qsc_code_num_chars_line_mean": 0, "qsc_code_frac_chars_alphabet": 0, "qsc_code_frac_chars_digital": 0, "qsc_code_frac_chars_whitespace": 0, "qsc_code_frac_chars_comments": 0, "qsc_code_cate_xml_start": 0, "qsc_code_frac_lines_dupe_lines": 0, "qsc_code_cate_autogen": 0, "qsc_code_frac_lines_long_string": 0, "qsc_code_frac_chars_string_length": 0, "qsc_code_frac_chars_long_word_length": 0, "qsc_code_cate_encoded_data": 0, "qsc_code_frac_chars_hex_words": 0, "qsc_code_frac_lines_prompt_comments": 0, "qsc_code_frac_lines_assert": 0, "qsc_codec_frac_lines_func_ratio": 0, "qsc_codec_nums_lines_main": 0, "qsc_codec_score_lines_no_logic": 0, "qsc_codec_frac_lines_preprocessor_directives": 0, "qsc_codec_frac_lines_print": 0}
0015/esp_rlottie
rlottie/src/lottie/rapidjson/msinttypes/stdint.h
// ISO C9x compliant stdint.h for Microsoft Visual Studio // Based on ISO/IEC 9899:TC2 Committee draft (May 6, 2005) WG14/N1124 // // Copyright (c) 2006-2013 Alexander Chemeris // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // // 3. Neither the name of the product nor the names of its contributors may // be used to endorse or promote products derived from this software // without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED // WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF // MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO // EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; // OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, // WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR // OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF // ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // /////////////////////////////////////////////////////////////////////////////// // The above software in this distribution may have been modified by // THL A29 Limited ("Tencent Modifications"). // All Tencent Modifications are Copyright (C) 2015 THL A29 Limited. #ifndef _MSC_VER // [ #error "Use this header only with Microsoft Visual C++ compilers!" #endif // _MSC_VER ] #ifndef _MSC_STDINT_H_ // [ #define _MSC_STDINT_H_ #if _MSC_VER > 1000 #pragma once #endif // miloyip: Originally Visual Studio 2010 uses its own stdint.h. However it generates warning with INT64_C(), so change to use this file for vs2010. #if _MSC_VER >= 1600 // [ #include <stdint.h> #if !defined(__cplusplus) || defined(__STDC_CONSTANT_MACROS) // [ See footnote 224 at page 260 #undef INT8_C #undef INT16_C #undef INT32_C #undef INT64_C #undef UINT8_C #undef UINT16_C #undef UINT32_C #undef UINT64_C // 7.18.4.1 Macros for minimum-width integer constants #define INT8_C(val) val##i8 #define INT16_C(val) val##i16 #define INT32_C(val) val##i32 #define INT64_C(val) val##i64 #define UINT8_C(val) val##ui8 #define UINT16_C(val) val##ui16 #define UINT32_C(val) val##ui32 #define UINT64_C(val) val##ui64 // 7.18.4.2 Macros for greatest-width integer constants // These #ifndef's are needed to prevent collisions with <boost/cstdint.hpp>. // Check out Issue 9 for the details. #ifndef INTMAX_C // [ # define INTMAX_C INT64_C #endif // INTMAX_C ] #ifndef UINTMAX_C // [ # define UINTMAX_C UINT64_C #endif // UINTMAX_C ] #endif // __STDC_CONSTANT_MACROS ] #else // ] _MSC_VER >= 1700 [ #include <limits.h> // For Visual Studio 6 in C++ mode and for many Visual Studio versions when // compiling for ARM we have to wrap <wchar.h> include with 'extern "C++" {}' // or compiler would give many errors like this: // error C2733: second C linkage of overloaded function 'wmemchr' not allowed #if defined(__cplusplus) && !defined(_M_ARM) extern "C" { #endif # include <wchar.h> #if defined(__cplusplus) && !defined(_M_ARM) } #endif // Define _W64 macros to mark types changing their size, like intptr_t. #ifndef _W64 # if !defined(__midl) && (defined(_X86_) || defined(_M_IX86)) && _MSC_VER >= 1300 # define _W64 __w64 # else # define _W64 # endif #endif // 7.18.1 Integer types // 7.18.1.1 Exact-width integer types // Visual Studio 6 and Embedded Visual C++ 4 doesn't // realize that, e.g. char has the same size as __int8 // so we give up on __intX for them. #if (_MSC_VER < 1300) typedef signed char int8_t; typedef signed short int16_t; typedef signed int int32_t; typedef unsigned char uint8_t; typedef unsigned short uint16_t; typedef unsigned int uint32_t; #else typedef signed __int8 int8_t; typedef signed __int16 int16_t; typedef signed __int32 int32_t; typedef unsigned __int8 uint8_t; typedef unsigned __int16 uint16_t; typedef unsigned __int32 uint32_t; #endif typedef signed __int64 int64_t; typedef unsigned __int64 uint64_t; // 7.18.1.2 Minimum-width integer types typedef int8_t int_least8_t; typedef int16_t int_least16_t; typedef int32_t int_least32_t; typedef int64_t int_least64_t; typedef uint8_t uint_least8_t; typedef uint16_t uint_least16_t; typedef uint32_t uint_least32_t; typedef uint64_t uint_least64_t; // 7.18.1.3 Fastest minimum-width integer types typedef int8_t int_fast8_t; typedef int16_t int_fast16_t; typedef int32_t int_fast32_t; typedef int64_t int_fast64_t; typedef uint8_t uint_fast8_t; typedef uint16_t uint_fast16_t; typedef uint32_t uint_fast32_t; typedef uint64_t uint_fast64_t; // 7.18.1.4 Integer types capable of holding object pointers #ifdef _WIN64 // [ typedef signed __int64 intptr_t; typedef unsigned __int64 uintptr_t; #else // _WIN64 ][ typedef _W64 signed int intptr_t; typedef _W64 unsigned int uintptr_t; #endif // _WIN64 ] // 7.18.1.5 Greatest-width integer types typedef int64_t intmax_t; typedef uint64_t uintmax_t; // 7.18.2 Limits of specified-width integer types #if !defined(__cplusplus) || defined(__STDC_LIMIT_MACROS) // [ See footnote 220 at page 257 and footnote 221 at page 259 // 7.18.2.1 Limits of exact-width integer types #define INT8_MIN ((int8_t)_I8_MIN) #define INT8_MAX _I8_MAX #define INT16_MIN ((int16_t)_I16_MIN) #define INT16_MAX _I16_MAX #define INT32_MIN ((int32_t)_I32_MIN) #define INT32_MAX _I32_MAX #define INT64_MIN ((int64_t)_I64_MIN) #define INT64_MAX _I64_MAX #define UINT8_MAX _UI8_MAX #define UINT16_MAX _UI16_MAX #define UINT32_MAX _UI32_MAX #define UINT64_MAX _UI64_MAX // 7.18.2.2 Limits of minimum-width integer types #define INT_LEAST8_MIN INT8_MIN #define INT_LEAST8_MAX INT8_MAX #define INT_LEAST16_MIN INT16_MIN #define INT_LEAST16_MAX INT16_MAX #define INT_LEAST32_MIN INT32_MIN #define INT_LEAST32_MAX INT32_MAX #define INT_LEAST64_MIN INT64_MIN #define INT_LEAST64_MAX INT64_MAX #define UINT_LEAST8_MAX UINT8_MAX #define UINT_LEAST16_MAX UINT16_MAX #define UINT_LEAST32_MAX UINT32_MAX #define UINT_LEAST64_MAX UINT64_MAX // 7.18.2.3 Limits of fastest minimum-width integer types #define INT_FAST8_MIN INT8_MIN #define INT_FAST8_MAX INT8_MAX #define INT_FAST16_MIN INT16_MIN #define INT_FAST16_MAX INT16_MAX #define INT_FAST32_MIN INT32_MIN #define INT_FAST32_MAX INT32_MAX #define INT_FAST64_MIN INT64_MIN #define INT_FAST64_MAX INT64_MAX #define UINT_FAST8_MAX UINT8_MAX #define UINT_FAST16_MAX UINT16_MAX #define UINT_FAST32_MAX UINT32_MAX #define UINT_FAST64_MAX UINT64_MAX // 7.18.2.4 Limits of integer types capable of holding object pointers #ifdef _WIN64 // [ # define INTPTR_MIN INT64_MIN # define INTPTR_MAX INT64_MAX # define UINTPTR_MAX UINT64_MAX #else // _WIN64 ][ # define INTPTR_MIN INT32_MIN # define INTPTR_MAX INT32_MAX # define UINTPTR_MAX UINT32_MAX #endif // _WIN64 ] // 7.18.2.5 Limits of greatest-width integer types #define INTMAX_MIN INT64_MIN #define INTMAX_MAX INT64_MAX #define UINTMAX_MAX UINT64_MAX // 7.18.3 Limits of other integer types #ifdef _WIN64 // [ # define PTRDIFF_MIN _I64_MIN # define PTRDIFF_MAX _I64_MAX #else // _WIN64 ][ # define PTRDIFF_MIN _I32_MIN # define PTRDIFF_MAX _I32_MAX #endif // _WIN64 ] #define SIG_ATOMIC_MIN INT_MIN #define SIG_ATOMIC_MAX INT_MAX #ifndef SIZE_MAX // [ # ifdef _WIN64 // [ # define SIZE_MAX _UI64_MAX # else // _WIN64 ][ # define SIZE_MAX _UI32_MAX # endif // _WIN64 ] #endif // SIZE_MAX ] // WCHAR_MIN and WCHAR_MAX are also defined in <wchar.h> #ifndef WCHAR_MIN // [ # define WCHAR_MIN 0 #endif // WCHAR_MIN ] #ifndef WCHAR_MAX // [ # define WCHAR_MAX _UI16_MAX #endif // WCHAR_MAX ] #define WINT_MIN 0 #define WINT_MAX _UI16_MAX #endif // __STDC_LIMIT_MACROS ] // 7.18.4 Limits of other integer types #if !defined(__cplusplus) || defined(__STDC_CONSTANT_MACROS) // [ See footnote 224 at page 260 // 7.18.4.1 Macros for minimum-width integer constants #define INT8_C(val) val##i8 #define INT16_C(val) val##i16 #define INT32_C(val) val##i32 #define INT64_C(val) val##i64 #define UINT8_C(val) val##ui8 #define UINT16_C(val) val##ui16 #define UINT32_C(val) val##ui32 #define UINT64_C(val) val##ui64 // 7.18.4.2 Macros for greatest-width integer constants // These #ifndef's are needed to prevent collisions with <boost/cstdint.hpp>. // Check out Issue 9 for the details. #ifndef INTMAX_C // [ # define INTMAX_C INT64_C #endif // INTMAX_C ] #ifndef UINTMAX_C // [ # define UINTMAX_C UINT64_C #endif // UINTMAX_C ] #endif // __STDC_CONSTANT_MACROS ] #endif // _MSC_VER >= 1600 ] #endif // _MSC_STDINT_H_ ]
9,386
stdint
h
en
c
code
{"qsc_code_num_words": 1470, "qsc_code_num_chars": 9386.0, "qsc_code_mean_word_length": 4.41360544, "qsc_code_frac_words_unique": 0.21428571, "qsc_code_frac_chars_top_2grams": 0.03452528, "qsc_code_frac_chars_top_3grams": 0.01726264, "qsc_code_frac_chars_top_4grams": 0.01926634, "qsc_code_frac_chars_dupe_5grams": 0.36868064, "qsc_code_frac_chars_dupe_6grams": 0.24275586, "qsc_code_frac_chars_dupe_7grams": 0.21871147, "qsc_code_frac_chars_dupe_8grams": 0.21054254, "qsc_code_frac_chars_dupe_9grams": 0.19852035, "qsc_code_frac_chars_dupe_10grams": 0.18249075, "qsc_code_frac_chars_replacement_symbols": 0.0, "qsc_code_frac_chars_digital": 0.07514227, "qsc_code_frac_chars_whitespace": 0.1762199, "qsc_code_size_file_byte": 9386.0, "qsc_code_num_lines": 300.0, "qsc_code_num_chars_line_max": 149.0, "qsc_code_num_chars_line_mean": 31.28666667, "qsc_code_frac_chars_alphabet": 0.76396793, "qsc_code_frac_chars_comments": 0.46153846, "qsc_code_cate_xml_start": 0.0, "qsc_code_frac_lines_dupe_lines": 0.27777778, "qsc_code_cate_autogen": 0.0, "qsc_code_frac_lines_long_string": 0.0, "qsc_code_frac_chars_string_length": 0.01147606, "qsc_code_frac_chars_long_word_length": 0.0, "qsc_code_frac_lines_string_concat": 0.0, "qsc_code_cate_encoded_data": 0.0, "qsc_code_frac_chars_hex_words": 0.0, "qsc_code_frac_lines_prompt_comments": 0.0, "qsc_code_frac_lines_assert": 0.0, "qsc_codec_frac_lines_func_ratio": 0.11111111, "qsc_codec_cate_bitsstdc": 0.0, "qsc_codec_nums_lines_main": 0, "qsc_codec_frac_lines_goto": 0.0, "qsc_codec_cate_var_zero": 0.0, "qsc_codec_score_lines_no_logic": 0.12345679, "qsc_codec_frac_lines_print": 0.0, "qsc_codec_frac_lines_preprocessor_directives": null}
1
{"qsc_code_frac_chars_replacement_symbols": 0, "qsc_code_num_words": 0, "qsc_code_num_chars": 0, "qsc_code_mean_word_length": 0, "qsc_code_frac_chars_top_2grams": 0, "qsc_code_frac_chars_top_3grams": 0, "qsc_code_frac_chars_top_4grams": 0, "qsc_code_frac_chars_dupe_5grams": 0, "qsc_code_frac_chars_dupe_6grams": 0, "qsc_code_frac_chars_dupe_7grams": 0, "qsc_code_frac_chars_dupe_8grams": 0, "qsc_code_frac_chars_dupe_9grams": 0, "qsc_code_frac_chars_dupe_10grams": 0, "qsc_code_size_file_byte": 0, "qsc_code_num_lines": 0, "qsc_code_num_chars_line_max": 0, "qsc_code_num_chars_line_mean": 0, "qsc_code_frac_chars_alphabet": 0, "qsc_code_frac_chars_digital": 0, "qsc_code_frac_chars_whitespace": 0, "qsc_code_frac_chars_comments": 0, "qsc_code_cate_xml_start": 0, "qsc_code_frac_lines_dupe_lines": 0, "qsc_code_cate_autogen": 0, "qsc_code_frac_lines_long_string": 0, "qsc_code_frac_chars_string_length": 0, "qsc_code_frac_chars_long_word_length": 0, "qsc_code_cate_encoded_data": 0, "qsc_code_frac_chars_hex_words": 0, "qsc_code_frac_lines_prompt_comments": 0, "qsc_code_frac_lines_assert": 0, "qsc_codec_frac_lines_func_ratio": 0, "qsc_codec_nums_lines_main": 0, "qsc_codec_score_lines_no_logic": 0, "qsc_codec_frac_lines_preprocessor_directives": 0, "qsc_codec_frac_lines_print": 0}
0015/esp_rlottie
rlottie/src/lottie/rapidjson/msinttypes/inttypes.h
// ISO C9x compliant inttypes.h for Microsoft Visual Studio // Based on ISO/IEC 9899:TC2 Committee draft (May 6, 2005) WG14/N1124 // // Copyright (c) 2006-2013 Alexander Chemeris // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // // 3. Neither the name of the product nor the names of its contributors may // be used to endorse or promote products derived from this software // without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED // WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF // MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO // EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; // OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, // WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR // OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF // ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // /////////////////////////////////////////////////////////////////////////////// // The above software in this distribution may have been modified by // THL A29 Limited ("Tencent Modifications"). // All Tencent Modifications are Copyright (C) 2015 THL A29 Limited. #ifndef _MSC_VER // [ #error "Use this header only with Microsoft Visual C++ compilers!" #endif // _MSC_VER ] #ifndef _MSC_INTTYPES_H_ // [ #define _MSC_INTTYPES_H_ #if _MSC_VER > 1000 #pragma once #endif #include "stdint.h" // miloyip: VC supports inttypes.h since VC2013 #if _MSC_VER >= 1800 #include <inttypes.h> #else // 7.8 Format conversion of integer types typedef struct { intmax_t quot; intmax_t rem; } imaxdiv_t; // 7.8.1 Macros for format specifiers #if !defined(__cplusplus) || defined(__STDC_FORMAT_MACROS) // [ See footnote 185 at page 198 // The fprintf macros for signed integers are: #define PRId8 "d" #define PRIi8 "i" #define PRIdLEAST8 "d" #define PRIiLEAST8 "i" #define PRIdFAST8 "d" #define PRIiFAST8 "i" #define PRId16 "hd" #define PRIi16 "hi" #define PRIdLEAST16 "hd" #define PRIiLEAST16 "hi" #define PRIdFAST16 "hd" #define PRIiFAST16 "hi" #define PRId32 "I32d" #define PRIi32 "I32i" #define PRIdLEAST32 "I32d" #define PRIiLEAST32 "I32i" #define PRIdFAST32 "I32d" #define PRIiFAST32 "I32i" #define PRId64 "I64d" #define PRIi64 "I64i" #define PRIdLEAST64 "I64d" #define PRIiLEAST64 "I64i" #define PRIdFAST64 "I64d" #define PRIiFAST64 "I64i" #define PRIdMAX "I64d" #define PRIiMAX "I64i" #define PRIdPTR "Id" #define PRIiPTR "Ii" // The fprintf macros for unsigned integers are: #define PRIo8 "o" #define PRIu8 "u" #define PRIx8 "x" #define PRIX8 "X" #define PRIoLEAST8 "o" #define PRIuLEAST8 "u" #define PRIxLEAST8 "x" #define PRIXLEAST8 "X" #define PRIoFAST8 "o" #define PRIuFAST8 "u" #define PRIxFAST8 "x" #define PRIXFAST8 "X" #define PRIo16 "ho" #define PRIu16 "hu" #define PRIx16 "hx" #define PRIX16 "hX" #define PRIoLEAST16 "ho" #define PRIuLEAST16 "hu" #define PRIxLEAST16 "hx" #define PRIXLEAST16 "hX" #define PRIoFAST16 "ho" #define PRIuFAST16 "hu" #define PRIxFAST16 "hx" #define PRIXFAST16 "hX" #define PRIo32 "I32o" #define PRIu32 "I32u" #define PRIx32 "I32x" #define PRIX32 "I32X" #define PRIoLEAST32 "I32o" #define PRIuLEAST32 "I32u" #define PRIxLEAST32 "I32x" #define PRIXLEAST32 "I32X" #define PRIoFAST32 "I32o" #define PRIuFAST32 "I32u" #define PRIxFAST32 "I32x" #define PRIXFAST32 "I32X" #define PRIo64 "I64o" #define PRIu64 "I64u" #define PRIx64 "I64x" #define PRIX64 "I64X" #define PRIoLEAST64 "I64o" #define PRIuLEAST64 "I64u" #define PRIxLEAST64 "I64x" #define PRIXLEAST64 "I64X" #define PRIoFAST64 "I64o" #define PRIuFAST64 "I64u" #define PRIxFAST64 "I64x" #define PRIXFAST64 "I64X" #define PRIoMAX "I64o" #define PRIuMAX "I64u" #define PRIxMAX "I64x" #define PRIXMAX "I64X" #define PRIoPTR "Io" #define PRIuPTR "Iu" #define PRIxPTR "Ix" #define PRIXPTR "IX" // The fscanf macros for signed integers are: #define SCNd8 "d" #define SCNi8 "i" #define SCNdLEAST8 "d" #define SCNiLEAST8 "i" #define SCNdFAST8 "d" #define SCNiFAST8 "i" #define SCNd16 "hd" #define SCNi16 "hi" #define SCNdLEAST16 "hd" #define SCNiLEAST16 "hi" #define SCNdFAST16 "hd" #define SCNiFAST16 "hi" #define SCNd32 "ld" #define SCNi32 "li" #define SCNdLEAST32 "ld" #define SCNiLEAST32 "li" #define SCNdFAST32 "ld" #define SCNiFAST32 "li" #define SCNd64 "I64d" #define SCNi64 "I64i" #define SCNdLEAST64 "I64d" #define SCNiLEAST64 "I64i" #define SCNdFAST64 "I64d" #define SCNiFAST64 "I64i" #define SCNdMAX "I64d" #define SCNiMAX "I64i" #ifdef _WIN64 // [ # define SCNdPTR "I64d" # define SCNiPTR "I64i" #else // _WIN64 ][ # define SCNdPTR "ld" # define SCNiPTR "li" #endif // _WIN64 ] // The fscanf macros for unsigned integers are: #define SCNo8 "o" #define SCNu8 "u" #define SCNx8 "x" #define SCNX8 "X" #define SCNoLEAST8 "o" #define SCNuLEAST8 "u" #define SCNxLEAST8 "x" #define SCNXLEAST8 "X" #define SCNoFAST8 "o" #define SCNuFAST8 "u" #define SCNxFAST8 "x" #define SCNXFAST8 "X" #define SCNo16 "ho" #define SCNu16 "hu" #define SCNx16 "hx" #define SCNX16 "hX" #define SCNoLEAST16 "ho" #define SCNuLEAST16 "hu" #define SCNxLEAST16 "hx" #define SCNXLEAST16 "hX" #define SCNoFAST16 "ho" #define SCNuFAST16 "hu" #define SCNxFAST16 "hx" #define SCNXFAST16 "hX" #define SCNo32 "lo" #define SCNu32 "lu" #define SCNx32 "lx" #define SCNX32 "lX" #define SCNoLEAST32 "lo" #define SCNuLEAST32 "lu" #define SCNxLEAST32 "lx" #define SCNXLEAST32 "lX" #define SCNoFAST32 "lo" #define SCNuFAST32 "lu" #define SCNxFAST32 "lx" #define SCNXFAST32 "lX" #define SCNo64 "I64o" #define SCNu64 "I64u" #define SCNx64 "I64x" #define SCNX64 "I64X" #define SCNoLEAST64 "I64o" #define SCNuLEAST64 "I64u" #define SCNxLEAST64 "I64x" #define SCNXLEAST64 "I64X" #define SCNoFAST64 "I64o" #define SCNuFAST64 "I64u" #define SCNxFAST64 "I64x" #define SCNXFAST64 "I64X" #define SCNoMAX "I64o" #define SCNuMAX "I64u" #define SCNxMAX "I64x" #define SCNXMAX "I64X" #ifdef _WIN64 // [ # define SCNoPTR "I64o" # define SCNuPTR "I64u" # define SCNxPTR "I64x" # define SCNXPTR "I64X" #else // _WIN64 ][ # define SCNoPTR "lo" # define SCNuPTR "lu" # define SCNxPTR "lx" # define SCNXPTR "lX" #endif // _WIN64 ] #endif // __STDC_FORMAT_MACROS ] // 7.8.2 Functions for greatest-width integer types // 7.8.2.1 The imaxabs function #define imaxabs _abs64 // 7.8.2.2 The imaxdiv function // This is modified version of div() function from Microsoft's div.c found // in %MSVC.NET%\crt\src\div.c #ifdef STATIC_IMAXDIV // [ static #else // STATIC_IMAXDIV ][ _inline #endif // STATIC_IMAXDIV ] imaxdiv_t __cdecl imaxdiv(intmax_t numer, intmax_t denom) { imaxdiv_t result; result.quot = numer / denom; result.rem = numer % denom; if (numer < 0 && result.rem > 0) { // did division wrong; must fix up ++result.quot; result.rem -= denom; } return result; } // 7.8.2.3 The strtoimax and strtoumax functions #define strtoimax _strtoi64 #define strtoumax _strtoui64 // 7.8.2.4 The wcstoimax and wcstoumax functions #define wcstoimax _wcstoi64 #define wcstoumax _wcstoui64 #endif // _MSC_VER >= 1800 #endif // _MSC_INTTYPES_H_ ]
8,372
inttypes
h
en
c
code
{"qsc_code_num_words": 1051, "qsc_code_num_chars": 8372.0, "qsc_code_mean_word_length": 5.31779258, "qsc_code_frac_words_unique": 0.38915319, "qsc_code_frac_chars_top_2grams": 0.02862766, "qsc_code_frac_chars_top_3grams": 0.00268384, "qsc_code_frac_chars_top_4grams": 0.00823045, "qsc_code_frac_chars_dupe_5grams": 0.05653963, "qsc_code_frac_chars_dupe_6grams": 0.04795133, "qsc_code_frac_chars_dupe_7grams": 0.02433351, "qsc_code_frac_chars_dupe_8grams": 0.02433351, "qsc_code_frac_chars_dupe_9grams": 0.02433351, "qsc_code_frac_chars_dupe_10grams": 0.02433351, "qsc_code_frac_chars_replacement_symbols": 0.0, "qsc_code_frac_chars_digital": 0.0763382, "qsc_code_frac_chars_whitespace": 0.21452461, "qsc_code_size_file_byte": 8372.0, "qsc_code_num_lines": 316.0, "qsc_code_num_chars_line_max": 95.0, "qsc_code_num_chars_line_mean": 26.49367089, "qsc_code_frac_chars_alphabet": 0.77357056, "qsc_code_frac_chars_comments": 0.33862876, "qsc_code_cate_xml_start": 0.0, "qsc_code_frac_lines_dupe_lines": 0.03301887, "qsc_code_cate_autogen": 0.0, "qsc_code_frac_lines_long_string": 0.0, "qsc_code_frac_chars_string_length": 0.09409427, "qsc_code_frac_chars_long_word_length": 0.0, "qsc_code_frac_lines_string_concat": 0.0, "qsc_code_cate_encoded_data": 0.0, "qsc_code_frac_chars_hex_words": 0.0, "qsc_code_frac_lines_prompt_comments": 0.0, "qsc_code_frac_lines_assert": 0.0, "qsc_codec_frac_lines_func_ratio": 0.00471698, "qsc_codec_cate_bitsstdc": 0.0, "qsc_codec_nums_lines_main": 0, "qsc_codec_frac_lines_goto": 0.0, "qsc_codec_cate_var_zero": 0.0, "qsc_codec_score_lines_no_logic": 0.01886792, "qsc_codec_frac_lines_print": 0.0, "qsc_codec_frac_lines_preprocessor_directives": null}
1
{"qsc_code_frac_chars_replacement_symbols": 0, "qsc_code_num_words": 0, "qsc_code_num_chars": 0, "qsc_code_mean_word_length": 0, "qsc_code_frac_chars_top_2grams": 0, "qsc_code_frac_chars_top_3grams": 0, "qsc_code_frac_chars_top_4grams": 0, "qsc_code_frac_chars_dupe_5grams": 0, "qsc_code_frac_chars_dupe_6grams": 0, "qsc_code_frac_chars_dupe_7grams": 0, "qsc_code_frac_chars_dupe_8grams": 0, "qsc_code_frac_chars_dupe_9grams": 0, "qsc_code_frac_chars_dupe_10grams": 0, "qsc_code_size_file_byte": 0, "qsc_code_num_lines": 0, "qsc_code_num_chars_line_max": 0, "qsc_code_num_chars_line_mean": 0, "qsc_code_frac_chars_alphabet": 0, "qsc_code_frac_chars_digital": 0, "qsc_code_frac_chars_whitespace": 0, "qsc_code_frac_chars_comments": 0, "qsc_code_cate_xml_start": 0, "qsc_code_frac_lines_dupe_lines": 0, "qsc_code_cate_autogen": 0, "qsc_code_frac_lines_long_string": 0, "qsc_code_frac_chars_string_length": 0, "qsc_code_frac_chars_long_word_length": 0, "qsc_code_cate_encoded_data": 0, "qsc_code_frac_chars_hex_words": 0, "qsc_code_frac_lines_prompt_comments": 0, "qsc_code_frac_lines_assert": 0, "qsc_codec_frac_lines_func_ratio": 0, "qsc_codec_nums_lines_main": 0, "qsc_codec_score_lines_no_logic": 0, "qsc_codec_frac_lines_preprocessor_directives": 0, "qsc_codec_frac_lines_print": 0}
007revad/Synology_DSM_Telnet_Password
dsm_telnet_password.sh
#!/bin/bash #---------------------------------------------------------------------------- # Default DSM telnet password used to be blank. # # Generate DSM telnet 'password of the day' if 101-0101 does not work. # # https://blog.thomasmarcussen.com/synology-nas-recovery-password-telnet/ # # In case you don't want to contact Synology here is how it's generated # # 1st char = month in hexadecimal, lower case (1=Jan, … , a=Oct, b=Nov, c=Dec) # 2-3 = month in decimal, zero padded and starting in 1 (01, 02, 03, …, 11, 12) # 4 = dash # 5-6 = day of the month in hex (01, 02 .., 0A, .., 1F) # 7-8 = greatest common divisor between month and day, zero padded. This is always a number between 01 and 12. # # If today is Oct 15, the password would be: a10-0f05 # a = month in hex # 10 = month in decimal # 0f = day in hex # 05 = greatest divisor between 10 and 15 # # https://servicemax.com.au/tips/synology-recovery-mode-telnet/ # https://github.com/adamphetamine/synology/blob/main/telnet-password #---------------------------------------------------------------------------- script="Synology_DSM_Telnet_Password" scriptver="1.0.2" repo="007revad/Synology_DSM_Telnet_Password" usage(){ cat <<EOF $script $scriptver - by 007revad Usage: $(basename "$0") [options] Options: --day= Set the day to calculate password from If --day= is used you must also use --month= Day must be numeric. e.g. --day=24 --month= Set the month to calculate password from If --month= is used you must also use --day= Month must be numeric. e.g. --month=9 -h, --help Show this help message -v, --version Show the script version EOF exit 0 } scriptversion(){ cat <<EOF $script $scriptver - by 007revad See https://github.com/$repo EOF exit 0 } # Save options used args=("$@") # Check for flags with getopt if options="$(getopt -o abcdefghijklmnopqrstuvwxyz0123456789 -l \ day:,month:,help,version -- "${args[@]}")"; then eval set -- "$options" while true; do case "${1,,}" in -h|--help) # Show usage options usage ;; -v|--version) # Show script version scriptversion ;; -d|--day) # Set day variable if [[ $2 =~ ^0[1-9]?$ ]]; then # Day is 01 to 09 day="${2#?}" shift elif [[ $2 =~ ^[1-3][0-9]?$ ]]; then # Day is 1 to 31 day="$2" shift fi ;; -m|--month) # Set month variable if [[ $2 =~ ^0[1-9]?$ ]]; then # Month is 01 to 09 month="${2#?}" shift elif [[ $2 =~ ^[1-9][0-9]?$ ]]; then # Month is 1 to 12 month="$2" shift fi ;; --) shift break ;; *) # Show usage options echo -e "Invalid option '$1'\n" usage "$1" ;; esac shift done else echo usage fi # Show script name and version echo -e "$script $scriptver - by 007revad \n" if [[ -z $month ]] && [[ -z $day ]]; then # Get current month and day month=$(date +%-m) # Month (1 to 12) day=$(date +%-d) # Day of the month (1 to 31) echo "Today's Day: $day" echo -e "Today's Month: $month \n" else echo "Day: $day" echo -e "Month: $month \n" fi # Validate day and month if [[ ! $day -gt "0" ]] || [[ ! $day -lt "32" ]]; then echo "Day is invalid!" && exit elif [[ ! $month -gt "0" ]] || [[ ! $month -lt "13" ]]; then echo "Month is invalid!" && exit fi # Function to calculate greatest common divisor in Bash gcd(){ # $1 decimal month as decimal # $2 decimal day as decimal if [[ $2 -eq 0 ]]; then echo "$1" else gcd "$2" $(($1 % $2)) fi } # Calculate greatest common divisor between month and day gcd_result=$(gcd "$month" "$day") # Format and print the password printf "DSM Telnet Password for today is: %x%02d-%02x%02d\n\n" "$month" "$month" "$day" "$gcd_result"
4,420
dsm_telnet_password
sh
en
shell
code
{"qsc_code_num_words": 562, "qsc_code_num_chars": 4420.0, "qsc_code_mean_word_length": 3.87188612, "qsc_code_frac_words_unique": 0.32206406, "qsc_code_frac_chars_top_2grams": 0.03860294, "qsc_code_frac_chars_top_3grams": 0.0390625, "qsc_code_frac_chars_top_4grams": 0.03446691, "qsc_code_frac_chars_dupe_5grams": 0.14705882, "qsc_code_frac_chars_dupe_6grams": 0.09926471, "qsc_code_frac_chars_dupe_7grams": 0.05238971, "qsc_code_frac_chars_dupe_8grams": 0.0, "qsc_code_frac_chars_dupe_9grams": 0.0, "qsc_code_frac_chars_dupe_10grams": 0.0, "qsc_code_frac_chars_replacement_symbols": 0.0, "qsc_code_frac_chars_digital": 0.0513439, "qsc_code_frac_chars_whitespace": 0.34343891, "qsc_code_size_file_byte": 4420.0, "qsc_code_num_lines": 156.0, "qsc_code_num_chars_line_max": 111.0, "qsc_code_num_chars_line_mean": 28.33333333, "qsc_code_frac_chars_alphabet": 0.69641626, "qsc_code_frac_chars_comments": 0.37262443, "qsc_code_cate_xml_start": 0.0, "qsc_code_frac_lines_dupe_lines": 0.3258427, "qsc_code_cate_autogen": 1.0, "qsc_code_frac_lines_long_string": 0.0, "qsc_code_frac_chars_string_length": 0.13492063, "qsc_code_frac_chars_long_word_length": 0.02344877, "qsc_code_frac_lines_string_concat": 0.0, "qsc_code_cate_encoded_data": 0.0, "qsc_code_frac_chars_hex_words": 0.0, "qsc_code_frac_lines_prompt_comments": 0.0, "qsc_code_frac_lines_assert": 0.0}
0
{"qsc_code_frac_chars_replacement_symbols": 0, "qsc_code_num_words": 0, "qsc_code_num_chars": 0, "qsc_code_mean_word_length": 0, "qsc_code_frac_chars_top_2grams": 0, "qsc_code_frac_chars_top_3grams": 0, "qsc_code_frac_chars_top_4grams": 0, "qsc_code_frac_chars_dupe_5grams": 0, "qsc_code_frac_chars_dupe_6grams": 0, "qsc_code_frac_chars_dupe_7grams": 0, "qsc_code_frac_chars_dupe_8grams": 0, "qsc_code_frac_chars_dupe_9grams": 0, "qsc_code_frac_chars_dupe_10grams": 0, "qsc_code_frac_lines_dupe_lines": 0, "qsc_code_size_file_byte": 0, "qsc_code_num_lines": 0, "qsc_code_num_chars_line_max": 0, "qsc_code_num_chars_line_mean": 0, "qsc_code_frac_chars_alphabet": 0, "qsc_code_frac_chars_digital": 0, "qsc_code_frac_chars_whitespace": 0, "qsc_code_frac_chars_comments": 0, "qsc_code_cate_xml_start": 0, "qsc_code_cate_autogen": 1, "qsc_code_frac_chars_long_word_length": 0, "qsc_code_cate_encoded_data": 0, "qsc_code_frac_chars_hex_words": 0, "qsc_code_frac_lines_prompt_comments": 0}
007revad/Synology_DSM_Telnet_Password
my-other-scripts.md
## All my scripts, tools and guides <img src="https://hitscounter.dev/api/hit?url=https%3A%2F%2F007revad.github.io%2F&label=Visitors&icon=github&color=%23198754&message=&style=flat&tz=UTC"> #### Contents - [Plex](#plex) - [Synology docker](#synology-docker) - [Synology recovery](#synology-recovery) - [Other Synology scripts](#other-synology-scripts) - [Synology hardware restrictions](#synology-hardware-restrictions) - [2025 plus models](#2025-plus-models) - [How To Guides](#how-to-guides) - [Synology dev](#synology-dev) *** ### Plex - **<a href="https://github.com/007revad/Synology_Plex_Backup">Synology_Plex_Backup</a>** - A script to backup Plex to a tgz file foror DSM 7 and DSM 6. - Works for Plex Synology package and Plex in docker. - **<a href="https://github.com/007revad/Asustor_Plex_Backup">Asustor_Plex_Backup</a>** - Backup your Asustor's Plex Media Server settings and database. - **<a href="https://github.com/007revad/Linux_Plex_Backup">Linux_Plex_Backup</a>** - Backup your Linux Plex Media Server's settings and database. - **<a href="https://github.com/007revad/Plex_Server_Sync">Plex_Server_Sync</a>** - Sync your main Plex server database & metadata to a backup Plex server. - Works for Synology, Asustor, Linux and supports Plex package or Plex in docker. &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; [Back to Contents](#contents) ### Synology docker - **<a href="https://github.com/007revad/Synology_Docker_Export">Synology_Docker_export</a>** - Export all Synology Container Manager or Docker containers' settings as json files to your docker shared folder. - **<a href="https://github.com/007revad/Synology_ContainerManager_IPv6">Synology_ContainerManager_IPv6</a>** - Enable IPv6 for Container Manager's bridge network. - **<a href="https://github.com/007revad/ContainerManager_for_all_armv8">ContainerManager_for_all_armv8</a>** - Script to install Container Manager on a RS819, DS119j, DS418, DS418j, DS218, DS218play or DS118. - **<a href="https://github.com/007revad/Docker_Autocompose">Docker_Autocompose</a>** - Create .yml files from your docker existing containers. - **<a href="https://github.com/007revad/Synology_docker_cleanup">Synology_docker_cleanup</a>** - Remove orphan docker btrfs subvolumes and images in Synology DSM 7 and DSM 6. &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; [Back to Contents](#contents) ### Synology recovery - **<a href="https://github.com/007revad/Synology_DSM_reinstall">Synology_DSM_reinstall</a>** - Easily re-install the same DSM version without losing any data or settings. - **<a href="https://github.com/007revad/Synology_Recover_Data">Synology_Recover_Data</a>** - A script to make it easy to recover your data from your Synology's drives using a computer. - **<a href="https://github.com/007revad/Synology_clear_drive_error">Synology clear drive error</a>** - Clear drive critical errors so DSM will let you use the drive. - **<a href="https://github.com/007revad/Synology_DSM_Telnet_Password">Synology_DSM_Telnet_Password</a>** - Synology DSM Recovery Telnet Password of the Day generator. - **<a href="https://github.com/007revad/Syno_DSM_Extractor_GUI">Syno_DSM_Extractor_GUI</a>** - Windows GUI for extracting Synology DSM 7 pat files and spk package files. - **<a href="https://github.com/007revad/Synoboot_backup">Synoboot_backup</a>** - Back up synoboot after each DSM update so you can recover from a corrupt USBDOM. &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; [Back to Contents](#contents) ### Other Synology scripts - **<a href="https://github.com/007revad/Synology_app_mover">Synology_app_mover</a>** - Easily move Synology packages from one volume to another volume. - **<a href="https://github.com/007revad/Video_Station_for_DSM_722">Video_Station_for_DSM_722</a>** - Script to install Video Station in DSM 7.2.2 - **<a href="https://github.com/007revad/SS_Motion_Detection">SS_Motion_Detection</a>** - Installs previous Surveillance Station and Advanced Media Extensions versions so motion detection and HEVC are supported. - **<a href="https://github.com/007revad/Synology_Config_Backup">Synology_Config_Backup</a>** - Backup and export your Synology DSM configuration. - **<a href="https://github.com/007revad/Synology_CPU_temperature">Synology_CPU_temperature</a>** - Get and log Synology NAS CPU temperature via SSH. - **<a href="https://github.com/007revad/Synology_SMART_info">Synology_SMART_info</a>** - Show Synology smart test progress or smart health and attributes. - **<a href="https://github.com/007revad/Synology_Cleanup_Coredumps">Synology_Cleanup_Coredumps</a>** - Cleanup memory core dumps from crashed processes. - **<a href="https://github.com/007revad/Synology_toggle_reset_button">Synology_toggle_reset_button</a>** - Script to disable or enable the reset button and show current setting. - **<a href="https://github.com/007revad/Synology_Download_Station_Chrome_Extension">Synology_Download_Station_Chrome_Extension</a>** - Download Station Chrome Extension. - **<a href="https://github.com/007revad/Seagate_lowCurrentSpinup">Seagate_lowCurrentSpinup</a>** - This script avoids the need to buy and install a higher wattage power supply when using multiple large Seagate SATA HDDs. &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; [Back to Contents](#contents) ### Synology hardware restrictions - **<a href="https://github.com/007revad/Synology_HDD_db">Synology_HDD_db</a>** - Add your SATA or SAS HDDs and SSDs plus SATA and NVMe M.2 drives to your Synology's compatible drive databases, including your Synology M.2 PCIe card and Expansion Unit databases. - **<a href="https://github.com/007revad/Synology_enable_M2_volume">Synology_enable_M2_volume</a>** - Enable creating volumes with non-Synology M.2 drives. - Enable Health Info for non-Synology NVMe drives (not in DSM 7.2.1 or later). - **<a href="https://github.com/007revad/Synology_M2_volume">Synology_M2_volume</a>** - Easily create an M.2 volume on Synology NAS. - **<a href="https://github.com/007revad/Synology_enable_M2_card">Synology_enable_M2_card</a>** - Enable Synology M.2 PCIe cards in Synology NAS that don't officially support them. - **<a href="https://github.com/007revad/Synology_enable_eunit">Synology_enable_eunit</a>** - Enable an unsupported Synology eSATA Expansion Unit models. - **<a href="https://github.com/007revad/Synology_enable_Deduplication">Synology_enable_Deduplication</a>** - Enable deduplication with non-Synology SSDs and unsupported NAS models. - **<a href="https://github.com/007revad/Synology_SHR_switch">Synology_SHR_switch</a>** - Easily switch between SHR and RAID Groups, or enable RAID F1. - **<a href="https://github.com/007revad/Synology_enable_sequential_IO">Synology_enable_sequential_IO</a>** - Enables sequential I/O for your SSD caches, like DSM 6 had. - **<a href="https://github.com/007revad/Synology_Information_Wiki">Synology_Information_Wiki</a>** - Information about Synology hardware. &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; [Back to Contents](#contents) ### 2025 plus models - **<a href="https://github.com/007revad/Transcode_for_x25">Transcode_for_x25</a>** - Installs the modules needed for Plex or Jellyfin hardware transcoding in DS425+ and DS225+. - **<a href="https://github.com/007revad/Synology_HDD_db/blob/main/2025_plus_models.md">2025 series or later Plus models</a>** - Unverified 3rd party drive limitations and unofficial solutions. - **<a href="https://github.com/007revad/Synology_HDD_db/blob/main/2025_plus_models.md#setting-up-a-new-2025-or-later-plus-model-with-only-unverified-hdds">Setup with only 3rd party drives</a>** - Setting up a new 2025 or later plus model with only unverified HDDs. - **<a href="https://github.com/007revad/Synology_HDD_db/blob/main/2025_plus_models.md#deleting-and-recreating-your-storage-pool-on-unverified-hdds">Recreating storage pool on migrated drives</a>** - Deleting and recreating your storage pool on unverified HDDs. &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; [Back to Contents](#contents) ### How To Guides - **<a href="https://github.com/007revad/Synology_SSH_key_setup">Synology_SSH_key_setup</a>** - How to setup SSH key authentication for your Synology. &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; [Back to Contents](#contents) ### Synology dev - **<a href="https://github.com/007revad/Download_Synology_Archive">Download_Synology_Archive</a>** - Download all or part of the Synology archive. - **<a href="https://github.com/007revad/Syno_DSM_Extractor_GUI">Syno_DSM_Extractor_GUI</a>** - Windows GUI for extracting Synology DSM 7 pat files and spk package files. - **<a href="https://github.com/007revad/ScriptNotify">ScriptNotify</a>** - DSM 7 package to allow your scripts to send DSM notifications. - **<a href="https://github.com/007revad/DTC_GUI_for_Windows">DTC_GUI_for_Windows</a>** - GUI for DTC.exe for Windows. &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; [Back to Contents](#contents)
9,099
my-other-scripts
md
en
markdown
text
{"qsc_doc_frac_chars_curly_bracket": 0.0, "qsc_doc_frac_words_redpajama_stop": 0.16632653, "qsc_doc_num_sentences": 107.0, "qsc_doc_num_words": 1341, "qsc_doc_num_chars": 9099.0, "qsc_doc_num_lines": 180.0, "qsc_doc_mean_word_length": 4.94630872, "qsc_doc_frac_words_full_bracket": 0.0, "qsc_doc_frac_lines_end_with_readmore": 0.0, "qsc_doc_frac_lines_start_with_bullet": 0.0, "qsc_doc_frac_words_unique": 0.23191648, "qsc_doc_entropy_unigram": 4.76529845, "qsc_doc_frac_words_all_caps": 0.02908163, "qsc_doc_frac_lines_dupe_lines": 0.1025641, "qsc_doc_frac_chars_dupe_lines": 0.10911978, "qsc_doc_frac_chars_top_2grams": 0.05789236, "qsc_doc_frac_chars_top_3grams": 0.06482738, "qsc_doc_frac_chars_top_4grams": 0.10372381, "qsc_doc_frac_chars_dupe_5grams": 0.39981909, "qsc_doc_frac_chars_dupe_6grams": 0.36891301, "qsc_doc_frac_chars_dupe_7grams": 0.34041912, "qsc_doc_frac_chars_dupe_8grams": 0.25569124, "qsc_doc_frac_chars_dupe_9grams": 0.20624152, "qsc_doc_frac_chars_dupe_10grams": 0.15829941, "qsc_doc_frac_chars_replacement_symbols": 0.0, "qsc_doc_cate_code_related_file_name": 0.0, "qsc_doc_num_chars_sentence_length_mean": 30.70731707, "qsc_doc_frac_chars_hyperlink_html_tag": 0.34762062, "qsc_doc_frac_chars_alphabet": 0.79007303, "qsc_doc_frac_chars_digital": 0.03094442, "qsc_doc_frac_chars_whitespace": 0.11210023, "qsc_doc_frac_chars_hex_words": 0.0}
1
{"qsc_doc_frac_chars_replacement_symbols": 0, "qsc_doc_entropy_unigram": 0, "qsc_doc_frac_chars_top_2grams": 0, "qsc_doc_frac_chars_top_3grams": 0, "qsc_doc_frac_chars_top_4grams": 0, "qsc_doc_frac_chars_dupe_5grams": 0, "qsc_doc_frac_chars_dupe_6grams": 0, "qsc_doc_frac_chars_dupe_7grams": 0, "qsc_doc_frac_chars_dupe_8grams": 0, "qsc_doc_frac_chars_dupe_9grams": 0, "qsc_doc_frac_chars_dupe_10grams": 0, "qsc_doc_frac_chars_dupe_lines": 0, "qsc_doc_frac_lines_dupe_lines": 0, "qsc_doc_frac_lines_end_with_readmore": 0, "qsc_doc_frac_lines_start_with_bullet": 0, "qsc_doc_frac_words_all_caps": 0, "qsc_doc_mean_word_length": 0, "qsc_doc_num_chars": 0, "qsc_doc_num_lines": 0, "qsc_doc_num_sentences": 0, "qsc_doc_num_words": 0, "qsc_doc_frac_chars_hex_words": 0, "qsc_doc_frac_chars_hyperlink_html_tag": 0, "qsc_doc_frac_chars_alphabet": 0, "qsc_doc_frac_chars_digital": 0, "qsc_doc_frac_chars_whitespace": 0}
007revad/Synoboot_backup
my-other-scripts.md
## All my scripts, tools and guides <img src="https://hitscounter.dev/api/hit?url=https%3A%2F%2F007revad.github.io%2F&label=Visitors&icon=github&color=%23198754&message=&style=flat&tz=UTC"> #### Contents - [Plex](#plex) - [Synology docker](#synology-docker) - [Synology recovery](#synology-recovery) - [Other Synology scripts](#other-synology-scripts) - [Synology hardware restrictions](#synology-hardware-restrictions) - [2025 plus models](#2025-plus-models) - [How To Guides](#how-to-guides) - [Synology dev](#synology-dev) *** ### Plex - **<a href="https://github.com/007revad/Synology_Plex_Backup">Synology_Plex_Backup</a>** - A script to backup Plex to a tgz file foror DSM 7 and DSM 6. - Works for Plex Synology package and Plex in docker. - **<a href="https://github.com/007revad/Asustor_Plex_Backup">Asustor_Plex_Backup</a>** - Backup your Asustor's Plex Media Server settings and database. - **<a href="https://github.com/007revad/Linux_Plex_Backup">Linux_Plex_Backup</a>** - Backup your Linux Plex Media Server's settings and database. - **<a href="https://github.com/007revad/Plex_Server_Sync">Plex_Server_Sync</a>** - Sync your main Plex server database & metadata to a backup Plex server. - Works for Synology, Asustor, Linux and supports Plex package or Plex in docker. &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; [Back to Contents](#contents) ### Synology docker - **<a href="https://github.com/007revad/Synology_Docker_Export">Synology_Docker_export</a>** - Export all Synology Container Manager or Docker containers' settings as json files to your docker shared folder. - **<a href="https://github.com/007revad/Synology_ContainerManager_IPv6">Synology_ContainerManager_IPv6</a>** - Enable IPv6 for Container Manager's bridge network. - **<a href="https://github.com/007revad/ContainerManager_for_all_armv8">ContainerManager_for_all_armv8</a>** - Script to install Container Manager on a RS819, DS119j, DS418, DS418j, DS218, DS218play or DS118. - **<a href="https://github.com/007revad/Docker_Autocompose">Docker_Autocompose</a>** - Create .yml files from your docker existing containers. - **<a href="https://github.com/007revad/Synology_docker_cleanup">Synology_docker_cleanup</a>** - Remove orphan docker btrfs subvolumes and images in Synology DSM 7 and DSM 6. &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; [Back to Contents](#contents) ### Synology recovery - **<a href="https://github.com/007revad/Synology_DSM_reinstall">Synology_DSM_reinstall</a>** - Easily re-install the same DSM version without losing any data or settings. - **<a href="https://github.com/007revad/Synology_Recover_Data">Synology_Recover_Data</a>** - A script to make it easy to recover your data from your Synology's drives using a computer. - **<a href="https://github.com/007revad/Synology_clear_drive_error">Synology clear drive error</a>** - Clear drive critical errors so DSM will let you use the drive. - **<a href="https://github.com/007revad/Synology_DSM_Telnet_Password">Synology_DSM_Telnet_Password</a>** - Synology DSM Recovery Telnet Password of the Day generator. - **<a href="https://github.com/007revad/Syno_DSM_Extractor_GUI">Syno_DSM_Extractor_GUI</a>** - Windows GUI for extracting Synology DSM 7 pat files and spk package files. - **<a href="https://github.com/007revad/Synoboot_backup">Synoboot_backup</a>** - Back up synoboot after each DSM update so you can recover from a corrupt USBDOM. &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; [Back to Contents](#contents) ### Other Synology scripts - **<a href="https://github.com/007revad/Synology_app_mover">Synology_app_mover</a>** - Easily move Synology packages from one volume to another volume. - **<a href="https://github.com/007revad/Video_Station_for_DSM_722">Video_Station_for_DSM_722</a>** - Script to install Video Station in DSM 7.2.2 - **<a href="https://github.com/007revad/SS_Motion_Detection">SS_Motion_Detection</a>** - Installs previous Surveillance Station and Advanced Media Extensions versions so motion detection and HEVC are supported. - **<a href="https://github.com/007revad/Synology_Config_Backup">Synology_Config_Backup</a>** - Backup and export your Synology DSM configuration. - **<a href="https://github.com/007revad/Synology_CPU_temperature">Synology_CPU_temperature</a>** - Get and log Synology NAS CPU temperature via SSH. - **<a href="https://github.com/007revad/Synology_SMART_info">Synology_SMART_info</a>** - Show Synology smart test progress or smart health and attributes. - **<a href="https://github.com/007revad/Synology_Cleanup_Coredumps">Synology_Cleanup_Coredumps</a>** - Cleanup memory core dumps from crashed processes. - **<a href="https://github.com/007revad/Synology_toggle_reset_button">Synology_toggle_reset_button</a>** - Script to disable or enable the reset button and show current setting. - **<a href="https://github.com/007revad/Synology_Download_Station_Chrome_Extension">Synology_Download_Station_Chrome_Extension</a>** - Download Station Chrome Extension. - **<a href="https://github.com/007revad/Seagate_lowCurrentSpinup">Seagate_lowCurrentSpinup</a>** - This script avoids the need to buy and install a higher wattage power supply when using multiple large Seagate SATA HDDs. &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; [Back to Contents](#contents) ### Synology hardware restrictions - **<a href="https://github.com/007revad/Synology_HDD_db">Synology_HDD_db</a>** - Add your SATA or SAS HDDs and SSDs plus SATA and NVMe M.2 drives to your Synology's compatible drive databases, including your Synology M.2 PCIe card and Expansion Unit databases. - **<a href="https://github.com/007revad/Synology_enable_M2_volume">Synology_enable_M2_volume</a>** - Enable creating volumes with non-Synology M.2 drives. - Enable Health Info for non-Synology NVMe drives (not in DSM 7.2.1 or later). - **<a href="https://github.com/007revad/Synology_M2_volume">Synology_M2_volume</a>** - Easily create an M.2 volume on Synology NAS. - **<a href="https://github.com/007revad/Synology_enable_M2_card">Synology_enable_M2_card</a>** - Enable Synology M.2 PCIe cards in Synology NAS that don't officially support them. - **<a href="https://github.com/007revad/Synology_enable_eunit">Synology_enable_eunit</a>** - Enable an unsupported Synology eSATA Expansion Unit models. - **<a href="https://github.com/007revad/Synology_enable_Deduplication">Synology_enable_Deduplication</a>** - Enable deduplication with non-Synology SSDs and unsupported NAS models. - **<a href="https://github.com/007revad/Synology_SHR_switch">Synology_SHR_switch</a>** - Easily switch between SHR and RAID Groups, or enable RAID F1. - **<a href="https://github.com/007revad/Synology_enable_sequential_IO">Synology_enable_sequential_IO</a>** - Enables sequential I/O for your SSD caches, like DSM 6 had. - **<a href="https://github.com/007revad/Synology_Information_Wiki">Synology_Information_Wiki</a>** - Information about Synology hardware. &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; [Back to Contents](#contents) ### 2025 plus models - **<a href="https://github.com/007revad/Transcode_for_x25">Transcode_for_x25</a>** - Installs the modules needed for Plex or Jellyfin hardware transcoding in DS425+ and DS225+. - **<a href="https://github.com/007revad/Synology_HDD_db/blob/main/2025_plus_models.md">2025 series or later Plus models</a>** - Unverified 3rd party drive limitations and unofficial solutions. - **<a href="https://github.com/007revad/Synology_HDD_db/blob/main/2025_plus_models.md#setting-up-a-new-2025-or-later-plus-model-with-only-unverified-hdds">Setup with only 3rd party drives</a>** - Setting up a new 2025 or later plus model with only unverified HDDs. - **<a href="https://github.com/007revad/Synology_HDD_db/blob/main/2025_plus_models.md#deleting-and-recreating-your-storage-pool-on-unverified-hdds">Recreating storage pool on migrated drives</a>** - Deleting and recreating your storage pool on unverified HDDs. &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; [Back to Contents](#contents) ### How To Guides - **<a href="https://github.com/007revad/Synology_SSH_key_setup">Synology_SSH_key_setup</a>** - How to setup SSH key authentication for your Synology. &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; [Back to Contents](#contents) ### Synology dev - **<a href="https://github.com/007revad/Download_Synology_Archive">Download_Synology_Archive</a>** - Download all or part of the Synology archive. - **<a href="https://github.com/007revad/Syno_DSM_Extractor_GUI">Syno_DSM_Extractor_GUI</a>** - Windows GUI for extracting Synology DSM 7 pat files and spk package files. - **<a href="https://github.com/007revad/ScriptNotify">ScriptNotify</a>** - DSM 7 package to allow your scripts to send DSM notifications. - **<a href="https://github.com/007revad/DTC_GUI_for_Windows">DTC_GUI_for_Windows</a>** - GUI for DTC.exe for Windows. &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; [Back to Contents](#contents)
9,099
my-other-scripts
md
en
markdown
text
{"qsc_doc_frac_chars_curly_bracket": 0.0, "qsc_doc_frac_words_redpajama_stop": 0.16632653, "qsc_doc_num_sentences": 107.0, "qsc_doc_num_words": 1341, "qsc_doc_num_chars": 9099.0, "qsc_doc_num_lines": 180.0, "qsc_doc_mean_word_length": 4.94630872, "qsc_doc_frac_words_full_bracket": 0.0, "qsc_doc_frac_lines_end_with_readmore": 0.0, "qsc_doc_frac_lines_start_with_bullet": 0.0, "qsc_doc_frac_words_unique": 0.23191648, "qsc_doc_entropy_unigram": 4.76529845, "qsc_doc_frac_words_all_caps": 0.02908163, "qsc_doc_frac_lines_dupe_lines": 0.1025641, "qsc_doc_frac_chars_dupe_lines": 0.10911978, "qsc_doc_frac_chars_top_2grams": 0.05789236, "qsc_doc_frac_chars_top_3grams": 0.06482738, "qsc_doc_frac_chars_top_4grams": 0.10372381, "qsc_doc_frac_chars_dupe_5grams": 0.39981909, "qsc_doc_frac_chars_dupe_6grams": 0.36891301, "qsc_doc_frac_chars_dupe_7grams": 0.34041912, "qsc_doc_frac_chars_dupe_8grams": 0.25569124, "qsc_doc_frac_chars_dupe_9grams": 0.20624152, "qsc_doc_frac_chars_dupe_10grams": 0.15829941, "qsc_doc_frac_chars_replacement_symbols": 0.0, "qsc_doc_cate_code_related_file_name": 0.0, "qsc_doc_num_chars_sentence_length_mean": 30.70731707, "qsc_doc_frac_chars_hyperlink_html_tag": 0.34762062, "qsc_doc_frac_chars_alphabet": 0.79007303, "qsc_doc_frac_chars_digital": 0.03094442, "qsc_doc_frac_chars_whitespace": 0.11210023, "qsc_doc_frac_chars_hex_words": 0.0}
1
{"qsc_doc_frac_chars_replacement_symbols": 0, "qsc_doc_entropy_unigram": 0, "qsc_doc_frac_chars_top_2grams": 0, "qsc_doc_frac_chars_top_3grams": 0, "qsc_doc_frac_chars_top_4grams": 0, "qsc_doc_frac_chars_dupe_5grams": 0, "qsc_doc_frac_chars_dupe_6grams": 0, "qsc_doc_frac_chars_dupe_7grams": 0, "qsc_doc_frac_chars_dupe_8grams": 0, "qsc_doc_frac_chars_dupe_9grams": 0, "qsc_doc_frac_chars_dupe_10grams": 0, "qsc_doc_frac_chars_dupe_lines": 0, "qsc_doc_frac_lines_dupe_lines": 0, "qsc_doc_frac_lines_end_with_readmore": 0, "qsc_doc_frac_lines_start_with_bullet": 0, "qsc_doc_frac_words_all_caps": 0, "qsc_doc_mean_word_length": 0, "qsc_doc_num_chars": 0, "qsc_doc_num_lines": 0, "qsc_doc_num_sentences": 0, "qsc_doc_num_words": 0, "qsc_doc_frac_chars_hex_words": 0, "qsc_doc_frac_chars_hyperlink_html_tag": 0, "qsc_doc_frac_chars_alphabet": 0, "qsc_doc_frac_chars_digital": 0, "qsc_doc_frac_chars_whitespace": 0}
007revad/Synology_DSM_Telnet_Password
README.md
# Synology DSM Recovery Telnet Password <a href="https://github.com/007revad/Synology_DSM_Telnet_Password/releases"><img src="https://img.shields.io/github/release/007revad/Synology_DSM_Telnet_Password.svg"></a> ![Badge](https://hitscounter.dev/api/hit?url=https%3A%2F%2Fgithub.com%2F007revad%2FSynology_DSM_Telnet_Password&label=Visitors&icon=github&color=%23198754&message=&style=flat&tz=Australia%2FSydney) [![Donate](https://img.shields.io/badge/Donate-PayPal-green.svg)](https://www.paypal.com/paypalme/007revad) [![](https://img.shields.io/static/v1?label=Sponsor&message=%E2%9D%A4&logo=GitHub&color=%23fe8e86)](https://github.com/sponsors/007revad) [![committers.top badge](https://user-badge.committers.top/australia/007revad.svg)](https://user-badge.committers.top/australia/007revad) ### Description Synology DSM Recovery Telnet Password of the Day generator If a DSM update fails the boot loader will enable telnet to make it possible to recover from the failed DSM update. The DSM recovery telnet password was originally blank. Later Synology changed it to 101-0101 If a blank password or 101-0101 does not work you need to either contact Synology Support for the 'password of the day', or you can run this script which will show you the 'password of the day'. The script can run on a Synology NAS or any computer or NAS that has bash. ### Options You can run the script with --day=X and --month=Y to get the telnet password for day X of month Y. ``` Usage: dsm_telnet_password.sh [options] Options: --day= Set the day to calculate password from If --day= is used you must also use --month= Day must be numeric. e.g. --day=24 --month= Set the month to calculate password from If --month= is used you must also use --day= Month must be numeric. e.g. --month=9 -h, --help Show this help message -v, --version Show the script version ``` ### Screen shots <br> Script on Windows with WSL <p align="left"><img src="images/windows2.png"></p> <br> Script on Synology NAS <p align="left"><img src="images/dsm2.png"></p> <br> v1.0.2 run with --day and --month options <p align="left"><img src="images/options.png"></p>
2,241
README
md
en
markdown
text
{"qsc_doc_frac_chars_curly_bracket": 0.0, "qsc_doc_frac_words_redpajama_stop": 0.18994413, "qsc_doc_num_sentences": 44.0, "qsc_doc_num_words": 358, "qsc_doc_num_chars": 2241.0, "qsc_doc_num_lines": 51.0, "qsc_doc_mean_word_length": 4.45810056, "qsc_doc_frac_words_full_bracket": 0.0, "qsc_doc_frac_lines_end_with_readmore": 0.0, "qsc_doc_frac_lines_start_with_bullet": 0.0, "qsc_doc_frac_words_unique": 0.40782123, "qsc_doc_entropy_unigram": 4.6426283, "qsc_doc_frac_words_all_caps": 0.03351955, "qsc_doc_frac_lines_dupe_lines": 0.14285714, "qsc_doc_frac_chars_dupe_lines": 0.00856327, "qsc_doc_frac_chars_top_2grams": 0.07017544, "qsc_doc_frac_chars_top_3grams": 0.04260652, "qsc_doc_frac_chars_top_4grams": 0.04699248, "qsc_doc_frac_chars_dupe_5grams": 0.27819549, "qsc_doc_frac_chars_dupe_6grams": 0.12155388, "qsc_doc_frac_chars_dupe_7grams": 0.05513784, "qsc_doc_frac_chars_dupe_8grams": 0.0, "qsc_doc_frac_chars_dupe_9grams": 0.0, "qsc_doc_frac_chars_dupe_10grams": 0.0, "qsc_doc_frac_chars_replacement_symbols": 0.0, "qsc_doc_cate_code_related_file_name": 1.0, "qsc_doc_num_chars_sentence_length_mean": 22.6, "qsc_doc_frac_chars_hyperlink_html_tag": 0.38509594, "qsc_doc_frac_chars_alphabet": 0.80909572, "qsc_doc_frac_chars_digital": 0.03490217, "qsc_doc_frac_chars_whitespace": 0.15618028, "qsc_doc_frac_chars_hex_words": 0.0}
1
{"qsc_doc_frac_chars_replacement_symbols": 0, "qsc_doc_entropy_unigram": 0, "qsc_doc_frac_chars_top_2grams": 0, "qsc_doc_frac_chars_top_3grams": 0, "qsc_doc_frac_chars_top_4grams": 0, "qsc_doc_frac_chars_dupe_5grams": 0, "qsc_doc_frac_chars_dupe_6grams": 0, "qsc_doc_frac_chars_dupe_7grams": 0, "qsc_doc_frac_chars_dupe_8grams": 0, "qsc_doc_frac_chars_dupe_9grams": 0, "qsc_doc_frac_chars_dupe_10grams": 0, "qsc_doc_frac_chars_dupe_lines": 0, "qsc_doc_frac_lines_dupe_lines": 0, "qsc_doc_frac_lines_end_with_readmore": 0, "qsc_doc_frac_lines_start_with_bullet": 0, "qsc_doc_frac_words_all_caps": 0, "qsc_doc_mean_word_length": 0, "qsc_doc_num_chars": 0, "qsc_doc_num_lines": 0, "qsc_doc_num_sentences": 0, "qsc_doc_num_words": 0, "qsc_doc_frac_chars_hex_words": 0, "qsc_doc_frac_chars_hyperlink_html_tag": 0, "qsc_doc_frac_chars_alphabet": 0, "qsc_doc_frac_chars_digital": 0, "qsc_doc_frac_chars_whitespace": 0}
007revad/Synoboot_backup
synoboot_backup.sh
#!/usr/bin/env bash #------------------------------------------------------------------------------ # Back up synoboot after each DSM update # so you can recover from a corrupt USBDOM or EEPROM. # # Github: https://github.com/007revad/Synoboot_backup # Script verified at https://www.shellcheck.net/ # # To run in a shell (replace /volume1/scripts/ with path to script): # sudo -s /volume1/scripts/synoboot_backup.sh #------------------------------------------------------------------------------ # Set bakpath to suit the location to backup to bakpath=/volume1/backups/synoboot scriptver="v1.0.2" script=Synoboot_backup #repo="007revad/Synoboot_backup" #scriptname=synoboot_backup # Shell Colors #Black='\e[0;30m' # ${Black} #Red='\e[0;31m' # ${Red} #Green='\e[0;32m' # ${Green} #Yellow='\e[0;33m' # ${Yellow} #Blue='\e[0;34m' # ${Blue} #Purple='\e[0;35m' # ${Purple} Cyan='\e[0;36m' # ${Cyan} #White='\e[0;37m' # ${White} Error='\e[41m' # ${Error} Off='\e[0m' # ${Off} # Show script version #echo -e "$script $scriptver\ngithub.com/$repo\n" echo "$script $scriptver" ding(){ printf \\a } # Check script is running as root if [[ $( whoami ) != "root" ]]; then ding echo -e "\n${Error}ERROR${Off} This script must be run as sudo or root!\n" exit 1 fi # Check script is running on a Synology NAS if ! /usr/bin/uname -a | grep -i synology >/dev/null; then ding echo -e "\n${Error}ERROR${Off} This script is NOT running on a Synology NAS!" echo -e "Copy the script to a folder on the Synology and run it from there.\n" exit 1 # Not a Synology NAS fi # Check backup folder exists if [[ ! -d $bakpath ]]; then ding echo -e "${Error}ERROR${Off} Backup path not found: ${bakpath}\n" exit 1 fi # Get NAS model model=$(cat /proc/sys/kernel/syno_hw_version) # Check for dodgy characters after model number if [[ $model =~ 'pv10-j'$ ]]; then # GitHub syno_hdd_db issue #10 model=${model%??????}+ # replace last 6 chars with + elif [[ $model =~ '-j'$ ]]; then # GitHub syno_hdd_db issue #2 model=${model%??} # remove last 2 chars fi # Get serial number serial=$(cat /proc/sys/kernel/syno_serial) # Get DSM full version productversion=$(/usr/syno/bin/synogetkeyvalue /etc.defaults/VERSION productversion) buildphase=$(/usr/syno/bin/synogetkeyvalue /etc.defaults/VERSION buildphase) buildnumber=$(/usr/syno/bin/synogetkeyvalue /etc.defaults/VERSION buildnumber) smallfixnumber=$(/usr/syno/bin/synogetkeyvalue /etc.defaults/VERSION smallfixnumber) #majorversion=$(/usr/syno/bin/synogetkeyvalue /etc.defaults/VERSION majorversion) # Show DSM full version and model if [[ $buildphase == GM ]]; then buildphase=""; fi if [[ $smallfixnumber -gt "0" ]]; then smallfix="-U$smallfixnumber"; fi echo -e "$model DSM $productversion-$buildnumber$smallfix $buildphase\n" echo -e "Backup path: ${bakpath}\n" # Check NAS has /dev/synoboot if [[ ! -e /dev/synoboot ]]; then ding echo -e "${Error}ERROR${Off} /dev/synoboot not found!" echo -e "Unsupported Synology model: $model\n" exit 1 fi # Set backup image name imgname="${model}_${serial}_synoboot_${productversion}-$buildnumber$smallfix" # Backup USB DOM synoboot disk if [[ ! -f ${bakpath}/${imgname}.img ]]; then echo -e "Backing up ${Cyan}${imgname}.img${Off}" dd if=/dev/synoboot of="${bakpath:?}/${imgname:?}".img else echo -e "synoboot backup already exists: \n${imgname}.img" fi # Set backup image name imgname="${model}_${serial}_synoboot1_${productversion}-$buildnumber$smallfix" # Backup USB DOM synoboot1 partition if [[ ! -f ${bakpath}/${imgname}.img ]]; then echo -e "\nBacking up ${Cyan}${imgname}.img${Off}" dd if=/dev/synoboot1 of="${bakpath:?}/${imgname:?}".img else echo -e "\nsynoboot1 backup already exists: \n${imgname}.img" fi # Set backup image name imgname="${model}_${serial}_synoboot2_${productversion}-$buildnumber$smallfix" # Backup USB DOM synoboot2 partition if [[ ! -f ${bakpath}/${imgname}.img ]]; then echo -e "\nBacking up ${Cyan}${imgname}.img${Off}" dd if=/dev/synoboot2 of="${bakpath:?}/${imgname:?}".img else echo -e "\nsynoboot2 backup already exists: \n${imgname}.img" fi echo -e "\nFinished\n" exit
4,262
synoboot_backup
sh
en
shell
code
{"qsc_code_num_words": 590, "qsc_code_num_chars": 4262.0, "qsc_code_mean_word_length": 4.61016949, "qsc_code_frac_words_unique": 0.29661017, "qsc_code_frac_chars_top_2grams": 0.02941176, "qsc_code_frac_chars_top_3grams": 0.0375, "qsc_code_frac_chars_top_4grams": 0.04595588, "qsc_code_frac_chars_dupe_5grams": 0.40330882, "qsc_code_frac_chars_dupe_6grams": 0.37316176, "qsc_code_frac_chars_dupe_7grams": 0.32352941, "qsc_code_frac_chars_dupe_8grams": 0.16433824, "qsc_code_frac_chars_dupe_9grams": 0.13014706, "qsc_code_frac_chars_dupe_10grams": 0.13014706, "qsc_code_frac_chars_replacement_symbols": 0.0, "qsc_code_frac_chars_digital": 0.01644829, "qsc_code_frac_chars_whitespace": 0.15837635, "qsc_code_size_file_byte": 4262.0, "qsc_code_num_lines": 140.0, "qsc_code_num_chars_line_max": 85.0, "qsc_code_num_chars_line_mean": 30.44285714, "qsc_code_frac_chars_alphabet": 0.74184555, "qsc_code_frac_chars_comments": 0.37799155, "qsc_code_cate_xml_start": 0.0, "qsc_code_frac_lines_dupe_lines": 0.33333333, "qsc_code_cate_autogen": 0.0, "qsc_code_frac_lines_long_string": 0.0, "qsc_code_frac_chars_string_length": 0.39698113, "qsc_code_frac_chars_long_word_length": 0.16528302, "qsc_code_frac_lines_string_concat": 0.0, "qsc_code_cate_encoded_data": 0.0, "qsc_code_frac_chars_hex_words": 0.0, "qsc_code_frac_lines_prompt_comments": 0.0, "qsc_code_frac_lines_assert": 0.0}
1
{"qsc_code_frac_chars_replacement_symbols": 0, "qsc_code_num_words": 0, "qsc_code_num_chars": 0, "qsc_code_mean_word_length": 0, "qsc_code_frac_chars_top_2grams": 0, "qsc_code_frac_chars_top_3grams": 0, "qsc_code_frac_chars_top_4grams": 0, "qsc_code_frac_chars_dupe_5grams": 0, "qsc_code_frac_chars_dupe_6grams": 0, "qsc_code_frac_chars_dupe_7grams": 0, "qsc_code_frac_chars_dupe_8grams": 0, "qsc_code_frac_chars_dupe_9grams": 0, "qsc_code_frac_chars_dupe_10grams": 0, "qsc_code_frac_lines_dupe_lines": 0, "qsc_code_size_file_byte": 0, "qsc_code_num_lines": 0, "qsc_code_num_chars_line_max": 0, "qsc_code_num_chars_line_mean": 0, "qsc_code_frac_chars_alphabet": 0, "qsc_code_frac_chars_digital": 0, "qsc_code_frac_chars_whitespace": 0, "qsc_code_frac_chars_comments": 0, "qsc_code_cate_xml_start": 0, "qsc_code_cate_autogen": 0, "qsc_code_frac_chars_long_word_length": 0, "qsc_code_cate_encoded_data": 0, "qsc_code_frac_chars_hex_words": 0, "qsc_code_frac_lines_prompt_comments": 0}
007revad/Synoboot_backup
README.md
# Synoboot backup <a href="https://github.com/007revad/Synoboot_backup/releases"><img src="https://img.shields.io/github/release/007revad/Synoboot_backup.svg"></a> ![Badge](https://hitscounter.dev/api/hit?url=https%3A%2F%2Fgithub.com%2F007revad%2FSynoboot_backup&label=Visitors&icon=github&color=%23198754&message=&style=flat&tz=Australia%2FSydney) [![Donate](https://img.shields.io/badge/Donate-PayPal-green.svg)](https://www.paypal.com/paypalme/007revad) [![](https://img.shields.io/static/v1?label=Sponsor&message=%E2%9D%A4&logo=GitHub&color=%23fe8e86)](https://github.com/sponsors/007revad) [![committers.top badge](https://user-badge.committers.top/australia/007revad.svg)](https://user-badge.committers.top/australia/007revad) ### Description Back up synoboot after each DSM update so you can recover from a corrupt USBDOM For Synology models that have a USBDOM only. ### What does it do When you run the script, either via SSH or Task Scheduler, it backs up synoboot to the path you set at the top of the script. It backs up synoboot, as well as synoboot1 and synoboot2. It only creates a new backup if there are no backups with the same filename. So it will only create backups on the first run and after a DSM update. The backup filenames include: 1. The Synology model. 2. The Synology's serial number. 3. synoboot or synoboot1 or synoboot2. 4. The DSM version. 1 and 2 are needed so you don't accidentially try to recover a corrupted USBDOM or EEPROM with the wrong image file (in case you have more than one Synology, or migrate the drives to a new Synology). <p align="center"><img src="/images/filenames.png"></p> ### Download the script 1. Download the latest version _Source code (zip)_ from https://github.com/007revad/Synoboot_backup/releases 2. Save the download zip file to a folder on the Synology. 3. Unzip the zip file. ### To run the script via task scheduler Schedule the script to run at bootup to automatically create new backups after each DMS update. See [How to run from task scheduler](https://github.com/007revad/Synoboot_backup/blob/main/how_to_run_from_scheduler.md) ### To run the script via SSH [How to enable SSH and login to DSM via SSH](https://kb.synology.com/en-global/DSM/tutorial/How_to_login_to_DSM_with_root_permission_via_SSH_Telnet) ```YAML sudo -s /volume1/scripts/synoboot_backup.sh ``` **Note:** Replace /volume1/scripts/ with the path to where the script is located. ### Troubleshooting If the script won't run check the following: 1. Make sure you download the zip file and unzipped it to a folder on your Synology (not on your computer). 2. If the path to the script contains any spaces you need to enclose the path/scriptname in double quotes: ```YAML sudo -s "/volume1/my scripts/synoboot_backup.sh" ``` 3. Make sure you unpacked the zip or rar file that you downloaded and are trying to run the synoboot_backup.sh file. 4. Set the script file as executable: ```YAML sudo chmod +x "/volume1/scripts/synoboot_backup.sh" ``` ### Screenshots <p align="center">Backing up synoboot</p> <p align="center"><img src="/images/do_backup.png"></p> <br> <p align="center">synoboot already backed up for this NAS and DSM version</p> <p align="center"><img src="/images/already_backed_up.png"></p>
3,285
README
md
en
markdown
text
{"qsc_doc_frac_chars_curly_bracket": 0.0, "qsc_doc_frac_words_redpajama_stop": 0.23056995, "qsc_doc_num_sentences": 66.0, "qsc_doc_num_words": 551, "qsc_doc_num_chars": 3285.0, "qsc_doc_num_lines": 78.0, "qsc_doc_mean_word_length": 4.47549909, "qsc_doc_frac_words_full_bracket": 0.0, "qsc_doc_frac_lines_end_with_readmore": 0.0, "qsc_doc_frac_lines_start_with_bullet": 0.0, "qsc_doc_frac_words_unique": 0.39019964, "qsc_doc_entropy_unigram": 4.91628175, "qsc_doc_frac_words_all_caps": 0.03108808, "qsc_doc_frac_lines_dupe_lines": 0.11764706, "qsc_doc_frac_chars_dupe_lines": 0.00941029, "qsc_doc_frac_chars_top_2grams": 0.03649635, "qsc_doc_frac_chars_top_3grams": 0.0243309, "qsc_doc_frac_chars_top_4grams": 0.02676399, "qsc_doc_frac_chars_dupe_5grams": 0.1540957, "qsc_doc_frac_chars_dupe_6grams": 0.11597729, "qsc_doc_frac_chars_dupe_7grams": 0.09164639, "qsc_doc_frac_chars_dupe_8grams": 0.0, "qsc_doc_frac_chars_dupe_9grams": 0.0, "qsc_doc_frac_chars_dupe_10grams": 0.0, "qsc_doc_frac_chars_replacement_symbols": 0.0, "qsc_doc_cate_code_related_file_name": 1.0, "qsc_doc_num_chars_sentence_length_mean": 21.81944444, "qsc_doc_frac_chars_hyperlink_html_tag": 0.32663623, "qsc_doc_frac_chars_alphabet": 0.8379986, "qsc_doc_frac_chars_digital": 0.02484255, "qsc_doc_frac_chars_whitespace": 0.12998478, "qsc_doc_frac_chars_hex_words": 0.0}
1
{"qsc_doc_frac_chars_replacement_symbols": 0, "qsc_doc_entropy_unigram": 0, "qsc_doc_frac_chars_top_2grams": 0, "qsc_doc_frac_chars_top_3grams": 0, "qsc_doc_frac_chars_top_4grams": 0, "qsc_doc_frac_chars_dupe_5grams": 0, "qsc_doc_frac_chars_dupe_6grams": 0, "qsc_doc_frac_chars_dupe_7grams": 0, "qsc_doc_frac_chars_dupe_8grams": 0, "qsc_doc_frac_chars_dupe_9grams": 0, "qsc_doc_frac_chars_dupe_10grams": 0, "qsc_doc_frac_chars_dupe_lines": 0, "qsc_doc_frac_lines_dupe_lines": 0, "qsc_doc_frac_lines_end_with_readmore": 0, "qsc_doc_frac_lines_start_with_bullet": 0, "qsc_doc_frac_words_all_caps": 0, "qsc_doc_mean_word_length": 0, "qsc_doc_num_chars": 0, "qsc_doc_num_lines": 0, "qsc_doc_num_sentences": 0, "qsc_doc_num_words": 0, "qsc_doc_frac_chars_hex_words": 0, "qsc_doc_frac_chars_hyperlink_html_tag": 0, "qsc_doc_frac_chars_alphabet": 0, "qsc_doc_frac_chars_digital": 0, "qsc_doc_frac_chars_whitespace": 0}
007revad/Synoboot_backup
how_to_run_from_scheduler.md
# How to schedule a script in Synology Task Scheduler To schedule a script to run on your Synology at boot-up or shut-down follow these steps: **Note:** You can setup a schedule task and leave it disabled, so it only runs when you select the task in the Task Scheduler and click on the Run button. 1. Go to **Control Panel** > **Task Scheduler** > click **Create** > and select **Triggered Task**. 2. Select **User-defined script**. 3. Enter a task name. 4. Select **root** as the user (The script needs to run as root). 5. Select **Boot-up** as the event that triggers the task. 6. Leave **Enable** ticked. 7. Click **Task Settings**. 8. Optionally you can tick **Send run details by email** and **Send run details only when the script terminates abnormally** then enter your email address. 9. In the box under **User-defined script** type the path to the script. - e.g. If you saved the script to a shared folder on volume1 called "scripts" you'd type: - **/volume1/scripts/synoboot_backup.sh** 11. Click **OK** to save the settings. Here's some screenshots showing what needs to be set: <p align="leftr"><img src="images/schedule1.png"></p> <p align="leftr"><img src="images/schedule2.png"></p> <p align="leftr"><img src="images/schedule3.png"></p>
1,268
how_to_run_from_scheduler
md
en
markdown
text
{"qsc_doc_frac_chars_curly_bracket": 0.0, "qsc_doc_frac_words_redpajama_stop": 0.24840764, "qsc_doc_num_sentences": 28.0, "qsc_doc_num_words": 218, "qsc_doc_num_chars": 1268.0, "qsc_doc_num_lines": 26.0, "qsc_doc_mean_word_length": 4.14220183, "qsc_doc_frac_words_full_bracket": 0.0, "qsc_doc_frac_lines_end_with_readmore": 0.0, "qsc_doc_frac_lines_start_with_bullet": 0.0, "qsc_doc_frac_words_unique": 0.51376147, "qsc_doc_entropy_unigram": 4.41735967, "qsc_doc_frac_words_all_caps": 0.00318471, "qsc_doc_frac_lines_dupe_lines": 0.0, "qsc_doc_frac_chars_dupe_lines": 0.0, "qsc_doc_frac_chars_top_2grams": 0.03986711, "qsc_doc_frac_chars_top_3grams": 0.03654485, "qsc_doc_frac_chars_top_4grams": 0.04651163, "qsc_doc_frac_chars_dupe_5grams": 0.08527132, "qsc_doc_frac_chars_dupe_6grams": 0.08527132, "qsc_doc_frac_chars_dupe_7grams": 0.05980066, "qsc_doc_frac_chars_dupe_8grams": 0.05980066, "qsc_doc_frac_chars_dupe_9grams": 0.0, "qsc_doc_frac_chars_dupe_10grams": 0.0, "qsc_doc_frac_chars_replacement_symbols": 0.0, "qsc_doc_cate_code_related_file_name": 0.0, "qsc_doc_num_chars_sentence_length_mean": 22.5, "qsc_doc_frac_chars_hyperlink_html_tag": 0.12539432, "qsc_doc_frac_chars_alphabet": 0.83837429, "qsc_doc_frac_chars_digital": 0.01512287, "qsc_doc_frac_chars_whitespace": 0.16561514, "qsc_doc_frac_chars_hex_words": 0.0}
1
{"qsc_doc_frac_chars_replacement_symbols": 0, "qsc_doc_entropy_unigram": 0, "qsc_doc_frac_chars_top_2grams": 0, "qsc_doc_frac_chars_top_3grams": 0, "qsc_doc_frac_chars_top_4grams": 0, "qsc_doc_frac_chars_dupe_5grams": 0, "qsc_doc_frac_chars_dupe_6grams": 0, "qsc_doc_frac_chars_dupe_7grams": 0, "qsc_doc_frac_chars_dupe_8grams": 0, "qsc_doc_frac_chars_dupe_9grams": 0, "qsc_doc_frac_chars_dupe_10grams": 0, "qsc_doc_frac_chars_dupe_lines": 0, "qsc_doc_frac_lines_dupe_lines": 0, "qsc_doc_frac_lines_end_with_readmore": 0, "qsc_doc_frac_lines_start_with_bullet": 0, "qsc_doc_frac_words_all_caps": 0, "qsc_doc_mean_word_length": 0, "qsc_doc_num_chars": 0, "qsc_doc_num_lines": 0, "qsc_doc_num_sentences": 0, "qsc_doc_num_words": 0, "qsc_doc_frac_chars_hex_words": 0, "qsc_doc_frac_chars_hyperlink_html_tag": 0, "qsc_doc_frac_chars_alphabet": 0, "qsc_doc_frac_chars_digital": 0, "qsc_doc_frac_chars_whitespace": 0}
007revad/Synology_app_mover
syno_app_mover.sh
#!/usr/bin/env bash # shellcheck disable=SC2076,SC2207,SC2238,SC2129 #------------------------------------------------------------------------------ # Easily move Synology packages from one volume to another volume. # Also can backup and restore packages. # # Github: https://github.com/007revad/Synology_app_mover # Script verified at https://www.shellcheck.net/ # # To run in a shell (replace /volume1/scripts/ with path to script): # sudo -s /volume1/scripts/syno_app_mover.sh #------------------------------------------------------------------------------ # TODO # Instead of moving large extra folders copy them to the target volume. # Then rename the source volume's @downloads to @downloads_backup. # # Add ability to move all apps # https://www.reddit.com/r/synology/comments/1eybzc1/comment/ljcj8re/ # # Maybe add backing up "/volume#/@iSCSI/VDISK_BLUN" (VMM VMs) # https://www.synology-forum.de/threads/backup-der-vms.135462/post-1194705 # https://www.synology-forum.de/threads/virtual-machine-manager-vms-sichern.91952/post-944113 # #------------------------------------------------------------------------------ # DONE Add `@database` as an app that can be moved. # DONE Added logging # DONE Added USB Copy to show how to move USB Copy database (move mode only) #------------------------------------------------------------------------------ scriptver="v4.2.94" script=Synology_app_mover repo="007revad/Synology_app_mover" scriptname=syno_app_mover logpath="$(dirname "$(realpath "$0")")" logfile="$logpath/${scriptname}_$(date +%Y-%m-%d_%H-%M).log" # Prevent Entware or user edited PATH causing issues # shellcheck disable=SC2155 # Declare and assign separately to avoid masking return values export PATH=$(echo "$PATH" | sed -e 's/\/opt\/bin:\/opt\/sbin://') ding(){ [ "$trace" == "yes" ] && echo "${FUNCNAME[0]} called from ${FUNCNAME[1]}" printf \\a } # Save options used for getopt args=("$@") if [[ $1 == "--debug" ]] || [[ $1 == "-d" ]]; then set -x export PS4='`[[ $? == 0 ]] || echo "\e[1;31;40m($?)\e[m\n "`LINE $LINENO ' fi if [[ $1 == "--trace" ]] || [[ $1 == "-t" ]]; then trace="yes" fi if [[ ${1,,} == "--fix" ]]; then # Bypass exit if dependent package failed to stop # For restoring broken package to original volume fix="yes" fi # Check script is running as root if [[ $( whoami ) != "root" ]]; then ding echo -e "${Error}ERROR${Off} This script must be run as sudo or root!" exit 1 # Not running as root fi # Check script is running on a Synology NAS if ! /usr/bin/uname -a | grep -i synology >/dev/null; then echo "This script is NOT running on a Synology NAS!" echo "Copy the script to a folder on the Synology" echo "and run it from there." exit 1 # Not a Synology NAS fi # Get NAS model model=$(cat /proc/sys/kernel/syno_hw_version) #modelname="$model" # Check for dodgy characters after model number if [[ $model =~ 'pv10-j'$ ]]; then # GitHub syno_hdd_db issue #10 model=${model%??????}+ # replace last 6 chars with + elif [[ $model =~ '-j'$ ]]; then # GitHub syno_hdd_db issue #2 model=${model%??} # remove last 2 chars fi # Show script version #echo -e "$script $scriptver\ngithub.com/$repo\n" echo "$script $scriptver" # Get DSM full version productversion=$(/usr/syno/bin/synogetkeyvalue /etc.defaults/VERSION productversion) buildphase=$(/usr/syno/bin/synogetkeyvalue /etc.defaults/VERSION buildphase) buildnumber=$(/usr/syno/bin/synogetkeyvalue /etc.defaults/VERSION buildnumber) smallfixnumber=$(/usr/syno/bin/synogetkeyvalue /etc.defaults/VERSION smallfixnumber) majorversion=$(/usr/syno/bin/synogetkeyvalue /etc.defaults/VERSION majorversion) #minorversion=$(/usr/syno/bin/synogetkeyvalue /etc.defaults/VERSION minorversion) # Show DSM full version and model if [[ $buildphase == GM ]]; then buildphase=""; fi if [[ $smallfixnumber -gt "0" ]]; then smallfix="-$smallfixnumber"; fi echo "$model DSM $productversion-$buildnumber$smallfix $buildphase" # Show options used if [[ ${#args[@]} -gt "0" ]]; then echo -e "Using options: ${args[*]}\n" else echo "" fi usage(){ cat <<EOF Usage: $(basename "$0") [options] Options: -h, --help Show this help message -v, --version Show the script version --autoupdate=AGE Auto update script (useful when script is scheduled) AGE is how many days old a release must be before auto-updating. AGE must be a number: 0 or greater --auto=APP Automatically backup APP (for scheduling backups) APP can be a single app or a comma separated list APP can also be 'all' to backup all apps (except any you excluded in the syno_app_mover.conf) Examples: --auto=radarr --auto=Calender,ContainerManager,radarr --auto=all APP names need to be the app's system name View the system names with the --list option --list Display installed apps' system names EOF } list_names(){ # List app system names if ! cd /var/packages; then echo "Failed to cd to /var/packages!" exit 1 fi # Print header echo -e "Use app system name for --auto option or exclude in conf file\n" printf -- '-%.0s' {1..62}; echo # print 62 - echo "APP SYSTEM NAME APP DISPLAY NAME" printf -- '-%.0s' {1..62}; echo # print 62 - for p in *; do if [[ -d "$p" ]]; then if [[ ! -a "$p/target" ]] ; then echo -e "\e[41mBroken symlink\e[0m $p" else if [[ -f "/var/packages/${p}/INFO" ]]; then long_name="$(/usr/syno/bin/synogetkeyvalue "/var/packages/${p}/INFO" displayname)" if [[ -z "$long_name" ]]; then long_name="$(/usr/syno/bin/synogetkeyvalue "/var/packages/${p}/INFO" package)" fi else # Package with no INFO file long_name="!!! MISSING INFO FILE !!!" fi # Pad with spaces to 29 chars pad=$(printf -- ' %.0s' {1..29}) printf '%.*s' 29 "$p${pad}" echo "$long_name" fi fi done < <(find . -maxdepth 1 -type d) echo "" exit 0 } scriptversion(){ cat <<EOF $script $scriptver - by 007revad See https://github.com/$repo EOF exit 0 } autoupdate="" # Check for flags with getopt if options="$(getopt -o abcdefghijklmnopqrstuvwxyz0123456789 -l \ auto:,list,help,version,autoupdate:,log,debug -- "${args[@]}")"; then eval set -- "$options" while true; do case "${1,,}" in -h|--help) # Show usage options usage exit ;; -v|--version) # Show script version scriptversion ;; -l|--log) # Log log=yes ;; -d|--debug) # Show and log debug info debug=yes ;; --list) # List installed app's system names list_names ;; --auto) # Specify pkgs for scheduled backup auto="yes" color=no # Disable colour text in task scheduler emails mode="Backup" action="Backing up" if [[ ${2,,} == "all" ]]; then all="yes" elif [[ $2 ]]; then IFS=',' read -r -a autos <<< "$2"; unset IFS if [[ ${#autos[@]} -gt "0" ]]; then for i in "${autos[@]}"; do # Trim leading and trailing spaces j=$(echo -n "$i" | xargs) # Check pkg name exists if [[ ! -d "/var/packages/$j" ]]; then echo -e "Invalid auto argument '$j'\n" else if readlink -f "/var/packages/$j/target" | grep -q -E '^/volume'; then autolist+=("$j") else skipped+=("$j") fi fi done else ding echo -e "Missing argument to auto!\n" usage exit 2 # Missing argument fi else ding echo -e "Missing argument to auto!\n" usage exit 2 # Missing argument fi shift ;; --autoupdate) # Auto update script autoupdate=yes if [[ $2 =~ ^[0-9]+$ ]]; then delay="$2" shift else delay="0" fi ;; --) shift break ;; *) # Show usage options ding echo -e "Invalid option '$1'\n" usage exit 2 # Invalid argument ;; esac shift done else echo usage exit fi # Abort if autolist is empty if [[ $auto == "yes" ]] && [[ $all != "yes" ]] && [[ ! ${#autolist[@]} -gt "0" ]]; then ding echo -e "No apps to backup!\n" exit 2 # autolist empty fi # Show apps to auto backup #if [[ ${#autolist[@]} -gt "0" ]]; then # debug # echo -e "Backing up ${autolist[*]}\n" # debug #fi # debug if [[ $debug == "yes" ]]; then set -x export PS4='`[[ $? == 0 ]] || echo "\e[1;31;40m($?)\e[m\n "`:.$LINENO:' fi # Shell Colors if [[ $color != "no" ]]; then #Black='\e[0;30m' # ${Black} Red='\e[0;31m' # ${Red} #Green='\e[0;32m' # ${Green} Yellow='\e[0;33m' # ${Yellow} #Blue='\e[0;34m' # ${Blue} #Purple='\e[0;35m' # ${Purple} Cyan='\e[0;36m' # ${Cyan} #White='\e[0;37m' # ${White} Error='\e[41m' # ${Error} #Warn='\e[47;31m' # ${Warn} Off='\e[0m' # ${Off} fi #------------------------------------------------------------------------------ # Check latest release with GitHub API # Get latest release info # Curl timeout options: # https://unix.stackexchange.com/questions/94604/does-curl-have-a-timeout release=$(curl --silent -m 10 --connect-timeout 5 \ "https://api.github.com/repos/$repo/releases/latest") # Release version tag=$(echo "$release" | grep '"tag_name":' | sed -E 's/.*"([^"]+)".*/\1/') shorttag="${tag:1}" # Release published date published=$(echo "$release" | grep '"published_at":' | sed -E 's/.*"([^"]+)".*/\1/') published="${published:0:10}" published=$(date -d "$published" '+%s') # Today's date now=$(date '+%s') # Days since release published age=$(((now - published)/(60*60*24))) # Get script location # https://stackoverflow.com/questions/59895/ source=${BASH_SOURCE[0]} while [ -L "$source" ]; do # Resolve $source until the file is no longer a symlink scriptpath=$( cd -P "$( dirname "$source" )" >/dev/null 2>&1 && pwd ) source=$(readlink "$source") # If $source was a relative symlink, we need to resolve it # relative to the path where the symlink file was located [[ $source != /* ]] && source=$scriptpath/$source done scriptpath=$( cd -P "$( dirname "$source" )" >/dev/null 2>&1 && pwd ) scriptfile=$( basename -- "$source" ) echo "Running from: ${scriptpath}/$scriptfile" #echo "Script location: $scriptpath" # debug #echo "Source: $source" # debug #echo "Script filename: $scriptfile" # debug #echo "tag: $tag" # debug #echo "scriptver: $scriptver" # debug cleanup_tmp(){ # Delete downloaded .tar.gz file if [[ -f "/tmp/$script-$shorttag.tar.gz" ]]; then if ! rm "/tmp/$script-$shorttag.tar.gz"; then echo -e "${Error}ERROR${Off} Failed to delete"\ "downloaded /tmp/$script-$shorttag.tar.gz!" >&2 fi fi # Delete extracted tmp files if [[ -d "/tmp/$script-$shorttag" ]]; then if ! rm -r "/tmp/$script-$shorttag"; then echo -e "${Error}ERROR${Off} Failed to delete"\ "downloaded /tmp/$script-$shorttag!" >&2 fi fi } if ! printf "%s\n%s\n" "$tag" "$scriptver" | sort --check=quiet --version-sort >/dev/null ; then echo -e "\n${Cyan}There is a newer version of this script available.${Off}" echo -e "Current version: ${scriptver}\nLatest version: $tag" scriptdl="$scriptpath/$script-$shorttag" if [[ -f ${scriptdl}.tar.gz ]] || [[ -f ${scriptdl}.zip ]]; then # They have the latest version tar.gz downloaded but are using older version echo "You have the latest version downloaded but are using an older version" sleep 10 elif [[ -d $scriptdl ]]; then # They have the latest version extracted but are using older version echo "You have the latest version extracted but are using an older version" sleep 10 else if [[ $autoupdate == "yes" ]]; then if [[ $age -gt "$delay" ]] || [[ $age -eq "$delay" ]]; then echo "Downloading $tag" reply=y else echo "Skipping as $tag is less than $delay days old." fi else echo -e "${Cyan}Do you want to download $tag now?${Off} [y/n]" read -r -t 30 reply fi if [[ ${reply,,} == "y" ]]; then # Delete previously downloaded .tar.gz file and extracted tmp files cleanup_tmp if cd /tmp; then url="https://github.com/$repo/archive/refs/tags/$tag.tar.gz" if ! curl -JLO -m 30 --connect-timeout 5 "$url"; then echo -e "${Error}ERROR${Off} Failed to download"\ "$script-$shorttag.tar.gz!" else if [[ -f /tmp/$script-$shorttag.tar.gz ]]; then # Extract tar file to /tmp/<script-name> if ! tar -xf "/tmp/$script-$shorttag.tar.gz" -C "/tmp"; then echo -e "${Error}ERROR${Off} Failed to"\ "extract $script-$shorttag.tar.gz!" else # Set script sh files as executable if ! chmod a+x "/tmp/$script-$shorttag/"*.sh ; then permerr=1 echo -e "${Error}ERROR${Off} Failed to set executable permissions" fi # Copy new script sh file to script location if ! cp -p "/tmp/$script-$shorttag/${scriptname}.sh" "${scriptpath}/${scriptfile}"; then copyerr=1 echo -e "${Error}ERROR${Off} Failed to copy"\ "$script-$shorttag sh file(s) to:\n $scriptpath/${scriptfile}" fi # Copy script's conf file to script location if missing if [[ ! -f "$scriptpath/${scriptname}.conf" ]]; then # Set permission on config file if ! chmod 664 "/tmp/$script-$shorttag/${scriptname}.conf"; then permerr=1 echo -e "${Error}ERROR${Off} Failed to set read/write permissions on:" echo "$scriptpath/${scriptname}.conf" fi # Copy existing conf file settings to new conf file while read -r LINE; do if [[ ${LINE:0:1} != "#" ]]; then if [[ $LINE =~ ^[a-z_]+=.* ]]; then oldfile="${scriptpath}/${scriptname}.conf" newfile="/tmp/$script-$shorttag/${scriptname}.conf" key="${LINE%=*}" oldvalue="$(synogetkeyvalue "$oldfile" "$key")" newvalue="$(synogetkeyvalue "$newfile" "$key")" if [[ $oldvalue != "$newvalue" ]]; then synosetkeyvalue "$newfile" "$key" "$oldvalue" fi fi fi done < "${scriptpath}/${scriptname}.conf" # Copy conf file to script location if ! cp -p "/tmp/$script-$shorttag/${scriptname}.conf"\ "${scriptpath}/${scriptname}.conf"; then copyerr=1 echo -e "${Error}ERROR${Off} Failed to copy"\ "$script-$shorttag conf file to:\n $scriptpath/${scriptname}.conf" else conftxt=", ${scriptname}.conf" fi fi # Copy new CHANGES.txt file to script location (if script on a volume) if [[ $scriptpath =~ /volume* ]]; then # Set permissions on CHANGES.txt if ! chmod 664 "/tmp/$script-$shorttag/CHANGES.txt"; then permerr=1 echo -e "${Error}ERROR${Off} Failed to set read/write permissions on:" echo "$scriptpath/CHANGES.txt" fi # Copy new CHANGES.txt file to script location if ! cp -p "/tmp/$script-$shorttag/CHANGES.txt"\ "${scriptpath}/${scriptname}_CHANGES.txt"; then echo -e "${Error}ERROR${Off} Failed to copy"\ "$script-$shorttag/CHANGES.txt to:\n $scriptpath" else changestxt=" and changes.txt" fi fi # Delete downloaded tmp files cleanup_tmp # Notify of success (if there were no errors) if [[ $copyerr != 1 ]] && [[ $permerr != 1 ]]; then echo -e "\n$tag ${scriptfile}$conftxt$changestxt downloaded to: ${scriptpath}\n" # Reload script printf -- '-%.0s' {1..79}; echo # print 79 - exec "${scriptpath}/$scriptfile" "${args[@]}" fi fi else echo -e "${Error}ERROR${Off}"\ "/tmp/$script-$shorttag.tar.gz not found!" #ls /tmp | grep "$script" # debug fi fi cd "$scriptpath" || echo -e "${Error}ERROR${Off} Failed to cd to script location!" else echo -e "${Error}ERROR${Off} Failed to cd to /tmp!" fi fi fi fi conffile="${scriptpath}/${scriptname}.conf" # Fix line endings # grep can't detect Windows or Mac line endings # but can detect if there's no Linux endings. if grep -rIl -m 1 $'\r' "$conffile" >/dev/null; then # Does not contain Linux line endings sed -i 's/\r\n/\n/g' "$conffile" # Fix Windows line endings sed -i 's/\r/\n/g' "$conffile" # Fix Mac line endings fi # Add log header echo "$script $scriptver" > "$logfile" echo -e "$model DSM $productversion-$buildnumber$smallfix $buildphase\n" >> "$logfile" echo "Running from: ${scriptpath}/$scriptfile" >> "$logfile" #------------------------------------------------------------------------------ # Functions # shellcheck disable=SC2317,SC2329 # Don't warn about unreachable commands in this function pause(){ # When debugging insert pause command where needed read -s -r -n 1 -p "Press any key to continue..." read -r -t 0.1 -s -e -- # Silently consume all input stty echo echok # Ensure read didn't disable echoing user input echo -e "\n" |& tee -a "$logfile" } # shellcheck disable=SC2317,SC2329 # Don't warn about unreachable commands in this function debug(){ if [[ $1 == "on" ]]; then set -x export PS4='`[[ $? == 0 ]] || echo "\e[1;31;40m($?)\e[m\n "`LINE $LINENO ' elif [[ $1 == "off" ]]; then set +x fi } progbar(){ # $1 is pid of process # $2 is string to echo string="$2" local dots local progress dots="" while [[ -d /proc/$1 ]]; do dots="${dots}." progress="$dots" if [[ ${#dots} -gt "10" ]]; then dots="" progress=" " fi echo -ne " ${2}$progress\r"; /usr/bin/sleep 0.3 done } progstatus(){ # $1 is return status of process # $2 is string to echo # $3 line number function was called from local tracestring local pad tracestring="${FUNCNAME[0]} called from ${FUNCNAME[1]} $3" pad=$(printf -- ' %.0s' {1..80}) [ "$trace" == "yes" ] && printf '%.*s' 80 "${tracestring}${pad}" && echo "" if [[ $1 == "0" ]]; then echo -e "$2 " else ding echo -e "Line ${LINENO}: ${Error}ERROR${Off} $2 failed!" |& tee -a "$logfile" echo "$tracestring ($scriptver)" |& tee -a "$logfile" if [[ $exitonerror != "no" ]]; then exit 1 # Skip exit if exitonerror != no fi fi exitonerror="" #echo "return: $1" # debug } package_status(){ # $1 is package name [ "$trace" == "yes" ] && echo "${FUNCNAME[0]} called from ${FUNCNAME[1]}" |& tee -a "$logfile" # local code /usr/syno/bin/synopkg status "${1}" >/dev/null code="$?" # DSM 7.2 0 = started, 17 = stopped, 255 = not_installed, 150 = broken # DSM 6 to 7.1 0 = started, 3 = stopped, 4 = not_installed, 150 = broken if [[ $code == "0" ]]; then #echo "$1 is started" # debug return 0 elif [[ $code == "17" ]] || [[ $code == "3" ]]; then #echo "$1 is stopped" # debug return 1 elif [[ $code == "255" ]] || [[ $code == "4" ]]; then #echo "$1 is not installed" # debug return 255 elif [[ $code == "150" ]]; then #echo "$1 is broken" # debug return 150 else return "$code" fi } package_is_running(){ # $1 is package name [ "$trace" == "yes" ] && echo "${FUNCNAME[0]} called from ${FUNCNAME[1]}" |& tee -a "$logfile" /usr/syno/bin/synopkg is_onoff "${1}" >/dev/null code="$?" return "$code" } wait_status(){ # Wait for package to finish stopping or starting # $1 is package # $2 is start or stop [ "$trace" == "yes" ] && echo "${FUNCNAME[0]} called from ${FUNCNAME[1]}" |& tee -a "$logfile" local num if [[ $2 == "start" ]]; then state="0" elif [[ $2 == "stop" ]]; then state="1" fi if [[ $state == "0" ]] || [[ $state == "1" ]]; then num="0" package_status "$1" while [[ $? != "$state" ]]; do sleep 1 num=$((num +1)) if [[ $num -gt "20" ]]; then break fi package_status "$1" done fi } package_stop(){ # $1 is package name # $2 is package display name [ "$trace" == "yes" ] && echo "${FUNCNAME[0]} called from ${FUNCNAME[1]}" |& tee -a "$logfile" if [[ ${#pkgs_sorted[@]} -gt "1" ]]; then /usr/syno/bin/synopkg stop "$1" >/dev/null & else # Only timeout if there are other packages to process #timeout 5m /usr/syno/bin/synopkg stop "$1" >/dev/null & # Docker can take 12 minutes to stop 70 containers timeout 30m /usr/syno/bin/synopkg stop "$1" >/dev/null & fi pid=$! string="Stopping ${Cyan}${2}${Off}" echo "Stopping $2" >> "$logfile" progbar "$pid" "$string" wait "$pid" progstatus "$?" "$string" "line ${LINENO}" # Allow package processes to finish stopping #wait_status "$1" stop wait_status "$1" stop & pid=$! string="Waiting for ${Cyan}${2}${Off} to stop" echo "Waiting for $2 to stop" >> "$logfile" progbar "$pid" "$string" wait "$pid" progstatus "$?" "$string" "line ${LINENO}" } package_start(){ # $1 is package name # $2 is package display name [ "$trace" == "yes" ] && echo "${FUNCNAME[0]} called from ${FUNCNAME[1]}" |& tee -a "$logfile" if [[ ${#pkgs_sorted[@]} -gt "1" ]]; then /usr/syno/bin/synopkg start "$1" >/dev/null & else # Only timeout if there are other packages to process #timeout 5m /usr/syno/bin/synopkg start "$1" >/dev/null & # Docker can take 15 minutes to start 70 containers timeout 30m /usr/syno/bin/synopkg start "$1" >/dev/null & fi pid=$! string="Starting ${Cyan}${2}${Off}" echo "Starting $2" >> "$logfile" progbar "$pid" "$string" wait "$pid" progstatus "$?" "$string" "line ${LINENO}" # Allow package processes to finish starting #wait_status "$1" start wait_status "$1" start & pid=$! string="Waiting for ${Cyan}${2}${Off} to start" echo "Waiting for $2 to start" >> "$logfile" progbar "$pid" "$string" wait "$pid" progstatus "$?" "$string" "line ${LINENO}" } # shellcheck disable=SC2317 # Don't warn about unreachable commands in this function package_uninstall(){ # $1 is package name [ "$trace" == "yes" ] && echo "${FUNCNAME[0]} called from ${FUNCNAME[1]}" |& tee -a "$logfile" /usr/syno/bin/synopkg uninstall "$1" >/dev/null & pid=$! string="Uninstalling ${Cyan}${1}${Off}" echo "Ininstalling $1" >> "$logfile" progbar "$pid" "$string" wait "$pid" progstatus "$?" "$string" "line ${LINENO}" } # shellcheck disable=SC2317 # Don't warn about unreachable commands in this function package_install(){ # $1 is package name # $2 is /volume2 etc [ "$trace" == "yes" ] && echo "${FUNCNAME[0]} called from ${FUNCNAME[1]}" |& tee -a "$logfile" /usr/syno/bin/synopkg install_from_server "$1" "$2" >/dev/null & pid=$! string="Installing ${Cyan}${1}${Off} on ${Cyan}$2${Off}" echo "Installing $1 on $2" >> "$logfile" progbar "$pid" "$string" wait "$pid" progstatus "$?" "$string" "line ${LINENO}" } is_empty(){ # $1 is /path/folder [ "$trace" == "yes" ] && echo "${FUNCNAME[0]} called from ${FUNCNAME[1]}" |& tee -a "$logfile" if [[ -d $1 ]]; then local contents contents=$(find "$1" -maxdepth 1 -printf '.') if [[ ${#contents} -gt 1 ]]; then return 1 # Not empty fi fi } backup_dir(){ # $1 is folder to backup (@docker etc) # $2 is volume (/volume1 etc) [ "$trace" == "yes" ] && echo "${FUNCNAME[0]} called from ${FUNCNAME[1]}" |& tee -a "$logfile" local perms if [[ -d "$2/$1" ]]; then # Make backup folder on $2 if [[ ! -d "${2}/${1}_backup" ]]; then # Set same permissions as original folder perms=$(stat -c %a "${2:?}/${1:?}") if ! mkdir -m "$perms" "${2:?}/${1:?}_backup"; then ding echo -e "Line ${LINENO}: ${Error}ERROR${Off} Failed to create directory!" echo -e "Line ${LINENO}: ERROR Failed to create directory!" >> "$logfile" process_error="yes" if [[ $all != "yes" ]] || [[ $fix != "yes" ]]; then exit 1 # Skip exit if mode != all and fix != yes fi return 1 fi fi # Backup $1 if ! is_empty "${2:?}/${1:?}_backup"; then # @docker_backup folder exists and is not empty echo -e "There is already a backup of $1" |& tee -a "$logfile" echo -e "Do you want to overwrite it? [y/n]" |& tee -a "$logfile" read -r answer echo "$answer" >> "$logfile" echo "" |& tee -a "$logfile" if [[ ${answer,,} != "y" ]]; then return fi fi cp -prf "${2:?}/${1:?}/." "${2:?}/${1:?}_backup" |& tee -a "$logfile" & pid=$! # If string is too long progbar repeats string for each dot string="Backing up $1 to ${Cyan}${1}_backup${Off}" echo "Backing up $1 to ${1}_backup" >> "$logfile" progbar "$pid" "$string" wait "$pid" progstatus "$?" "$string" "line ${LINENO}" fi } cdir(){ # $1 is path to cd to [ "$trace" == "yes" ] && echo "${FUNCNAME[0]} called from ${FUNCNAME[1]}" |& tee -a "$logfile" if ! cd "$1"; then ding echo -e "Line ${LINENO}: ${Error}ERROR${Off} cd to $1 failed!" echo -e "Line ${LINENO}: ERROR cd to $1 failed!" >> "$logfile" process_error="yes" if [[ $all != "yes" ]] || [[ $fix != "yes" ]]; then exit 1 # Skip exit if mode != all and fix != yes fi return 1 fi } create_dir(){ # $1 is source /path/folder # $2 is target /path/folder [ "$trace" == "yes" ] && echo "${FUNCNAME[0]} called from ${FUNCNAME[1]}" |& tee -a "$logfile" # Create target folder with source folder's permissions if [[ ! -d "$2" ]]; then # Set same permissions as original folder perms=$(stat -c %a "${1:?}") if ! mkdir -m "$perms" "${2:?}"; then ding echo -e "Line ${LINENO}: ${Error}ERROR${Off} Failed to create directory!" echo -e "Line ${LINENO}: ERROR Failed to create directory!" >> "$logfile" process_error="yes" if [[ $all != "yes" ]] || [[ $fix != "yes" ]]; then exit 1 # Skip exit if mode != all and fix != yes fi return 1 fi fi } move_pkg_do(){ # $1 is package name # $2 is destination volume or path [ "$trace" == "yes" ] && echo "${FUNCNAME[0]} called from ${FUNCNAME[1]}" |& tee -a "$logfile" # Move package's @app directories if [[ ${mode,,} == "move" ]]; then #mv -f "${source:?}" "${2:?}/${appdir:?}" |& tee -a "$logfile" & #pid=$! #string="${action} $source to ${Cyan}$2${Off}" #echo "${action} $source to $2" >> "$logfile" #progbar "$pid" "$string" #wait "$pid" #progstatus "$?" "$string" if [[ ! -d "${2:?}/${appdir:?}/${1:?}" ]] ||\ is_empty "${2:?}/${appdir:?}/${1:?}"; then # Move source folder to target folder if [[ -w "/$sourcevol" ]]; then mv -f "${source:?}" "${2:?}/${appdir:?}" |& tee -a "$logfile" & else # Source volume is read only cp -prf "${source:?}" "${2:?}/${appdir:?}" |& tee -a "$logfile" & fi pid=$! string="${action} $source to ${Cyan}$2${Off}" echo "${action} $source to $2" >> "$logfile" progbar "$pid" "$string" wait "$pid" progstatus "$?" "$string" "line ${LINENO}" else # Copy source contents if target folder exists cp -prf "${source:?}" "${2:?}/${appdir:?}" |& tee -a "$logfile" & pid=$! string="Copying $source to ${Cyan}$2${Off}" echo "Copying $source to $2" >> "$logfile" progbar "$pid" "$string" wait "$pid" progstatus "$?" "$string" "line ${LINENO}" #rm -rf "${source:?}" |& tee -a "$logfile" & rm -r --preserve-root "${source:?}" |& tee -a "$logfile" & pid=$! exitonerror="no" string="Removing $source" echo "$string" >> "$logfile" progbar "$pid" "$string" wait "$pid" progstatus "$?" "$string" "line ${LINENO}" fi else # if ! is_empty "${destination:?}/${appdir:?}/${1:?}"; then # echo "Skipping ${action,,} ${appdir}/$1 as target is not empty:" |& tee -a "$logfile" # echo " ${destination}/${appdir}/$1" |& tee -a "$logfile" # else #mv -f "${source:?}" "${2:?}/${appdir:?}" |& tee -a "$logfile" & #pid=$! #string="${action} $source to ${Cyan}$2${Off}" #echo "${action} $source to $2" >> "$logfile" #progbar "$pid" "$string" #wait "$pid" #progstatus "$?" "$string" exitonerror="no" && move_dir "$appdir" # fi fi } edit_symlinks(){ # $1 is package name # $2 is destination volume [ "$trace" == "yes" ] && echo "${FUNCNAME[0]} called from ${FUNCNAME[1]}" |& tee -a "$logfile" # Edit /var/packages symlinks case "$appdir" in @appconf) # etc --> @appconf rm "/var/packages/${1:?}/etc" |& tee -a "$logfile" ln -s "${2:?}/@appconf/${1:?}" "/var/packages/${1:?}/etc" |& tee -a "$logfile" # /usr/syno/etc/packages/$1 # /volume1/@appconf/$1 if [[ -L "/usr/syno/etc/packages/${1:?}" ]]; then rm "/usr/syno/etc/packages/${1:?}" |& tee -a "$logfile" ln -s "${2:?}/@appconf/${1:?}" "/usr/syno/etc/packages/${1:?}" |& tee -a "$logfile" fi ;; @apphome) # home --> @apphome rm "/var/packages/${1:?}/home" |& tee -a "$logfile" ln -s "${2:?}/@apphome/${1:?}" "/var/packages/${1:?}/home" |& tee -a "$logfile" ;; @appshare) # share --> @appshare rm "/var/packages/${1:?}/share" |& tee -a "$logfile" ln -s "${2:?}/@appshare/${1:?}" "/var/packages/${1:?}/share" |& tee -a "$logfile" ;; @appstore) # target --> @appstore rm "/var/packages/${1:?}/target" |& tee -a "$logfile" ln -s "${2:?}/@appstore/${1:?}" "/var/packages/${1:?}/target" |& tee -a "$logfile" # DSM 6 - Some packages have var symlink if [[ $majorversion -lt 7 ]]; then if [[ -L "/var/packages/${1:?}/var" ]]; then rm "/var/packages/${1:?}/var" |& tee -a "$logfile" ln -s "${2:?}/@appstore/${1:?}/var" "/var/packages/${1:?}/var" |& tee -a "$logfile" fi fi ;; @apptemp) # tmp --> @apptemp rm "/var/packages/${1:?}/tmp" |& tee -a "$logfile" ln -s "${2:?}/@apptemp/${1:?}" "/var/packages/${1:?}/tmp" |& tee -a "$logfile" ;; @appdata) # var --> @appdata rm "/var/packages/${1:?}/var" |& tee -a "$logfile" ln -s "${2:?}/@appdata/${1:?}" "/var/packages/${1:?}/var" |& tee -a "$logfile" ;; *) echo -e "${Red}Oops!${Off} appdir: ${appdir}\n" echo -e "Oops! appdir: ${appdir}\n" >> "$logfile" return ;; esac } move_pkg(){ # $1 is package name # $2 is destination volume [ "$trace" == "yes" ] && echo "${FUNCNAME[0]} called from ${FUNCNAME[1]}" |& tee -a "$logfile" local appdir local perms local destination local appdirs_tmp local app_paths_tmp if [[ ${mode,,} == "backup" ]]; then destination="$bkpath" elif [[ ${mode,,} == "restore" ]]; then destination="$2" else destination="$2" fi if [[ $majorversion -gt 6 ]]; then applist=( "@appconf" "@appdata" "@apphome" "@appshare" "@appstore" "@apptemp" ) else applist=( "@appstore" ) fi if [[ ${mode,,} == "restore" ]]; then if ! cdir "$bkpath"; then process_error="yes" return 1 fi sourcevol=$(echo "$bkpath" | cut -d "/" -f2) # var is used later in script # shellcheck disable=SC1083 while IFS= read -r appdir; do if [[ "${applist[*]}" =~ "$appdir" ]]; then appdirs_tmp+=("$appdir") fi done < <(find . -name "@app*" -exec basename \{} \;) # Sort array IFS=$'\n' appdirs=($(sort <<<"${appdirs_tmp[*]}")); unset IFS if [[ ${#appdirs[@]} -gt 0 ]]; then for appdir in "${appdirs[@]}"; do create_dir "/${sourcevol:?}/${appdir:?}" "${destination:?}/${appdir:?}" move_pkg_do "$1" "$destination" done fi else if ! cdir /var/packages; then process_error="yes" return 1 fi # shellcheck disable=SC2162 # `read` without `-r` will mangle backslashes while read -r link source; do app_paths_tmp+=("$source") done < <(find . -maxdepth 2 -type l -ls | grep '/'"${1// /\\\\ }"'$' | cut -d'.' -f2- | sed 's/ ->//') # Sort array IFS=$'\n' app_paths=($(sort <<<"${app_paths_tmp[*]}")); unset IFS if [[ ${#app_paths[@]} -gt 0 ]]; then for source in "${app_paths[@]}"; do appdir=$(echo "$source" | cut -d "/" -f3) sourcevol=$(echo "$source" | cut -d "/" -f2) # var is used later in script if [[ "${applist[*]}" =~ "$appdir" ]]; then create_dir "/${sourcevol:?}/${appdir:?}" "${destination:?}/${appdir:?}" move_pkg_do "$1" "$2" if [[ ${mode,,} == "move" ]]; then edit_symlinks "$pkg" "$destination" fi fi done fi fi # Backup or restore DSM 6 /usr/syno/etc/packages/$pkg/ if [[ $majorversion -lt "7" ]]; then copy_dir_dsm6 "$1" "$2" fi } set_buffer(){ # Set buffer GBs so we don't fill volume bufferGB=$(/usr/syno/bin/synogetkeyvalue "$conffile" buffer) if [[ $bufferGB -gt "0" ]]; then buffer=$((bufferGB *1048576)) else buffer=0 fi } folder_size(){ # $1 is folder to check size of [ "$trace" == "yes" ] && echo "${FUNCNAME[0]} called from ${FUNCNAME[1]}" |& tee -a "$logfile" need="" # var is used later in script needed="" # var is used later in script if [[ -d "$1" ]]; then # Get size of $1 folder need=$(/usr/bin/du -s "$1" | awk '{print $1}') if [[ ! $need =~ ^[0-9]+$ ]]; then echo -e "${Yellow}WARNING${Off} Failed to get size of $1" echo -e "WARNING Failed to get size of $1" >> "$logfile" need=0 fi # Add buffer GBs so we don't fill volume set_buffer needed=$((need +buffer)) fi } vol_free_space(){ # $1 is volume to check free space [ "$trace" == "yes" ] && echo "${FUNCNAME[0]} called from ${FUNCNAME[1]}" |& tee -a "$logfile" free="" # var is used later in script if [[ -d "$1" ]]; then # Get amount of free space on $1 volume if [[ $1 =~ ^"/volumeUSB" ]]; then # Issue #63 and #138 tmp_usb="/$(echo "$1" | cut -d"/" -f2)/usbshare" free=$(df --output=avail "$tmp_usb" | grep -A1 Avail | grep -v Avail) else free=$(df --output=avail "$1" | grep -A1 Avail | grep -v Avail) fi fi } need_show(){ if [[ $need -gt "999999" ]]; then size_show="$((need /1048576)) GB" elif [[ $need -gt "999" ]]; then size_show="$((need /1048)) MB" else size_show="$need KB" fi } check_space(){ # $1 is /path/folder # $2 is source volume or target volume # $3 is 'extra' or null [ "$trace" == "yes" ] && echo "${FUNCNAME[0]} called from ${FUNCNAME[1]}" |& tee -a "$logfile" # Skip USBCopy and @database if [[ $pkg == USBCopy ]] || [[ $pkg == "@database" ]]; then return 0 fi if [[ $3 == "extra" ]]; then # Get size of extra @ folder folder_size "$1" else # Total size of pkg or all pkgs need="$all_pkg_size" # Add buffer GBs so we don't fill volume set_buffer needed=$((need +buffer)) fi # Get amount of free space on target volume vol_free_space "$2" # Check we have enough space if [[ ! $free -gt $needed ]]; then if [[ $all == "yes" ]] && [[ $3 != "extra" ]]; then echo -e "${Yellow}WARNING${Off} Not enough space to ${mode,,}"\ "${Cyan}All apps${Off} to $targetvol" echo -e "WARNING Not enough space to ${mode,,}"\ "All apps to $targetvol" >> "$logfile" else echo -e "${Yellow}WARNING${Off} Not enough space to ${mode,,}"\ "/${sourcevol}/${Cyan}$(basename -- "$1")${Off} to $targetvol" echo -e "WARNING Not enough space to ${mode,,}"\ "/${sourcevol}/$(basename -- "$1") to $targetvol" >> "$logfile" fi need_show echo -en "Free: $((free /1048576)) GB Needed: $size_show" |& tee -a "$logfile" if [[ $buffer -gt "0" ]]; then echo -e " (plus $bufferGB GB buffer)\n" |& tee -a "$logfile" else echo -e "\n" |& tee -a "$logfile" fi return 1 else return 0 fi } show_move_share(){ # $1 is package name # $2 is share name # $3 is stopped or running # $4 is more or null [ "$trace" == "yes" ] && echo "${FUNCNAME[0]} called from ${FUNCNAME[1]}" |& tee -a "$logfile" echo -e "\nIf you want to move your $2 shared folder to $targetvol" |& tee -a "$logfile" echo -e " While ${Cyan}$1${Off} is ${Cyan}$3${Off}:" echo -e " While $1 is $3:" >> "$logfile" echo " 1. Go to 'Control Panel > Shared Folders'." |& tee -a "$logfile" echo " 2. Select your $2 shared folder and click Edit." |& tee -a "$logfile" echo " 3. Change Location to $targetvol" |& tee -a "$logfile" echo " 4. Click on Advanced and check that 'Enable data checksums' is selected." |& tee -a "$logfile" echo " - 'Enable data checksums' is only available if moving to a Btrfs volume." |& tee -a "$logfile" echo " 5. Click Save." |& tee -a "$logfile" if [[ $4 == "more" ]]; then echo " - If $1 has more shared folders repeat steps 2 to 5." |& tee -a "$logfile" fi if [[ $3 == "stopped" ]]; then echo -e " 6. After step 5 has finished start $1 \n" |& tee -a "$logfile" fi } copy_dir_dsm6(){ # Backup or restore DSM 6 /usr/syno/etc/packages/$pkg/ [ "$trace" == "yes" ] && echo "${FUNCNAME[0]} called from ${FUNCNAME[1]}" |& tee -a "$logfile" # $1 is package name # $2 is destination volume local pack local packshow local extras pack="/${pkg:?}" packshow="${pkg:?}" if [[ ${mode,,} == "backup" ]]; then if [[ ! -d "${bkpath:?}/etc" ]]; then mkdir -m 700 "${bkpath:?}/etc" fi #if ! is_empty "/usr/syno/etc/packages/${1:?}"; then # If string is too long progbar gets messed up cp -prf "/usr/syno/etc/packages/${1:?}" "${bkpath:?}/etc" |& tee -a "$logfile" & pid=$! string="${action} /usr/syno/etc/packages/${Cyan}${1}${Off}" echo "${action} /usr/syno/etc/packages/${1}" >> "$logfile" progbar "$pid" "$string" wait "$pid" progstatus "$?" "$string" "line ${LINENO}" #fi elif [[ ${mode,,} == "restore" ]]; then #if [[ -d "${bkpath}/$1" ]]; then # If string is too long progbar gets messed up cp -prf "${bkpath:?}/etc/${1:?}" "/usr/syno/etc/packages" |& tee -a "$logfile" & pid=$! string="${action} $1 to /usr/syno/etc/packages" echo "$string" >> "$logfile" progbar "$pid" "$string" wait "$pid" progstatus "$?" "$string" "line ${LINENO}" #fi fi } copy_dir(){ # Used by package backup and restore [ "$trace" == "yes" ] && echo "${FUNCNAME[0]} called from ${FUNCNAME[1]}" |& tee -a "$logfile" # $1 is folder (@surveillance etc) # $2 is "extras" or null local pack local packshow local extras if [[ $2 == "extras" ]]; then #pack="" extras="/extras" else pack="/${pkg:?}" packshow="${pkg:?}" #extras="" fi if [[ ${mode,,} == "backup" ]]; then if [[ $2 == "extras" ]] && [[ ! -d "${bkpath:?}/extras" ]]; then mkdir -m 700 "${bkpath:?}/extras" fi create_dir "/${sourcevol:?}/${1:?}$pack" "${bkpath:?}${extras}/${1:?}" #if ! is_empty "/${sourcevol:?}/${1:?}$pack"; then if [[ $2 == "extras" ]]; then # If string is too long progbar gets messed up #cp -prf "/${sourcevol:?}/${1:?}$pack" "${bkpath:?}${extras}" |& tee -a "$logfile" & if [[ $1 == "@docker" ]]; then excludeargs=( "--exclude=subvolumes/*/tmp/" # btfs Issue #120 "--exclude=subvolumes/*/run/" # btfs Issue #120 "--exclude=aufs/diff/*/run/" # aufs (ext4) Issue #117 "--exclude=subvolumes/*/syslog-ng.ctl" # 0 byte file Issue #186 ) rsync -q -aHX --delete --compress-level=0 "${excludeargs[@]}" "/${sourcevol:?}/${1:?}$pack"/ "${bkpath:?}${extras}/${1:?}" |& tee -a "$logfile" & else rsync -q -aHX --delete --compress-level=0 "/${sourcevol:?}/${1:?}$pack"/ "${bkpath:?}${extras}/${1:?}" |& tee -a "$logfile" & fi pid=$! string="${action} /${sourcevol}/${1}" echo "$string" >> "$logfile" progbar "$pid" "$string" wait "$pid" progstatus "$?" "$string" "line ${LINENO}" else # If string is too long progbar gets messed up #cp -prf "/${sourcevol:?}/${1:?}$pack" "${bkpath:?}${extras}/${1:?}" |& tee -a "$logfile" & rsync -q -aHX --delete --compress-level=0 "/${sourcevol:?}/${1:?}$pack"/ "${bkpath:?}${extras}/${1:?}" |& tee -a "$logfile" & pid=$! string="${action} /${sourcevol}/${1}/${Cyan}$pkg${Off}" echo "${action} /${sourcevol}/${1}/$pkg" >> "$logfile" progbar "$pid" "$string" wait "$pid" progstatus "$?" "$string" "line ${LINENO}" fi #fi elif [[ ${mode,,} == "restore" ]]; then #if [[ -d "${bkpath}/$1" ]]; then # If string is too long progbar gets messed up cp -prf "${bkpath:?}${extras}/${1:?}" "${targetvol:?}" |& tee -a "$logfile" & pid=$! if [[ -n "$extras" ]]; then string="${action} $1 to $targetvol" echo "$string" >> "$logfile" else string="${action} ${1}/${Cyan}$packshow${Off} to $targetvol" echo "${action} ${1}/$packshow to $targetvol" >> "$logfile" fi progbar "$pid" "$string" wait "$pid" progstatus "$?" "$string" "line ${LINENO}" #fi fi } move_dir(){ # $1 is folder (@surveillance etc) # $2 is "extras" or null [ "$trace" == "yes" ] && echo "${FUNCNAME[0]} called from ${FUNCNAME[1]}" |& tee -a "$logfile" # Delete @eaDir to prevent errors # e.g. "mv: cannot remove '/volume1/@<folder>': Operation not permitted" if [[ -d "/${sourcevol:?}/${1:?}/@eaDir" ]]; then rm -rf "/${sourcevol:?}/${1:?}/@eaDir" |& tee -a "$logfile" fi # Warn if folder is larger than 1GB if [[ ! "${applist[*]}" =~ $1 ]]; then folder_size "/${sourcevol:?}/$1" if [[ $need -gt "1048576" ]]; then echo -e "${Red}WARNING $action $1 could take a long time${Off}" echo -e "WARNING $action $1 could take a long time" >> "$logfile" fi fi if [[ -d "/${sourcevol:?}/${1:?}" ]]; then if [[ ${mode,,} == "move" ]]; then if [[ ! -d "/${targetvol:?}/${1:?}" ]]; then if [[ $1 == "@docker" ]] || [[ $1 == "@img_bkp_cache" ]]; then # Create @docker folder on target volume create_dir "/${sourcevol:?}/${1:?}" "${targetvol:?}/${1:?}" # Move contents of @docker to @docker on target volume if [[ -w "/$sourcevol" ]]; then mv -f "/${sourcevol:?}/${1:?}"/* "${targetvol:?}/${1:?}" |& tee -a "$logfile" & else # Source volume is read only cp -prf "/${sourcevol:?}/${1:?}"/* "${targetvol:?}/${1:?}" |& tee -a "$logfile" & fi else if [[ -w "/$sourcevol" ]]; then mv -f "/${sourcevol:?}/${1:?}" "${targetvol:?}/${1:?}" |& tee -a "$logfile" & else # Source volume is read only cp -prf "/${sourcevol:?}/${1:?}" "${targetvol:?}/${1:?}" |& tee -a "$logfile" & fi fi pid=$! string="${action} /${sourcevol}/$1 to ${Cyan}$targetvol${Off}" echo "$string" >> "$logfile" progbar "$pid" "$string" wait "$pid" progstatus "$?" "$string" "line ${LINENO}" elif ! is_empty "/${sourcevol:?}/${1:?}"; then # Copy source contents if target folder exists cp -prf "/${sourcevol:?}/${1:?}" "${targetvol:?}" |& tee -a "$logfile" & pid=$! string="Copying /${sourcevol}/$1 to ${Cyan}$targetvol${Off}" echo "$string" >> "$logfile" progbar "$pid" "$string" wait "$pid" progstatus "$?" "$string" "line ${LINENO}" # Delete source folder if empty # if [[ $1 != "@docker" ]]; then if is_empty "/${sourcevol:?}/${1:?}"; then rm -rf --preserve-root "/${sourcevol:?}/${1:?}" |& tee -a "$logfile" & pid=$! exitonerror="no" string="Removing /${sourcevol}/$1" echo "$string" >> "$logfile" progbar "$pid" "$string" wait "$pid" progstatus "$?" "$string" "line ${LINENO}" fi fi # fi else copy_dir "$1" "$2" fi elif [[ ${mode,,} == "restore" ]]; then # Restore from USB backup if [[ -d "/${bkpath:?}/${1:?}" ]]; then copy_dir "$1" "$2" fi else if [[ ${mode,,} != "restore" ]]; then echo -e "No /${sourcevol}/$1 to ${mode,,}" |& tee -a "$logfile" else echo -e "No ${bkpath}/$1 to ${mode,,}" |& tee -a "$logfile" fi fi } move_extras(){ # $1 is package name # $2 is destination /volume [ "$trace" == "yes" ] && echo "${FUNCNAME[0]} called from ${FUNCNAME[1]}" |& tee -a "$logfile" local file local value # Change /volume1 to /volume2 etc case "$1" in ActiveBackup) exitonerror="no" && move_dir "@ActiveBackup" extras # /var/packages/ActiveBackup/target/log/ if [[ ${mode,,} != "backup" ]]; then if ! readlink /var/packages/ActiveBackup/target/log | grep "${2:?}" >/dev/null; then rm /var/packages/ActiveBackup/target/log |& tee -a "$logfile" ln -s "${2:?}/@ActiveBackup/log" /var/packages/ActiveBackup/target/log |& tee -a "$logfile" fi file=/var/packages/ActiveBackup/target/etc/setting.conf if [[ -f "$file" ]]; then echo "{\"conf_repo_volume_path\":\"$2\"}" > "$file" fi fi ;; ActiveBackup-GSuite) exitonerror="no" && move_dir "@ActiveBackup-GSuite" extras ;; ActiveBackup-Office365) exitonerror="no" && move_dir "@ActiveBackup-Office365" extras ;; AntiVirus) exitonerror="no" && move_dir "@quarantine" extras if [[ -d "$sourcevol/.quarantine" ]]; then mv -f "$sourcevol/.quarantine" "${2:?}/}" |& tee -a "$logfile" & fi ;; Chat) if [[ ${mode,,} == "move" ]]; then echo -e "Are you going to move the ${Cyan}chat${Off} shared folder to ${Cyan}${targetvol}${Off}? [y/n]" echo -e "Are you going to move the chat shared folder to ${targetvol}? [y/n]" >> "$logfile" read -r answer echo "$answer" >> "$logfile" echo "" |& tee -a "$logfile" if [[ ${answer,,} == y ]]; then # /var/packages/Chat/shares/chat --> /volume1/chat rm "/var/packages/${1:?}/shares/chat" |& tee -a "$logfile" ln -s "${2:?}/chat" "/var/packages/${1:?}shares/chat" |& tee -a "$logfile" # /var/packages/Chat/target/synochat --> /volume1/chat/@ChatWorking rm "/var/packages/${1:?}/target/synochat" |& tee -a "$logfile" ln -s "${2:?}/chat/@ChatWorking" "/var/packages/${1:?}target/synochat" |& tee -a "$logfile" fi fi ;; Calendar) exitonerror="no" && move_dir "@calendar" extras if [[ -d "/@synocalendar" ]]; then exitonerror="no" && move_dir "$sourcevol/@synocalendar" extras fi file="/var/packages/Calendar/etc/share_link.json" if [[ -f "$file" ]]; then if grep "$sourcevol/@calendar/attach" "$file" >/dev/null; then instring="/$sourcevol/@calendar/attach" repstring="$2/@calendar/attach" sed -i 's|'"$instring"'|'"$repstring"'|g' "$file" |& tee -a "$logfile" chmod 600 "$file" |& tee -a "$logfile" fi fi ;; ContainerManager|Docker) # /var/services/web_packages/docker ??? # Edit symlink before moving @docker # If edit after it does not get edited if move @docker errors if [[ ${mode,,} != "backup" ]]; then if [[ $majorversion -gt "6" ]]; then # /var/packages/ContainerManager/var/docker/ --> /volume1/@docker # /var/packages/Docker/var/docker/ --> /volume1/@docker if [[ -L "/var/packages/${pkg:?}/var/docker" ]]; then rm "/var/packages/${pkg:?}/var/docker" |& tee -a "$logfile" fi ln -s "${2:?}/@docker" "/var/packages/${pkg:?}/var/docker" |& tee -a "$logfile" else # /var/packages/Docker/target/docker/ --> /volume1/@docker if [[ -L "/var/packages/${pkg:?}/target/docker" ]]; then rm "/var/packages/${pkg:?}/target/docker" |& tee -a "$logfile" fi ln -s "${2:?}/@docker" "/var/packages/${pkg:?}/target/docker" |& tee -a "$logfile" fi fi exitonerror="no" && move_dir "@docker" extras ;; DownloadStation) exitonerror="no" && move_dir "@download" extras ;; GlacierBackup) exitonerror="no" && move_dir "@GlacierBackup" extras if [[ ${mode,,} != "backup" ]]; then file=/var/packages/GlacierBackup/etc/common.conf if [[ -f "$file" ]]; then echo "cache_volume=$2" > "$file" fi fi ;; HyperBackup) # Most of this section is not needed for moving HyperBackup. # I left it here in case I can use it for some other package in future. # Moving "@img_bkp_cache" and editing synobackup.conf # to point the repos to the new location causes backup tasks # to show as offline with no way to fix them or delete them! # # Thankfully HyperBackup recreates the data in @img_bkp_cache # when the backup task is run, or a resync is done. # file=/var/packages/HyperBackup/etc/synobackup.conf # [repo_1] # client_cache="/volume1/@img_bkp_cache/ClientCache_image_image_local.oJCDvd" # if [[ -f "$file" ]]; then # Get list of [repo_#] in $file # readarray -t contents < "$file" # for r in "${contents[@]}"; do # l=$(echo "$r" | grep -E "repo_[0-9]+") # if [[ -n "$l" ]]; then # l="${l/]/}" && l="${l/[/}" # repos+=("$l") # fi # done # Edit values with sourcevol to targetvol # for section in "${repos[@]}"; do # value="$(/usr/syno/bin/get_section_key_value "$file" "$section" client_cache)" # #echo "$value" # debug # if echo "$value" | grep "$sourcevol" >/dev/null; then # newvalue="${value/$sourcevol/$targetvol}" #echo "$newvalue" # debug #echo "" # debug # /usr/syno/bin/set_section_key_value "$file" "$section" client_cache "$newvalue" #echo "set_section_key_value $file $section client_cache $newvalue" # debug #echo "" # debug #echo "" # debug # fi # done # fi # Move @img_bkp folders #if [[ -d "/${sourcevol}/@img_bkp_cache" ]] ||\ # [[ -d "/${sourcevol}/@img_bkp_mount" ]]; then # backup_dir "@img_bkp_cache" "$sourcevol" # backup_dir "@img_bkp_mount" "$sourcevol" # exitonerror="no" && move_dir "@img_bkp_cache" # exitonerror="no" && move_dir "@img_bkp_mount" #fi if [[ -d "/${sourcevol}/@img_bkp_cache" ]]; then #backup_dir "@img_bkp_cache" "$sourcevol" exitonerror="no" && move_dir "@img_bkp_cache" extras fi ;; jellyfin) if [[ ${mode,,} != "backup" ]]; then file=/var/packages/jellyfin/var/config/system.xml # Issue #171 if [[ -f "$file" ]]; then sed -i 's|'"/$sourcevol/@appdata"'|'"${2:?}/@appdata"'|g' "$file" fi fi ;; MailPlus-Server) # Moving MailPlus-Server does not update # /var/packages/MailPlus-Server/etc/synopkg_conf/reg_volume # I'm not sure if it matters? if [[ ${mode,,} != "backup" ]]; then # Edit symlink /var/spool/@MailPlus-Server -> /volume1/@MailPlus-Server if ! readlink /var/spool/@MailPlus-Server | grep "${2:?}" >/dev/null; then rm /var/spool/@MailPlus-Server |& tee -a "$logfile" ln -s "${2:?}/@MailPlus-Server" /var/spool/@MailPlus-Server |& tee -a "$logfile" chown -h MailPlus-Server:MailPlus-Server /var/spool/@MailPlus-Server |& tee -a "$logfile" fi # Edit logfile /volume1/@maillog/rspamd_redis.log # in /volume2/@MailPlus-Server/rspamd/redis/redis.conf file="/$sourcevol/@MailPlus-Server/rspamd/redis/redis.conf" if [[ -f "$file" ]]; then if grep "$sourcevol" "$file" >/dev/null; then sed -i 's|'"logfile /$sourcevol"'|'"logfile ${2:?}"'|g' "$file" |& tee -a "$logfile" chmod 600 "$file" |& tee -a "$logfile" fi fi fi exitonerror="no" && move_dir "@maillog" extras exitonerror="no" && move_dir "@MailPlus-Server" extras ;; MailServer) exitonerror="no" && move_dir "@maillog" extras exitonerror="no" && move_dir "@MailScanner" extras exitonerror="no" && move_dir "@clamav" extras ;; Node.js_v*) if [[ ${mode,,} != "backup" ]]; then if readlink /usr/local/bin/node | grep "${1:?}" >/dev/null; then rm /usr/local/bin/node |& tee -a "$logfile" ln -s "${2:?}/@appstore/${1:?}/usr/local/bin/node" /usr/local/bin/node |& tee -a "$logfile" fi for n in /usr/local/node/nvm/versions/* ; do if readlink "${n:?}/bin/node" | grep "${1:?}" >/dev/null; then rm "${n:?}/bin/node" |& tee -a "$logfile" ln -s "${2:?}/@appstore/${1:?}/usr/local/bin/node" "${n:?}/bin/node" |& tee -a "$logfile" fi done fi ;; PrestoServer) exitonerror="no" && move_dir "@presto" extras if [[ ${mode,,} != "backup" ]]; then file=/var/packages/PrestoServer/etc/db-path.conf if [[ -f "$file" ]]; then echo "db-vol=${2:?}" > "$file" fi fi ;; SurveillanceStation) exitonerror="no" && move_dir "@ssbackup" extras exitonerror="no" && move_dir "@surveillance" extras if [[ ${mode,,} != "backup" ]]; then file=/var/packages/SurveillanceStation/etc/settings.conf if [[ -f "$file" ]]; then /usr/syno/bin/synosetkeyvalue "$file" active_volume "${2:?}" |& tee -a "$logfile" file=/var/packages/SurveillanceStation/target/@surveillance rm "$file" |& tee -a "$logfile" ln -s "${2:?}/@surveillance" /var/packages/SurveillanceStation/target |& tee -a "$logfile" chown -h SurveillanceStation:SurveillanceStation "$file" |& tee -a "$logfile" fi fi ;; synocli*) #exitonerror="no" && move_dir "@$1" ;; SynologyApplicationService) exitonerror="no" && move_dir "@SynologyApplicationService" extras if [[ ${mode,,} != "backup" ]]; then file=/var/packages/SynologyApplicationService/etc/settings.conf if [[ -f "$file" ]]; then /usr/syno/bin/synosetkeyvalue "$file" volume "${2:?}/@SynologyApplicationService" |& tee -a "$logfile" fi fi ;; SynologyDrive) # Synology Drive database # Moving the database in Synology Drive Admin moves @synologydrive #exitonerror="no" && move_dir "@synologydrive" extras # Synology Drive ShareSync Folder exitonerror="no" && move_dir "@SynologyDriveShareSync" extras if [[ ${mode,,} != "backup" ]]; then file=/var/packages/SynologyDrive/etc/sharesync/daemon.conf if [[ -f "$file" ]]; then sed -i 's|'/"$sourcevol"'|'"${2:?}"'|g' "$file" |& tee -a "$logfile" chmod 644 "$file" |& tee -a "$logfile" fi file=/var/packages/SynologyDrive/etc/sharesync/monitor.conf if [[ -f "$file" ]]; then value="$(synogetkeyvalue "$file" system_db_path)" if [[ -n $value ]]; then /usr/syno/bin/synosetkeyvalue "$file" system_db_path "${value/${sourcevol}/$(basename "${2:?}")}" |& tee -a "$logfile" fi fi file=/var/packages/SynologyDrive/etc/sharesync/service.conf if [[ -f "$file" ]]; then /usr/syno/bin/synosetkeyvalue "$file" volume "${2:?}" |& tee -a "$logfile" fi # Moving the database in Synology Drive Admin changes # the repo symlink and the db-vol setting # in /var/packages/SynologyDrive/etc/db-path.conf #if ! readlink /var/packages/SynologyDrive/etc/repo | grep "${2:?}" >/dev/null; then # rm /var/packages/SynologyDrive/etc/repo |& tee -a "$logfile" # ln -s "${2:?}/@synologydrive/@sync" /var/packages/SynologyDrive/etc/repo |& tee -a "$logfile" #fi fi ;; WebDAVServer) exitonerror="no" && move_dir "@webdav" extras ;; Virtualization) exitonerror="no" && move_dir "@GuestImage" extras exitonerror="no" && move_dir "@Repository" extras # Move Virtual Machines - target must be btrfs #exitonerror="no" && move_dir "@iSCSI" extras # VMM creates /volume#/vdsm_repo.conf so no need to move it ;; *) return ;; esac } web_packages(){ # $1 is pkg in lower case [ "$trace" == "yes" ] && echo "${FUNCNAME[0]} called from ${FUNCNAME[1]}" |& tee -a "$logfile" if [[ $buildnumber -gt "64570" ]]; then # DSM 7.2.1 and later # synoshare --get-real-path is case insensitive web_pkg_path=$(/usr/syno/sbin/synoshare --get-real-path web_packages) else # DSM 7.2 and earlier # synoshare --getmap is case insensitive web_pkg_path=$(/usr/syno/sbin/synoshare --getmap web_packages | grep volume | cut -d"[" -f2 | cut -d"]" -f1) # I could also have used: # web_pkg_path=$(/usr/syno/sbin/synoshare --get web_packages | tr '[]' '\n' | sed -n "9p") fi if [[ -d "$web_pkg_path" ]]; then if [[ -n "${pkg:?}" ]] && [[ -d "$web_pkg_path/${pkg,,}" ]]; then if [[ ${mode,,} == "backup" ]]; then if [[ ! -d "${bkpath}/web_packages" ]]; then mkdir -m 755 "${bkpath:?}/web_packages" fi if [[ -d "${bkpath}/web_packages" ]]; then # If string is too long progbar gets messed up cp -prf "${web_pkg_path:?}/${1:?}" "${bkpath:?}/web_packages" |& tee -a "$logfile" & pid=$! string="${action} $web_pkg_path/${pkg,,}" echo "$string" >> "$logfile" progbar "$pid" "$string" wait "$pid" progstatus "$?" "$string" "line ${LINENO}" else ding echo -e "Line ${LINENO}: ${Error}ERROR${Off} Failed to create directory!" echo -e "Line ${LINENO}: ERROR Failed to create directory!" >> "$logfile" echo -e " ${bkpath:?}/web_packages\n" |& tee -a "$logfile" fi elif [[ ${mode,,} == "restore" ]]; then if [[ -d "${bkpath}/web_packages/${1}" ]]; then # If string is too long progbar gets messed up cp -prf "${bkpath:?}/web_packages/${1:?}" "${web_pkg_path:?}" |& tee -a "$logfile" & pid=$! string="${action} $web_pkg_path/${pkg,,}" echo "$string" >> "$logfile" progbar "$pid" "$string" wait "$pid" progstatus "$?" "$string" "line ${LINENO}" fi fi fi fi } check_pkg_installed(){ # Check if package is installed [ "$trace" == "yes" ] && echo "${FUNCNAME[0]} called from ${FUNCNAME[1]}" |& tee -a "$logfile" # $1 is package # $2 is package name /usr/syno/bin/synopkg status "${1:?}" >/dev/null code="$?" if [[ $code == "255" ]] || [[ $code == "4" ]]; then ding echo -e "${Error}ERROR${Off} ${Cyan}${2}${Off} is not installed!" echo -e "ERROR ${2} is not installed!" >> "$logfile" echo -e "Install ${Cyan}${2}${Off} then try Restore again" echo -e "Install ${2} then try Restore again" >> "$logfile" process_error="yes" if [[ $all != "yes" ]]; then exit 1 # Skip exit if mode is All fi return 1 else return 0 fi } check_pkg_versions_match(){ # $1 is installed package version # $2 is backed up package version [ "$trace" == "yes" ] && echo "${FUNCNAME[0]} called from ${FUNCNAME[1]}" |& tee -a "$logfile" if [[ $1 != "$2" ]]; then ding echo -e "${Yellow}Backup and installed package versions don't match!${Off}" echo -e "Backup and installed package versions don't match!" >> "$logfile" echo " Backed up version: $2" |& tee -a "$logfile" echo " Installed version: $1" |& tee -a "$logfile" echo "Do you want to continue restoring ${pkg_name}? [y/n]" |& tee -a "$logfile" read -r reply if [[ ${reply,,} != "y" ]]; then exit # Answered no else echo "" |& tee -a "$logfile" fi fi } skip_dev_tools(){ # $1 is $pkg [ "$trace" == "yes" ] && echo "${FUNCNAME[0]} called from ${FUNCNAME[1]}" |& tee -a "$logfile" local skip1 local skip2 if [[ ${mode,,} == "backup" ]]; then skip1="$(/usr/syno/bin/synogetkeyvalue "/var/packages/${package}/INFO" startable)" skip2="$(/usr/syno/bin/synogetkeyvalue "/var/packages/${package}/INFO" ctl_stop)" elif [[ ${mode,,} == "restore" ]]; then skip1="$(/usr/syno/bin/synogetkeyvalue "${backuppath}/syno_app_mover/${package}/INFO" startable)" skip2="$(/usr/syno/bin/synogetkeyvalue "${backuppath}/syno_app_mover/${package}/INFO" ctl_stop)" fi if [[ $skip1 == "no" ]] || [[ $skip2 == "no" ]]; then return 0 else return 1 fi } prune_dangling(){ if [[ $pkg == "ContainerManager" ]] || [[ $pkg == "Docker" ]]; then if [[ -w "/$sourcevol" ]]; then # Start package if needed so we can prune images if ! package_is_running "$pkg"; then package_start "$pkg" "$pkg_name" fi if [[ ${mode,,} == "restore" ]]; then # Remove dangling and unused images echo "Removing dangling and unused docker images" |& tee -a "$logfile" docker image prune --all --force >/dev/null else # Remove dangling images echo "Removing dangling docker images" |& tee -a "$logfile" docker image prune --force >/dev/null fi else # Skip read only source volume echo "/$sourcevol is read only. Skipping:" |& tee -a "$logfile" echo " - Removing dangling and unused docker images" |& tee -a "$logfile" fi fi } check_pkg_size(){ # $1 is package name # $2 is package source volume [ "$trace" == "yes" ] && echo "${FUNCNAME[0]} called from ${FUNCNAME[1]}" |& tee -a "$logfile" if [[ $pkg == "@database" ]]; then size=$(/usr/bin/du -s /var/services/pgsql/ | awk '{print $1}') else #size=$(/usr/bin/du -sL /var/packages/"$1"/target | awk '{print $1}') size=$(/usr/bin/du -s /var/packages/"$1"/target/ | awk '{print $1}') case "$1" in ActiveBackup) if [[ -d "/$sourcevol/@ActiveBackup" ]]; then size2=$(/usr/bin/du -s /"$sourcevol"/@ActiveBackup | awk '{print $1}') size=$((size +"$size2")) fi ;; ActiveBackup-GSuite) if [[ -d "/$sourcevol/@ActiveBackup-GSuite" ]]; then size2=$(/usr/bin/du -s /"$sourcevol"/@ActiveBackup-GSuite | awk '{print $1}') size=$((size +"$size2")) fi ;; ActiveBackup-Office365) if [[ -d "/$sourcevol/@ActiveBackup-Office365" ]]; then size2=$(/usr/bin/du -s /"$sourcevol"/@ActiveBackup-Office365 | awk '{print $1}') size=$((size +"$size2")) fi ;; Calendar) if [[ -d "/$sourcevol/@calendar" ]]; then size2=$(/usr/bin/du -s /"$sourcevol"/@calendar | awk '{print $1}') size=$((size +"$size2")) fi ;; ContainerManager|Docker) prune_dangling # Prune dangling docker images if [[ -d "/$sourcevol/@docker" ]]; then size2=$(/usr/bin/du -s /"$sourcevol"/@docker | awk '{print $1}') size=$((size +"$size2")) fi ;; DownloadStation) if [[ -d "/$sourcevol/@download" ]]; then size2=$(/usr/bin/du -s /"$sourcevol"/@download | awk '{print $1}') size=$((size +"$size2")) fi ;; GlacierBackup) if [[ -d "/$sourcevol/@GlacierBackup" ]]; then size2=$(/usr/bin/du -s /"$sourcevol"/@GlacierBackup | awk '{print $1}') size=$((size +"$size2")) fi ;; HyperBackup) if [[ -d "/$sourcevol/@img_bkp_cache" ]]; then size2=$(/usr/bin/du -s /"$sourcevol"/@img_bkp_cache | awk '{print $1}') size=$((size +"$size2")) fi ;; MailPlus-Server) if [[ -d "/$sourcevol/@maillog" ]]; then size2=$(/usr/bin/du -s /"$sourcevol"/@maillog | awk '{print $1}') size=$((size +"$size2")) fi if [[ -d "/$sourcevol/@MailPlus-Server" ]]; then size2=$(/usr/bin/du -s /"$sourcevol"/@MailPlus-Server | awk '{print $1}') size=$((size +"$size2")) fi ;; MailServer) if [[ -d "/$sourcevol/@maillog" ]]; then size2=$(/usr/bin/du -s /"$sourcevol"/@maillog | awk '{print $1}') size=$((size +"$size2")) fi if [[ -d "/$sourcevol/@MailScanner" ]]; then size2=$(/usr/bin/du -s /"$sourcevol"/@MailScanner | awk '{print $1}') size=$((size +"$size2")) fi if [[ -d "/$sourcevol/@clamav" ]]; then size2=$(/usr/bin/du -s /"$sourcevol"/@clamav | awk '{print $1}') size=$((size +"$size2")) fi ;; PrestoServer) if [[ -d "/$sourcevol/@presto" ]]; then size2=$(/usr/bin/du -s /"$sourcevol"/@presto | awk '{print $1}') size=$((size +"$size2")) fi ;; SurveillanceStation) if [[ -d "/$sourcevol/@ssbackup" ]]; then size2=$(/usr/bin/du -s /"$sourcevol"/@ssbackup | awk '{print $1}') size=$((size +"$size2")) fi if [[ -d "/$sourcevol/@surveillance" ]]; then size2=$(/usr/bin/du -s /"$sourcevol"/@surveillance | awk '{print $1}') size=$((size +"$size2")) fi ;; SynologyApplicationService) if [[ -d "/$sourcevol/@SynologyApplicationService" ]]; then size2=$(/usr/bin/du -s /"$sourcevol"/@SynologyApplicationService | awk '{print $1}') size=$((size +"$size2")) fi ;; SynologyDrive) # Moving the database in Synology Drive Admin moves @synologydrive #if [[ -d "/$sourcevol/@synologydrive" ]]; then # size2=$(/usr/bin/du -s /"$sourcevol"/@synologydrive | awk '{print $1}') # size=$((size +"$size2")) #fi if [[ -d "/$sourcevol/@SynologyDriveShareSync" ]]; then size2=$(/usr/bin/du -s /"$sourcevol"/@SynologyDriveShareSync | awk '{print $1}') size=$((size +"$size2")) fi ;; WebDAVServer) if [[ -d "/$sourcevol/@webdav" ]]; then size2=$(/usr/bin/du -s /"$sourcevol"/@webdav | awk '{print $1}') size=$((size +"$size2")) fi ;; Virtualization) if [[ -d "/$sourcevol/@GuestImage" ]]; then size2=$(/usr/bin/du -s /"$sourcevol"/@GuestImage | awk '{print $1}') size=$((size +"$size2")) fi if [[ -d "/$sourcevol/@Repository" ]]; then size2=$(/usr/bin/du -s /"$sourcevol"/@Repository | awk '{print $1}') size=$((size +"$size2")) fi ;; *) total_size="$size" return ;; esac fi total_size="$size" } source_fs(){ # $1 is $sourcevol sourcefs="$(df --print-type "/${1:?}" | tail -n +2 | awk '{print $2}')" } target_fs(){ # $1 is $targetvol targetfs="$(df --print-type "/${1:?}" | tail -n +2 | awk '{print $2}')" } #------------------------------------------------------------------------------ # Select mode echo "" |& tee -a "$logfile" if [[ $auto == "yes" ]]; then echo -e "Using auto ${Cyan}${mode}${Off} mode\n" echo -e "Using auto $mode mode\n" >> tee -a "$logfile" else modes=( "Move" "Backup" "Restore" ) x="1" for m in "${modes[@]}"; do echo "$x) $m" >> "$logfile" x=$((x +1)) done echo "Select the mode " >> "$logfile" PS3="Select the mode: " select m in "${modes[@]}"; do case "$m" in Move) mode="Move" action="Moving" break ;; Backup) mode="Backup" action="Backing up" break ;; Restore) mode="Restore" action="Restoring" break ;; *) echo "Invalid choice!" |& tee -a "$logfile" ;; esac done echo -e "You selected ${Cyan}${mode}${Off}\n" echo -e "You selected ${mode}\n" >> "$logfile" fi # Check backup path if mode is backup or restore if [[ ${mode,,} != "move" ]]; then if [[ ! -f "$conffile" ]]; then ding echo -e "Line ${LINENO}: ${Error}ERROR${Off} $conffile not found!" echo -e "Line ${LINENO}: ERROR $conffile not found!" >> "$logfile" exit 1 # Conf file not found fi if [[ ! -r "$conffile" ]]; then ding echo -e "Line ${LINENO}: ${Error}ERROR${Off} $conffile not readable!" echo -e "Line ${LINENO}: ERROR $conffile not readable!" >> "$logfile" exit 1 # Conf file not readable fi # Get and validate backup path backuppath="$(/usr/syno/bin/synogetkeyvalue "$conffile" backuppath)" if [[ -z "$backuppath" ]]; then ding echo -e "Line ${LINENO}: ${Error}ERROR${Off} backuppath missing from ${conffile}!" echo -e "Line ${LINENO}: ERROR backuppath missing from ${conffile}!" >> "$logfile" exit 1 # Backup path missing in conf file elif [[ ! -d "$backuppath" ]]; then ding echo -e "Line ${LINENO}: ${Error}ERROR${Off} Backup folder ${Cyan}$backuppath${Off} not found!" echo -e "Line ${LINENO}: ERROR Backup folder $backuppath not found!" >> "$logfile" exit 1 # Backup folder not found fi # Get list of excluded packages exclude="$(/usr/syno/bin/synogetkeyvalue "$conffile" exclude)" if [[ $exclude ]]; then IFS=',' read -r -a excludes <<< "$exclude"; unset IFS # Trim leading and trailing spaces for i in "${excludes[@]}"; do excludelist+=($(echo -n "$i" | xargs)) done fi # Get age of container settings exports to delete delete_older="$(/usr/syno/bin/synogetkeyvalue "$conffile" delete_older)" # Get list of ignored containers ignored_containers="$(/usr/syno/bin/synogetkeyvalue "$conffile" ignored_containers)" if [[ $ignored_containers ]]; then IFS=',' read -r -a ignoreds <<< "$ignored_containers"; unset IFS # Trim leading and trailing spaces for i in "${ignoreds[@]}"; do ignored_containers_list+=($(echo -n "$i" | xargs)) done fi fi if [[ ${mode,,} == "backup" ]]; then echo -e "Backup path is: ${Cyan}${backuppath}${Off}\n" echo -e "Backup path is: ${backuppath}\n" >> "$logfile" elif [[ ${mode,,} == "restore" ]]; then echo -e "Restore from path is: ${Cyan}${backuppath}${Off}\n" echo -e "Restore from path is: ${backuppath}\n" >> "$logfile" fi # Check USB backup path file system is ext3, ext4 or btrfs if mode is backup backupvol="$(echo "$backuppath" | cut -d"/" -f2)" if [[ $backupvol =~ volumeUSB[1-9] ]]; then filesys="$(mount | grep "/${backupvol:?}/usbshare " | awk '{print $5}')" if [[ ! $filesys =~ ^ext[3-4]$ ]] && [[ ! $filesys =~ ^btrfs$ ]]; then ding echo -e "${Yellow}WARNING${Off} Only backup to ext3, ext4 or btrfs USB partition!" echo -e "WARNING Only backup to ext3, ext4 or btrfs USB partition!" >> "$logfile" exit 1 # USB volume is not ext3, ext4 of btrfs fi fi #------------------------------------------------------------------------------ # Select package declare -A package_names declare -A package_names_rev package_infos=( ) if [[ ${mode,,} != "restore" ]]; then if [[ $auto == "yes" ]] && [[ $all != "yes" ]]; then # Add auto packages to array for package in "${autolist[@]}"; do package_name="$(/usr/syno/bin/synogetkeyvalue "/var/packages/${package}/INFO" displayname)" if [[ -z "$package_name" ]]; then package_name="$(/usr/syno/bin/synogetkeyvalue "/var/packages/${package}/INFO" package)" fi # Skip packages that are dev tools with no data if ! skip_dev_tools "$package"; then #package_infos+=("${package_name}") package_names["${package_name}"]="${package}" package_names_rev["${package}"]="${package_name}" else echo -e "Skipping non-stoppable app: $package_name" |& tee -a "$logfile" skip_echo="yes" fi done # Show skipped system apps if [[ ${#skipped[*]} -gt "0" ]]; then echo -e "Skipping system app(s): ${skipped[*]}" |& tee -a "$logfile" skip_echo="yes" fi if [[ $skip_echo == "yes" ]]; then echo "" |& tee -a "$logfile" fi else # Add non-system packages to array cdir /var/packages || exit while IFS= read -r -d '' link && IFS= read -r -d '' target; do if [[ ${link##*/} == "target" ]] && echo "$target" | grep -q 'volume'; then # Check symlink target exists if [[ -a "/var/packages${link#.}" ]] ; then # Skip broken packages with no INFO file package="$(printf %s "$link" | cut -d'/' -f2 )" if [[ -f "/var/packages/${package}/INFO" ]]; then package_volume="$(printf %s "$target" | cut -d'/' -f1,2 )" package_name="$(/usr/syno/bin/synogetkeyvalue "/var/packages/${package}/INFO" displayname)" if [[ -z "$package_name" ]]; then package_name="$(/usr/syno/bin/synogetkeyvalue "/var/packages/${package}/INFO" package)" fi # Skip packages that are dev tools with no data if ! skip_dev_tools "$package"; then package_infos+=("${package_volume}|${package_name}") package_names["${package_name}"]="${package}" package_names_rev["${package}"]="${package_name}" fi fi fi fi done < <(find . -maxdepth 2 -type l -printf '%p\0%l\0') fi elif [[ ${mode,,} == "restore" ]]; then # Add list of backed up packages to array cdir "${backuppath}/syno_app_mover" || exit for package in *; do if [[ -d "$package" ]] && [[ $package != "@eaDir" ]]; then if [[ ${package:0:1} != "-" ]]; then package_name="$(/usr/syno/bin/synogetkeyvalue "${backuppath}/syno_app_mover/${package}/INFO" displayname)" if [[ -z "$package_name" ]]; then package_name="$(/usr/syno/bin/synogetkeyvalue "${backuppath}/syno_app_mover/${package}/INFO" package)" fi # Skip packages that are dev tools with no data if ! skip_dev_tools "$package"; then package_infos+=("${package_name}") package_names["${package_name}"]="${package}" package_names_rev["${package}"]="${package_name}" fi fi fi done < <(find . -maxdepth 2 -type d) fi # Add USB Copy if installed (so we can show how to move USB Copy's database) if [[ ${mode,,} == "move" ]]; then package_status USBCopy >/dev/null code="$?" if [[ $code -lt "2" ]]; then package_names["USB Copy"]="USBCopy" package_names_rev["USBCopy"]="USB Copy" file="/var/packages/USBCopy/etc/setting.conf" package_volume=$(synogetkeyvalue "$file" repo_vol_path) usbcopy_vol="$package_volume" if [[ ${mode,,} != "restore" ]]; then package_infos+=("${package_volume}|USB Copy") elif [[ ${mode,,} == "restore" ]]; then package_infos+=("USB Copy") fi fi fi # Add @database if Move selected if [[ ${mode,,} == "move" ]]; then package_names["@database"]="@database" package_names_rev["@database"]="@database" package_volume="/$(readlink "/var/services/pgsql" | cut -d"/" -f2)" database_vol="$package_volume" if [[ ${mode,,} != "restore" ]]; then package_infos+=("${package_volume}|@database") elif [[ ${mode,,} == "restore" ]]; then package_infos+=("@database") fi fi # Sort array IFS=$'\n' package_infos_sorted=($(sort <<<"${package_infos[*]}")); unset IFS if [[ $auto != "yes" ]]; then # Offer to backup or restore all packages if [[ ${mode,,} == "backup" ]]; then echo -e "Do you want to backup ${Cyan}All${Off} packages? [y/n]" echo -e "Do you want to backup All packages? [y/n]" >> "$logfile" read -r answer echo "$answer" >> "$logfile" #echo "" |& tee -a "$logfile" if [[ ${answer,,} == "y" ]]; then all="yes" echo -e "You selected ${Cyan}All${Off}\n" echo -e "You selected All\n" >> "$logfile" fi elif [[ ${mode,,} == "restore" ]]; then echo -e "Do you want to restore ${Cyan}All${Off} backed up packages? [y/n]" echo -e "Do you want to restore All backed up packages? [y/n]" >> "$logfile" read -r answer #echo "" |& tee -a "$logfile" if [[ ${answer,,} == "y" ]]; then all="yes" echo -e "You selected ${Cyan}All${Off}\n" echo -e "You selected All\n" >> "$logfile" fi fi if [[ $all != "yes" ]]; then if [[ ${mode,,} != "restore" ]]; then # Select package to move or backup if [[ ${#package_infos_sorted[@]} -gt 0 ]]; then echo -e "[Installed package list]" |& tee -a "$logfile" for ((i=1; i<=${#package_infos_sorted[@]}; i++)); do info="${package_infos_sorted[i-1]}" before_pipe="${info%%|*}" after_pipe="${info#*|}" package_infos_show+=("$before_pipe $after_pipe") done fi if [[ ${#package_infos_show[@]} -gt 0 ]]; then x="1" for m in "${package_infos_show[@]}"; do echo "$x) $m" >> "$logfile" x=$((x +1)) done echo "Select the package to ${mode,,} " >> "$logfile" PS3="Select the package to ${mode,,}: " select m in "${package_infos_show[@]}"; do case "$m" in /volume*) # Parse selected element of array package_volume="$(echo "$m" | awk '{print $1}')" pkg_name=${m#"$package_volume "} pkg="${package_names[${pkg_name}]}" break ;; *) echo "Invalid choice! $m" |& tee -a "$logfile" ;; esac done else echo "No movable packages found!" |& tee -a "$logfile" exit 1 fi echo -e "You selected ${Cyan}${pkg_name}${Off} in ${Cyan}${package_volume}${Off}\n" echo -e "You selected ${pkg_name} in ${package_volume}\n" >> "$logfile" if [[ ${pkg_name} == "USB Copy" ]]; then linktargetvol="$usbcopy_vol" elif [[ ${pkg_name} == "@database" ]]; then linktargetvol="$database_vol" else target=$(readlink "/var/packages/${pkg}/target") linktargetvol="/$(printf %s "${target:?}" | cut -d'/' -f2 )" fi elif [[ ${mode,,} == "restore" ]]; then # Select package to backup # Select package to restore if [[ ${#package_infos_sorted[@]} -gt 0 ]]; then echo -e "[Restorable package list]" |& tee -a "$logfile" x="1" for p in "${package_infos_sorted[@]}"; do echo "$x) $p" >> "$logfile" x=$((x +1)) done echo "Select the package to restore " >> "$logfile" PS3="Select the package to restore: " select pkg_name in "${package_infos_sorted[@]}"; do if [[ $pkg_name ]]; then pkg="${package_names[${pkg_name}]}" if [[ -d $pkg ]]; then echo -e "You selected ${Cyan}${pkg_name}${Off}\n" echo -e "You selected ${pkg_name}\n" >> "$logfile" break else ding echo -e "Line ${LINENO}: ${Error}ERROR${Off} $pkg_name not found!" echo -e "Line ${LINENO}: ERROR $pkg_name not found!" >> "$logfile" exit 1 # Selected package not found fi else echo "Invalid choice!" |& tee -a "$logfile" fi done # Check if package is installed check_pkg_installed "$pkg" "$pkg_name" else ding echo -e "Line ${LINENO}: ${Error}ERROR${Off} No package backups found!" echo -e "Line ${LINENO}: ERROR No package backups found!" >> "$logfile" exit 1 # No package backups found fi fi fi fi # Assign just the selected package to array if [[ $all != "yes" ]] && [[ $auto != "yes" ]]; then unset package_names declare -A package_names package_names["${pkg_name:?}"]="${pkg:?}" unset package_names_rev declare -A package_names_rev package_names_rev["${pkg:?}"]="${pkg_name:?}" fi #------------------------------------------------------------------------------ # Select volume # Get list of available volumes volumes=( ) for volume in /volume*; do # Ignore /volumeUSB# and /volume0 if [[ $volume =~ /volume[1-9][0-9]?$ ]]; then # Skip volume package is currently installed on if [[ $volume != "$linktargetvol" ]]; then # Ignore unmounted volumes if df -h | grep "$volume" >/dev/null ; then volumes+=("$volume") fi fi fi done # Select destination volume if [[ ${mode,,} == "move" ]]; then if [[ ${#volumes[@]} -gt 1 ]]; then x="1" for v in "${volumes[@]}"; do echo "$x) $v" >> "$logfile" x=$((x +1)) done echo "Select the destination volume " >> "$logfile" PS3="Select the destination volume: " select targetvol in "${volumes[@]}"; do if [[ $targetvol ]]; then if [[ -d $targetvol ]]; then echo -e "You selected ${Cyan}${targetvol}${Off}\n" echo -e "You selected ${targetvol}\n" >> "$logfile" break else ding echo -e "Line ${LINENO}: ${Error}ERROR${Off} $targetvol not found!" echo -e "Line ${LINENO}: ERROR $targetvol not found!" >> "$logfile" exit 1 # Target volume not found fi else echo "Invalid choice!" |& tee -a "$logfile" fi done elif [[ ${#volumes[@]} -eq 1 ]]; then targetvol="${volumes[0]}" echo -e "Destination volume is ${Cyan}${targetvol}${Off}\n" echo -e "Destination volume is ${targetvol}\n" >> "$logfile" else ding echo -e "Line ${LINENO}: ${Error}ERROR${Off} Only 1 volume found!" echo -e "Line ${LINENO}: ERROR Only 1 volume found!" >> "$logfile" exit 1 # Only 1 volume fi elif [[ ${mode,,} == "backup" ]]; then targetvol="/$(echo "${backuppath:?}" | cut -d"/" -f2)" if [[ $all != "yes" ]]; then echo -e "Destination volume is ${Cyan}${targetvol}${Off}\n" echo -e "Destination volume is ${targetvol}\n" >> "$logfile" fi elif [[ ${mode,,} == "restore" ]]; then if [[ $all != "yes" ]]; then targetvol="/$(readlink "/var/packages/${pkg:?}/target" | cut -d"/" -f2)" echo -e "Destination volume is ${Cyan}${targetvol}${Off}\n" echo -e "Destination volume is ${targetvol}\n" >> "$logfile" fi fi warn_docker(){ ding echo -en "${Yellow}WARNING${Off} $action $pkg_name containers from " echo -e "${Cyan}$sourcefs${Off} volume to ${Cyan}$targetfs${Off} volume" echo -e "results in needing to migrate the containers. Some may fail to migrate.\n" echo -n "WARNING $action docker containers from " >> "$logfile" echo "$sourcefs volume to $targetfs volume" >> "$logfile" echo -e "results in needing to migrate the containers. Some may fail to migrate.\n" >> "$logfile" sleep 2 } # Check source and target filesystem if Docker or Container Manager selected if [[ ${package_names[*]} =~ "ContainerManager" ]] || [[ ${package_names[*]} =~ "Docker" ]]; then if [[ $mode == "restore" ]]; then sourcevol=$(echo "$bkpath" | cut -d "/" -f2) else if [[ ${package_names[*]} =~ "ContainerManager" ]]; then pkg="ContainerManager" pkg_name="Container Manager" elif [[ ${package_names[*]} =~ "Docker" ]]; then pkg="Docker" pkg_name="Docker" fi target=$(readlink "/var/packages/${pkg}/target") sourcevol="$(printf %s "${target:?}" | cut -d'/' -f2 )" fi source_fs "$sourcevol" target_fs "$targetvol" if [[ $targetfs != "$sourcefs" ]]; then # Warn about different filesystems warn_docker docker_migrate="yes" fi fi # Check selected pkgs will fit on target volume # Should add a progress bar? if [[ "${#package_names[@]}" -gt "1" ]]; then echo -e "Checking size of selected apps" |& tee -a "$logfile" else echo -e "Checking size of ${package_names_rev[*]}" |& tee -a "$logfile" fi for pkg in "${package_names[@]}"; do # Get volume package is installed on sourcevol="$(readlink "/var/packages/$pkg/target" | cut -d'/' -f2)" # Get pkg total size check_pkg_size "$pkg" "/$sourcevol" all_pkg_size=$((all_pkg_size +total_size)) done # Abort if not enough space on target volume if ! check_space "$pkg" "${targetvol:?}" "$all_pkg_size"; then ding exit 1 # Not enough space fi # Show size of selected packages if [[ $all_pkg_size -gt "999999" ]]; then echo -e "Size of selected app(s) is $((all_pkg_size /1048576)) GB\n" |& tee -a "$logfile" elif [[ $all_pkg_size -gt "999" ]]; then echo -e "Size of selected app(s) is $((all_pkg_size /1048)) MB\n" |& tee -a "$logfile" else echo -e "Size of selected app(s) is $all_pkg_size KB\n" |& tee -a "$logfile" fi # Check user is ready if [[ $auto != "yes" ]]; then if [[ $all == "yes" ]]; then if [[ ${mode,,} == "backup" ]]; then echo -e "Ready to ${Yellow}${mode}${Off} ${Cyan}All${Off} packages to ${Cyan}${backuppath}${Off}? [y/n]" echo -e "Ready to $mode All packages to ${backuppath}? [y/n]" >> "$logfile" else echo -e "Ready to ${Yellow}${mode}${Off} ${Cyan}All${Off} backed up packages? [y/n]" echo -e "Ready to $mode All backed up packages? [y/n]" >> "$logfile" fi elif [[ ${mode,,} == "backup" ]]; then echo -e "Ready to ${Yellow}${mode}${Off} ${Cyan}${pkg_name}${Off} to ${Cyan}${backuppath}${Off}? [y/n]" echo -e "Ready to $mode ${Cyan}${pkg_name} to ${backuppath}? [y/n]" >> "$logfile" else echo -e "Ready to ${Yellow}${mode}${Off} ${Cyan}${pkg_name}${Off} to ${Cyan}${targetvol}${Off}? [y/n]" echo -e "Ready to $mode ${pkg_name} to ${targetvol}? [y/n]" >> "$logfile" fi read -r answer echo "$answer" >> "$logfile" echo "" |& tee -a "$logfile" if [[ ${answer,,} != y ]]; then exit # Answered no fi fi # Reset shell's SECONDS var to later show how long the script took SECONDS=0 #------------------------------------------------------------------------------ # Get list of packages sorted by with dependents, with dependencies then others # Loop through package_names associative array for pkg_name in "${!package_names[@]}"; do pkg="${package_names["$pkg_name"]}" # Get list of packages with dependents has_dependtents=() has_dependtents+=($(/usr/syno/bin/synopkg list --name --depend-on "$pkg")) if [[ ${#has_dependtents[@]} -gt "0" ]]; then # Add to list of running packages with dependents pkgs_with_deps+=("$pkg") else # Get list of packages with dependencies has_deps="" info="/var/packages/${pkg}/INFO" has_deps=$(/usr/syno/bin/synogetkeyvalue "$info" install_dep_packages) if [[ -n "$has_deps" ]]; then # Add to list of packages with dependencies dep_pkgs+=("$pkg") else # Add to list of other packages pkgs_no_dep+=("$pkg") fi fi done # Sort array IFS=$'\n' pkgs_with_deps_sorted=($(sort -u <<<"${pkgs_with_deps[*]}")); unset IFS # Sort array IFS=$'\n' dep_pkgs_sorted=($(sort -u <<<"${dep_pkgs[*]}")); unset IFS # Sort array IFS=$'\n' pkgs_no_dep_sorted=($(sort -u <<<"${pkgs_no_dep[*]}")); unset IFS # Add packages with dependents to pkgs_sorted for v in "${!pkgs_with_deps_sorted[@]}"; do pkgs_sorted+=("${pkgs_with_deps_sorted["$v"]}") done # Append packages with dependencies to pkgs_sorted for v in "${!dep_pkgs_sorted[@]}"; do pkgs_sorted+=("${dep_pkgs_sorted["$v"]}") done # Append other packages to pkgs_sorted for v in "${!pkgs_no_dep_sorted[@]}"; do pkgs_sorted+=("${pkgs_no_dep_sorted["$v"]}") done # Free some memory unset pkgs_with_deps unset dep_pkgs unset pkgs_no_dep unset pkgs_with_deps_sorted unset dep_pkgs_sorted unset pkgs_no_dep_sorted # Get list of running packages from array sorted by # with dependents, with dependencies then others for pkg in "${pkgs_sorted[@]}"; do if [[ -f "/var/packages/${pkg}/enabled" ]]; then running_pkgs_sorted+=("$pkg") fi done # Get list of running packages dependent on pgsql service if [[ ${pkgs_sorted[*]} =~ "@database" ]]; then # Add running packages that use pgsql that need starting to array if cd "/var/packages"; then for package in *; do if [[ -d "$package" ]]; then depservice="$(synogetkeyvalue "/var/packages/${package}/INFO" start_dep_services)" #long_name="$(synogetkeyvalue "/var/packages/${package}/INFO" displayname)" if echo "$depservice" | grep -q 'pgsql'; then if package_is_running "$package"; then running_pkgs_dep_pgsql+=("$package") fi fi fi done < <(find . -maxdepth 2 -type d) fi fi #------------------------------------------------------------------------------ # Stop the package or packages stop_packages(){ # Check package is running [ "$trace" == "yes" ] && echo "${FUNCNAME[0]} called from ${FUNCNAME[1]}" |& tee -a "$logfile" if package_is_running "$pkg"; then # Stop package package_stop "$pkg" "$pkg_name" # Check package stopped if package_is_running "$pkg"; then stop_pkg_fail="yes" ding echo -e "Line ${LINENO}: ${Error}ERROR${Off} Failed to stop ${pkg_name}!" |& tee -a "$logfile" # echo "${pkg_name} status $code" |& tee -a "$logfile" process_error="yes" if [[ $all != "yes" ]] || [[ $fix != "yes" ]]; then exit 1 # Skip exit if mode != all and fix != yes fi return 1 else stop_pkg_fail="" fi if [[ $pkg == "ContainerManager" ]] || [[ $pkg == "Docker" ]]; then # Stop containerd-shim killall containerd-shim >/dev/null 2>&1 fi # else # skip_start="yes" fi } #------------------------------------------------------------------------------ # Backup extra @folders backup_extras(){ # $1 is @folder (@docker or @downloads etc) local extrabakvol local answer # Skip if source volume is read only if [[ -w "/$sourcevol" ]]; then if [[ ${mode,,} != "backup" ]]; then if [[ ${mode,,} == "move" ]]; then extrabakvol="/$sourcevol" elif [[ ${mode,,} == "restore" ]]; then extrabakvol="$targetvol" fi echo -e "NOTE: A backup of ${Cyan}$1${Off} is required"\ "for recovery if the ${mode,,} fails." echo -e "NOTE: A backup of $1 is required"\ "for recovery if the ${mode,,} fails." >> "$logfile" echo -e "Do you want to ${Yellow}backup${Off} the"\ "${Cyan}$1${Off} folder on $extrabakvol? [y/n]" echo -e "Do you want to backup the"\ "$1 folder on $extrabakvol? [y/n]" >> "$logfile" read -r answer echo "$answer" >> "$logfile" if [[ ${answer,,} == "y" ]]; then # Check we have enough space if ! check_space "/${sourcevol}/$1" "/${sourcevol}" extra; then ding echo -e "${Error}ERROR${Off} Not enough space on $extrabakvol to backup ${Cyan}$1${Off}!" echo -e "ERROR Not enough space on $extrabakvol to backup $1!" >> "$logfile" echo "Do you want to continue ${action,,} ${1}? [y/n]" |& tee -a "$logfile" read -r answer echo "$answer" >> "$logfile" if [[ ${answer,,} != "y" ]]; then exit # Answered no fi else echo -e "${Red}WARNING Backing up $1 could take a long time${Off}" echo -e "WARNING Backing up $1 could take a long time" >> "$logfile" backup_dir "$1" "$extrabakvol" fi fi fi fi } #------------------------------------------------------------------------------ # Move the package or packages prepare_backup_restore(){ [ "$trace" == "yes" ] && echo "${FUNCNAME[0]} called from ${FUNCNAME[1]}" |& tee -a "$logfile" # Set bkpath variable if [[ ${mode,,} != "move" ]]; then bkpath="${backuppath}/syno_app_mover/$pkg" fi # Set targetvol variable if [[ ${mode,,} == "restore" ]] && [[ $all == "yes" ]]; then targetvol="/$(readlink "/var/packages/${pkg:?}/target" | cut -d"/" -f2)" fi # Check installed package version and backup version # Get package version if [[ ${mode,,} != "move" ]]; then pkgversion=$(/usr/syno/bin/synogetkeyvalue "/var/packages/$pkg/INFO" version) fi # Get backup package version if [[ ${mode,,} == "restore" ]]; then pkgbackupversion=$(/usr/syno/bin/synogetkeyvalue "$bkpath/INFO" version) if [[ $pkgversion ]] && [[ $pkgbackupversion ]]; then check_pkg_versions_match "$pkgversion" "$pkgbackupversion" fi fi # Create package folder if mode is backup if [[ ${mode,,} == "backup" ]]; then if [[ ! -d "$bkpath" ]]; then if ! mkdir -p "${bkpath:?}"; then ding echo -e "Line ${LINENO}: ${Error}ERROR${Off} Failed to create directory!" echo -e "Line ${LINENO}: ERROR Failed to create directory!" >> "$logfile" process_error="yes" if [[ $all != "yes" ]]; then exit 1 # Skip exit if mode is All fi return 1 fi fi # Backup package's INFO file cp -p "/var/packages/$pkg/INFO" "$bkpath/INFO" |& tee -a "$logfile" fi } process_packages(){ [ "$trace" == "yes" ] && echo "${FUNCNAME[0]} called from ${FUNCNAME[1]}" |& tee -a "$logfile" target=$(readlink "/var/packages/${pkg}/target") #sourcevol="/$(printf %s "${target:?}" | cut -d'/' -f2 )" sourcevol="$(printf %s "${target:?}" | cut -d'/' -f2 )" # Move package if [[ $pkg == "ContainerManager" ]] || [[ $pkg == "Docker" ]]; then # Move @docker if package is ContainerManager or Docker # Check if @docker is on same volume as Docker package if [[ -d "/${sourcevol}/@docker" ]]; then # Check we have enough space if ! check_space "/${sourcevol}/@docker" "${targetvol}" extra; then ding echo -e "${Error}ERROR${Off} Not enough space on $targetvol to ${mode,,} ${Cyan}@docker${Off}!" echo -e "ERROR Not enough space on $targetvol to ${mode,,} @docker!" >> "$logfile" process_error="yes" if [[ $all != "yes" ]]; then exit 1 # Skip exit if mode is All fi return 1 fi fi # Backup @docker backup_extras "@docker" # Move package and edit symlinks move_pkg "$pkg" "$targetvol" elif [[ $pkg == "DownloadStation" ]]; then # Move @download if package is DownloadStation # Check if @download is on same volume as DownloadStation package if [[ -d "/${sourcevol}/@download" ]]; then # Check we have enough space if ! check_space "/${sourcevol}/@download" "${targetvol}" extra; then ding echo -e "${Error}ERROR${Off} Not enough space on $targetvol to ${mode,,} ${Cyan}@download${Off}!" echo -e "ERROR Not enough space on $targetvol to ${mode,,} @download!" >> "$logfile" process_error="yes" if [[ $all != "yes" ]]; then exit 1 # Skip exit if mode is All fi return 1 fi fi # Backup @download backup_extras "@download" # Move package and edit symlinks move_pkg "$pkg" "$targetvol" else # Move package and edit symlinks move_pkg "$pkg" "$targetvol" fi # Move package's other folders move_extras "$pkg" "$targetvol" # Backup or restore package's web_packages folder if [[ ${mode,,} != "move" ]]; then web_packages "${pkg,,}" fi } start_packages(){ [ "$trace" == "yes" ] && echo "${FUNCNAME[0]} called from ${FUNCNAME[1]}" |& tee -a "$logfile" # if [[ $skip_start != "yes" ]]; then if [[ $pkg != "@database" ]]; then # Only start package if not already running if ! package_is_running "$pkg"; then if [[ ${mode,,} == "backup" ]]; then answer="y" elif [[ $all == "yes" ]]; then answer="y" else echo -e "\nDo you want to start ${Cyan}$pkg_name${Off} now? [y/n]" echo -e "\nDo you want to start $pkg_name now? [y/n]" >> "$logfile" read -r answer echo "$answer" >> "$logfile" fi if [[ ${answer,,} == "y" ]]; then # Start package package_start "$pkg" "$pkg_name" # Check package started if ! package_is_running "$pkg"; then ding echo -e "Line ${LINENO}: ${Error}ERROR${Off} Failed to start ${pkg_name}!" echo -e "Line ${LINENO}: ERROR Failed to start ${pkg_name}!" >> "$logfile" # echo "${pkg_name} status $code" |& tee -a "$logfile" process_error="yes" if [[ $all != "yes" ]]; then exit 1 # Skip exit if mode is All fi else did_start_pkg="yes" fi else no_start_pkg="yes" fi fi fi # fi } check_last_process_time(){ # $1 is pkg if [[ ${mode,,} != "move" ]]; then #now=$(date +%s) if [[ -f "${backuppath}/syno_app_mover/$1/last${mode,,}" ]]; then last_process_time=$(cat "${backuppath}/syno_app_mover/$1/last${mode,,}") skip_minutes=$(/usr/syno/bin/synogetkeyvalue "$conffile" skip_minutes) if [[ $skip_minutes -gt "0" ]]; then skip_secs=$((skip_minutes *60)) #if $(($(date +%s) +skip_secs)) -gt if [[ $((last_process_time +skip_secs)) -gt $(date +%s) ]]; then return 1 fi fi fi fi } docker_export(){ local docker_share local export_dir local container local export_file export_date="$(date +%Y%m%d_%H%M)" # Get docker share location if [[ $buildnumber -gt "64570" ]]; then # DSM 7.2.1 and later # synoshare --get-real-path is case insensitive (docker or Docker both work) docker_share=$(/usr/syno/sbin/synoshare --get-real-path docker) else # DSM 7.2 and earlier # synoshare --getmap is case insensitive (docker or Docker both work) docker_share=$(/usr/syno/sbin/synoshare --getmap docker | grep volume | cut -d"[" -f2 | cut -d"]" -f1) # I could also have used: # docker_share=$(/usr/syno/sbin/synoshare --get docker | tr '[]' '\n' | sed -n "9p") fi if [[ ! -d "$docker_share" ]]; then echo "${Error}WARNING${Off} docker shared folder not found!" echo "WARNING docker shared folder not found!" >> "$logfile" return else export_dir="${docker_share}/app_mover_exports" fi if [[ ! -d "$export_dir" ]]; then if ! mkdir "$export_dir"; then echo "${Error}WARNING${Off} Failed to create docker export folder!" echo "WARNING Failed to create docker export folder!" >> "$logfile" return else chmod 755 "$export_dir" |& tee -a "$logfile" fi fi echo "Exporting container settings to ${export_dir}" |& tee -a "$logfile" # Get list of all containers (running and stopped) for container in $(docker ps --all --format "{{ .Names }}"); do if grep -q "$container" <<< "${ignored_containers_list[@]}" ; then echo "Skipping ${container} on ignore list." |& tee -a "$logfile" continue else export_file="${export_dir:?}/${container}_${export_date}.json" echo "Exporting $container json" |& tee -a "$logfile" # synowebapi -s or --silent does not work /usr/syno/bin/synowebapi --exec api=SYNO.Docker.Container.Profile method=export version=1 outfile="$export_file" name="$container" &>/dev/null # Check export was successful if [[ ! -f "$export_file" ]] || [[ $(stat -c %s "$export_file") -eq "0" ]]; then # No file or 0 bytes echo "${Error}WARNING${Off} Failed to export $container settings!" echo "WARNING Failed to export $container settings!" >> "$logfile" return else chmod 660 "${export_dir:?}/${container}_${export_date}.json" |& tee -a "$logfile" fi # Delete settings exports older than $delete_older days if [[ $delete_older =~ ^[2-9][0-9]?$ ]]; then find "$export_dir" -name "${container,,}_*.json" -mtime +"$delete_older" -exec rm {} \; fi fi done } move_database(){ # Get volume where @database currently is target=$(readlink "/var/services/pgsql") #sourcevol="/$(printf %s "${target:?}" | cut -d'/' -f2 )" sourcevol="$(printf %s "${target:?}" | cut -d'/' -f2 )" # Stop pgsql service if [[ $majorversion -gt 6 ]]; then # Stopping the pgsql service also stops dependant apps systemctl stop pgsql-adapter.service & else # DSM 6 synoservicectl --stop pgsql-adapter & fi pid=$! string="Stopping pgsql service and dependent apps" echo "Stopping pgsql service and dependent apps" >> "$logfile" progbar "$pid" "$string" wait "$pid" progstatus "$?" "$string" "line ${LINENO}" # Check pgsql service has stopped if [[ $majorversion -gt 6 ]]; then # DSM 7, running = 0 stopped = 3 if systemctl status pgsql-adapter.service >/dev/null; then ding echo "ERROR Failed to stop pgsql service!" |& tee -a "$logfile" return 1 #else # echo "Stopped pgsql service" |& tee -a "$logfile" fi else # DSM 6, running = 0 stopped = 1 if synoservicectl --status pgsql-adapter >/dev/null; then ding echo "ERROR Failed to stop pgsql service!" |& tee -a "$logfile" return 1 #else # echo "Stopped pgsql service" |& tee -a "$logfile" fi fi # Stop synologand service if [[ $majorversion -gt 6 ]]; then systemctl stop synologand & else # DSM 6 synoservicectl --stop synologand & fi pid=$! string="Stopping synologand service" echo "Stopping synologand service" >> "$logfile" progbar "$pid" "$string" wait "$pid" progstatus "$?" "$string" "line ${LINENO}" # Check synologan service has stopped if [[ $majorversion -gt 6 ]]; then # DSM 7, running = 0 stopped = 3 if systemctl status synologand >/dev/null; then ding echo "ERROR Failed to stop synologand service!" |& tee -a "$logfile" return 1 #else # echo "Stopped synologand service" |& tee -a "$logfile" fi else # DSM 6, running = 0 stopped = 1 if synoservicectl --status synologand >/dev/null; then ding echo "ERROR Failed to stop synologand service!" |& tee -a "$logfile" return 1 #else # echo "Stopped synologand service" |& tee -a "$logfile" fi fi # Create @database folder if needed if [[ ! -d "${targetvol:?}/@database" ]]; then mkdir -m755 "${targetvol:?}/@database" fi # Copy pgsql folder cp -pr "/${sourcevol:?}/@database/pgsql" "${targetvol:?}/@database/pgsql" & pid=$! string="Copying pgsql database to $targetvol/@database" echo "Copying pgsql database to $targetvol/@database" >> "$logfile" progbar "$pid" "$string" wait "$pid" progstatus "$?" "$string" "line ${LINENO}" # Copy other folders if [[ -d "/${sourcevol:?}/@database/autoupdate" ]]; then cp -pr "/${sourcevol:?}/@database/autoupdate" "${targetvol:?}/@database/autoupdate" fi if [[ -d "/${sourcevol:?}/@database/synolog" ]]; then cp -pr "/${sourcevol:?}/@database/synolog" "${targetvol:?}/@database/synolog" fi if [[ -d "/${sourcevol:?}/@database/synologan" ]]; then cp -pr "/${sourcevol:?}/@database/synologan" "${targetvol:?}/@database/synologan" fi # Edit pgsql symlink rm /var/services/pgsql ln -s "${targetvol:?}/@database/pgsql" /var/services/pgsql # Edit synologan symlink rm /var/lib/synologan/database/alert.sqlite ln -s "${targetvol:?}/@database/synologan/alert.sqlite" /var/lib/synologan/database/alert.sqlite # Start the pgsql service echo "Starting pgsql service" |& tee -a "$logfile" if [[ $majorversion -gt 6 ]]; then systemctl start pgsql-adapter.service else # DSM 6 synoservicectl --start pgsql-adapter fi # Check pgsql service is ok if [[ $majorversion -gt 6 ]]; then # DSM 7, running = 0 stopped = 3 if ! systemctl status pgsql-adapter.service >/dev/null; then ding echo "ERROR Failed to start pgsql service!" |& tee -a "$logfile" return 1 #else # echo "Started pgsql service" |& tee -a "$logfile" fi else # DSM 6, running = 0 stopped = 1 if ! synoservicectl --status pgsql-adapter >/dev/null; then ding echo "ERROR Failed to start pgsql service!" |& tee -a "$logfile" return 1 #else # echo "Started pgsql service" |& tee -a "$logfile" fi fi # Start the synologand service echo "Starting synologand service" |& tee -a "$logfile" if [[ $majorversion -gt 6 ]]; then systemctl start synologand else # DSM 6 synoservicectl --start synologand fi # Check synologand service is ok if [[ $majorversion -gt 6 ]]; then # DSM 7, running = 0 stopped = 3 if ! systemctl status synologand >/dev/null; then ding echo "ERROR Failed to start synologand service!" |& tee -a "$logfile" return 1 #else # echo "Started synologand service" |& tee -a "$logfile" fi else # DSM 6, running = 0 stopped = 1 if ! synoservicectl --status synologand >/dev/null; then ding echo "ERROR Failed to start synologand service!" |& tee -a "$logfile" return 1 #else # echo "Started synologand service" |& tee -a "$logfile" fi fi return 0 } # Loop through pkgs_sorted array and process package for pkg in "${pkgs_sorted[@]}"; do pkg_name="${package_names_rev["$pkg"]}" process_error="" # Skip backup or restore for excluded apps if [[ $all == "yes" ]] && [[ "${excludelist[*]}" =~ $pkg ]] &&\ [[ $mode != "move" ]]; then echo -e "Excluding $pkg\n" |& tee -a "$logfile" continue fi #if [[ $pkg == USBCopy ]] && [[ ${mode,,} == "move" ]]; then if [[ $pkg == USBCopy ]]; then # USBCopy only needs database location changed in USB Copy ui continue fi #if [[ $pkg == "@database" ]] && [[ ${mode,,} == "move" ]]; then if [[ $pkg == "@database" ]]; then move_database continue fi if [[ $pkg == "ContainerManager" ]] || [[ $pkg == "Docker" ]]; then if [[ -w "/$sourcevol" ]]; then # Start package if needed so we can prune images # and export container configurations if ! package_is_running "$pkg"; then package_start "$pkg" "$pkg_name" fi if [[ ${mode,,} != "restore" ]]; then # Export container settings to json files docker_export fi #if [[ ${mode,,} == "restore" ]]; then # # Remove dangling and unused images # echo "Removing dangling and unused docker images" |& tee -a "$logfile" # docker image prune --all --force >/dev/null #else # # Remove dangling images # echo "Removing dangling docker images" |& tee -a "$logfile" # docker image prune --force >/dev/null #fi else # Skip read only source volume echo "/$sourcevol is read only. Skipping:" |& tee -a "$logfile" echo " - Exporting container settings" |& tee -a "$logfile" #echo " - Removing dangling and unused docker images" |& tee -a "$logfile" fi fi if ! check_last_process_time "$pkg" && [[ $all == "yes" ]]; then echo "Skipping $pkg_name as a ${mode,,} was done less than $skip_minutes minutes ago" |& tee -a "$logfile" else if [[ ${mode,,} != "move" ]]; then prepare_backup_restore fi stop_packages if [[ ${1,,} == "--test" ]] || [[ ${1,,} == "test" ]]; then echo "process_packages" else if [[ $stop_pkg_fail != "yes" ]]; then process_packages if [[ ${mode,,} != "move" ]] && [[ $process_error != "yes" ]]; then # Save last backup time echo -n "$(date +%s)" > "${backuppath}/syno_app_mover/$pkg/last${mode,,}" chmod 755 "${backuppath}/syno_app_mover/$pkg/last${mode,,}" |& tee -a "$logfile" fi fi fi # shellcheck disable=SC2143 # Use grep -q if [[ $(echo "${running_pkgs_sorted[@]}" | grep -w "$pkg") ]]; then start_packages fi fi echo "" |& tee -a "$logfile" done #------------------------------------------------------------------------------ # Show how to move related shared folder(s) docker_volume_edit(){ # Remind user to edit container's volume setting echo "If you moved shared folders that your $pkg_name containers use" |& tee -a "$logfile" echo "as volumes you will need to edit your docker compose or .env files," |& tee -a "$logfile" echo -e "or the container's settings, to point to the changed volume number.\n" |& tee -a "$logfile" } suggest_move_share(){ # show_move_share <package-name> <share-name> if [[ ${mode,,} == "move" ]]; then case "$pkg" in ActiveBackup) show_move_share "Active Backup for Business" ActiveBackupforBusiness stopped ;; AudioStation) share_link=$(readlink /var/packages/AudioStation/shares/music) if [[ $share_link == "/${sourcevol}/music" ]]; then show_move_share "Audio Station" music stopped more fi ;; Chat) show_move_share "Chat Server" chat stopped ;; CloudSync) show_move_share "Cloud Sync" CloudSync stopped ;; ContainerManager) show_move_share "Container Manager" docker stopped docker_volume_edit ;; Docker) show_move_share "Docker" docker stopped docker_volume_edit ;; MailPlus-Server) show_move_share "MailPlus Server" MailPlus running ;; MinimServer) show_move_share "Minim Server" MinimServer stopped ;; Plex*Media*Server) if [[ $majorversion -gt "6" ]]; then show_move_share "Plex Media Server" PlexMediaServer stopped else show_move_share "Plex Media Server" Plex stopped fi ;; SurveillanceStation) show_move_share "Surveillance Station" surveillance stopped ;; SynologyPhotos) share_link=$(readlink /var/services/photo) if [[ -d "$share_link" ]]; then if [[ $share_link == "/${sourcevol}/photo" ]]; then show_move_share "Synology Photos" photo stopped fi fi ;; VideoStation) share_link=$(readlink /var/packages/VideoStation/shares/video) if [[ $share_link == "/${sourcevol}/video" ]]; then show_move_share "Video Station" video stopped more fi ;; *) ;; esac fi } if [[ ${mode,,} == "move" ]]; then if [[ $all == "yes" ]]; then # Loop through pkgs_sorted array and process package for pkg in "${pkgs_sorted[@]}"; do pkg_name="${package_names_rev["$pkg"]}" suggest_move_share done else suggest_move_share fi fi #------------------------------------------------------------------------------ # Start package and dependent packages that aren't running # Loop through running_pkgs_sorted array if [[ $no_start_pkg != "yes" ]]; then did_start_pkg="" for pkg in "${running_pkgs_sorted[@]}"; do pkg_name="${package_names_rev["$pkg"]}" start_packages done if [[ $did_start_pkg == "yes" ]]; then echo "" |& tee -a "$logfile" fi fi # Start pqsql dependent pkgs that were running but aren't now # Loop through running_pkgs_dep_pgsql array if [[ $no_start_pkg != "yes" ]]; then did_start_pkg="" for pgsql_pkg in "${running_pkgs_dep_pgsql[@]}"; do if ! package_is_running "$pgsql_pkg"; then pgsql_pkg_name="$(synogetkeyvalue "/var/packages/${pgsql_pkg}/INFO" displayname)" package_start "$pgsql_pkg" "$pgsql_pkg_name" fi done if [[ $did_start_pkg == "yes" ]]; then echo "" |& tee -a "$logfile" fi fi if [[ $all == "yes" ]]; then echo -e "Finished ${action,,} all packages\n" |& tee -a "$logfile" elif [[ $auto == "yes" ]]; then echo -e "Finished ${action,,} ${pkgs_sorted[*]}\n" |& tee -a "$logfile" else echo -e "Finished ${action,,} $pkg_name\n" |& tee -a "$logfile" fi # Show how long the script took end="$SECONDS" if [[ $end -ge 3600 ]]; then printf 'Duration: %dh %dm\n\n' $((end/3600)) $((end%3600/60)) |& tee -a "$logfile" elif [[ $end -ge 60 ]]; then echo -e "Duration: $((end/60))m $((end%60))s\n" |& tee -a "$logfile" else echo -e "Duration: ${end} seconds\n" |& tee -a "$logfile" fi #------------------------------------------------------------------------------ # Show how to export and import package's database if dependent on MariaDB10 # Loop through package_names associative array for pkg_name in "${!package_names[@]}"; do pkg="${package_names[$pkg_name]}" if [[ ${mode,,} != "move" ]]; then info="/var/packages/${pkg}/INFO" if /usr/syno/bin/synogetkeyvalue "$info" install_dep_packages | grep 'MariaDB' >/dev/null then mariadb_list+=("${pkg_name}") mariadb_show="yes" fi fi done if [[ $mariadb_show == "yes" ]]; then if [[ ${mode,,} == "backup" ]]; then # Show how to export package's database echo -e "If you want to ${Yellow}backup${Off} the database of"\ "${Cyan}${mariadb_list[*]}${Off} do the following:" echo -e "If you want to backup the database of"\ "${mariadb_list[*]} do the following:" >> "$logfile" echo " If you don't have phpMyAdmin installed:" |& tee -a "$logfile" echo " 1. Install phpMyAdmin." |& tee -a "$logfile" echo " 2. Open phpMyAdmin" |& tee -a "$logfile" echo " 3. Log in with user root and your MariaDB password." |& tee -a "$logfile" echo " Once you are logged in to phpMyAdmin:" |& tee -a "$logfile" echo " 1. Click on the package name on the left." |& tee -a "$logfile" echo " 2. Click on the Export tab at the top." |& tee -a "$logfile" echo " 3. Click on the Export button." |& tee -a "$logfile" echo -e " 4. Save the export to a safe location.\n" |& tee -a "$logfile" elif [[ ${mode,,} == "restore" ]]; then # Show how to import package's exported database echo -e "If you want to ${Yellow}restore${Off} the database of"\ "${Cyan}${mariadb_list[*]}${Off} do the following:" echo -e "If you want to restore the database of"\ "${mariadb_list[*]} do the following:" >> "$logfile" echo " If you don't have phpMyAdmin installed:" |& tee -a "$logfile" echo " 1. Install phpMyAdmin." |& tee -a "$logfile" echo " 2. Open phpMyAdmin" |& tee -a "$logfile" echo " 3. Log in with user root and your MariaDB password." |& tee -a "$logfile" echo " Once you are logged in to phpMyAdmin:" |& tee -a "$logfile" echo " 1. Click on the package name on the left." |& tee -a "$logfile" echo " 2. Click on the Import tab at the top." |& tee -a "$logfile" echo " 3. Click on the 'Choose file' button." |& tee -a "$logfile" echo -e " 4. Browse to your exported .sql file and import it.\n" |& tee -a "$logfile" fi fi #------------------------------------------------------------------------------ # Show how to migrate docker containers if different file system if [[ $docker_migrate == "yes" ]]; then echo -e "You will need to migrate your containers" |& tee -a "$logfile" echo " 1. Open Container Manager." |& tee -a "$logfile" echo " 2. Click the Manage link." |& tee -a "$logfile" echo " 3. Select the container you want to migrate." |& tee -a "$logfile" echo " 4. Click Migrate." |& tee -a "$logfile" echo -e " 5. Click Continue.\n" |& tee -a "$logfile" fi #------------------------------------------------------------------------------ # Suggest change location of shared folder(s) if package moved suggest_change_location(){ # Suggest moving CloudSync database if package is CloudSync if [[ $pkg == CloudSync ]]; then # Show how to move CloudSync database echo -e "If you want to move the CloudSync database to $targetvol" |& tee -a "$logfile" echo " 1. Open Cloud Sync." |& tee -a "$logfile" echo " 2. Click Settings." |& tee -a "$logfile" echo " 3. Change 'Database Location Settings' to $targetvol" |& tee -a "$logfile" echo -e " 4. Click Save.\n" |& tee -a "$logfile" fi # Suggest moving @download if package is DownloadStation if [[ $pkg == DownloadStation ]]; then # Show how to move DownloadStation database and temp files #file="/var/packages/DownloadStation/etc/db-path.conf" #value="$(/usr/syno/bin/synogetkeyvalue "$file" db-vol)" #if [[ $value != "$targetvol" ]]; then echo -e "If you want to move the DownloadStation database & temp files to $targetvol" |& tee -a "$logfile" echo " 1. Open Download Station." |& tee -a "$logfile" echo " 2. Click Settings." |& tee -a "$logfile" echo " 3. Click General." |& tee -a "$logfile" echo " 4. Change 'Temporary location' to $targetvol" |& tee -a "$logfile" echo -e " 5. Click OK.\n" |& tee -a "$logfile" #fi fi # Suggest moving Note Station database if package is NoteStation if [[ $pkg == NoteStation ]]; then # Show how to move Note Station database echo -e "If you want to move the Note Station database to $targetvol" |& tee -a "$logfile" echo " 1. Open Note Station." |& tee -a "$logfile" echo " 2. Click Settings." |& tee -a "$logfile" echo " 3. Click Administration." |& tee -a "$logfile" echo " 4. Change Volume to $targetvol" |& tee -a "$logfile" echo -e " 5. Click OK.\n" |& tee -a "$logfile" fi # Suggest moving Synology Drive database if package is SynologyDrive if [[ $pkg == SynologyDrive ]]; then # Show how to move Drive database file="/var/packages/SynologyDrive/etc/db-path.conf" value="$(/usr/syno/bin/synogetkeyvalue "$file" db-vol)" if [[ $value != "$targetvol" ]]; then echo -e "If you want to move the Synology Drive database to $targetvol" |& tee -a "$logfile" echo -e "If you're migrating the database from an ext4 volume to a Btrfs volume,\n please review this note: https://github.com/007revad/Synology_app_mover#synology-drive-and-btrfs-snapshots\n" |& tee -a "$logfile" echo " 1. Open Synology Drive Admin Console." |& tee -a "$logfile" echo " 2. Click Settings." |& tee -a "$logfile" echo " 3. Change Location to $targetvol" |& tee -a "$logfile" echo -e " 4. Click Apply.\n" |& tee -a "$logfile" fi fi # Suggest moving database if package is USBCopy if [[ $pkg == USBCopy ]]; then # Show how to move USB Copy database echo -e "To move the USB Copy database to $targetvol" echo " 1. Open 'USB Copy'." echo " 2. Click the gear icon to open settings." echo " 3. Change Database location to $targetvol" echo -e " 4. Click OK.\n" fi # Suggest moving VMs if package is Virtualization if [[ $pkg == Virtualization ]]; then # Show how to move VMs echo -e "If you want to move your VMs to $targetvol\n" |& tee -a "$logfile" echo "1. Add $targetvol as Storage in Virtual Machine Manager" |& tee -a "$logfile" echo " 1. Open Virtual Machine Manager." |& tee -a "$logfile" echo " 2. Click Storage and Click Add." |& tee -a "$logfile" echo " 3. Complete the steps to add $targetvol" |& tee -a "$logfile" echo -e "\n2. Move the VM to $targetvol" |& tee -a "$logfile" echo " 1. Click on Virtual Machine." |& tee -a "$logfile" echo " 2. Click on the VM to move." |& tee -a "$logfile" echo " 3. Shut Down the VM." |& tee -a "$logfile" echo " 4. Click Action then click Migrate." |& tee -a "$logfile" echo " 5. Make sure Change Storage is selected." |& tee -a "$logfile" echo " 6. Click Next." |& tee -a "$logfile" echo -e " 7. Complete the steps to migrate the VM.\n" |& tee -a "$logfile" fi } if [[ ${mode,,} == "move" ]]; then if [[ $all == "yes" ]]; then # Loop through pkgs_sorted array and process package for pkg in "${pkgs_sorted[@]}"; do pkg_name="${package_names_rev["$pkg"]}" suggest_change_location done else suggest_change_location fi fi exit
137,030
syno_app_mover
sh
en
shell
code
{"qsc_code_num_words": 15188, "qsc_code_num_chars": 137030.0, "qsc_code_mean_word_length": 4.35653147, "qsc_code_frac_words_unique": 0.06768501, "qsc_code_frac_chars_top_2grams": 0.01602007, "qsc_code_frac_chars_top_3grams": 0.04405519, "qsc_code_frac_chars_top_4grams": 0.01609564, "qsc_code_frac_chars_dupe_5grams": 0.53765472, "qsc_code_frac_chars_dupe_6grams": 0.47109586, "qsc_code_frac_chars_dupe_7grams": 0.41446643, "qsc_code_frac_chars_dupe_8grams": 0.35026524, "qsc_code_frac_chars_dupe_9grams": 0.30569619, "qsc_code_frac_chars_dupe_10grams": 0.28166609, "qsc_code_frac_chars_replacement_symbols": 0.0, "qsc_code_frac_chars_digital": 0.01480188, "qsc_code_frac_chars_whitespace": 0.34378603, "qsc_code_size_file_byte": 137030.0, "qsc_code_num_lines": 3480.0, "qsc_code_num_chars_line_max": 226.0, "qsc_code_num_chars_line_mean": 39.37643678, "qsc_code_frac_chars_alphabet": 0.72103291, "qsc_code_frac_chars_comments": 0.1883894, "qsc_code_cate_xml_start": 0.0, "qsc_code_frac_lines_dupe_lines": 0.51264552, "qsc_code_cate_autogen": 0.0, "qsc_code_frac_lines_long_string": 0.00562023, "qsc_code_frac_chars_string_length": 0.30790811, "qsc_code_frac_chars_long_word_length": 0.0728319, "qsc_code_frac_lines_string_concat": 0.0, "qsc_code_cate_encoded_data": 0.0, "qsc_code_frac_chars_hex_words": 0.0, "qsc_code_frac_lines_prompt_comments": 0.00028736, "qsc_code_frac_lines_assert": 0.0}
1
{"qsc_code_frac_chars_replacement_symbols": 0, "qsc_code_num_words": 0, "qsc_code_num_chars": 0, "qsc_code_mean_word_length": 0, "qsc_code_frac_chars_top_2grams": 0, "qsc_code_frac_chars_top_3grams": 0, "qsc_code_frac_chars_top_4grams": 0, "qsc_code_frac_chars_dupe_5grams": 0, "qsc_code_frac_chars_dupe_6grams": 0, "qsc_code_frac_chars_dupe_7grams": 0, "qsc_code_frac_chars_dupe_8grams": 0, "qsc_code_frac_chars_dupe_9grams": 0, "qsc_code_frac_chars_dupe_10grams": 0, "qsc_code_frac_lines_dupe_lines": 0, "qsc_code_size_file_byte": 0, "qsc_code_num_lines": 0, "qsc_code_num_chars_line_max": 0, "qsc_code_num_chars_line_mean": 0, "qsc_code_frac_chars_alphabet": 0, "qsc_code_frac_chars_digital": 0, "qsc_code_frac_chars_whitespace": 0, "qsc_code_frac_chars_comments": 0, "qsc_code_cate_xml_start": 0, "qsc_code_cate_autogen": 0, "qsc_code_frac_chars_long_word_length": 0, "qsc_code_cate_encoded_data": 0, "qsc_code_frac_chars_hex_words": 0, "qsc_code_frac_lines_prompt_comments": 0}
003random/003Recon
tools/edited_tools/files_and_links_extractor.py
#!/usr/bin/python #This is an edit of /tools/javascript_files_extractor.py and /tools/javascript_files_link_extractor.sh #it combines those 2 and takes 1 domain as string as argument 1. not a domain file import re, requests, sys, os input_string = sys.argv[1] output_file = sys.argv[2] extractor_file = sys.argv[3] print("\n-- Extracting javascript links from "+input_string+" with output file, "+output_file+" --\n") black_listed_domains = ["ajax.googleapis.com", "cdn.optimizely.com", "googletagmanager.com", "fontawesome.com"] if input_string is not "": domain = input_string domain_written = False i = 0 b_amount = 0 full_domain = "" if domain != "": matches = "" r = "" regex = r'script src="(.*?)"' try: r = requests.get("http://"+domain).content except: print "[-]Error in http://"+domain matches = re.findall(regex, r, re.MULTILINE) if matches == []: regex = r"script src='(.*?)'" matches = re.findall(regex, r, re.MULTILINE) for m in matches: black_listed = False for b in black_listed_domains: if b in m: black_listed = True if black_listed != True: if m.startswith("/"): if m.startswith("//"): full_domain = "https:"+m else: full_domain = "https://"+domain+m elif m.startswith("http"): full_domain = m else: full_domain = "https://"+domain+"/"+m else: b_amount += 1 if black_listed != True: i += 1 os.system("echo '"+full_domain + ": \n\r ' >> " + output_file) os.system("ruby " + extractor_file + " " + full_domain + " >> " + output_file) print("\n-- Done --")
1,675
files_and_links_extractor
py
en
python
code
{"qsc_code_num_words": 227, "qsc_code_num_chars": 1675.0, "qsc_code_mean_word_length": 4.32599119, "qsc_code_frac_words_unique": 0.38325991, "qsc_code_frac_chars_top_2grams": 0.0712831, "qsc_code_frac_chars_top_3grams": 0.04582485, "qsc_code_frac_chars_top_4grams": 0.0305499, "qsc_code_frac_chars_dupe_5grams": 0.12219959, "qsc_code_frac_chars_dupe_6grams": 0.12219959, "qsc_code_frac_chars_dupe_7grams": 0.12219959, "qsc_code_frac_chars_dupe_8grams": 0.0, "qsc_code_frac_chars_dupe_9grams": 0.0, "qsc_code_frac_chars_dupe_10grams": 0.0, "qsc_code_frac_chars_replacement_symbols": 0.0, "qsc_code_frac_chars_digital": 0.00784929, "qsc_code_frac_chars_whitespace": 0.23940299, "qsc_code_size_file_byte": 1675.0, "qsc_code_num_lines": 64.0, "qsc_code_num_chars_line_max": 103.0, "qsc_code_num_chars_line_mean": 26.171875, "qsc_code_frac_chars_alphabet": 0.76295133, "qsc_code_frac_chars_comments": 0.11820896, "qsc_code_cate_xml_start": 0.0, "qsc_code_frac_lines_dupe_lines": 0.14285714, "qsc_code_cate_autogen": 0.0, "qsc_code_frac_lines_long_string": 0.0, "qsc_code_frac_chars_string_length": 0.18046133, "qsc_code_frac_chars_long_word_length": 0.0, "qsc_code_frac_lines_string_concat": 0.0, "qsc_code_cate_encoded_data": 0.0, "qsc_code_frac_chars_hex_words": 0.0, "qsc_code_frac_lines_prompt_comments": 0.0, "qsc_code_frac_lines_assert": 0.0, "qsc_codepython_cate_ast": 0.0, "qsc_codepython_frac_lines_func_ratio": null, "qsc_codepython_cate_var_zero": null, "qsc_codepython_frac_lines_pass": 0.0, "qsc_codepython_frac_lines_import": 0.02040816, "qsc_codepython_frac_lines_simplefunc": null, "qsc_codepython_score_lines_no_logic": null, "qsc_codepython_frac_lines_print": 0.06122449}
0
{"qsc_code_frac_chars_replacement_symbols": 0, "qsc_code_num_words": 0, "qsc_code_num_chars": 0, "qsc_code_mean_word_length": 0, "qsc_code_frac_chars_top_2grams": 0, "qsc_code_frac_chars_top_3grams": 0, "qsc_code_frac_chars_top_4grams": 0, "qsc_code_frac_chars_dupe_5grams": 0, "qsc_code_frac_chars_dupe_6grams": 0, "qsc_code_frac_chars_dupe_7grams": 0, "qsc_code_frac_chars_dupe_8grams": 0, "qsc_code_frac_chars_dupe_9grams": 0, "qsc_code_frac_chars_dupe_10grams": 0, "qsc_code_frac_lines_dupe_lines": 0, "qsc_code_size_file_byte": 0, "qsc_code_num_lines": 0, "qsc_code_num_chars_line_max": 0, "qsc_code_num_chars_line_mean": 0, "qsc_code_frac_chars_alphabet": 0, "qsc_code_frac_chars_digital": 0, "qsc_code_frac_chars_whitespace": 0, "qsc_code_frac_chars_comments": 0, "qsc_code_cate_xml_start": 0, "qsc_code_cate_autogen": 0, "qsc_code_frac_lines_long_string": 0, "qsc_code_frac_chars_string_length": 0, "qsc_code_frac_chars_long_word_length": 0, "qsc_code_cate_encoded_data": 0, "qsc_code_frac_chars_hex_words": 0, "qsc_code_frac_lines_prompt_comments": 0, "qsc_code_frac_lines_assert": 0, "qsc_codepython_cate_ast": 1, "qsc_codepython_frac_lines_func_ratio": 0, "qsc_codepython_cate_var_zero": 0, "qsc_codepython_frac_lines_pass": 0, "qsc_codepython_frac_lines_import": 0, "qsc_codepython_frac_lines_simplefunc": 0, "qsc_codepython_score_lines_no_logic": 0, "qsc_codepython_frac_lines_print": 0}
002and001/FHHFPSIndicator
README.md
# FHHFPSIndicator [![License MIT](https://img.shields.io/badge/license-MIT-green.svg?style=flat)](https://raw.githubusercontent.com/jvjishou/FHHFPSIndicator/master/LICENSE)&nbsp; [![CocoaPods](http://img.shields.io/cocoapods/v/FHHFPSIndicator.svg?style=flat)](http://cocoapods.org/?q=FHHFPSIndicator)&nbsp; [![CocoaPods](http://img.shields.io/cocoapods/p/FHHFPSIndicator.svg?style=flat)](http://cocoapods.org/?q=FHHFPSIndicator)&nbsp; FHHFPSIndicator can show FPS in your APP Demo Project ============== See `Demo/FHHFPSIndicatorDemo` <img src="https://raw.githubusercontent.com/jvjishou/FHHFPSIndicator/master/Demo/Snapshots/snapshot1.PNG" width="320"><br/> <img src="https://raw.githubusercontent.com/jvjishou/FHHFPSIndicator/master/Demo/Snapshots/snapshot2.PNG" width="320"><br/> <img src="https://raw.githubusercontent.com/jvjishou/FHHFPSIndicator/master/Demo/Snapshots/snapshot3.PNG" width="320"><br/> <img src="https://raw.githubusercontent.com/jvjishou/FHHFPSIndicator/master/Demo/Snapshots/snapshot4.PNG" width="320"><br/><br/> Installation ============== ### CocoaPods 1. Add `pod "FHHFPSIndicator"` to your Podfile. 2. Run `pod install` or `pod update`. 3. Import \<FHHFPSIndicator/FHHFPSIndicator.h\>. ### Manually 1. Drag all source files under floder `FHHFPSIndicator` to your project 2. Import the main header file:`#import "FHHFPSIndicator.h"` ###Instruction you shoud call after the keyWindw becomes keyAndVisible; Advice:Use FHHFPSIndicator in DEBUG mode add the code in AppDelegate.m <pre> #if defined(DEBUG) || defined(_DEBUG) #import "FHHFPSIndicator.h" #endif - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { // Override point for customization after application launch. self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds]; [self.window makeKeyAndVisible]; // add the follwing code after the window become keyAndVisible #if defined(DEBUG) || defined(_DEBUG) [[FHHFPSIndicator sharedFPSIndicator] show]; // [FHHFPSIndicator sharedFPSIndicator].fpsLabelPosition = FPSIndicatorPositionTopRight; #endif self.window.rootViewController = [[UINavigationController alloc] initWithRootViewController:[[HomeViewController alloc] init]]; return YES; } </pre> License ============== FHHFPSIndicator is provided under the MIT license. See LICENSE file for details. <br/> --- 中文介绍 ============== FHHFPSIndicator可以用于在iOS开发中显示当前画面的FPS. 演示项目 ============== 查看并运行 `Demo/FHHFPSIndicatorDemo` <img src="https://raw.githubusercontent.com/jvjishou/FHHFPSIndicator/master/Demo/Snapshots/snapshot1.PNG" width="320"><br/> <img src="https://raw.githubusercontent.com/jvjishou/FHHFPSIndicator/master/Demo/Snapshots/snapshot2.PNG" width="320"><br/> <img src="https://raw.githubusercontent.com/jvjishou/FHHFPSIndicator/master/Demo/Snapshots/snapshot3.PNG" width="320"><br/> <img src="https://raw.githubusercontent.com/jvjishou/FHHFPSIndicator/master/Demo/Snapshots/snapshot4.PNG" width="320"><br/><br/> 安装 ============== ### CocoaPods 1. 在 Podfile 中添加 `pod "FHHFPSIndicator"`。 2. 执行 `pod install` 或 `pod update`。 3. 导入 \<FHHFPSIndicator/FHHFPSIndicator.h\>。 ### 手动安装 1. 将`FHHFPSIndicator`文件夹中的所有源代码拽入项目中。 2. 导入主头文件:`#import "FHHFPSIndicator.h"`。 ###使用说明 在AppDelegate.m文件中的didFinishLaunchingWithOptions方法中,当执行了`[self.window makeKeyAndVisible];`后,调用`[[FHHFPSIndicator sharedFPSIndicator] show]`。<br/> 建议:在DEBUG模式下使用显示FPS功能 <pre> #if defined(DEBUG) || defined(_DEBUG) #import "FHHFPSIndicator.h" #endif - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { // Override point for customization after application launch. self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds]; [self.window makeKeyAndVisible]; // add the follwing code after the window become keyAndVisible #if defined(DEBUG) || defined(_DEBUG) [[FHHFPSIndicator sharedFPSIndicator] show]; // [FHHFPSIndicator sharedFPSIndicator].fpsLabelPosition = FPSIndicatorPositionTopRight; #endif self.window.rootViewController = [[UINavigationController alloc] initWithRootViewController:[[HomeViewController alloc] init]]; return YES; } </pre> 许可证 ============== FHHFPSIndicator 使用 MIT 许可证,详情见 LICENSE 文件。
4,387
README
md
en
markdown
text
{"qsc_doc_frac_chars_curly_bracket": 0.00091178, "qsc_doc_frac_words_redpajama_stop": 0.07462687, "qsc_doc_num_sentences": 91.0, "qsc_doc_num_words": 473, "qsc_doc_num_chars": 4387.0, "qsc_doc_num_lines": 132.0, "qsc_doc_mean_word_length": 6.86469345, "qsc_doc_frac_words_full_bracket": 0.0, "qsc_doc_frac_lines_end_with_readmore": 0.0, "qsc_doc_frac_lines_start_with_bullet": 0.0, "qsc_doc_frac_words_unique": 0.31501057, "qsc_doc_entropy_unigram": 4.58126045, "qsc_doc_frac_words_all_caps": 0.03559127, "qsc_doc_frac_lines_dupe_lines": 0.57303371, "qsc_doc_frac_chars_dupe_lines": 0.6286818, "qsc_doc_frac_chars_top_2grams": 0.02217431, "qsc_doc_frac_chars_top_3grams": 0.06929473, "qsc_doc_frac_chars_top_4grams": 0.0776101, "qsc_doc_frac_chars_dupe_5grams": 0.70680628, "qsc_doc_frac_chars_dupe_6grams": 0.70680628, "qsc_doc_frac_chars_dupe_7grams": 0.70680628, "qsc_doc_frac_chars_dupe_8grams": 0.6670773, "qsc_doc_frac_chars_dupe_9grams": 0.6670773, "qsc_doc_frac_chars_dupe_10grams": 0.6670773, "qsc_doc_frac_chars_replacement_symbols": 0.0, "qsc_doc_cate_code_related_file_name": 1.0, "qsc_doc_num_chars_sentence_length_mean": 19.22119816, "qsc_doc_frac_chars_hyperlink_html_tag": 0.33120584, "qsc_doc_frac_chars_alphabet": 0.81760204, "qsc_doc_frac_chars_digital": 0.01071429, "qsc_doc_frac_chars_whitespace": 0.10645088, "qsc_doc_frac_chars_hex_words": 0.0}
0
{"qsc_doc_frac_chars_replacement_symbols": 0, "qsc_doc_entropy_unigram": 0, "qsc_doc_frac_chars_top_2grams": 0, "qsc_doc_frac_chars_top_3grams": 0, "qsc_doc_frac_chars_top_4grams": 0, "qsc_doc_frac_chars_dupe_5grams": 1, "qsc_doc_frac_chars_dupe_6grams": 1, "qsc_doc_frac_chars_dupe_7grams": 1, "qsc_doc_frac_chars_dupe_8grams": 1, "qsc_doc_frac_chars_dupe_9grams": 1, "qsc_doc_frac_chars_dupe_10grams": 1, "qsc_doc_frac_chars_dupe_lines": 1, "qsc_doc_frac_lines_dupe_lines": 0, "qsc_doc_frac_lines_end_with_readmore": 0, "qsc_doc_frac_lines_start_with_bullet": 0, "qsc_doc_frac_words_all_caps": 0, "qsc_doc_mean_word_length": 0, "qsc_doc_num_chars": 0, "qsc_doc_num_lines": 0, "qsc_doc_num_sentences": 0, "qsc_doc_num_words": 0, "qsc_doc_frac_chars_hex_words": 0, "qsc_doc_frac_chars_hyperlink_html_tag": 0, "qsc_doc_frac_chars_alphabet": 0, "qsc_doc_frac_chars_digital": 0, "qsc_doc_frac_chars_whitespace": 0}
002and001/FHHFPSIndicator
FHHFPSIndicator/FHHFPSIndicator.m
// // FHHFPSIndicator.m // FHHFPSIndicator // // Created by 002 on 16/6/27. // Copyright © 2016年 002. All rights reserved. // #import "FHHFPSIndicator.h" #define kScreenWidth ([[UIScreen mainScreen] bounds].size.width) #define SIZE_fpsLabel CGSizeMake(44, 15) #define FONT_SIZE_fpsLabel (12) #define TAG_fpsLabel (110213) #define TEXTCOLOR_fpsLabel ([UIColor colorWithRed:85 / 255.0 green:214 / 255.0 blue:110 / 255.0 alpha:1.00]) #define PADDING_TOP_fpsLabel (15) #if TARGET_IPHONE_SIMULATOR // SIMULATOR #define PADDING_LEFT_fpsLabel (47) #define PADDING_RIGHT_fpsLabel (9) #define PADDING_CENTER_fpsLabel (1) #elif TARGET_OS_IPHONE // iPhone #define PADDING_LEFT_fpsLabel (36) #define PADDING_RIGHT_fpsLabel (-3) #define PADDING_CENTER_fpsLabel (3) #endif @interface FHHFPSIndicator () { CADisplayLink *_displayLink; NSTimeInterval _lastTime; NSUInteger _count; } @property (nonatomic, strong) UILabel *fpsLabel; @end @implementation FHHFPSIndicator + (FHHFPSIndicator *)sharedFPSIndicator { static dispatch_once_t onceToken; static FHHFPSIndicator *_instance; dispatch_once(&onceToken, ^{ _instance = [[FHHFPSIndicator alloc] init]; }); return _instance; } - (id)init { if (self = [super init]) { _displayLink = [CADisplayLink displayLinkWithTarget:self selector:@selector(p_displayLinkTick:)]; [_displayLink setPaused:YES]; [_displayLink addToRunLoop:[NSRunLoop currentRunLoop] forMode:NSRunLoopCommonModes]; // create fpsLabel _fpsLabel = [[UILabel alloc] init]; self.fpsLabelPosition = FPSIndicatorPositionBottomCenter; _fpsLabel.tag = TAG_fpsLabel; // set style for fpsLabel [self p_configFPSLabel]; [[NSNotificationCenter defaultCenter] addObserver: self selector: @selector(applicationDidBecomeActiveNotification) name: UIApplicationDidBecomeActiveNotification object: nil]; [[NSNotificationCenter defaultCenter] addObserver: self selector: @selector(applicationWillResignActiveNotification) name: UIApplicationWillResignActiveNotification object: nil]; } return self; } /** You can change the fpsLabel style for your app in this function */ - (void)p_configFPSLabel { _fpsLabel.font = [UIFont boldSystemFontOfSize:FONT_SIZE_fpsLabel]; _fpsLabel.backgroundColor = [UIColor clearColor]; _fpsLabel.textColor = TEXTCOLOR_fpsLabel; _fpsLabel.textAlignment = NSTextAlignmentCenter; } - (void)p_displayLinkTick:(CADisplayLink *)link { if (_lastTime == 0) { _lastTime = link.timestamp; return; } _count++; NSTimeInterval delta = link.timestamp - _lastTime; if (delta < 1) { return; } _lastTime = link.timestamp; float fps = _count / delta; _count = 0; NSString *text = [NSString stringWithFormat:@"%d FPS",(int)round(fps)]; [_fpsLabel setText: text]; } - (void)show { UIWindow *keyWindow = [UIApplication sharedApplication].keyWindow; for (NSUInteger i = 0; i < keyWindow.subviews.count; ++i) { UIView *view = keyWindow.subviews[keyWindow.subviews.count - 1 - i]; if ([view isKindOfClass:[UILabel class]] && view.tag == TAG_fpsLabel) { return; } } [_displayLink setPaused:NO]; [keyWindow addSubview:_fpsLabel]; } - (void)hide { [_displayLink setPaused:YES]; UIWindow *keyWindow = [UIApplication sharedApplication].keyWindow; for (UIView *label in keyWindow.subviews) { if ([label isKindOfClass:[UILabel class]]&& label.tag == TAG_fpsLabel) { [label removeFromSuperview]; return; } } } - (BOOL)isShowingFps { if (_fpsLabel.superview != nil) { return YES; } return NO; } #pragma mark - notification - (void)applicationDidBecomeActiveNotification { [_displayLink setPaused:NO]; } - (void)applicationWillResignActiveNotification { [_displayLink setPaused:YES]; } #pragma mark - setter - (void)setFpsLabelPosition:(FPSIndicatorPosition)fpsLabelPosition { _fpsLabelPosition = fpsLabelPosition; switch (_fpsLabelPosition) { case FPSIndicatorPositionTopLeft: _fpsLabel.frame = CGRectMake((kScreenWidth - SIZE_fpsLabel.width) / 2 - PADDING_LEFT_fpsLabel - 1, 2.5, SIZE_fpsLabel.width, SIZE_fpsLabel.height); break; case FPSIndicatorPositionTopRight: _fpsLabel.frame = CGRectMake((kScreenWidth + SIZE_fpsLabel.width) / 2 + (PADDING_RIGHT_fpsLabel) , 2.5, SIZE_fpsLabel.width, SIZE_fpsLabel.height); break; case FPSIndicatorPositionBottomCenter: _fpsLabel.frame = CGRectMake((kScreenWidth - SIZE_fpsLabel.width) / 2 + PADDING_CENTER_fpsLabel, PADDING_TOP_fpsLabel, SIZE_fpsLabel.width, SIZE_fpsLabel.height); break; default: break; } } - (void)setFpsLabelColor:(UIColor *)color { if (color == nil) { _fpsLabel.textColor = TEXTCOLOR_fpsLabel; } else { _fpsLabel.textColor = color; } } @end
5,409
FHHFPSIndicator
m
en
limbo
code
{"qsc_code_num_words": 474, "qsc_code_num_chars": 5409.0, "qsc_code_mean_word_length": 7.19831224, "qsc_code_frac_words_unique": 0.38396624, "qsc_code_frac_chars_top_2grams": 0.04220399, "qsc_code_frac_chars_top_3grams": 0.02989449, "qsc_code_frac_chars_top_4grams": 0.03077374, "qsc_code_frac_chars_dupe_5grams": 0.16354045, "qsc_code_frac_chars_dupe_6grams": 0.16354045, "qsc_code_frac_chars_dupe_7grams": 0.09144197, "qsc_code_frac_chars_dupe_8grams": 0.07971864, "qsc_code_frac_chars_dupe_9grams": 0.07971864, "qsc_code_frac_chars_dupe_10grams": 0.02696366, "qsc_code_frac_chars_replacement_symbols": 0.0, "qsc_code_frac_chars_digital": 0.01814115, "qsc_code_frac_chars_whitespace": 0.25605472, "qsc_code_size_file_byte": 5409.0, "qsc_code_num_lines": 173.0, "qsc_code_num_chars_line_max": 175.0, "qsc_code_num_chars_line_mean": 31.26589595, "qsc_code_frac_chars_alphabet": 0.82952286, "qsc_code_frac_chars_comments": 0.12645591, "qsc_code_cate_xml_start": 0.0, "qsc_code_frac_lines_dupe_lines": 0.21875, "qsc_code_cate_autogen": 0.0, "qsc_code_frac_lines_long_string": 0.0, "qsc_code_frac_chars_string_length": 0.00126984, "qsc_code_frac_chars_long_word_length": 0.0, "qsc_code_frac_lines_string_concat": 0.0, "qsc_code_cate_encoded_data": 0.0, "qsc_code_frac_chars_hex_words": 0.0, "qsc_code_frac_lines_prompt_comments": 0.0, "qsc_code_frac_lines_assert": 0.0}
1
{"qsc_code_frac_chars_replacement_symbols": 0, "qsc_code_num_words": 0, "qsc_code_num_chars": 0, "qsc_code_mean_word_length": 0, "qsc_code_frac_chars_top_2grams": 0, "qsc_code_frac_chars_top_3grams": 0, "qsc_code_frac_chars_top_4grams": 0, "qsc_code_frac_chars_dupe_5grams": 0, "qsc_code_frac_chars_dupe_6grams": 0, "qsc_code_frac_chars_dupe_7grams": 0, "qsc_code_frac_chars_dupe_8grams": 0, "qsc_code_frac_chars_dupe_9grams": 0, "qsc_code_frac_chars_dupe_10grams": 0, "qsc_code_frac_lines_dupe_lines": 0, "qsc_code_size_file_byte": 0, "qsc_code_num_lines": 0, "qsc_code_num_chars_line_max": 0, "qsc_code_num_chars_line_mean": 0, "qsc_code_frac_chars_alphabet": 0, "qsc_code_frac_chars_digital": 0, "qsc_code_frac_chars_whitespace": 0, "qsc_code_frac_chars_comments": 0, "qsc_code_cate_xml_start": 0, "qsc_code_cate_autogen": 0, "qsc_code_frac_lines_long_string": 0, "qsc_code_frac_chars_string_length": 0, "qsc_code_frac_chars_long_word_length": 0, "qsc_code_cate_encoded_data": 0, "qsc_code_frac_chars_hex_words": 0, "qsc_code_frac_lines_prompt_comments": 0, "qsc_code_frac_lines_assert": 0}
002and001/FHHFPSIndicator
FHHFPSIndicator/FHHFPSIndicator.h
// // FHHFPSIndicator.h // FHHFPSIndicator:https://github.com/jvjishou/FHHFPSIndicator // // Created by 002 on 16/6/27. // Copyright © 2016年 002. All rights reserved. // // This source code is licensed under the MIT-style license found in the // LICENSE file in the root directory of this source tree. // #import <Foundation/Foundation.h> #import <UIKit/UIKit.h> #import "UIWindow+FHH.h" // FpsLabel's position. Default is FPSIndicatorPositionBottomCenter // If your device is iPhone4's or iPhone5's series,use FPSIndicatorPositionBottomCenter to make the fpsLabel show completed. typedef enum { FPSIndicatorPositionTopLeft, ///<left-center on statusBar FPSIndicatorPositionTopRight, ///<right-center on statusBar FPSIndicatorPositionBottomCenter ///<under the statusBar } FPSIndicatorPosition; @interface FHHFPSIndicator : NSObject #pragma mark - Attribute ///============================================================================= /// @name Attribute ///============================================================================= @property(nonatomic,assign) FPSIndicatorPosition fpsLabelPosition; #pragma mark - Initializer ///============================================================================= /// @name Initializer ///============================================================================= /** Returns global shared FHHFPSIndicator instance. @return The singleton FHHFPSIndicator instance. */ + (FHHFPSIndicator *)sharedFPSIndicator; #pragma mark - Access Methods ///============================================================================= /// @name Access Methods ///============================================================================= /** Set fpsLabel.textColor @param color The color to be setted for fpsLabel.textColor. If nil,the default Color will be setted. */ - (void)setFpsLabelColor:(UIColor *)color; /** Show fpsLabel at the top of keyWindow Note:If you change the keyWindow,you shoud call this function again after the new keyWindw becomes keyAndVisible. */ - (void)show; /** Hide fpsLabel Note:If you call this function in the code,the fpsLabel will always be hided in the keyWindow until you call 'show' function again. */ - (void)hide; /** return ture if fpsLabel shown on the screen.otherwhise return false */ - (BOOL)isShowingFps; @end
2,361
FHHFPSIndicator
h
en
c
code
{"qsc_code_num_words": 229, "qsc_code_num_chars": 2361.0, "qsc_code_mean_word_length": 6.1441048, "qsc_code_frac_words_unique": 0.55021834, "qsc_code_frac_chars_top_2grams": 0.01421464, "qsc_code_frac_chars_top_3grams": 0.02416489, "qsc_code_frac_chars_top_4grams": 0.0, "qsc_code_frac_chars_dupe_5grams": 0.0, "qsc_code_frac_chars_dupe_6grams": 0.0, "qsc_code_frac_chars_dupe_7grams": 0.0, "qsc_code_frac_chars_dupe_8grams": 0.0, "qsc_code_frac_chars_dupe_9grams": 0.0, "qsc_code_frac_chars_dupe_10grams": 0.0, "qsc_code_frac_chars_replacement_symbols": 0.0, "qsc_code_frac_chars_digital": 0.00825243, "qsc_code_frac_chars_whitespace": 0.12748835, "qsc_code_size_file_byte": 2361.0, "qsc_code_num_lines": 75.0, "qsc_code_num_chars_line_max": 133.0, "qsc_code_num_chars_line_mean": 31.48, "qsc_code_frac_chars_alphabet": 0.67427184, "qsc_code_frac_chars_comments": 0.75095299, "qsc_code_cate_xml_start": 0.0, "qsc_code_frac_lines_dupe_lines": 0.0, "qsc_code_cate_autogen": 0.0, "qsc_code_frac_lines_long_string": 0.0, "qsc_code_frac_chars_string_length": 0.02380952, "qsc_code_frac_chars_long_word_length": 0.0, "qsc_code_frac_lines_string_concat": 0.0, "qsc_code_cate_encoded_data": 0.0, "qsc_code_frac_chars_hex_words": 0.0, "qsc_code_frac_lines_prompt_comments": 0.0, "qsc_code_frac_lines_assert": 0.0, "qsc_codec_frac_lines_func_ratio": 0.0, "qsc_codec_cate_bitsstdc": 0.0, "qsc_codec_nums_lines_main": 0, "qsc_codec_frac_lines_goto": 0.0, "qsc_codec_cate_var_zero": 0.0, "qsc_codec_score_lines_no_logic": 0.0, "qsc_codec_frac_lines_print": 0.0, "qsc_codec_frac_lines_preprocessor_directives": null}
1
{"qsc_code_frac_chars_replacement_symbols": 0, "qsc_code_num_words": 0, "qsc_code_num_chars": 0, "qsc_code_mean_word_length": 0, "qsc_code_frac_chars_top_2grams": 0, "qsc_code_frac_chars_top_3grams": 0, "qsc_code_frac_chars_top_4grams": 0, "qsc_code_frac_chars_dupe_5grams": 0, "qsc_code_frac_chars_dupe_6grams": 0, "qsc_code_frac_chars_dupe_7grams": 0, "qsc_code_frac_chars_dupe_8grams": 0, "qsc_code_frac_chars_dupe_9grams": 0, "qsc_code_frac_chars_dupe_10grams": 0, "qsc_code_size_file_byte": 0, "qsc_code_num_lines": 0, "qsc_code_num_chars_line_max": 0, "qsc_code_num_chars_line_mean": 0, "qsc_code_frac_chars_alphabet": 0, "qsc_code_frac_chars_digital": 0, "qsc_code_frac_chars_whitespace": 0, "qsc_code_frac_chars_comments": 0, "qsc_code_cate_xml_start": 0, "qsc_code_frac_lines_dupe_lines": 0, "qsc_code_cate_autogen": 0, "qsc_code_frac_lines_long_string": 0, "qsc_code_frac_chars_string_length": 0, "qsc_code_frac_chars_long_word_length": 0, "qsc_code_cate_encoded_data": 0, "qsc_code_frac_chars_hex_words": 0, "qsc_code_frac_lines_prompt_comments": 0, "qsc_code_frac_lines_assert": 0, "qsc_codec_frac_lines_func_ratio": 0, "qsc_codec_nums_lines_main": 0, "qsc_codec_score_lines_no_logic": 0, "qsc_codec_frac_lines_preprocessor_directives": 0, "qsc_codec_frac_lines_print": 0}
002and001/FHHFPSIndicator
Demo/FHHFPSIndicatorDemo.xcodeproj/project.pbxproj
// !$*UTF8*$! { archiveVersion = 1; classes = { }; objectVersion = 46; objects = { /* Begin PBXBuildFile section */ 25C90C9C1D227566002F1B5E /* main.m in Sources */ = {isa = PBXBuildFile; fileRef = 25C90C9B1D227566002F1B5E /* main.m */; }; 25C90CA71D227566002F1B5E /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 25C90CA61D227566002F1B5E /* Assets.xcassets */; }; 25C90CAA1D227566002F1B5E /* LaunchScreen.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 25C90CA81D227566002F1B5E /* LaunchScreen.storyboard */; }; 25C90CBC1D22762D002F1B5E /* AppDelegate.m in Sources */ = {isa = PBXBuildFile; fileRef = 25C90CB31D22762D002F1B5E /* AppDelegate.m */; }; 25C90CBD1D22762D002F1B5E /* HomeViewController.m in Sources */ = {isa = PBXBuildFile; fileRef = 25C90CB51D22762D002F1B5E /* HomeViewController.m */; }; 25C90CBE1D22762D002F1B5E /* LastHomeViewController.m in Sources */ = {isa = PBXBuildFile; fileRef = 25C90CB71D22762D002F1B5E /* LastHomeViewController.m */; }; 25C90CBF1D22762D002F1B5E /* SubHomeViewController.m in Sources */ = {isa = PBXBuildFile; fileRef = 25C90CB91D22762D002F1B5E /* SubHomeViewController.m */; }; 25C90CC01D22762D002F1B5E /* WildernessViewController.m in Sources */ = {isa = PBXBuildFile; fileRef = 25C90CBB1D22762D002F1B5E /* WildernessViewController.m */; }; 25C90CC61D227636002F1B5E /* UIView+FHH.m in Sources */ = {isa = PBXBuildFile; fileRef = 25C90CC31D227636002F1B5E /* UIView+FHH.m */; }; 25C90CC71D227636002F1B5E /* UIViewController+CustomNavigationBar.m in Sources */ = {isa = PBXBuildFile; fileRef = 25C90CC51D227636002F1B5E /* UIViewController+CustomNavigationBar.m */; }; 25C90CD41D237DF0002F1B5E /* FHHFPSIndicator.m in Sources */ = {isa = PBXBuildFile; fileRef = 25C90CD11D237DF0002F1B5E /* FHHFPSIndicator.m */; }; 25C90CD51D237DF0002F1B5E /* UIWindow+FHH.m in Sources */ = {isa = PBXBuildFile; fileRef = 25C90CD31D237DF0002F1B5E /* UIWindow+FHH.m */; }; /* End PBXBuildFile section */ /* Begin PBXFileReference section */ 257574D81F5E9D440069680F /* Commom.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = Commom.h; sourceTree = "<group>"; }; 257574D91F5E9D510069680F /* PrefixHeader.pch */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = PrefixHeader.pch; sourceTree = "<group>"; }; 257574DB1F5E9EF50069680F /* CommonFont.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CommonFont.h; sourceTree = "<group>"; }; 257574DC1F5E9F120069680F /* CommonColor.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CommonColor.h; sourceTree = "<group>"; }; 257574DD1F5EA0010069680F /* CommonPadding.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CommonPadding.h; sourceTree = "<group>"; }; 25C90C971D227566002F1B5E /* FHHFPSIndicatorDemo.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = FHHFPSIndicatorDemo.app; sourceTree = BUILT_PRODUCTS_DIR; }; 25C90C9B1D227566002F1B5E /* main.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = main.m; sourceTree = "<group>"; }; 25C90CA61D227566002F1B5E /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Assets.xcassets; sourceTree = "<group>"; }; 25C90CA91D227566002F1B5E /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/LaunchScreen.storyboard; sourceTree = "<group>"; }; 25C90CAB1D227566002F1B5E /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = "<group>"; }; 25C90CB21D22762D002F1B5E /* AppDelegate.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = AppDelegate.h; sourceTree = "<group>"; }; 25C90CB31D22762D002F1B5E /* AppDelegate.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = AppDelegate.m; sourceTree = "<group>"; }; 25C90CB41D22762D002F1B5E /* HomeViewController.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = HomeViewController.h; sourceTree = "<group>"; }; 25C90CB51D22762D002F1B5E /* HomeViewController.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = HomeViewController.m; sourceTree = "<group>"; }; 25C90CB61D22762D002F1B5E /* LastHomeViewController.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = LastHomeViewController.h; sourceTree = "<group>"; }; 25C90CB71D22762D002F1B5E /* LastHomeViewController.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = LastHomeViewController.m; sourceTree = "<group>"; }; 25C90CB81D22762D002F1B5E /* SubHomeViewController.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = SubHomeViewController.h; sourceTree = "<group>"; }; 25C90CB91D22762D002F1B5E /* SubHomeViewController.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = SubHomeViewController.m; sourceTree = "<group>"; }; 25C90CBA1D22762D002F1B5E /* WildernessViewController.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = WildernessViewController.h; sourceTree = "<group>"; }; 25C90CBB1D22762D002F1B5E /* WildernessViewController.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = WildernessViewController.m; sourceTree = "<group>"; }; 25C90CC21D227636002F1B5E /* UIView+FHH.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = "UIView+FHH.h"; sourceTree = "<group>"; }; 25C90CC31D227636002F1B5E /* UIView+FHH.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = "UIView+FHH.m"; sourceTree = "<group>"; }; 25C90CC41D227636002F1B5E /* UIViewController+CustomNavigationBar.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = "UIViewController+CustomNavigationBar.h"; sourceTree = "<group>"; }; 25C90CC51D227636002F1B5E /* UIViewController+CustomNavigationBar.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = "UIViewController+CustomNavigationBar.m"; sourceTree = "<group>"; }; 25C90CD01D237DF0002F1B5E /* FHHFPSIndicator.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = FHHFPSIndicator.h; sourceTree = "<group>"; }; 25C90CD11D237DF0002F1B5E /* FHHFPSIndicator.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = FHHFPSIndicator.m; sourceTree = "<group>"; }; 25C90CD21D237DF0002F1B5E /* UIWindow+FHH.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = "UIWindow+FHH.h"; sourceTree = "<group>"; }; 25C90CD31D237DF0002F1B5E /* UIWindow+FHH.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = "UIWindow+FHH.m"; sourceTree = "<group>"; }; /* End PBXFileReference section */ /* Begin PBXFrameworksBuildPhase section */ 25C90C941D227566002F1B5E /* Frameworks */ = { isa = PBXFrameworksBuildPhase; buildActionMask = 2147483647; files = ( ); runOnlyForDeploymentPostprocessing = 0; }; /* End PBXFrameworksBuildPhase section */ /* Begin PBXGroup section */ 25C90C8E1D227566002F1B5E = { isa = PBXGroup; children = ( 25C90C991D227566002F1B5E /* FHHFPSIndicatorDemo */, 25C90C981D227566002F1B5E /* Products */, ); sourceTree = "<group>"; }; 25C90C981D227566002F1B5E /* Products */ = { isa = PBXGroup; children = ( 25C90C971D227566002F1B5E /* FHHFPSIndicatorDemo.app */, ); name = Products; sourceTree = "<group>"; }; 25C90C991D227566002F1B5E /* FHHFPSIndicatorDemo */ = { isa = PBXGroup; children = ( 25C90CCF1D237DF0002F1B5E /* FHHFPSIndicator */, 25C90CC11D227636002F1B5E /* Utility */, 25C90CB11D22762D002F1B5E /* Classes */, 25C90CA61D227566002F1B5E /* Assets.xcassets */, 25C90CA81D227566002F1B5E /* LaunchScreen.storyboard */, 25C90CAB1D227566002F1B5E /* Info.plist */, 25C90C9A1D227566002F1B5E /* Supporting Files */, ); path = FHHFPSIndicatorDemo; sourceTree = "<group>"; }; 25C90C9A1D227566002F1B5E /* Supporting Files */ = { isa = PBXGroup; children = ( 25C90C9B1D227566002F1B5E /* main.m */, 257574D81F5E9D440069680F /* Commom.h */, 257574D91F5E9D510069680F /* PrefixHeader.pch */, 257574DB1F5E9EF50069680F /* CommonFont.h */, 257574DC1F5E9F120069680F /* CommonColor.h */, 257574DD1F5EA0010069680F /* CommonPadding.h */, ); name = "Supporting Files"; sourceTree = "<group>"; }; 25C90CB11D22762D002F1B5E /* Classes */ = { isa = PBXGroup; children = ( 25C90CB21D22762D002F1B5E /* AppDelegate.h */, 25C90CB31D22762D002F1B5E /* AppDelegate.m */, 25C90CB41D22762D002F1B5E /* HomeViewController.h */, 25C90CB51D22762D002F1B5E /* HomeViewController.m */, 25C90CB81D22762D002F1B5E /* SubHomeViewController.h */, 25C90CB91D22762D002F1B5E /* SubHomeViewController.m */, 25C90CB61D22762D002F1B5E /* LastHomeViewController.h */, 25C90CB71D22762D002F1B5E /* LastHomeViewController.m */, 25C90CBA1D22762D002F1B5E /* WildernessViewController.h */, 25C90CBB1D22762D002F1B5E /* WildernessViewController.m */, ); path = Classes; sourceTree = "<group>"; }; 25C90CC11D227636002F1B5E /* Utility */ = { isa = PBXGroup; children = ( 25C90CC21D227636002F1B5E /* UIView+FHH.h */, 25C90CC31D227636002F1B5E /* UIView+FHH.m */, 25C90CC41D227636002F1B5E /* UIViewController+CustomNavigationBar.h */, 25C90CC51D227636002F1B5E /* UIViewController+CustomNavigationBar.m */, ); path = Utility; sourceTree = "<group>"; }; 25C90CCF1D237DF0002F1B5E /* FHHFPSIndicator */ = { isa = PBXGroup; children = ( 25C90CD01D237DF0002F1B5E /* FHHFPSIndicator.h */, 25C90CD11D237DF0002F1B5E /* FHHFPSIndicator.m */, 25C90CD21D237DF0002F1B5E /* UIWindow+FHH.h */, 25C90CD31D237DF0002F1B5E /* UIWindow+FHH.m */, ); name = FHHFPSIndicator; path = ../../FHHFPSIndicator; sourceTree = "<group>"; }; /* End PBXGroup section */ /* Begin PBXNativeTarget section */ 25C90C961D227566002F1B5E /* FHHFPSIndicatorDemo */ = { isa = PBXNativeTarget; buildConfigurationList = 25C90CAE1D227566002F1B5E /* Build configuration list for PBXNativeTarget "FHHFPSIndicatorDemo" */; buildPhases = ( 25C90C931D227566002F1B5E /* Sources */, 25C90C941D227566002F1B5E /* Frameworks */, 25C90C951D227566002F1B5E /* Resources */, ); buildRules = ( ); dependencies = ( ); name = FHHFPSIndicatorDemo; productName = FHHFPSIndicatorDemo; productReference = 25C90C971D227566002F1B5E /* FHHFPSIndicatorDemo.app */; productType = "com.apple.product-type.application"; }; /* End PBXNativeTarget section */ /* Begin PBXProject section */ 25C90C8F1D227566002F1B5E /* Project object */ = { isa = PBXProject; attributes = { LastUpgradeCheck = 0730; ORGANIZATIONNAME = 002; TargetAttributes = { 25C90C961D227566002F1B5E = { CreatedOnToolsVersion = 7.3; }; }; }; buildConfigurationList = 25C90C921D227566002F1B5E /* Build configuration list for PBXProject "FHHFPSIndicatorDemo" */; compatibilityVersion = "Xcode 3.2"; developmentRegion = English; hasScannedForEncodings = 0; knownRegions = ( en, Base, ); mainGroup = 25C90C8E1D227566002F1B5E; productRefGroup = 25C90C981D227566002F1B5E /* Products */; projectDirPath = ""; projectRoot = ""; targets = ( 25C90C961D227566002F1B5E /* FHHFPSIndicatorDemo */, ); }; /* End PBXProject section */ /* Begin PBXResourcesBuildPhase section */ 25C90C951D227566002F1B5E /* Resources */ = { isa = PBXResourcesBuildPhase; buildActionMask = 2147483647; files = ( 25C90CAA1D227566002F1B5E /* LaunchScreen.storyboard in Resources */, 25C90CA71D227566002F1B5E /* Assets.xcassets in Resources */, ); runOnlyForDeploymentPostprocessing = 0; }; /* End PBXResourcesBuildPhase section */ /* Begin PBXSourcesBuildPhase section */ 25C90C931D227566002F1B5E /* Sources */ = { isa = PBXSourcesBuildPhase; buildActionMask = 2147483647; files = ( 25C90CC01D22762D002F1B5E /* WildernessViewController.m in Sources */, 25C90CC71D227636002F1B5E /* UIViewController+CustomNavigationBar.m in Sources */, 25C90CD51D237DF0002F1B5E /* UIWindow+FHH.m in Sources */, 25C90CBC1D22762D002F1B5E /* AppDelegate.m in Sources */, 25C90CC61D227636002F1B5E /* UIView+FHH.m in Sources */, 25C90CBF1D22762D002F1B5E /* SubHomeViewController.m in Sources */, 25C90C9C1D227566002F1B5E /* main.m in Sources */, 25C90CBD1D22762D002F1B5E /* HomeViewController.m in Sources */, 25C90CD41D237DF0002F1B5E /* FHHFPSIndicator.m in Sources */, 25C90CBE1D22762D002F1B5E /* LastHomeViewController.m in Sources */, ); runOnlyForDeploymentPostprocessing = 0; }; /* End PBXSourcesBuildPhase section */ /* Begin PBXVariantGroup section */ 25C90CA81D227566002F1B5E /* LaunchScreen.storyboard */ = { isa = PBXVariantGroup; children = ( 25C90CA91D227566002F1B5E /* Base */, ); name = LaunchScreen.storyboard; sourceTree = "<group>"; }; /* End PBXVariantGroup section */ /* Begin XCBuildConfiguration section */ 25C90CAC1D227566002F1B5E /* Debug */ = { isa = XCBuildConfiguration; buildSettings = { ALWAYS_SEARCH_USER_PATHS = NO; CLANG_ANALYZER_NONNULL = YES; CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; CLANG_CXX_LIBRARY = "libc++"; CLANG_ENABLE_MODULES = YES; CLANG_ENABLE_OBJC_ARC = YES; CLANG_WARN_BOOL_CONVERSION = YES; CLANG_WARN_CONSTANT_CONVERSION = YES; CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; CLANG_WARN_EMPTY_BODY = YES; CLANG_WARN_ENUM_CONVERSION = YES; CLANG_WARN_INT_CONVERSION = YES; CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; CLANG_WARN_UNREACHABLE_CODE = YES; CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; COPY_PHASE_STRIP = NO; DEBUG_INFORMATION_FORMAT = dwarf; ENABLE_STRICT_OBJC_MSGSEND = YES; ENABLE_TESTABILITY = YES; GCC_C_LANGUAGE_STANDARD = gnu99; GCC_DYNAMIC_NO_PIC = NO; GCC_NO_COMMON_BLOCKS = YES; GCC_OPTIMIZATION_LEVEL = 0; GCC_PREPROCESSOR_DEFINITIONS = ( "DEBUG=1", "$(inherited)", ); GCC_WARN_64_TO_32_BIT_CONVERSION = YES; GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; GCC_WARN_UNDECLARED_SELECTOR = YES; GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; GCC_WARN_UNUSED_FUNCTION = YES; GCC_WARN_UNUSED_VARIABLE = YES; IPHONEOS_DEPLOYMENT_TARGET = 9.3; MTL_ENABLE_DEBUG_INFO = YES; ONLY_ACTIVE_ARCH = YES; SDKROOT = iphoneos; TARGETED_DEVICE_FAMILY = "1,2"; }; name = Debug; }; 25C90CAD1D227566002F1B5E /* Release */ = { isa = XCBuildConfiguration; buildSettings = { ALWAYS_SEARCH_USER_PATHS = NO; CLANG_ANALYZER_NONNULL = YES; CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; CLANG_CXX_LIBRARY = "libc++"; CLANG_ENABLE_MODULES = YES; CLANG_ENABLE_OBJC_ARC = YES; CLANG_WARN_BOOL_CONVERSION = YES; CLANG_WARN_CONSTANT_CONVERSION = YES; CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; CLANG_WARN_EMPTY_BODY = YES; CLANG_WARN_ENUM_CONVERSION = YES; CLANG_WARN_INT_CONVERSION = YES; CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; CLANG_WARN_UNREACHABLE_CODE = YES; CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; COPY_PHASE_STRIP = NO; DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; ENABLE_NS_ASSERTIONS = NO; ENABLE_STRICT_OBJC_MSGSEND = YES; GCC_C_LANGUAGE_STANDARD = gnu99; GCC_NO_COMMON_BLOCKS = YES; GCC_WARN_64_TO_32_BIT_CONVERSION = YES; GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; GCC_WARN_UNDECLARED_SELECTOR = YES; GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; GCC_WARN_UNUSED_FUNCTION = YES; GCC_WARN_UNUSED_VARIABLE = YES; IPHONEOS_DEPLOYMENT_TARGET = 9.3; MTL_ENABLE_DEBUG_INFO = NO; SDKROOT = iphoneos; TARGETED_DEVICE_FAMILY = "1,2"; VALIDATE_PRODUCT = YES; }; name = Release; }; 25C90CAF1D227566002F1B5E /* Debug */ = { isa = XCBuildConfiguration; buildSettings = { ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; GCC_PRECOMPILE_PREFIX_HEADER = YES; GCC_PREFIX_HEADER = FHHFPSIndicatorDemo/PrefixHeader.pch; INFOPLIST_FILE = FHHFPSIndicatorDemo/Info.plist; IPHONEOS_DEPLOYMENT_TARGET = 7.0; LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks"; PRODUCT_BUNDLE_IDENTIFIER = com.fhhe.FHHFPSIndicatorDemo; PRODUCT_NAME = "$(TARGET_NAME)"; PROVISIONING_PROFILE = "21ab5b6e-3985-4566-9933-d7c4ba336123"; }; name = Debug; }; 25C90CB01D227566002F1B5E /* Release */ = { isa = XCBuildConfiguration; buildSettings = { ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; GCC_PRECOMPILE_PREFIX_HEADER = YES; GCC_PREFIX_HEADER = FHHFPSIndicatorDemo/PrefixHeader.pch; INFOPLIST_FILE = FHHFPSIndicatorDemo/Info.plist; IPHONEOS_DEPLOYMENT_TARGET = 7.0; LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks"; PRODUCT_BUNDLE_IDENTIFIER = com.fhhe.FHHFPSIndicatorDemo; PRODUCT_NAME = "$(TARGET_NAME)"; PROVISIONING_PROFILE = "21ab5b6e-3985-4566-9933-d7c4ba336123"; }; name = Release; }; /* End XCBuildConfiguration section */ /* Begin XCConfigurationList section */ 25C90C921D227566002F1B5E /* Build configuration list for PBXProject "FHHFPSIndicatorDemo" */ = { isa = XCConfigurationList; buildConfigurations = ( 25C90CAC1D227566002F1B5E /* Debug */, 25C90CAD1D227566002F1B5E /* Release */, ); defaultConfigurationIsVisible = 0; defaultConfigurationName = Release; }; 25C90CAE1D227566002F1B5E /* Build configuration list for PBXNativeTarget "FHHFPSIndicatorDemo" */ = { isa = XCConfigurationList; buildConfigurations = ( 25C90CAF1D227566002F1B5E /* Debug */, 25C90CB01D227566002F1B5E /* Release */, ); defaultConfigurationIsVisible = 0; defaultConfigurationName = Release; }; /* End XCConfigurationList section */ }; rootObject = 25C90C8F1D227566002F1B5E /* Project object */; }
18,633
project
pbxproj
en
unknown
unknown
{}
0
{}
002and001/FHHFPSIndicator
Demo/FHHFPSIndicatorDemo/CommonColor.h
// // CommonColor.h // FHHFPSIndicatorDemo // // Created by hefanghui on 2017/9/5. // Copyright © 2017年 002. All rights reserved. // #ifndef CommonColor_h #define CommonColor_h #define RandomColor [UIColor colorWithRed:arc4random_uniform(255)/255.0 green:arc4random_uniform(255)/255.0 blue:arc4random_uniform(255)/255.0 alpha:1.0] #define RGBColor(r, g, b) [UIColor colorWithRed:(r)/255.0 green:(g)/255.0 blue:(b)/255.0 alpha:1.0] #define HQColor(RED, GREEN, BLUE, ALPHA) [UIColor colorWithRed:RED green:GREEN blue:BLUE alpha:ALPHA] #define kColorAlpha(color, alpha) [color colorWithAlphaComponent:alpha] #define kColorBackGround RGBColor(246,246,246) #define kColorLine RGBColor(237,237,237) #define kColorC1_1 RGBColor(255,128,35) #define kColorC1_2 RGBColor(240,118,29) #define kColorC2_1 RGBColor(250,151,39) #define kColorC2_2 RGBColor(250,201,71) #define kColorC2_3 RGBColor(197,144,105) #define kColorC2_4 RGBColor(255,133,133) #define kColorC2_5 RGBColor(124,219,90) #define kColorC3_1 RGBColor(40,40,40) #define kColorC3_2 RGBColor(58,58,58) #define kColorC3_3 RGBColor(80,80,80) #define kColorC3_4 RGBColor(119,119,119) #define kColorC3_5 RGBColor(156,156,156) #define kColorC3_6 RGBColor(187,187,187) #define kColorC3_7 RGBColor(204,204,204) #define kColorC4_1 RGBColor(255,255,255) #define kColorC4_2 RGBColor(245,246,247) #define kColorC4_3 RGBColor(250,250,250) #define kColorC4_4 RGBColor(237,237,237) #define kColorC4_5 RGBColor(220,220,220) #define kColorC4_6 RGBColor(240,240,240) #endif /* CommonColor_h */
1,538
CommonColor
h
en
c
code
{"qsc_code_num_words": 245, "qsc_code_num_chars": 1538.0, "qsc_code_mean_word_length": 4.79183673, "qsc_code_frac_words_unique": 0.32653061, "qsc_code_frac_chars_top_2grams": 0.0834753, "qsc_code_frac_chars_top_3grams": 0.05110733, "qsc_code_frac_chars_top_4grams": 0.05877342, "qsc_code_frac_chars_dupe_5grams": 0.12606474, "qsc_code_frac_chars_dupe_6grams": 0.02896082, "qsc_code_frac_chars_dupe_7grams": 0.0, "qsc_code_frac_chars_dupe_8grams": 0.0, "qsc_code_frac_chars_dupe_9grams": 0.0, "qsc_code_frac_chars_dupe_10grams": 0.0, "qsc_code_frac_chars_replacement_symbols": 0.0, "qsc_code_frac_chars_digital": 0.19785714, "qsc_code_frac_chars_whitespace": 0.08972692, "qsc_code_size_file_byte": 1538.0, "qsc_code_num_lines": 44.0, "qsc_code_num_chars_line_max": 154.0, "qsc_code_num_chars_line_mean": 34.95454545, "qsc_code_frac_chars_alphabet": 0.64, "qsc_code_frac_chars_comments": 0.10143043, "qsc_code_cate_xml_start": 0.0, "qsc_code_frac_lines_dupe_lines": 0.0, "qsc_code_cate_autogen": 0.0, "qsc_code_frac_lines_long_string": 0.0, "qsc_code_frac_chars_string_length": 0.0, "qsc_code_frac_chars_long_word_length": 0.0, "qsc_code_frac_lines_string_concat": 0.0, "qsc_code_cate_encoded_data": 0.0, "qsc_code_frac_chars_hex_words": 0.0, "qsc_code_frac_lines_prompt_comments": 0.0, "qsc_code_frac_lines_assert": 0.0, "qsc_codec_frac_lines_func_ratio": 0.86206897, "qsc_codec_cate_bitsstdc": 0.0, "qsc_codec_nums_lines_main": 0, "qsc_codec_frac_lines_goto": 0.0, "qsc_codec_cate_var_zero": 1.0, "qsc_codec_score_lines_no_logic": 0.86206897, "qsc_codec_frac_lines_print": 0.0, "qsc_codec_frac_lines_preprocessor_directives": null}
0
{"qsc_code_frac_chars_replacement_symbols": 0, "qsc_code_num_words": 0, "qsc_code_num_chars": 0, "qsc_code_mean_word_length": 0, "qsc_code_frac_chars_top_2grams": 0, "qsc_code_frac_chars_top_3grams": 0, "qsc_code_frac_chars_top_4grams": 0, "qsc_code_frac_chars_dupe_5grams": 0, "qsc_code_frac_chars_dupe_6grams": 0, "qsc_code_frac_chars_dupe_7grams": 0, "qsc_code_frac_chars_dupe_8grams": 0, "qsc_code_frac_chars_dupe_9grams": 0, "qsc_code_frac_chars_dupe_10grams": 0, "qsc_code_size_file_byte": 0, "qsc_code_num_lines": 0, "qsc_code_num_chars_line_max": 0, "qsc_code_num_chars_line_mean": 0, "qsc_code_frac_chars_alphabet": 0, "qsc_code_frac_chars_digital": 0, "qsc_code_frac_chars_whitespace": 0, "qsc_code_frac_chars_comments": 0, "qsc_code_cate_xml_start": 0, "qsc_code_frac_lines_dupe_lines": 0, "qsc_code_cate_autogen": 0, "qsc_code_frac_lines_long_string": 0, "qsc_code_frac_chars_string_length": 0, "qsc_code_frac_chars_long_word_length": 0, "qsc_code_cate_encoded_data": 0, "qsc_code_frac_chars_hex_words": 0, "qsc_code_frac_lines_prompt_comments": 0, "qsc_code_frac_lines_assert": 0, "qsc_codec_frac_lines_func_ratio": 1, "qsc_codec_nums_lines_main": 0, "qsc_codec_score_lines_no_logic": 1, "qsc_codec_frac_lines_preprocessor_directives": 0, "qsc_codec_frac_lines_print": 0}
002and001/FHHFPSIndicator
Demo/FHHFPSIndicatorDemo/Info.plist
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> <plist version="1.0"> <dict> <key>CFBundleDevelopmentRegion</key> <string>en</string> <key>CFBundleExecutable</key> <string>$(EXECUTABLE_NAME)</string> <key>CFBundleIdentifier</key> <string>$(PRODUCT_BUNDLE_IDENTIFIER)</string> <key>CFBundleInfoDictionaryVersion</key> <string>6.0</string> <key>CFBundleName</key> <string>$(PRODUCT_NAME)</string> <key>CFBundlePackageType</key> <string>APPL</string> <key>CFBundleShortVersionString</key> <string>1.0</string> <key>CFBundleSignature</key> <string>????</string> <key>CFBundleVersion</key> <string>1</string> <key>LSRequiresIPhoneOS</key> <true/> <key>UILaunchStoryboardName</key> <string>LaunchScreen</string> <key>UIRequiredDeviceCapabilities</key> <array> <string>armv7</string> </array> <key>UISupportedInterfaceOrientations</key> <array> <string>UIInterfaceOrientationPortrait</string> <string>UIInterfaceOrientationLandscapeLeft</string> <string>UIInterfaceOrientationLandscapeRight</string> </array> <key>UISupportedInterfaceOrientations~ipad</key> <array> <string>UIInterfaceOrientationPortrait</string> <string>UIInterfaceOrientationPortraitUpsideDown</string> <string>UIInterfaceOrientationLandscapeLeft</string> <string>UIInterfaceOrientationLandscapeRight</string> </array> </dict> </plist>
1,439
Info
plist
en
openstep property list
data
{"qsc_code_num_words": 141, "qsc_code_num_chars": 1439.0, "qsc_code_mean_word_length": 7.72340426, "qsc_code_frac_words_unique": 0.35460993, "qsc_code_frac_chars_top_2grams": 0.08264463, "qsc_code_frac_chars_top_3grams": 0.03856749, "qsc_code_frac_chars_top_4grams": 0.08448118, "qsc_code_frac_chars_dupe_5grams": 0.28650138, "qsc_code_frac_chars_dupe_6grams": 0.28650138, "qsc_code_frac_chars_dupe_7grams": 0.19467401, "qsc_code_frac_chars_dupe_8grams": 0.19467401, "qsc_code_frac_chars_dupe_9grams": 0.0, "qsc_code_frac_chars_dupe_10grams": 0.0, "qsc_code_frac_chars_replacement_symbols": 0.0, "qsc_code_frac_chars_digital": 0.01121076, "qsc_code_frac_chars_whitespace": 0.07018763, "qsc_code_size_file_byte": 1439.0, "qsc_code_num_lines": 45.0, "qsc_code_num_chars_line_max": 103.0, "qsc_code_num_chars_line_mean": 31.97777778, "qsc_code_frac_chars_alphabet": 0.80269058, "qsc_code_frac_chars_comments": 0.0, "qsc_code_cate_xml_start": 1.0, "qsc_code_frac_lines_dupe_lines": 0.26666667, "qsc_code_cate_autogen": 0.0, "qsc_code_frac_lines_long_string": 0.0, "qsc_code_frac_chars_string_length": 0.05837387, "qsc_code_frac_chars_long_word_length": 0.0, "qsc_code_frac_lines_string_concat": 0.0, "qsc_code_cate_encoded_data": 0.0, "qsc_code_frac_chars_hex_words": 0.0, "qsc_code_frac_lines_prompt_comments": 0.0, "qsc_code_frac_lines_assert": 0.0}
0
{"qsc_code_frac_chars_replacement_symbols": 0, "qsc_code_num_words": 0, "qsc_code_num_chars": 0, "qsc_code_mean_word_length": 0, "qsc_code_frac_words_unique": 1, "qsc_code_frac_chars_top_2grams": 0, "qsc_code_frac_chars_top_3grams": 0, "qsc_code_frac_chars_top_4grams": 0, "qsc_code_frac_chars_dupe_5grams": 0, "qsc_code_frac_chars_dupe_6grams": 0, "qsc_code_frac_chars_dupe_7grams": 0, "qsc_code_frac_chars_dupe_8grams": 0, "qsc_code_frac_chars_dupe_9grams": 0, "qsc_code_frac_chars_dupe_10grams": 0, "qsc_code_frac_lines_dupe_lines": 0, "qsc_code_size_file_byte": 0, "qsc_code_num_lines": 0, "qsc_code_num_chars_line_max": 0, "qsc_code_num_chars_line_mean": 0, "qsc_code_frac_chars_alphabet": 0, "qsc_code_frac_chars_digital": 0, "qsc_code_frac_chars_whitespace": 0, "qsc_code_frac_chars_comments": 0, "qsc_code_cate_xml_start": 1, "qsc_code_cate_autogen": 0, "qsc_code_frac_chars_long_word_length": 0, "qsc_code_cate_encoded_data": 0, "qsc_code_frac_chars_hex_words": 0}
002and001/FHHFPSIndicator
Demo/FHHFPSIndicatorDemo/Utility/UIViewController+CustomNavigationBar.h
// // UIViewController+CustomNavigationBar.h // LoveTourGuide // // Created by 002 on 16/1/5. // Copyright © 2016年 fhhe. All rights reserved. // #import <UIKit/UIKit.h> @interface UIViewController (CustomNavigationBar) @property (nonatomic, strong) UIView *navigationBar; // 自定义navigationBar @property (nonatomic, strong) UIButton *navMiddleButton; // 中间按钮 @property (nonatomic, strong) UIButton *navLeftButton; // 左边按钮 @property (nonatomic, strong) UIButton *navRightButton; // 右边按钮 @property (nonatomic, assign) BOOL isPushed; // 是否push进来 /** 只有 ‘标题’ @param title 导航栏标题 */ - (void)setNavigationBarTitle:(NSString *)title; /** 有 ‘标题’ 和 ‘左边按钮’ @param title 导航栏标题 @param navLeftButtonIcon 左边按钮的 ‘图片’ 名称 */ - (void)setNavigationBarTitle:(NSString *)title navLeftButtonIcon:(NSString *)navLeftButtonIcon; /** 有 ‘标题’ 和 ‘左边按钮’ 和 ‘右边按钮’(显示为文字) @param title 导航栏标题 @param navLeftButtonIcon 左边按钮的 ‘图片’ 名称 @param navRightButtonTitle 右边按钮的 ‘title’ 名称 */ - (void)setNavigationBarTitle:(NSString *)title navLeftButtonIcon:(NSString *)navLeftButtonIcon navRightButtonTitle:(NSString *)navRightButtonTitle; /** 有 ‘标题’ 和 ‘左边按钮’ 和 ‘右边按钮’(显示图片) @param title 导航栏标题 @param navLeftButtonIcon 左边按钮的 ‘图片’ 名称 @param navRightButtonIcon 右边按钮的 ‘title’ 名称 */ - (void)setNavigationBarTitle:(NSString *)title navLeftButtonIcon:(NSString *)navLeftButtonIcon navRightButtonIcon:(NSString *)navRightButtonIcon; /** 有 ‘标题’ 和 ‘左边按钮’ 和 ‘右边按钮’(包含图片和文字) @param title 导航栏标题 @param navLeftButtonIcon 左边按钮的 ‘图片’ 名称 @param navRightButtonIcon 右边按钮的 ‘title’ 名称 @param navRightButtonTitle 右边按钮的 ‘图片’ 名称 */ - (void)setNavigationBarTitle:(NSString *)title navLeftButtonIcon:(NSString *)navLeftButtonIcon navRightButtonIcon:(NSString *)navRightButtonIcon navRightButtonTitle:(NSString *)navRightButtonTitle; /** 删除左边按钮默认返回事件 */ - (void)removeNavLeftButtonDefaultEvent; /** 中间按钮重新布局 */ - (void)reConfigNavMiddleButton; /** 右边按钮重新布局 */ - (void)reConfigNavRightButton; @end
2,173
UIViewController+CustomNavigationBar
h
zh
c
code
{"qsc_code_num_words": 248, "qsc_code_num_chars": 2173.0, "qsc_code_mean_word_length": 5.94354839, "qsc_code_frac_words_unique": 0.29435484, "qsc_code_frac_chars_top_2grams": 0.02713704, "qsc_code_frac_chars_top_3grams": 0.04070556, "qsc_code_frac_chars_top_4grams": 0.04409769, "qsc_code_frac_chars_dupe_5grams": 0.58819539, "qsc_code_frac_chars_dupe_6grams": 0.52781547, "qsc_code_frac_chars_dupe_7grams": 0.4972863, "qsc_code_frac_chars_dupe_8grams": 0.4972863, "qsc_code_frac_chars_dupe_9grams": 0.48846676, "qsc_code_frac_chars_dupe_10grams": 0.46811398, "qsc_code_frac_chars_replacement_symbols": 0.0, "qsc_code_frac_chars_digital": 0.00637312, "qsc_code_frac_chars_whitespace": 0.2057064, "qsc_code_size_file_byte": 2173.0, "qsc_code_num_lines": 89.0, "qsc_code_num_chars_line_max": 97.0, "qsc_code_num_chars_line_mean": 24.41573034, "qsc_code_frac_chars_alphabet": 0.84704519, "qsc_code_frac_chars_comments": 0.44960884, "qsc_code_cate_xml_start": 0.0, "qsc_code_frac_lines_dupe_lines": 0.42105263, "qsc_code_cate_autogen": 0.0, "qsc_code_frac_lines_long_string": 0.0, "qsc_code_frac_chars_string_length": 0.0, "qsc_code_frac_chars_long_word_length": 0.0, "qsc_code_frac_lines_string_concat": 0.0, "qsc_code_cate_encoded_data": 0.0, "qsc_code_frac_chars_hex_words": 0.0, "qsc_code_frac_lines_prompt_comments": 0.0, "qsc_code_frac_lines_assert": 0.0, "qsc_codec_frac_lines_func_ratio": 0.0, "qsc_codec_cate_bitsstdc": 0.0, "qsc_codec_nums_lines_main": 0, "qsc_codec_frac_lines_goto": 0.0, "qsc_codec_cate_var_zero": 0.0, "qsc_codec_score_lines_no_logic": 0.0, "qsc_codec_frac_lines_print": 0.0, "qsc_codec_frac_lines_preprocessor_directives": null}
1
{"qsc_code_frac_chars_replacement_symbols": 0, "qsc_code_num_words": 0, "qsc_code_num_chars": 0, "qsc_code_mean_word_length": 0, "qsc_code_frac_chars_top_2grams": 0, "qsc_code_frac_chars_top_3grams": 0, "qsc_code_frac_chars_top_4grams": 0, "qsc_code_frac_chars_dupe_5grams": 0, "qsc_code_frac_chars_dupe_6grams": 0, "qsc_code_frac_chars_dupe_7grams": 0, "qsc_code_frac_chars_dupe_8grams": 0, "qsc_code_frac_chars_dupe_9grams": 0, "qsc_code_frac_chars_dupe_10grams": 0, "qsc_code_size_file_byte": 0, "qsc_code_num_lines": 0, "qsc_code_num_chars_line_max": 0, "qsc_code_num_chars_line_mean": 0, "qsc_code_frac_chars_alphabet": 0, "qsc_code_frac_chars_digital": 0, "qsc_code_frac_chars_whitespace": 0, "qsc_code_frac_chars_comments": 0, "qsc_code_cate_xml_start": 0, "qsc_code_frac_lines_dupe_lines": 0, "qsc_code_cate_autogen": 0, "qsc_code_frac_lines_long_string": 0, "qsc_code_frac_chars_string_length": 0, "qsc_code_frac_chars_long_word_length": 0, "qsc_code_cate_encoded_data": 0, "qsc_code_frac_chars_hex_words": 0, "qsc_code_frac_lines_prompt_comments": 0, "qsc_code_frac_lines_assert": 0, "qsc_codec_frac_lines_func_ratio": 0, "qsc_codec_nums_lines_main": 0, "qsc_codec_score_lines_no_logic": 0, "qsc_codec_frac_lines_preprocessor_directives": 0, "qsc_codec_frac_lines_print": 0}
007revad/Synology_enable_M2_card
my-other-scripts.md
## All my scripts, tools and guides <img src="https://hitscounter.dev/api/hit?url=https%3A%2F%2F007revad.github.io%2F&label=Visitors&icon=github&color=%23198754&message=&style=flat&tz=UTC"> #### Contents - [Plex](#plex) - [Synology docker](#synology-docker) - [Synology recovery](#synology-recovery) - [Other Synology scripts](#other-synology-scripts) - [Synology hardware restrictions](#synology-hardware-restrictions) - [2025 plus models](#2025-plus-models) - [How To Guides](#how-to-guides) - [Synology dev](#synology-dev) *** ### Plex - **<a href="https://github.com/007revad/Synology_Plex_Backup">Synology_Plex_Backup</a>** - A script to backup Plex to a tgz file foror DSM 7 and DSM 6. - Works for Plex Synology package and Plex in docker. - **<a href="https://github.com/007revad/Asustor_Plex_Backup">Asustor_Plex_Backup</a>** - Backup your Asustor's Plex Media Server settings and database. - **<a href="https://github.com/007revad/Linux_Plex_Backup">Linux_Plex_Backup</a>** - Backup your Linux Plex Media Server's settings and database. - **<a href="https://github.com/007revad/Plex_Server_Sync">Plex_Server_Sync</a>** - Sync your main Plex server database & metadata to a backup Plex server. - Works for Synology, Asustor, Linux and supports Plex package or Plex in docker. &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; [Back to Contents](#contents) ### Synology docker - **<a href="https://github.com/007revad/Synology_Docker_Export">Synology_Docker_export</a>** - Export all Synology Container Manager or Docker containers' settings as json files to your docker shared folder. - **<a href="https://github.com/007revad/Synology_ContainerManager_IPv6">Synology_ContainerManager_IPv6</a>** - Enable IPv6 for Container Manager's bridge network. - **<a href="https://github.com/007revad/ContainerManager_for_all_armv8">ContainerManager_for_all_armv8</a>** - Script to install Container Manager on a RS819, DS119j, DS418, DS418j, DS218, DS218play or DS118. - **<a href="https://github.com/007revad/Docker_Autocompose">Docker_Autocompose</a>** - Create .yml files from your docker existing containers. - **<a href="https://github.com/007revad/Synology_docker_cleanup">Synology_docker_cleanup</a>** - Remove orphan docker btrfs subvolumes and images in Synology DSM 7 and DSM 6. &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; [Back to Contents](#contents) ### Synology recovery - **<a href="https://github.com/007revad/Synology_DSM_reinstall">Synology_DSM_reinstall</a>** - Easily re-install the same DSM version without losing any data or settings. - **<a href="https://github.com/007revad/Synology_Recover_Data">Synology_Recover_Data</a>** - A script to make it easy to recover your data from your Synology's drives using a computer. - **<a href="https://github.com/007revad/Synology_clear_drive_error">Synology clear drive error</a>** - Clear drive critical errors so DSM will let you use the drive. - **<a href="https://github.com/007revad/Synology_DSM_Telnet_Password">Synology_DSM_Telnet_Password</a>** - Synology DSM Recovery Telnet Password of the Day generator. - **<a href="https://github.com/007revad/Syno_DSM_Extractor_GUI">Syno_DSM_Extractor_GUI</a>** - Windows GUI for extracting Synology DSM 7 pat files and spk package files. - **<a href="https://github.com/007revad/Synoboot_backup">Synoboot_backup</a>** - Back up synoboot after each DSM update so you can recover from a corrupt USBDOM. &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; [Back to Contents](#contents) ### Other Synology scripts - **<a href="https://github.com/007revad/Synology_app_mover">Synology_app_mover</a>** - Easily move Synology packages from one volume to another volume. - **<a href="https://github.com/007revad/Video_Station_for_DSM_722">Video_Station_for_DSM_722</a>** - Script to install Video Station in DSM 7.2.2 - **<a href="https://github.com/007revad/SS_Motion_Detection">SS_Motion_Detection</a>** - Installs previous Surveillance Station and Advanced Media Extensions versions so motion detection and HEVC are supported. - **<a href="https://github.com/007revad/Synology_Config_Backup">Synology_Config_Backup</a>** - Backup and export your Synology DSM configuration. - **<a href="https://github.com/007revad/Synology_CPU_temperature">Synology_CPU_temperature</a>** - Get and log Synology NAS CPU temperature via SSH. - **<a href="https://github.com/007revad/Synology_SMART_info">Synology_SMART_info</a>** - Show Synology smart test progress or smart health and attributes. - **<a href="https://github.com/007revad/Synology_Cleanup_Coredumps">Synology_Cleanup_Coredumps</a>** - Cleanup memory core dumps from crashed processes. - **<a href="https://github.com/007revad/Synology_toggle_reset_button">Synology_toggle_reset_button</a>** - Script to disable or enable the reset button and show current setting. - **<a href="https://github.com/007revad/Synology_Download_Station_Chrome_Extension">Synology_Download_Station_Chrome_Extension</a>** - Download Station Chrome Extension. - **<a href="https://github.com/007revad/Seagate_lowCurrentSpinup">Seagate_lowCurrentSpinup</a>** - This script avoids the need to buy and install a higher wattage power supply when using multiple large Seagate SATA HDDs. &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; [Back to Contents](#contents) ### Synology hardware restrictions - **<a href="https://github.com/007revad/Synology_HDD_db">Synology_HDD_db</a>** - Add your SATA or SAS HDDs and SSDs plus SATA and NVMe M.2 drives to your Synology's compatible drive databases, including your Synology M.2 PCIe card and Expansion Unit databases. - **<a href="https://github.com/007revad/Synology_enable_M2_volume">Synology_enable_M2_volume</a>** - Enable creating volumes with non-Synology M.2 drives. - Enable Health Info for non-Synology NVMe drives (not in DSM 7.2.1 or later). - **<a href="https://github.com/007revad/Synology_M2_volume">Synology_M2_volume</a>** - Easily create an M.2 volume on Synology NAS. - **<a href="https://github.com/007revad/Synology_enable_M2_card">Synology_enable_M2_card</a>** - Enable Synology M.2 PCIe cards in Synology NAS that don't officially support them. - **<a href="https://github.com/007revad/Synology_enable_eunit">Synology_enable_eunit</a>** - Enable an unsupported Synology eSATA Expansion Unit models. - **<a href="https://github.com/007revad/Synology_enable_Deduplication">Synology_enable_Deduplication</a>** - Enable deduplication with non-Synology SSDs and unsupported NAS models. - **<a href="https://github.com/007revad/Synology_SHR_switch">Synology_SHR_switch</a>** - Easily switch between SHR and RAID Groups, or enable RAID F1. - **<a href="https://github.com/007revad/Synology_enable_sequential_IO">Synology_enable_sequential_IO</a>** - Enables sequential I/O for your SSD caches, like DSM 6 had. - **<a href="https://github.com/007revad/Synology_Information_Wiki">Synology_Information_Wiki</a>** - Information about Synology hardware. &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; [Back to Contents](#contents) ### 2025 plus models - **<a href="https://github.com/007revad/Transcode_for_x25">Transcode_for_x25</a>** - Installs the modules needed for Plex or Jellyfin hardware transcoding in DS425+ and DS225+. - **<a href="https://github.com/007revad/Synology_HDD_db/blob/main/2025_plus_models.md">2025 series or later Plus models</a>** - Unverified 3rd party drive limitations and unofficial solutions. - **<a href="https://github.com/007revad/Synology_HDD_db/blob/main/2025_plus_models.md#setting-up-a-new-2025-or-later-plus-model-with-only-unverified-hdds">Setup with only 3rd party drives</a>** - Setting up a new 2025 or later plus model with only unverified HDDs. - **<a href="https://github.com/007revad/Synology_HDD_db/blob/main/2025_plus_models.md#deleting-and-recreating-your-storage-pool-on-unverified-hdds">Recreating storage pool on migrated drives</a>** - Deleting and recreating your storage pool on unverified HDDs. &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; [Back to Contents](#contents) ### How To Guides - **<a href="https://github.com/007revad/Synology_SSH_key_setup">Synology_SSH_key_setup</a>** - How to setup SSH key authentication for your Synology. &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; [Back to Contents](#contents) ### Synology dev - **<a href="https://github.com/007revad/Download_Synology_Archive">Download_Synology_Archive</a>** - Download all or part of the Synology archive. - **<a href="https://github.com/007revad/Syno_DSM_Extractor_GUI">Syno_DSM_Extractor_GUI</a>** - Windows GUI for extracting Synology DSM 7 pat files and spk package files. - **<a href="https://github.com/007revad/ScriptNotify">ScriptNotify</a>** - DSM 7 package to allow your scripts to send DSM notifications. - **<a href="https://github.com/007revad/DTC_GUI_for_Windows">DTC_GUI_for_Windows</a>** - GUI for DTC.exe for Windows. &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; [Back to Contents](#contents)
9,099
my-other-scripts
md
en
markdown
text
{"qsc_doc_frac_chars_curly_bracket": 0.0, "qsc_doc_frac_words_redpajama_stop": 0.16632653, "qsc_doc_num_sentences": 107.0, "qsc_doc_num_words": 1341, "qsc_doc_num_chars": 9099.0, "qsc_doc_num_lines": 180.0, "qsc_doc_mean_word_length": 4.94630872, "qsc_doc_frac_words_full_bracket": 0.0, "qsc_doc_frac_lines_end_with_readmore": 0.0, "qsc_doc_frac_lines_start_with_bullet": 0.0, "qsc_doc_frac_words_unique": 0.23191648, "qsc_doc_entropy_unigram": 4.76529845, "qsc_doc_frac_words_all_caps": 0.02908163, "qsc_doc_frac_lines_dupe_lines": 0.1025641, "qsc_doc_frac_chars_dupe_lines": 0.10911978, "qsc_doc_frac_chars_top_2grams": 0.05789236, "qsc_doc_frac_chars_top_3grams": 0.06482738, "qsc_doc_frac_chars_top_4grams": 0.10372381, "qsc_doc_frac_chars_dupe_5grams": 0.39981909, "qsc_doc_frac_chars_dupe_6grams": 0.36891301, "qsc_doc_frac_chars_dupe_7grams": 0.34041912, "qsc_doc_frac_chars_dupe_8grams": 0.25569124, "qsc_doc_frac_chars_dupe_9grams": 0.20624152, "qsc_doc_frac_chars_dupe_10grams": 0.15829941, "qsc_doc_frac_chars_replacement_symbols": 0.0, "qsc_doc_cate_code_related_file_name": 0.0, "qsc_doc_num_chars_sentence_length_mean": 30.70731707, "qsc_doc_frac_chars_hyperlink_html_tag": 0.34762062, "qsc_doc_frac_chars_alphabet": 0.79007303, "qsc_doc_frac_chars_digital": 0.03094442, "qsc_doc_frac_chars_whitespace": 0.11210023, "qsc_doc_frac_chars_hex_words": 0.0}
1
{"qsc_doc_frac_chars_replacement_symbols": 0, "qsc_doc_entropy_unigram": 0, "qsc_doc_frac_chars_top_2grams": 0, "qsc_doc_frac_chars_top_3grams": 0, "qsc_doc_frac_chars_top_4grams": 0, "qsc_doc_frac_chars_dupe_5grams": 0, "qsc_doc_frac_chars_dupe_6grams": 0, "qsc_doc_frac_chars_dupe_7grams": 0, "qsc_doc_frac_chars_dupe_8grams": 0, "qsc_doc_frac_chars_dupe_9grams": 0, "qsc_doc_frac_chars_dupe_10grams": 0, "qsc_doc_frac_chars_dupe_lines": 0, "qsc_doc_frac_lines_dupe_lines": 0, "qsc_doc_frac_lines_end_with_readmore": 0, "qsc_doc_frac_lines_start_with_bullet": 0, "qsc_doc_frac_words_all_caps": 0, "qsc_doc_mean_word_length": 0, "qsc_doc_num_chars": 0, "qsc_doc_num_lines": 0, "qsc_doc_num_sentences": 0, "qsc_doc_num_words": 0, "qsc_doc_frac_chars_hex_words": 0, "qsc_doc_frac_chars_hyperlink_html_tag": 0, "qsc_doc_frac_chars_alphabet": 0, "qsc_doc_frac_chars_digital": 0, "qsc_doc_frac_chars_whitespace": 0}
007revad/Synology_enable_M2_card
README.md
# Synology enable M2 card <a href="https://github.com/007revad/Synology_enable_M2_card/releases"><img src="https://img.shields.io/github/release/007revad/Synology_enable_M2_card.svg"></a> ![Badge](https://hitscounter.dev/api/hit?url=https%3A%2F%2Fgithub.com%2F007revad%2FSynology_enable_M2_card&label=Visitors&icon=github&color=%23198754&message=&style=flat&tz=Australia%2FSydney) [![Donate](https://img.shields.io/badge/Donate-PayPal-green.svg)](https://www.paypal.com/paypalme/007revad) [![](https://img.shields.io/static/v1?label=Sponsor&message=%E2%9D%A4&logo=GitHub&color=%23fe8e86)](https://github.com/sponsors/007revad) [![committers.top badge](https://user-badge.committers.top/australia/007revad.svg)](https://user-badge.committers.top/australia/007revad) ### Description Enable Synology M.2 PCIe cards in Synology NAS that don't officially support them Allows using E10M20-T1, M2D20, M2D18 or M2D17 cards in Synology NAS models that aren't on their [supported model list](https://github.com/007revad/Synology_enable_M2_volume/wiki/Models-that-support-PCIe-M.2-cards). - Enables E10M20-T1, M2D20, M2D18 and M2D17 for DS1823xs+, DS1821+, DS1621+. - Enables M2D18 and M2D17 for DS2422+, RS2423+, RS2421+, RS2421RP+, RS2821RP+. - Enables M2D18 and M2D17 for RS822RP+, RS822+, RS1221RP+ and RS1221+ using DSM 7.1.1 and older. - May enable E10M20-T1, M2D20, M2D18 and M2D17 for other models with a PCIe x8 slot that have /usr/syno/synonvme. [Synology HDD db](https://github.com/007revad/Synology_HDD_db) now enables using Storage Manager to create volumes on M.2 drives in a PCIe M.2 adaptor card. <br> ## Which Synology models will this work on </br>**Works on the following models:** <details> <summary>Click here to see list</summary> | Model | E10M20-T1 | M2D20 | M2D18 | M2D17 | Notes | |-|-|-|-|-|-| | DS1825+ | yes | yes | yes | yes | | | DS1821+ | yes | yes | yes | yes | | | DS1621+ | yes | yes | yes | yes | | | DS1823xs+ | yes | yes | yes | yes | | | DS2422+ | yes | yes | yes | yes | E10M20-T1 and M2D20 already enabled in DSM | | | | | | | | RS2423+ | yes | yes | yes | yes | E10M20-T1 and M2D20 already enabled in DSM | | RS2423RP+ | yes | yes | yes | yes | E10M20-T1 and M2D20 already enabled in DSM | | RS2421+ | yes | yes | yes | yes | E10M20-T1 and M2D20 already enabled in DSM | | RS2421RP+ | yes | yes | yes | yes | E10M20-T1 and M2D20 already enabled in DSM | | RS2821RP+ | yes | yes | yes | yes | E10M20-T1 and M2D20 already enabled in DSM | | RS822+ | yes | yes | yes | yes | E10M20-T1 and M2D18 already enabled in DSM* | | RS822RP+ | yes | yes | yes | yes | E10M20-T1 and M2D18 already enabled in DSM* | | RS1221+ | yes | yes | yes | yes | E10M20-T1 and M2D18 already enabled in DSM* | | RS1221RP+ | yes | yes | yes | yes | E10M20-T1 and M2D18 already enabled in DSM* | | RS2418+ | yes | yes | yes | yes | M2D20, M2D18 and M2D17 already enabled in DSM. E10M20-T1 see note 2 | | RS2418RP+ | yes | yes | yes | yes | M2D20, M2D18 and M2D17 already enabled in DSM. E10M20-T1 see note 2 | | | | | | | | **others** | maybe | maybe | maybe | maybe | See Other Models Notes | **Notes** 1. Synology added support for the M2D18 in RS822+ and RS1221+ in DSM 7.2 2. [E10M20-T1 needs 1cm cut off](https://github.com/007revad/Synology_enable_M2_card/discussions/59) to fit into a RS2418RP+/RS2418+ **Other Models Notes** - The Synology must have a PCIe x8 slot - DSM must include /usr/syno/bin/synonvme - DSM must include /usr/lib/libsynonvme.so.1 </details> </br>**Should work for the following models but I have not tested them:** <details> <summary>Click here to see list</summary> | Model | E10M20-T1 | M2D20 | M2D18 | M2D17 | Notes | |-|-|-|-|-|-| | FS2500 | yes | yes | yes | yes | | | FS3410 | yes | yes | yes | yes | | | FS6400 | yes | yes | yes | yes | | | | | | | | | HD6500 | yes | yes | yes | yes | | | | | | | | | SA4310 | yes | yes | yes | yes | E10M20-T1 and M2D20 already enabled in DSM | | SA3610 | yes | yes | yes | yes | E10M20-T1 and M2D20 already enabled in DSM | | SA6400 | yes | yes | yes | yes | E10M20-T1 and M2D20 already enabled in DSM | </details> </br>**Synology NAS models that this script may work on?** <details> <summary>Click here to see list</summary> | Model | E10M20-T1 | M2D20 | M2D18 | M2D17 | Notes | |-|-|-|-|-|-| | DS1621xs+ | ??? | yes | ??? | ??? | | </details> </br>**Synology NAS models that this script won't work on:** <details> <summary>Click here to see list</summary> | Model | E10M20-T1 | M2D20 | M2D18 | M2D17 | Notes | |-|-|-|-|-|-| | DS923+ | no | no | no | no | PCIe x2 slot only fits the E10G22-T1-Mini | | DS723+ | no | no | no | no | PCIe x2 slot only fits the E10G22-T1-Mini | | DS1522+ | no | no | no | no | PCIe x2 slot only fits the E10G22-T1-Mini | | RS422+ | no | no | no | no | PCIe x2 slot only fits the E10G22-T1-Mini | | | | | | | | DS1817+ | no | no | no | no | Does not have /usr/syno/bin/synonvme | | DS1517+ | no | no | no | no | Does not have /usr/syno/bin/synonvme | | | | | | | | RS1219+ | no | no | no | no | Does not have /usr/syno/bin/synonvme | | RS818+ | no | no | no | no | Does not have /usr/syno/bin/synonvme | | RS818RP+ | no | no | no | no | Does not have /usr/syno/bin/synonvme | | RS3617xs | no | no | no | no | Does not have /usr/syno/bin/synonvme | | RS18016xs+ | no | no | no | no | Does not have /usr/syno/bin/synonvme | | | | | | | | FS3017 | no | no | no | no | Does not have /usr/syno/bin/synonvme | </details> <br> ## How to run the script ### Download the script 1. Download the latest version _Source code (zip)_ from https://github.com/007revad/Synology_enable_M2_card/releases 2. Save the download zip file to a folder on the Synology. - Do ***NOT*** save the script to a M.2 volume. After a DSM or Storage Manager update the M.2 volume won't be available until after the script has run. 3. Unzip the zip file. ### Running the script via SSH [How to enable SSH and login to DSM via SSH](https://kb.synology.com/en-global/DSM/tutorial/How_to_login_to_DSM_with_root_permission_via_SSH_Telnet) **Note:** Replace /volume1/scripts/ with the path to where the script is located. Run the script then reboot the Synology: ```YAML sudo -s /volume1/scripts/syno_enable_m2_card.sh ``` **Options:** ```YAML -c, --check Check M.2 card status -r, --restore Restore from backups to undo changes -e, --email Disable colored text in output scheduler emails. --autoupdate=AGE Auto update script (useful when script is scheduled) AGE is how many days old a release must be before auto-updating. AGE must be a number: 0 or greater --model=CARD Automatically enable specified card model Required if you want to schedule the script CARD can be E10M20-T1, M2D20, M2D18 or M2D17 -h, --help Show this help message -v, --version Show the script version ``` ### What about DSM updates? After any DSM update you will need to run this script again. ### Schedule the script to run at shutdown Or you can schedule Synology_enable_M2_card to run when the Synology shuts down, to avoid having to remember to run the script after a DSM update. See <a href=how_to_schedule.md/>How to schedule a script in Synology Task Scheduler</a> </br> ## Screenshots <p align="center">Available options</p> <p align="center"><img src="/images/help.png"></p> <p align="center">Enabling all M.2 card models</p> <p align="center"><img src="/images/edited.png"></p> <p align="center">Checking the current M.2 card settings</p> <p align="center"><img src="/images/check.png"></p> <p align="center">E10M20-T1 already enabled</p> <p align="center"><img src="/images/e10m20.png"></p> <p align="center">All M.2 card models already enabled</p> <p align="center"><img src="/images/all.png"></p> <p align="center">Restoring the original M.2 card settings</p> <p align="center"><img src="/images/restore.png"></p> <p align="center">DS1821+ with a E10M20-T1</p> <p align="center"><img src="/images/1821_e10m20-1.png"></p> <p align="center"><img src="/images/1821_e10m20-2.png"></p>
8,294
README
md
en
markdown
text
{"qsc_doc_frac_chars_curly_bracket": 0.0, "qsc_doc_frac_words_redpajama_stop": 0.21418506, "qsc_doc_num_sentences": 85.0, "qsc_doc_num_words": 1284, "qsc_doc_num_chars": 8294.0, "qsc_doc_num_lines": 191.0, "qsc_doc_mean_word_length": 4.23130841, "qsc_doc_frac_words_full_bracket": 0.0, "qsc_doc_frac_lines_end_with_readmore": 0.0, "qsc_doc_frac_lines_start_with_bullet": 0.0, "qsc_doc_frac_words_unique": 0.2453271, "qsc_doc_entropy_unigram": 4.96039149, "qsc_doc_frac_words_all_caps": 0.10098638, "qsc_doc_frac_lines_dupe_lines": 0.23404255, "qsc_doc_frac_chars_dupe_lines": 0.07648832, "qsc_doc_frac_chars_top_2grams": 0.07620099, "qsc_doc_frac_chars_top_3grams": 0.07620099, "qsc_doc_frac_chars_top_4grams": 0.05080066, "qsc_doc_frac_chars_dupe_5grams": 0.45389288, "qsc_doc_frac_chars_dupe_6grams": 0.41100681, "qsc_doc_frac_chars_dupe_7grams": 0.40180379, "qsc_doc_frac_chars_dupe_8grams": 0.35873366, "qsc_doc_frac_chars_dupe_9grams": 0.3362783, "qsc_doc_frac_chars_dupe_10grams": 0.29063133, "qsc_doc_frac_chars_replacement_symbols": 0.0, "qsc_doc_cate_code_related_file_name": 1.0, "qsc_doc_num_chars_sentence_length_mean": 28.31095406, "qsc_doc_frac_chars_hyperlink_html_tag": 0.21654208, "qsc_doc_frac_chars_alphabet": 0.724195, "qsc_doc_frac_chars_digital": 0.0932892, "qsc_doc_frac_chars_whitespace": 0.19869785, "qsc_doc_frac_chars_hex_words": 0.0}
1
{"qsc_doc_frac_chars_replacement_symbols": 0, "qsc_doc_entropy_unigram": 0, "qsc_doc_frac_chars_top_2grams": 0, "qsc_doc_frac_chars_top_3grams": 0, "qsc_doc_frac_chars_top_4grams": 0, "qsc_doc_frac_chars_dupe_5grams": 0, "qsc_doc_frac_chars_dupe_6grams": 0, "qsc_doc_frac_chars_dupe_7grams": 0, "qsc_doc_frac_chars_dupe_8grams": 0, "qsc_doc_frac_chars_dupe_9grams": 0, "qsc_doc_frac_chars_dupe_10grams": 0, "qsc_doc_frac_chars_dupe_lines": 0, "qsc_doc_frac_lines_dupe_lines": 0, "qsc_doc_frac_lines_end_with_readmore": 0, "qsc_doc_frac_lines_start_with_bullet": 0, "qsc_doc_frac_words_all_caps": 0, "qsc_doc_mean_word_length": 0, "qsc_doc_num_chars": 0, "qsc_doc_num_lines": 0, "qsc_doc_num_sentences": 0, "qsc_doc_num_words": 0, "qsc_doc_frac_chars_hex_words": 0, "qsc_doc_frac_chars_hyperlink_html_tag": 0, "qsc_doc_frac_chars_alphabet": 0, "qsc_doc_frac_chars_digital": 0, "qsc_doc_frac_chars_whitespace": 0}
007revad/Synology_enable_M2_card
how_to_schedule.md
# How to schedule a script in Synology Task Scheduler To schedule a script to run on your Synology at boot-up or shutdown follow these steps: **Note:** You can setup a schedule task and leave it disabled, so it only runs when you select the task in the Task Scheduler and click on the Run button. 1. Go to **Control Panel** > **Task Scheduler** > click **Create** > and select **Triggered Task**. 2. Select **User-defined script**. 3. Enter a task name. 4. Select **root** as the user (The script needs to run as root). 5. Select **Shutdown** as the event that triggers the task. 6. Leave **Enable** ticked. 7. Click **Task Settings**. 8. Optionally you can tick **Send run details by email** and **Send run details only when the script terminates abnormally** then enter your email address. 9. In the box under **User-defined script** type the path to the script. - e.g. If you saved the script to a shared folder on volume1 called "scripts" you'd type: **/volume1/scripts/syno_enable_m2_card.sh** 11. Click **OK** to save the settings. Here's some screenshots showing what needs to be set: <p align="leftr"><img src="images/schedule1.png"></p> <p align="leftr"><img src="images/schedule2b.png"></p> <p align="leftr"><img src="images/schedule3.png"></p>
1,267
how_to_schedule
md
en
markdown
text
{"qsc_doc_frac_chars_curly_bracket": 0.0, "qsc_doc_frac_words_redpajama_stop": 0.24595469, "qsc_doc_num_sentences": 28.0, "qsc_doc_num_words": 218, "qsc_doc_num_chars": 1267.0, "qsc_doc_num_lines": 25.0, "qsc_doc_mean_word_length": 4.16513761, "qsc_doc_frac_words_full_bracket": 0.0, "qsc_doc_frac_lines_end_with_readmore": 0.0, "qsc_doc_frac_lines_start_with_bullet": 0.0, "qsc_doc_frac_words_unique": 0.51376147, "qsc_doc_entropy_unigram": 4.41735967, "qsc_doc_frac_words_all_caps": 0.00323625, "qsc_doc_frac_lines_dupe_lines": 0.0, "qsc_doc_frac_chars_dupe_lines": 0.0, "qsc_doc_frac_chars_top_2grams": 0.03964758, "qsc_doc_frac_chars_top_3grams": 0.03634361, "qsc_doc_frac_chars_top_4grams": 0.04625551, "qsc_doc_frac_chars_dupe_5grams": 0.08480176, "qsc_doc_frac_chars_dupe_6grams": 0.08480176, "qsc_doc_frac_chars_dupe_7grams": 0.05947137, "qsc_doc_frac_chars_dupe_8grams": 0.05947137, "qsc_doc_frac_chars_dupe_9grams": 0.0, "qsc_doc_frac_chars_dupe_10grams": 0.0, "qsc_doc_frac_chars_replacement_symbols": 0.0, "qsc_doc_cate_code_related_file_name": 0.0, "qsc_doc_num_chars_sentence_length_mean": 22.9245283, "qsc_doc_frac_chars_hyperlink_html_tag": 0.12628256, "qsc_doc_frac_chars_alphabet": 0.83898305, "qsc_doc_frac_chars_digital": 0.01600753, "qsc_doc_frac_chars_whitespace": 0.16179953, "qsc_doc_frac_chars_hex_words": 0.0}
1
{"qsc_doc_frac_chars_replacement_symbols": 0, "qsc_doc_entropy_unigram": 0, "qsc_doc_frac_chars_top_2grams": 0, "qsc_doc_frac_chars_top_3grams": 0, "qsc_doc_frac_chars_top_4grams": 0, "qsc_doc_frac_chars_dupe_5grams": 0, "qsc_doc_frac_chars_dupe_6grams": 0, "qsc_doc_frac_chars_dupe_7grams": 0, "qsc_doc_frac_chars_dupe_8grams": 0, "qsc_doc_frac_chars_dupe_9grams": 0, "qsc_doc_frac_chars_dupe_10grams": 0, "qsc_doc_frac_chars_dupe_lines": 0, "qsc_doc_frac_lines_dupe_lines": 0, "qsc_doc_frac_lines_end_with_readmore": 0, "qsc_doc_frac_lines_start_with_bullet": 0, "qsc_doc_frac_words_all_caps": 0, "qsc_doc_mean_word_length": 0, "qsc_doc_num_chars": 0, "qsc_doc_num_lines": 0, "qsc_doc_num_sentences": 0, "qsc_doc_num_words": 0, "qsc_doc_frac_chars_hex_words": 0, "qsc_doc_frac_chars_hyperlink_html_tag": 0, "qsc_doc_frac_chars_alphabet": 0, "qsc_doc_frac_chars_digital": 0, "qsc_doc_frac_chars_whitespace": 0}
007revad/Synology_enable_M2_card
syno_enable_m2_card.sh
#!/usr/bin/env bash #----------------------------------------------------------------------------------- # Enable M.2 PCIe cards in Synology NAS that don't officially support them. # # Allows using your E10M20-T1, M2D20, M2D18, M2D17 or FX2422N cards # in Synology NAS models that aren't on their supported model list. # # Github: https://github.com/007revad/Synology_enable_M2_card # Script verified at https://www.shellcheck.net/ # # To run in a shell (replace /volume1/scripts/ with path to script): # sudo -i /volume1/scripts/syno_enable_m2_card.sh #----------------------------------------------------------------------------------- scriptver="v3.1.17" script=Synology_enable_M2_card repo="007revad/Synology_enable_M2_card" scriptname=syno_enable_m2_card # Check BASH variable is bash if [ ! "$(basename "$BASH")" = bash ]; then echo "This is a bash script. Do not run it with $(basename "$BASH")" printf \\a exit 1 fi # Check script is running on a Synology NAS if ! /usr/bin/uname -a | grep -i synology >/dev/null; then echo "This script is NOT running on a Synology NAS!" echo "Copy the script to a folder on the Synology" echo "and run it from there." exit 1 fi ding(){ printf \\a } usage(){ cat <<EOF $script $scriptver - by 007revad Usage: $(basename "$0") [options] Options: -c, --check Check M.2 card status -r, --restore Restore from backups to undo changes -e, --email Disable colored text in output scheduler emails. --autoupdate=AGE Auto update script (useful when script is scheduled) AGE is how many days old a release must be before auto-updating. AGE must be a number: 0 or greater --model=CARD Automatically enable specified card model Required if you want to schedule the script CARD can be E10M20-T1, M2D20, M2D18 or M2D17 -h, --help Show this help message -v, --version Show the script version EOF exit 0 } scriptversion(){ cat <<EOF $script $scriptver - by 007revad See https://github.com/$repo EOF exit 0 } # Save options used args=("$@") autoupdate="" # Check for flags with getopt if options="$(getopt -o abcdefghijklmnopqrstuvwxyz0123456789 -l \ check,restore,help,version,email,autoupdate:,model:,log,debug -- "${args[@]}")"; then eval set -- "$options" while true; do case "${1,,}" in -h|--help) # Show usage options usage ;; -v|--version) # Show script version scriptversion ;; -l|--log) # Log #log=yes ;; -d|--debug) # Show and log debug info debug=yes ;; -c|--check) # Check current settings check=yes break ;; -r|--restore) # Restore original settings restore=yes break ;; --model) # Auto enable specified card card="${2^^}" # Convert to uppercase shift ;; -e|--email) # Disable colour text in task scheduler emails color=no ;; --autoupdate) # Auto update script autoupdate=yes if [[ $2 =~ ^[0-9]+$ ]]; then delay="$2" shift else delay="0" fi ;; --) shift break ;; *) # Show usage options echo -e "Invalid option '$1'\n" usage "$1" ;; esac shift done else echo usage fi if [[ $debug == "yes" ]]; then set -x export PS4='`[[ $? == 0 ]] || echo "\e[1;31;40m($?)\e[m\n "`:.$LINENO:' fi # Shell Colors if [[ $color != "no" ]]; then #Black='\e[0;30m' # ${Black} #Red='\e[0;31m' # ${Red} #Green='\e[0;32m' # ${Green} Yellow='\e[0;33m' # ${Yellow} #Blue='\e[0;34m' # ${Blue} #Purple='\e[0;35m' # ${Purple} Cyan='\e[0;36m' # ${Cyan} #White='\e[0;37m' # ${White} Error='\e[41m' # ${Error} Off='\e[0m' # ${Off} else echo "" # For task scheduler email readability fi # Check script is running as root if [[ $( whoami ) != "root" ]]; then ding echo -e "${Error}ERROR${Off} This script must be run as sudo or root!" exit 1 fi # Get DSM major and minor versions #dsm=$(/usr/syno/bin/synogetkeyvalue /etc.defaults/VERSION majorversion) #dsminor=$(/usr/syno/bin/synogetkeyvalue /etc.defaults/VERSION minorversion) #if [[ $dsm -gt "6" ]] && [[ $dsminor -gt "1" ]]; then # dsm72="yes" #fi #if [[ $dsm -gt "6" ]] && [[ $dsminor -gt "0" ]]; then # dsm71="yes" #fi # Get NAS model model=$(cat /proc/sys/kernel/syno_hw_version) modelname="$model" # Show script version #echo -e "$script $scriptver\ngithub.com/$repo\n" echo "$script $scriptver" # Get DSM full version productversion=$(/usr/syno/bin/synogetkeyvalue /etc.defaults/VERSION productversion) buildphase=$(/usr/syno/bin/synogetkeyvalue /etc.defaults/VERSION buildphase) buildnumber=$(/usr/syno/bin/synogetkeyvalue /etc.defaults/VERSION buildnumber) smallfixnumber=$(/usr/syno/bin/synogetkeyvalue /etc.defaults/VERSION smallfixnumber) # Show DSM full version and model if [[ $buildphase == GM ]]; then buildphase=""; fi if [[ $smallfixnumber -gt "0" ]]; then smallfix="-$smallfixnumber"; fi echo -e "$model DSM $productversion-$buildnumber$smallfix $buildphase\n" # Get StorageManager version storagemgrver=$(/usr/syno/bin/synopkg version StorageManager) # Show StorageManager version if [[ $storagemgrver ]]; then echo -e "StorageManager $storagemgrver\n"; fi # Show options used if [[ ${#args[@]} -gt "0" ]]; then echo "Using options: ${args[*]}" fi # Check Synology has a PCIe x8 or x16 slot if which dmidecode >/dev/null; then if ! dmidecode -t slot | grep "PCI Express" | grep -E "x(8|16)" >/dev/null ; then echo "${model}: No PCIe x8 slot found!" exit 1 fi else echo "${model} does not have dmidecode!" exit 1 fi # Check Synology has synonvme if ! which synonvme >/dev/null; then echo "${model} does not have synonvme!" exit 1 fi # Check Synology has libsynonvme.so.1 if [[ ! -e /usr/lib/libsynonvme.so ]]; then echo "${model} does not have libsynonvme.so.1!" exit 1 fi #------------------------------------------------------------------------------ # Check latest release with GitHub API syslog_set(){ if [[ ${1,,} == "info" ]] || [[ ${1,,} == "warn" ]] || [[ ${1,,} == "err" ]]; then if [[ $autoupdate == "yes" ]]; then # Add entry to Synology system log /usr/syno/bin/synologset1 sys "$1" 0x11100000 "$2" fi fi } # Get latest release info # Curl timeout options: # https://unix.stackexchange.com/questions/94604/does-curl-have-a-timeout release=$(curl --silent -m 10 --connect-timeout 5 \ "https://api.github.com/repos/$repo/releases/latest") # Release version tag=$(echo "$release" | grep '"tag_name":' | sed -E 's/.*"([^"]+)".*/\1/') shorttag="${tag:1}" # Release published date published=$(echo "$release" | grep '"published_at":' | sed -E 's/.*"([^"]+)".*/\1/') published="${published:0:10}" published=$(date -d "$published" '+%s') # Today's date now=$(date '+%s') # Days since release published age=$(((now - published)/(60*60*24))) # Get script location # https://stackoverflow.com/questions/59895/ source=${BASH_SOURCE[0]} while [ -L "$source" ]; do # Resolve $source until the file is no longer a symlink scriptpath=$( cd -P "$( dirname "$source" )" >/dev/null 2>&1 && pwd ) source=$(readlink "$source") # If $source was a relative symlink, we need to resolve it # relative to the path where the symlink file was located [[ $source != /* ]] && source=$scriptpath/$source done scriptpath=$( cd -P "$( dirname "$source" )" >/dev/null 2>&1 && pwd ) scriptfile=$( basename -- "$source" ) echo "Running from: ${scriptpath}/$scriptfile" # Warn if script located on M.2 drive scriptvol=$(echo "$scriptpath" | cut -d"/" -f2) vg=$(lvdisplay | grep /volume_"${scriptvol#volume}" | cut -d"/" -f3) md=$(pvdisplay | grep -B 1 -E '[ ]'"$vg" | grep /dev/ | cut -d"/" -f3) if cat /proc/mdstat | grep "$md" | grep nvme >/dev/null; then echo -e "${Yellow}WARNING${Off} Don't store this script on an NVMe volume!" fi cleanup_tmp(){ cleanup_err= # Delete downloaded .tar.gz file if [[ -f "/tmp/$script-$shorttag.tar.gz" ]]; then if ! rm "/tmp/$script-$shorttag.tar.gz"; then echo -e "${Error}ERROR${Off} Failed to delete"\ "downloaded /tmp/$script-$shorttag.tar.gz!" >&2 cleanup_err=1 fi fi # Delete extracted tmp files if [[ -d "/tmp/$script-$shorttag" ]]; then if ! rm -r "/tmp/$script-$shorttag"; then echo -e "${Error}ERROR${Off} Failed to delete"\ "downloaded /tmp/$script-$shorttag!" >&2 cleanup_err=1 fi fi # Add warning to DSM log if [[ $cleanup_err ]]; then syslog_set warn "$script update failed to delete tmp files" fi } if ! printf "%s\n%s\n" "$tag" "$scriptver" | sort --check=quiet --version-sort >/dev/null ; then echo -e "\n${Cyan}There is a newer version of this script available.${Off}" echo -e "Current version: ${scriptver}\nLatest version: $tag" scriptdl="$scriptpath/$script-$shorttag" if [[ -f ${scriptdl}.tar.gz ]] || [[ -f ${scriptdl}.zip ]]; then # They have the latest version tar.gz downloaded but are using older version echo "You have the latest version downloaded but are using an older version" sleep 10 elif [[ -d $scriptdl ]]; then # They have the latest version extracted but are using older version echo "You have the latest version extracted but are using an older version" sleep 10 else if [[ $autoupdate == "yes" ]]; then if [[ $age -gt "$delay" ]] || [[ $age -eq "$delay" ]]; then echo "Downloading $tag" reply=y else echo "Skipping as $tag is less than $delay days old." fi else echo -e "${Cyan}Do you want to download $tag now?${Off} [y/n]" read -r -t 30 reply fi if [[ ${reply,,} == "y" ]]; then # Delete previously downloaded .tar.gz file and extracted tmp files cleanup_tmp if cd /tmp; then url="https://github.com/$repo/archive/refs/tags/$tag.tar.gz" if ! curl -JLO -m 30 --connect-timeout 5 "$url"; then echo -e "${Error}ERROR${Off} Failed to download"\ "$script-$shorttag.tar.gz!" syslog_set warn "$script $tag failed to download" else if [[ -f /tmp/$script-$shorttag.tar.gz ]]; then # Extract tar file to /tmp/<script-name> if ! tar -xf "/tmp/$script-$shorttag.tar.gz" -C "/tmp"; then echo -e "${Error}ERROR${Off} Failed to"\ "extract $script-$shorttag.tar.gz!" syslog_set warn "$script failed to extract $script-$shorttag.tar.gz!" else # Set script sh files as executable if ! chmod a+x "/tmp/$script-$shorttag/"*.sh ; then permerr=1 echo -e "${Error}ERROR${Off} Failed to set executable permissions" syslog_set warn "$script failed to set permissions on $tag" fi # Copy new script sh file to script location if ! cp -p "/tmp/$script-$shorttag/${scriptname}.sh" "${scriptpath}/${scriptfile}"; then copyerr=1 echo -e "${Error}ERROR${Off} Failed to copy"\ "$script-$shorttag sh file(s) to:\n $scriptpath/${scriptfile}" syslog_set warn "$script failed to copy $tag to script location" fi # Copy new CHANGES.txt file to script location (if script on a volume) if [[ $scriptpath =~ /volume* ]]; then # Set permissions on CHANGES.txt if ! chmod 664 "/tmp/$script-$shorttag/CHANGES.txt"; then permerr=1 echo -e "${Error}ERROR${Off} Failed to set permissions on:" echo "$scriptpath/CHANGES.txt" fi # Copy new CHANGES.txt file to script location if ! cp -p "/tmp/$script-$shorttag/CHANGES.txt"\ "${scriptpath}/${scriptname}_CHANGES.txt"; then if [[ $autoupdate != "yes" ]]; then copyerr=1; fi echo -e "${Error}ERROR${Off} Failed to copy"\ "$script-$shorttag/CHANGES.txt to:\n $scriptpath" else changestxt=" and changes.txt" fi fi # Delete downloaded tmp files cleanup_tmp # Notify of success (if there were no errors) if [[ $copyerr != 1 ]] && [[ $permerr != 1 ]]; then echo -e "\n$tag ${scriptfile}$changestxt downloaded to: ${scriptpath}\n" syslog_set info "$script successfully updated to $tag" # Reload script printf -- '-%.0s' {1..79}; echo # print 79 - exec "${scriptpath}/$scriptfile" "${args[@]}" else syslog_set warn "$script update to $tag had errors" fi fi else echo -e "${Error}ERROR${Off}"\ "/tmp/$script-$shorttag.tar.gz not found!" syslog_set warn "/tmp/$script-$shorttag.tar.gz not found" fi fi cd "$scriptpath" || echo -e "${Error}ERROR${Off} Failed to cd to script location!" else echo -e "${Error}ERROR${Off} Failed to cd to /tmp!" syslog_set warn "$script update failed to cd to /tmp" fi fi fi fi #------------------------------------------------------------------------------ # Set file variables if [[ -f /etc.defaults/model.dtb ]]; then # Is device tree model # Get syn_hw_revision, r1 or r2 etc (or just a linefeed if not a revision) hwrevision=$(cat /proc/sys/kernel/syno_hw_revision) # If syno_hw_revision is r1 or r2 it's a real Synology, # and I need to edit model_rN.dtb instead of model.dtb if [[ $hwrevision =~ r[0-9] ]]; then hwrev="_$hwrevision" fi dtb_file="/etc.defaults/model${hwrev}.dtb" dtb2_file="/etc/model${hwrev}.dtb" #dts_file="/etc.defaults/model${hwrev}.dts" fi #synoinfo="/etc.defaults/synoinfo.conf" adapter_cards="/usr/syno/etc.defaults/adapter_cards.conf" adapter_cards2="/usr/syno/etc/adapter_cards.conf" #------------------------------------------------------------------------------ # Restore changes from backups if [[ $restore == "yes" ]]; then echo if [[ -f ${dtb_file}.bak ]] || [[ -f ${adapter_cards}.bak ]] ; then # Restore adapter_cards.conf from backup # /usr/syno/etc.defaults/adapter_cards.conf if [[ -f ${adapter_cards}.bak ]]; then if cp -p "${adapter_cards}.bak" "${adapter_cards}"; then echo -e "Restored ${adapter_cards}\n" else restoreerr=1 echo -e "${Error}ERROR${Off} Failed to restore ${adapter_cards}!\n" fi fi # /usr/syno/etc/adapter_cards.conf if [[ -f ${adapter_cards2}.bak ]]; then if cp -p "${adapter_cards2}.bak" "${adapter_cards2}"; then echo -e "Restored ${adapter_cards2}\n" else restoreerr=1 echo -e "${Error}ERROR${Off} Failed to restore ${adapter_cards2}!\n" fi fi # Restore model.dtb from backup if [[ -f ${dtb_file}.bak ]]; then # /etc.default/model.dtb if cp -p "${dtb_file}.bak" "${dtb_file}"; then echo -e "Restored ${dtb_file}\n" else restoreerr=1 echo -e "${Error}ERROR${Off} Failed to restore ${dtb_file}!\n" fi # Restore /etc/model.dtb from /etc.default/model.dtb if cp -p "${dtb_file}.bak" "${dtb2_file}"; then echo -e "Restored ${dtb2_file}\n" else restoreerr=1 echo -e "${Error}ERROR${Off} Failed to restore ${dtb2_file}!\n" fi fi if [[ -z $restoreerr ]]; then echo -e "Restore successful." fi else echo -e "Nothing to restore." fi exit fi #---------------------------------------------------------- # Check currently enabled M2 cards check_key_value(){ # $1 is path/file # $2 is key setting="$(/usr/syno/bin/synogetkeyvalue "$1" "$2")" if [[ -f $1 ]]; then if [[ -n $2 ]]; then echo -e "${Yellow}$2${Off} = $setting" >&2 else echo -e "Key name not specified!" >&2 fi else echo -e "File not found: $1" >&2 fi } check_section_key_value(){ # $1 is path/file # $2 is section # $3 is key # $4 is description setting="$(/usr/syno/bin/get_section_key_value "$1" "$2" "$3")" if [[ -f $1 ]]; then if [[ -n $2 ]]; then if [[ -n $3 ]]; then if [[ $setting == "yes" ]]; then echo -e "${Yellow}$4${Off} is enabled for ${Cyan}$3${Off}" >&2 else echo -e "$4 is ${Cyan}not${Off} enabled for $3" >&2 fi else echo -e "Key name not specified!" >&2 fi else echo -e "Section name not specified!" >&2 fi else echo -e "File not found: $1" >&2 fi } check_modeldtb(){ # $1 is E10M20-T1 or M2D20 or M2D18 or M2D17 or FX2422N if [[ -f "${dtb_file}" ]]; then if grep --text "$1" "${dtb_file}" >/dev/null; then echo -e "${Yellow}$1${Off} is enabled in ${dtb_file}" >& 2 else echo -e "$1 is ${Cyan}not${Off} enabled in ${dtb_file}" >& 2 fi #else # echo -e "No ${dtb2_file}" >& 2 fi if [[ -f "${dtb2_file}" ]]; then if grep --text "$1" "${dtb2_file}" >/dev/null; then echo -e "${Yellow}$1${Off} is enabled in ${dtb2_file}" >& 2 else echo -e "$1 is ${Cyan}not${Off} enabled in ${dtb2_file}" >& 2 fi #else # echo -e "No ${dtb2_file}" >& 2 fi } if [[ $check == "yes" ]]; then # Only check /usr/syno/etc.defaults/adapter_cards.conf echo "" check_section_key_value "$adapter_cards" E10M20-T1_sup_nic "${modelname}" "E10M20-T1 NIC" check_section_key_value "$adapter_cards" E10M20-T1_sup_nvme "${modelname}" "E10M20-T1 NVMe" #check_section_key_value "$adapter_cards" E10M20-T1_sup_sata "${modelname}" "E10M20-T1 SATA" check_modeldtb "E10M20-T1" echo "" check_section_key_value "$adapter_cards" M2D20_sup_nvme "${modelname}" "M2D20 NVMe" check_modeldtb "M2D20" echo "" check_section_key_value "$adapter_cards" M2D18_sup_nvme "${modelname}" "M2D18 NVMe" check_section_key_value "$adapter_cards" M2D18_sup_sata "${modelname}" "M2D18 SATA" check_modeldtb "M2D18" echo "" check_section_key_value "$adapter_cards" M2D17_sup_sata "${modelname}" "M2D17 SATA" check_modeldtb "M2D17" echo "" check_section_key_value "$adapter_cards" FX2422N_sup_nvme "${modelname}" "FX2422N NVMe" check_modeldtb "FX2422N" echo "" exit fi #------------------------------------------------------------------------------ # Enable unsupported Synology M2 PCIe cards # In DSM 7.2 every NAS model has the same /usr/syno/etc.defaults/adapter_cards.conf # DS1821+ and DS1621+ also need edited device tree blob file /etc.defaults/model.dtb # To support M2D18: # DS1823xs+, DS2422+, RS2423+, RS2421+, RS2421RP+ and RS2821RP+ need edited model.dtb # RS822+, RS822RP+, RS1221+ and RS1221RP+ with DSM older than 7.2 need model.dtb from DSM 7.2 backupdb(){ # Backup file if needed if [[ ! -f "$1.bak" ]]; then if [[ $(basename "$1") == "synoinfo.conf" ]]; then echo "" >&2 # Formatting for stdout fi if [[ $2 == "long" ]]; then fname="$1" else fname=$(basename -- "${1}") fi if cp -p "$1" "$1.bak"; then echo -e "Backed up ${fname}" >&2 else echo -e "${Error}ERROR 5${Off} Failed to backup ${fname}!" >&2 return 1 fi fi # Fix permissions if needed octal=$(stat -c "%a %n" "$1" | cut -d" " -f1) if [[ ! $octal -eq 644 ]]; then chmod 644 "$1" fi return 0 } enable_card(){ # $1 is the file # $2 is the section # $3 is the card model and mode if [[ -f $1 ]] && [[ -n $2 ]] && [[ -n $3 ]]; then backupdb "$adapter_cards" long backupdb "$adapter_cards2" long # Check if section exists if ! grep '^\['"$2"'\]$' "$1" >/dev/null; then echo -e "Section [$2] not found in $(basename -- "$1")!" >&2 return fi # Check if already enabled # # No idea if "cat /proc/sys/kernel/syno_hw_version" returns upper or lower case RP # "/usr/syno/etc.defaults/adapter_cards.conf" uses lower case rp but upper case RS # So we'll convert RP to rp when needed. # modelrplowercase=${modelname//RP/rp} val=$(/usr/syno/bin/get_section_key_value "$1" "$2" "$modelrplowercase") if [[ $val != "yes" ]]; then # /usr/syno/etc.defaults/adapter_cards.conf if /usr/syno/bin/set_section_key_value "$1" "$2" "$modelrplowercase" yes; then # /usr/syno/etc/adapter_cards.conf /usr/syno/bin/set_section_key_value "$adapter_cards2" "$2" "$modelrplowercase" yes echo -e "Enabled ${Yellow}$3${Off} for ${Cyan}$modelname${Off}" >&2 reboot=yes else echo -e "${Error}ERROR 9${Off} Failed to enable $3 for ${modelname}!" >&2 fi else echo -e "${Yellow}$3${Off} already enabled for ${Cyan}$modelname${Off}" >&2 fi fi } dts_m2_card(){ # $1 is the card model # $2 is the dts file # Remove last }; so we can append to dts file sed -i '/^};/d' "$2" # Append PCIe M.2 card node to dts file if [[ $1 == E10M20-T1 ]] || [[ $1 == M2D20 ]]; then cat >> "$2" <<EOM2D $1 { compatible = "Synology"; model = "synology_${1,,}"; power_limit = "14.85,14.85"; m2_card@1 { nvme { pcie_postfix = "00.0,08.0,00.0"; port_type = "ssdcache"; }; }; m2_card@2 { nvme { pcie_postfix = "00.0,04.0,00.0"; port_type = "ssdcache"; }; }; }; }; EOM2D elif [[ $1 == M2D18 ]]; then cat >> "$2" <<EOM2D18 M2D18 { compatible = "Synology"; model = "synology_m2d18"; power_limit = "9.9,9.9"; m2_card@1 { ahci { pcie_postfix = "00.0,03.0,00.0"; ata_port = <0x00>; }; nvme { pcie_postfix = "00.0,04.0,00.0"; port_type = "ssdcache"; }; }; m2_card@2 { ahci { pcie_postfix = "00.0,03.0,00.0"; ata_port = <0x01>; }; nvme { pcie_postfix = "00.0,05.0,00.0"; port_type = "ssdcache"; }; }; }; }; EOM2D18 elif [[ $1 == M2D17 ]]; then cat >> "$2" <<EOM2D17 M2D17 { compatible = "Synology"; model = "synology_m2d17"; power_limit = "9.9,9.9"; m2_card@1 { ahci { pcie_postfix = "00.0,03.0,00.0"; ata_port = <0x00>; }; }; m2_card@2 { ahci { pcie_postfix = "00.0,03.0,00.0"; ata_port = <0x01>; }; }; }; }; EOM2D17 # https://new.reddit.com/r/synology/comments/18tdli8/using_a_cheap_pcie_m2_card_in_a_synology_nas_part/ elif [[ $1 == FX2422N ]]; then # Experimental cat >> "$2" <<EOFX2422N $1 { compatible = "Synology"; model = "synology_${1,,}"; power_limit = "14.85,14.85"; m2_card@1 { nvme { pcie_postfix = "00.0,04.0,00.0"; port_type = "ssdcache"; }; }; m2_card@2 { nvme { pcie_postfix = "00.0,08.0,00.0"; port_type = "ssdcache"; }; }; m2_card@3 { nvme { pcie_postfix = "00.0,0c.0,00.0"; port_type = "ssdcache"; }; }; m2_card@4 { nvme { pcie_postfix = "00.0,10.0,00.0"; port_type = "ssdcache"; }; }; }; }; EOFX2422N fi } install_binfile(){ # install_binfile <file> <file-url> <destination> <chmod> <bundled-path> <hash> # example: # file_url="https://raw.githubusercontent.com/${repo}/main/bin/dtc" # install_binfile dtc "$file_url" /usr/bin/bc a+x bin/dtc if [[ -f "${scriptpath}/$5" ]]; then binfile="${scriptpath}/$5" echo -e "\nInstalling ${1}" elif [[ -f "${scriptpath}/$(basename -- "$5")" ]]; then binfile="${scriptpath}/$(basename -- "$5")" echo -e "\nInstalling ${1}" else # Download binfile if [[ $autoupdate == "yes" ]]; then reply=y else echo -e "\nNeed to download ${1}" echo -e "${Cyan}Do you want to download ${1}?${Off} [y/n]" read -r -t 30 reply fi if [[ ${reply,,} == "y" ]]; then echo -e "\nDownloading ${1}" if ! curl -kL -m 30 --connect-timeout 5 "$2" -o "/tmp/$1"; then echo -e "${Error}ERROR${Off} Failed to download ${1}!" return fi binfile="/tmp/${1}" printf "Downloaded md5: " md5sum -b "$binfile" | awk '{print $1}' md5=$(md5sum -b "$binfile" | awk '{print $1}') if [[ $md5 != "$6" ]]; then echo "Expected md5: $6" echo -e "${Error}ERROR${Off} Downloaded $1 md5 hash does not match!" exit 1 fi else echo -e "${Error}ERROR${Off} Cannot add M2 PCIe card without ${1}!" exit 1 fi fi # Set binfile executable chmod "$4" "$binfile" # Copy binfile to destination cp -p "$binfile" "$3" } edit_modeldtb(){ # $1 is E10M20-T1 or M2D20 or M2D18 or M2D17 or FX2422N if [[ -f /etc.defaults/model.dtb ]]; then # Is device tree model # Check if dtc exists and is executable if [[ ! -x $(which dtc) ]]; then md5hash="01381dabbe86e13a2f4a8017b5552918" branch="main" file_url="https://raw.githubusercontent.com/${repo}/${branch}/bin/dtc" # install_binfile <file> <file-url> <destination> <chmod> <bundled-path> <hash> install_binfile dtc "$file_url" /usr/sbin/dtc "a+x" bin/dtc "$md5hash" fi # Check again if dtc exists and is executable if [[ -x /usr/sbin/dtc ]]; then # Backup model.dtb backupdb "$dtb_file" long # Output model.dtb to model.dts dtc -q -I dtb -O dts -o "$dts_file" "$dtb_file" # -q Suppress warnings chmod 644 "$dts_file" # Edit model.dts for c in "${cards[@]}"; do # Edit model.dts if needed if ! grep "$c" "$dtb_file" >/dev/null; then dts_m2_card "$c" "$dts_file" echo -e "Added ${Yellow}$c${Off} to ${Cyan}model${hwrev}.dtb${Off}" >&2 else echo -e "${Yellow}$c${Off} already exists in ${Cyan}model${hwrev}.dtb${Off}" >&2 fi done # Compile model.dts to model.dtb dtc -q -I dts -O dtb -o "$dtb_file" "$dts_file" # -q Suppress warnings # Set owner and permissions for model.dtb chmod a+r "$dtb_file" chown root:root "$dtb_file" cp -pu "$dtb_file" "$dtb2_file" # Copy dtb file to /etc else echo -e "${Error}ERROR${Off} Missing /usr/sbin/dtc or not executable!" >&2 fi fi } #------------------------------------------------------------------------------ # Select M2 card model to enable select_card(){ case "$1" in E10M20-T1) echo "" enable_card "$adapter_cards" E10M20-T1_sup_nic "E10M20-T1 NIC" enable_card "$adapter_cards" E10M20-T1_sup_nvme "E10M20-T1 NVMe" #enable_card "$adapter_cards" E10M20-T1_sup_sata "E10M20-T1 SATA" cards=(E10M20-T1) && edit_modeldtb return ;; M2D20) echo "" enable_card "$adapter_cards" M2D20_sup_nvme "M2D20 NVMe" cards=(M2D20) && edit_modeldtb return ;; M2D18) echo "" enable_card "$adapter_cards" M2D18_sup_nvme "M2D18 NVMe" enable_card "$adapter_cards" M2D18_sup_sata "M2D18 SATA" cards=(M2D18) && edit_modeldtb return ;; M2D17) echo "" enable_card "$adapter_cards" M2D17_sup_sata "M2D17 SATA" cards=(M2D17) && edit_modeldtb return ;; FX2422N) echo "" enable_card "$adapter_cards" FX2422N_sup_nvme "FX2422N" cards=(FX2422N) && edit_modeldtb return ;; ALL) echo "" enable_card "$adapter_cards" E10M20-T1_sup_nic "E10M20-T1 NIC" enable_card "$adapter_cards" E10M20-T1_sup_nvme "E10M20-T1 NVMe" #enable_card "$adapter_cards" E10M20-T1_sup_sata "E10M20-T1 SATA" enable_card "$adapter_cards" M2D20_sup_nvme "M2D20 NVMe" enable_card "$adapter_cards" M2D18_sup_nvme "M2D18 NVMe" enable_card "$adapter_cards" M2D18_sup_sata "M2D18 SATA" enable_card "$adapter_cards" M2D17_sup_sata "M2D17 SATA" enable_card "$adapter_cards" FX2422N_sup_nvme "FX2422N" cards=("E10M20-T1" "M2D20" "M2D18" "M2D17" "FX2422N") && edit_modeldtb return ;; *) echo -e "Unknown M2 card type: $choice" ;; esac } if [[ -n $card ]]; then select_card "$card" else PS3="Select your M.2 Card: " options=("E10M20-T1" "M2D20" "M2D18" "M2D17" "FX2422N" "ALL" "Quit") select choice in "${options[@]}"; do case "$choice" in Quit) exit ;; *) select_card "$choice" break ;; esac done fi #------------------------------------------------------------------------------ # Finished if [[ $reboot == "yes" ]]; then # Reboot prompt echo -e "\n${Cyan}The Synology needs to restart.${Off}" echo -e "Type ${Cyan}yes${Off} to reboot now." echo -e "Type anything else to quit (if you will restart it yourself)." read -r -t 10 answer if [[ ${answer,,} != "yes" ]]; then exit; fi # # Reboot in the background so user can see DSM's "going down" message # reboot & if [[ -x /usr/syno/sbin/synopoweroff ]]; then /usr/syno/sbin/synopoweroff -r || reboot else reboot fi else echo -e "\nFinished" fi
32,493
syno_enable_m2_card
sh
en
shell
code
{"qsc_code_num_words": 3949, "qsc_code_num_chars": 32493.0, "qsc_code_mean_word_length": 4.15269689, "qsc_code_frac_words_unique": 0.14687263, "qsc_code_frac_chars_top_2grams": 0.02073297, "qsc_code_frac_chars_top_3grams": 0.01341545, "qsc_code_frac_chars_top_4grams": 0.02012318, "qsc_code_frac_chars_dupe_5grams": 0.40721995, "qsc_code_frac_chars_dupe_6grams": 0.34471614, "qsc_code_frac_chars_dupe_7grams": 0.29489603, "qsc_code_frac_chars_dupe_8grams": 0.23531923, "qsc_code_frac_chars_dupe_9grams": 0.19659735, "qsc_code_frac_chars_dupe_10grams": 0.16043661, "qsc_code_frac_chars_replacement_symbols": 0.0, "qsc_code_frac_chars_digital": 0.0465361, "qsc_code_frac_chars_whitespace": 0.32742437, "qsc_code_size_file_byte": 32493.0, "qsc_code_num_lines": 1023.0, "qsc_code_num_chars_line_max": 112.0, "qsc_code_num_chars_line_mean": 31.76246334, "qsc_code_frac_chars_alphabet": 0.70385284, "qsc_code_frac_chars_comments": 0.21595421, "qsc_code_cate_xml_start": 0.0, "qsc_code_frac_lines_dupe_lines": 0.47391304, "qsc_code_cate_autogen": 0.0, "qsc_code_frac_lines_long_string": 0.00289855, "qsc_code_frac_chars_string_length": 0.27466143, "qsc_code_frac_chars_long_word_length": 0.04737978, "qsc_code_frac_lines_string_concat": 0.0, "qsc_code_cate_encoded_data": 0.0, "qsc_code_frac_chars_hex_words": 0.00102061, "qsc_code_frac_lines_prompt_comments": 0.0, "qsc_code_frac_lines_assert": 0.0}
1
{"qsc_code_frac_chars_replacement_symbols": 0, "qsc_code_num_words": 0, "qsc_code_num_chars": 0, "qsc_code_mean_word_length": 0, "qsc_code_frac_chars_top_2grams": 0, "qsc_code_frac_chars_top_3grams": 0, "qsc_code_frac_chars_top_4grams": 0, "qsc_code_frac_chars_dupe_5grams": 0, "qsc_code_frac_chars_dupe_6grams": 0, "qsc_code_frac_chars_dupe_7grams": 0, "qsc_code_frac_chars_dupe_8grams": 0, "qsc_code_frac_chars_dupe_9grams": 0, "qsc_code_frac_chars_dupe_10grams": 0, "qsc_code_frac_lines_dupe_lines": 0, "qsc_code_size_file_byte": 0, "qsc_code_num_lines": 0, "qsc_code_num_chars_line_max": 0, "qsc_code_num_chars_line_mean": 0, "qsc_code_frac_chars_alphabet": 0, "qsc_code_frac_chars_digital": 0, "qsc_code_frac_chars_whitespace": 0, "qsc_code_frac_chars_comments": 0, "qsc_code_cate_xml_start": 0, "qsc_code_cate_autogen": 0, "qsc_code_frac_chars_long_word_length": 0, "qsc_code_cate_encoded_data": 0, "qsc_code_frac_chars_hex_words": 0, "qsc_code_frac_lines_prompt_comments": 0}
007revad/Synology_enable_M2_volume
my-other-scripts.md
## All my scripts, tools and guides <img src="https://hitscounter.dev/api/hit?url=https%3A%2F%2F007revad.github.io%2F&label=Visitors&icon=github&color=%23198754&message=&style=flat&tz=UTC"> #### Contents - [Plex](#plex) - [Synology docker](#synology-docker) - [Synology recovery](#synology-recovery) - [Other Synology scripts](#other-synology-scripts) - [Synology hardware restrictions](#synology-hardware-restrictions) - [2025 plus models](#2025-plus-models) - [How To Guides](#how-to-guides) - [Synology dev](#synology-dev) *** ### Plex - **<a href="https://github.com/007revad/Synology_Plex_Backup">Synology_Plex_Backup</a>** - A script to backup Plex to a tgz file foror DSM 7 and DSM 6. - Works for Plex Synology package and Plex in docker. - **<a href="https://github.com/007revad/Asustor_Plex_Backup">Asustor_Plex_Backup</a>** - Backup your Asustor's Plex Media Server settings and database. - **<a href="https://github.com/007revad/Linux_Plex_Backup">Linux_Plex_Backup</a>** - Backup your Linux Plex Media Server's settings and database. - **<a href="https://github.com/007revad/Plex_Server_Sync">Plex_Server_Sync</a>** - Sync your main Plex server database & metadata to a backup Plex server. - Works for Synology, Asustor, Linux and supports Plex package or Plex in docker. &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; [Back to Contents](#contents) ### Synology docker - **<a href="https://github.com/007revad/Synology_Docker_Export">Synology_Docker_export</a>** - Export all Synology Container Manager or Docker containers' settings as json files to your docker shared folder. - **<a href="https://github.com/007revad/Synology_ContainerManager_IPv6">Synology_ContainerManager_IPv6</a>** - Enable IPv6 for Container Manager's bridge network. - **<a href="https://github.com/007revad/ContainerManager_for_all_armv8">ContainerManager_for_all_armv8</a>** - Script to install Container Manager on a RS819, DS119j, DS418, DS418j, DS218, DS218play or DS118. - **<a href="https://github.com/007revad/Docker_Autocompose">Docker_Autocompose</a>** - Create .yml files from your docker existing containers. - **<a href="https://github.com/007revad/Synology_docker_cleanup">Synology_docker_cleanup</a>** - Remove orphan docker btrfs subvolumes and images in Synology DSM 7 and DSM 6. &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; [Back to Contents](#contents) ### Synology recovery - **<a href="https://github.com/007revad/Synology_DSM_reinstall">Synology_DSM_reinstall</a>** - Easily re-install the same DSM version without losing any data or settings. - **<a href="https://github.com/007revad/Synology_Recover_Data">Synology_Recover_Data</a>** - A script to make it easy to recover your data from your Synology's drives using a computer. - **<a href="https://github.com/007revad/Synology_clear_drive_error">Synology clear drive error</a>** - Clear drive critical errors so DSM will let you use the drive. - **<a href="https://github.com/007revad/Synology_DSM_Telnet_Password">Synology_DSM_Telnet_Password</a>** - Synology DSM Recovery Telnet Password of the Day generator. - **<a href="https://github.com/007revad/Syno_DSM_Extractor_GUI">Syno_DSM_Extractor_GUI</a>** - Windows GUI for extracting Synology DSM 7 pat files and spk package files. - **<a href="https://github.com/007revad/Synoboot_backup">Synoboot_backup</a>** - Back up synoboot after each DSM update so you can recover from a corrupt USBDOM. &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; [Back to Contents](#contents) ### Other Synology scripts - **<a href="https://github.com/007revad/Synology_app_mover">Synology_app_mover</a>** - Easily move Synology packages from one volume to another volume. - **<a href="https://github.com/007revad/Video_Station_for_DSM_722">Video_Station_for_DSM_722</a>** - Script to install Video Station in DSM 7.2.2 - **<a href="https://github.com/007revad/SS_Motion_Detection">SS_Motion_Detection</a>** - Installs previous Surveillance Station and Advanced Media Extensions versions so motion detection and HEVC are supported. - **<a href="https://github.com/007revad/Synology_Config_Backup">Synology_Config_Backup</a>** - Backup and export your Synology DSM configuration. - **<a href="https://github.com/007revad/Synology_CPU_temperature">Synology_CPU_temperature</a>** - Get and log Synology NAS CPU temperature via SSH. - **<a href="https://github.com/007revad/Synology_SMART_info">Synology_SMART_info</a>** - Show Synology smart test progress or smart health and attributes. - **<a href="https://github.com/007revad/Synology_Cleanup_Coredumps">Synology_Cleanup_Coredumps</a>** - Cleanup memory core dumps from crashed processes. - **<a href="https://github.com/007revad/Synology_toggle_reset_button">Synology_toggle_reset_button</a>** - Script to disable or enable the reset button and show current setting. - **<a href="https://github.com/007revad/Synology_Download_Station_Chrome_Extension">Synology_Download_Station_Chrome_Extension</a>** - Download Station Chrome Extension. - **<a href="https://github.com/007revad/Seagate_lowCurrentSpinup">Seagate_lowCurrentSpinup</a>** - This script avoids the need to buy and install a higher wattage power supply when using multiple large Seagate SATA HDDs. &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; [Back to Contents](#contents) ### Synology hardware restrictions - **<a href="https://github.com/007revad/Synology_HDD_db">Synology_HDD_db</a>** - Add your SATA or SAS HDDs and SSDs plus SATA and NVMe M.2 drives to your Synology's compatible drive databases, including your Synology M.2 PCIe card and Expansion Unit databases. - **<a href="https://github.com/007revad/Synology_enable_M2_volume">Synology_enable_M2_volume</a>** - Enable creating volumes with non-Synology M.2 drives. - Enable Health Info for non-Synology NVMe drives (not in DSM 7.2.1 or later). - **<a href="https://github.com/007revad/Synology_M2_volume">Synology_M2_volume</a>** - Easily create an M.2 volume on Synology NAS. - **<a href="https://github.com/007revad/Synology_enable_M2_card">Synology_enable_M2_card</a>** - Enable Synology M.2 PCIe cards in Synology NAS that don't officially support them. - **<a href="https://github.com/007revad/Synology_enable_eunit">Synology_enable_eunit</a>** - Enable an unsupported Synology eSATA Expansion Unit models. - **<a href="https://github.com/007revad/Synology_enable_Deduplication">Synology_enable_Deduplication</a>** - Enable deduplication with non-Synology SSDs and unsupported NAS models. - **<a href="https://github.com/007revad/Synology_SHR_switch">Synology_SHR_switch</a>** - Easily switch between SHR and RAID Groups, or enable RAID F1. - **<a href="https://github.com/007revad/Synology_enable_sequential_IO">Synology_enable_sequential_IO</a>** - Enables sequential I/O for your SSD caches, like DSM 6 had. - **<a href="https://github.com/007revad/Synology_Information_Wiki">Synology_Information_Wiki</a>** - Information about Synology hardware. &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; [Back to Contents](#contents) ### 2025 plus models - **<a href="https://github.com/007revad/Transcode_for_x25">Transcode_for_x25</a>** - Installs the modules needed for Plex or Jellyfin hardware transcoding in DS425+ and DS225+. - **<a href="https://github.com/007revad/Synology_HDD_db/blob/main/2025_plus_models.md">2025 series or later Plus models</a>** - Unverified 3rd party drive limitations and unofficial solutions. - **<a href="https://github.com/007revad/Synology_HDD_db/blob/main/2025_plus_models.md#setting-up-a-new-2025-or-later-plus-model-with-only-unverified-hdds">Setup with only 3rd party drives</a>** - Setting up a new 2025 or later plus model with only unverified HDDs. - **<a href="https://github.com/007revad/Synology_HDD_db/blob/main/2025_plus_models.md#deleting-and-recreating-your-storage-pool-on-unverified-hdds">Recreating storage pool on migrated drives</a>** - Deleting and recreating your storage pool on unverified HDDs. &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; [Back to Contents](#contents) ### How To Guides - **<a href="https://github.com/007revad/Synology_SSH_key_setup">Synology_SSH_key_setup</a>** - How to setup SSH key authentication for your Synology. &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; [Back to Contents](#contents) ### Synology dev - **<a href="https://github.com/007revad/Download_Synology_Archive">Download_Synology_Archive</a>** - Download all or part of the Synology archive. - **<a href="https://github.com/007revad/Syno_DSM_Extractor_GUI">Syno_DSM_Extractor_GUI</a>** - Windows GUI for extracting Synology DSM 7 pat files and spk package files. - **<a href="https://github.com/007revad/ScriptNotify">ScriptNotify</a>** - DSM 7 package to allow your scripts to send DSM notifications. - **<a href="https://github.com/007revad/DTC_GUI_for_Windows">DTC_GUI_for_Windows</a>** - GUI for DTC.exe for Windows. &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; [Back to Contents](#contents)
9,099
my-other-scripts
md
en
markdown
text
{"qsc_doc_frac_chars_curly_bracket": 0.0, "qsc_doc_frac_words_redpajama_stop": 0.16632653, "qsc_doc_num_sentences": 107.0, "qsc_doc_num_words": 1341, "qsc_doc_num_chars": 9099.0, "qsc_doc_num_lines": 180.0, "qsc_doc_mean_word_length": 4.94630872, "qsc_doc_frac_words_full_bracket": 0.0, "qsc_doc_frac_lines_end_with_readmore": 0.0, "qsc_doc_frac_lines_start_with_bullet": 0.0, "qsc_doc_frac_words_unique": 0.23191648, "qsc_doc_entropy_unigram": 4.76529845, "qsc_doc_frac_words_all_caps": 0.02908163, "qsc_doc_frac_lines_dupe_lines": 0.1025641, "qsc_doc_frac_chars_dupe_lines": 0.10911978, "qsc_doc_frac_chars_top_2grams": 0.05789236, "qsc_doc_frac_chars_top_3grams": 0.06482738, "qsc_doc_frac_chars_top_4grams": 0.10372381, "qsc_doc_frac_chars_dupe_5grams": 0.39981909, "qsc_doc_frac_chars_dupe_6grams": 0.36891301, "qsc_doc_frac_chars_dupe_7grams": 0.34041912, "qsc_doc_frac_chars_dupe_8grams": 0.25569124, "qsc_doc_frac_chars_dupe_9grams": 0.20624152, "qsc_doc_frac_chars_dupe_10grams": 0.15829941, "qsc_doc_frac_chars_replacement_symbols": 0.0, "qsc_doc_cate_code_related_file_name": 0.0, "qsc_doc_num_chars_sentence_length_mean": 30.70731707, "qsc_doc_frac_chars_hyperlink_html_tag": 0.34762062, "qsc_doc_frac_chars_alphabet": 0.79007303, "qsc_doc_frac_chars_digital": 0.03094442, "qsc_doc_frac_chars_whitespace": 0.11210023, "qsc_doc_frac_chars_hex_words": 0.0}
1
{"qsc_doc_frac_chars_replacement_symbols": 0, "qsc_doc_entropy_unigram": 0, "qsc_doc_frac_chars_top_2grams": 0, "qsc_doc_frac_chars_top_3grams": 0, "qsc_doc_frac_chars_top_4grams": 0, "qsc_doc_frac_chars_dupe_5grams": 0, "qsc_doc_frac_chars_dupe_6grams": 0, "qsc_doc_frac_chars_dupe_7grams": 0, "qsc_doc_frac_chars_dupe_8grams": 0, "qsc_doc_frac_chars_dupe_9grams": 0, "qsc_doc_frac_chars_dupe_10grams": 0, "qsc_doc_frac_chars_dupe_lines": 0, "qsc_doc_frac_lines_dupe_lines": 0, "qsc_doc_frac_lines_end_with_readmore": 0, "qsc_doc_frac_lines_start_with_bullet": 0, "qsc_doc_frac_words_all_caps": 0, "qsc_doc_mean_word_length": 0, "qsc_doc_num_chars": 0, "qsc_doc_num_lines": 0, "qsc_doc_num_sentences": 0, "qsc_doc_num_words": 0, "qsc_doc_frac_chars_hex_words": 0, "qsc_doc_frac_chars_hyperlink_html_tag": 0, "qsc_doc_frac_chars_alphabet": 0, "qsc_doc_frac_chars_digital": 0, "qsc_doc_frac_chars_whitespace": 0}
007revad/Synology_enable_M2_volume
README.md
# Synology enable M2 volume <a href="https://github.com/007revad/Synology_enable_M2_volume/releases"><img src="https://img.shields.io/github/release/007revad/Synology_enable_M2_volume.svg"></a> ![Badge](https://hitscounter.dev/api/hit?url=https%3A%2F%2Fgithub.com%2F007revad%2FSynology_enable_M2_volume&label=Visitors&icon=github&color=%23198754&message=&style=flat&tz=Australia%2FSydney) [![Donate](https://img.shields.io/badge/Donate-PayPal-green.svg)](https://www.paypal.com/paypalme/007revad) [![](https://img.shields.io/static/v1?label=Sponsor&message=%E2%9D%A4&logo=GitHub&color=%23fe8e86)](https://github.com/sponsors/007revad) [![committers.top badge](https://user-badge.committers.top/australia/007revad.svg)](https://user-badge.committers.top/australia/007revad) ### Description Enable creating volumes with non-Synology M.2 drives This script will: - Enable creating M.2 storage pools and volumes all from within Storage Manager. - Enable Health Info for non-Synology NVMe drives (not in DSM 7.2.1 or later). It will work for DSM 7.2 and some models running DSM 7.1.1. As for a full list of which models it will work with, I don't know yet. I do know it does work on models listed by Synology as supported for creating M.2 volumes, and some '21 and newer enterprise models. ### Confirmed working on <details> <summary>Click here to see list</summary> | Model | Platform | DSM version | Works | Note | | ------------ |----------|--------------------------|-------|------| | **E10M20-T1** | | DSM 7.2.1 and later | **No** | Use <a href="https://github.com/007revad/Synology_HDD_db">Synology_HDD_db</a> instead | | **M2D20** | | DSM 7.2.1 and later | **No** | Use <a href="https://github.com/007revad/Synology_HDD_db">Synology_HDD_db</a> instead | | **M2D18** | | DSM 7.2.1 and later | **No** | Use <a href="https://github.com/007revad/Synology_HDD_db">Synology_HDD_db</a> instead | | **E10M20-T1** | | Older DSM versions | **No** | Use <a href="https://github.com/007revad/Synology_M2_volume">Synology_M2_volume</a> instead | | **M2D20** | | Older DSM versions | **No** | Use <a href="https://github.com/007revad/Synology_M2_volume">Synology_M2_volume</a> instead | | **M2D18** | | Older DSM versions | **No** | Use <a href="https://github.com/007revad/Synology_M2_volume">Synology_M2_volume</a> instead | || | **23 Series** | | DS1823xs+ | V1000 | DSM 7.2.1 and later | **No** | Use <a href="https://github.com/007revad/Synology_HDD_db">Synology_HDD_db</a> instead | | DS923+ | R1000 | DSM 7.2.1-69057 Update 5 | yes | Use only <a href="https://github.com/007revad/Synology_HDD_db">Synology_HDD_db</a> instead | | DS923+ | R1000 | DSM 7.2.1-69057 Update 4 | yes | Use only <a href="https://github.com/007revad/Synology_HDD_db">Synology_HDD_db</a> instead | | DS923+ | R1000 | DSM 7.2-64570 Update 3 | yes | Use only <a href="https://github.com/007revad/Synology_HDD_db">Synology_HDD_db</a> instead | | DS923+ | R1000 | DSM 7.2-64570 | yes | Use only <a href="https://github.com/007revad/Synology_HDD_db">Synology_HDD_db</a> instead | | DS923+ | R1000 | DSM 7.1.1-42962 Update 4 | yes | Use only <a href="https://github.com/007revad/Synology_HDD_db">Synology_HDD_db</a> instead | | DS723+ | R1000 | DSM 7.2-64570 Update 3 | yes | Use only <a href="https://github.com/007revad/Synology_HDD_db">Synology_HDD_db</a> instead | | DS423+ | Geminilake | DSM 7.1.1-42962 Update 5 | yes | Use only <a href="https://github.com/007revad/Synology_HDD_db">Synology_HDD_db</a> instead | | **22 Series** | | DS3622xs+ | Broadwellnk | DSM 7.2.1-69057 Update 4 | **No** | M.2 panel missing in storage manager | | DS3622xs+ | Broadwellnk | DSM 7.2-64570 Update 3 | **No** | M.2 panel missing in storage manager | | DS3622xs+ | Broadwellnk | DSM 7.2-64570 | yes | | DS3622xs+ | Broadwellnk | DSM 7.1.1-42962 Update 4 | yes | | DS3622xs+ | Broadwellnk | DSM 7.1.1-42962 Update 1 | **No** | Use newer DSM version | | DS1522+ | R1000 | DSM 7.2.1-69057 Update 4 | yes | Use only <a href="https://github.com/007revad/Synology_HDD_db">Synology_HDD_db</a> instead | | DS1522+ | R1000 | DSM 7.2-64570 | yes | Use only <a href="https://github.com/007revad/Synology_HDD_db">Synology_HDD_db</a> instead | | DS1522+ | R1000 | DSM 7.1.1-42962 Update 4 | **No** | Use newer DSM version | | **21 Series** | | RS4021xs+ | Broadwellnk | DSM 7.2.1-69057 Update 4 | **No** | M.2 panel missing in storage manager | | RS4021xs+ | Broadwellnk | DSM 7.2-64570 Update 3 | **No** | M.2 panel missing in storage manager | | RS4021xs+ | Broadwellnk | DSM 7.2-64570 | yes | | RS4021xs+ | Broadwellnk | DSM 7.1.1-42962 Update 2 | yes | | DS1821+ | V1000 | DSM 7.2.1-69057 Update 4 | yes | Use only <a href="https://github.com/007revad/Synology_HDD_db">Synology_HDD_db</a> instead | | DS1821+ | V1000 | DSM 7.2-64570 Update 3 | yes | Use only <a href="https://github.com/007revad/Synology_HDD_db">Synology_HDD_db</a> instead | | DS1821+ | V1000 | DSM 7.2-64570 Update 2 | yes | Use only <a href="https://github.com/007revad/Synology_HDD_db">Synology_HDD_db</a> instead | | DS1821+ | V1000 | DSM 7.2-64570 Update 1 | yes | Use only <a href="https://github.com/007revad/Synology_HDD_db">Synology_HDD_db</a> instead | | DS1821+ | V1000 | DSM 7.2-64570 | yes | Use only <a href="https://github.com/007revad/Synology_HDD_db">Synology_HDD_db</a> instead | | DS1621xs+ | Broadwellnk | DSM 7.2.1-69057 Update 5 | yes | Use only <a href="https://github.com/007revad/Synology_HDD_db">Synology_HDD_db</a> instead | | DS1621xs+ | Broadwellnk | DSM 7.2.1-69057 Update 4 | yes | Use only <a href="https://github.com/007revad/Synology_HDD_db">Synology_HDD_db</a> instead | | DS1621xs+ | Broadwellnk | DSM 7.2-64570 Update 3 | yes | Use only <a href="https://github.com/007revad/Synology_HDD_db">Synology_HDD_db</a> instead | | DS1621xs+ | Broadwellnk | DSM 7.2-64570 Update 1 | yes | Use only <a href="https://github.com/007revad/Synology_HDD_db">Synology_HDD_db</a> instead | | DS1621+ | V1000 | DSM 7.2.1-69057 Update 5 | yes | Use only <a href="https://github.com/007revad/Synology_HDD_db">Synology_HDD_db</a> instead | | DVA3221 | Denverton | DSM 7.x | **No** | Not working with any DSM version | | **20 Series** | | DS1520+ | Geminilake | DSM 7.2.1-69057 Update 4 | yes | | DS1520+ | Geminilake | DSM 7.2.1-69057 | yes | | DS920+ | Geminilake | DSM 7.2.2-72806 Update 2 | yes | | DS920+ | Geminilake | DSM 7.2.1-69057 Update 6 | yes | | DS920+ | Geminilake | DSM 7.2.1-69057 Update 5 | yes | | DS920+ | Geminilake | DSM 7.2.1-69057 Update 4 | yes | | DS920+ | Geminilake | DSM 7.2.1-69057 Update 3 | yes | | DS920+ | Geminilake | DSM 7.2.1-69057 Update 2 | yes | | DS920+ | Geminilake | DSM 7.2.1-69057 Update 1 | yes | | DS920+ | Geminilake | DSM 7.2.1-69057 | yes | | DS920+ | Geminilake | DSM 7.2-64570 Update 3 | yes | | DS920+ | Geminilake | DSM 7.2-64570 Update 1 | yes | | DS920+ | Geminilake | DSM 7.2-64570 | yes | | DS920+ | Geminilake | DSM 7.1.1-42962 Update 5 | **No** | Use newer DSM version | | DS920+ | Geminilake | DSM 7.1.1-42962 Update 4 | **No** | Use newer DSM version | | DS720+ | Geminilake | DSM 7.2.1-69057 Update 4 | yes | | DS720+ | Geminilake | DSM 7.2.1-69057 | yes | | DS720+ | Geminilake | DSM 7.2-64570 Update 3 | yes | | DS720+ | Geminilake | DSM 7.2-64570 | yes | | DS620slim | Apollolake | DSM 7.2.1-69057 Update 4 | **No** | M.2 panel missing in storage manager | | DS420+ | Geminilake | DSM 7.2.1-69057 Update 4 | yes | | DS420+ | Geminilake | DSM 7.2-64570 | yes | | **19 Series** | | DS1019+ | Apollolake | DSM 7.2.1-69057 Update 4 | yes | Only one M.2 NVMe is supported | | DS1019+ | Apollolake | DSM 7.2-64570 Update 3 | yes | Only one M.2 NVMe is supported | | DS1019+ | Apollolake | DSM 7.2-64570 Update 1 | yes | Only one M.2 NVMe is supported | | DS1019+ | Apollolake | DSM 7.2-64570 | yes | Only one M.2 NVMe is supported | | **18 Series** | | DS918+ | Apollolake | DSM 7.2.1-69057 Update 4 | yes | | DS918+ | Apollolake | DSM 7.2-64570 Update 3 | yes | | DS918+ | Apollolake | DSM 7.2-64570 | yes | | DS918+ | Apollolake | DSM 7.1.1-42962 Update 5 | **No** | Use newer DSM version | | **17 Series** | | DS3617xs | Broadwell | DSM 7.x | **No** | Not working with any DSM version | | **15 Series** | | DS3615xs | Bromolow | DSM 7.x | **No** | Not working with any DSM version | | **SA Series** | | SA6400 | EPYC7002 | DSM 7.2.1-69057 Update 4 | yes | </details> ### How is this different to the Synology_M2_volume script? - **<a href="https://github.com/007revad/Synology_HDD_db">Synology_HDD_db</a>:** - Allows creating an M.2 storage pool and volume all from within Storage Manager with any brand M.2 drive. - Works with most '20 series and newer model Synology NAS using DSM 7.2 or later without needing Synology_enable_M2_volume or Synology_M2_volume. - **Synology_enable_M2_volume:** - Allows creating an M.2 storage pool and volume all from within Storage Manager with any brand M.2 drive. - Gives you the option of **SHR and JBOD**, as well as RAID 0, RAID 1 and Basic. - Enables Health Info for non-Synology NVMe drives. - Add drive(s) and change RAID type work from within Storage Manager. - RAID repair and expansion work from within Storage Manager. - Easy to run as there a no questions to answer. - Works with DSM 7.2 beta and 7.1.1 (may work with DSM 7.1 and 7.0). - Works with any brand M.2 drives. - May only work with models Synology listed as supporting M.2 volumes. - Can be scheduled to run at boot or shut down. - Does **NOT** work for M.2 drives in a M2D20, M2D18, M2D17 or E10M20-T1. - Does **NOT** allow creating a storage pool/volume spanning internal NVMe drives and NVMe drives in a Synology M.2 PCIe card. - **<a href="https://github.com/007revad/Synology_M2_volume">Synology_M2_volume</a>:** - Creates the synology partitions. - Creates the storage pool. - Requires you to do an Online Assemble in Storage Manager before you can create your volume. - A little more complicated as there are questions that you need to answer. - Gives you the option of Basic, RAID 0, RAID 1, **RAID 5**, **RAID 6** and **RAID 10**. - Works with any DSM version. - Works with any brand M.2 drives. - Works with any Synology model that has M.2 slots or can install a Synology PCIe M.2 card. - Works for M.2 drives in a M2D20, M2D18, M2D17 or E10M20-T1. - Works for creating a storage pool/volume spanning internal NVMe drives and NVMe drives in a Synology M.2 PCIe card. - Can **NOT** be scheduled to run at boot or shut down. | Feature | Synology_HDD_db | Synology_enable_M2_volume | Synology_M2_volume | |--------------------------|-----------------------------------------|-----------------------------------------|-----------------------------------| | DSM version | DSM 7.2 and later (7.1.1 for some NAS models) | DSM 7.2 and later (7.1.1 for some NAS models) | Any DSM version | | Non-Synology M.2 drives | Yes | Yes | Yes | | Ease of use | Easy | Easy | Medium | | Prompts for answers | No | No | Yes, multiple times | | Can be scheduled | Yes | Yes | No | Online Assemble required | No | No | DSM 7 Yes - DSM 6 No | | RAID levels supported | Basic, RAID 0, 1, 5, 6, 10, SHR, SHR-2, JBOD and RAID F1 (see Notes 1 and 2) | Basic, RAID 0, 1, SHR, JBOD and RAID F1 (see Note 1) | Basic, RAID 0, 1, 5, 6, 10, SHR, SHR-2, JBOD and RAID F1 (see Notes 1, 2 and 3) | | Add drive(s) to RAID | Yes, via Storage Manager | Yes, via Storage Manager | No | | Change RAID type | Yes, via Storage Manager | Yes, via Storage Manager | No | | RAID repair | Yes, via Storage Manager | Yes, via Storage Manager | No | | RAID expansion | Yes, via Storage Manager | Yes, via Storage Manager | No | | NVMe Health Info | Yes | Yes | No | | M.2 drive location | Internal M.2 and Synology M.2 PCie cards | Internal M.2 slots only | Internal M.2 and Synology M.2 PCie cards | | Span internal and PCIe NVMes | Yes | No | Yes | | What it does | Edits a few files in DSM | Edits 1 file in DSM | Creates partitons on M.2 drive(s) | ***Note 1:*** RAID F1 requires a Synology model that supports RAID F1. Or you can [enable RAID F1 on other models](https://github.com/007revad/Synology_SHR_switch). ***Note 2:*** RAID 5 requires 3 or more NVMe drives. RAID 6 and 10 require 4 or more NVMe drives. ***Note 3:*** Synology_M2_volume requires DSM 7 for SHR, SHR-2, JBOD and RAID F1. ***TRIM support:*** - DSM 7.2 and later has no SSD TRIM setting for M.2 RAID 0 storage pools. - DSM 7.1.1. has no SSD TRIM setting for M.2 storage pools. If you run this script then use Storage Manager to create your M.2 storage pool and volume and then run the script again with the --restore option to restore the original setting your storage pool and volume survive and the annoying notifications and warnings are gone. Your volume also survives reboots and DSM updates. ### Download the script 1. Download the latest version _Source code (zip)_ from https://github.com/007revad/Synology_enable_M2_volume/releases 2. Save the download zip file to a folder on the Synology. - Do ***NOT*** save the script to a M.2 volume. After a DSM or Storage Manager update the M.2 volume won't be available until after the script has run. 3. Unzip the zip file. ## How to run the script ### Running the script via SSH [How to enable SSH and login to DSM via SSH](https://kb.synology.com/en-global/DSM/tutorial/How_to_login_to_DSM_with_root_permission_via_SSH_Telnet) **Note:** Replace /volume1/scripts/ with the path to where the script is located. 1. Run the script then reboot the Synology: ```YAML sudo -s /volume1/scripts/syno_enable_m2_volume.sh ``` 2. Go to Storage Manager and create your M.2 storage pool and volume(s). **Options:** ```YAML -c, --check Check value in file and backup file -r, --restore Restore backup to undo changes -n, --noreboot Don't reboot after script has run -e, --email Disable colored text in output scheduler emails --autoupdate=AGE Auto update script (useful when script is scheduled) AGE is how many days old a release must be before auto-updating. AGE must be a number: 0 or greater -h, --help Show this help message -v, --version Show the script version ``` **Extra Steps:** To get rid of <a href="images/notification.png">drive database outdated</a> notifications and <a href=images/before_running_syno_hdd_db.png>unrecognised firmware</a> warnings run <a href=https://github.com/007revad/Synology_HDD_db>Synology_HDD_db</a> which will add your drives to DSM's compatibile drive databases, and prevent the drive compatability databases being updated between DSM updates. ```YAML sudo -s /path-to-script/syno_hdd_db.sh --noupdate ``` ### What about DSM updates? After any DSM update you will need to run this script, and the Synology_HDD_db script again. ### Schedule the script to run at shutdown Or you can schedule Synology_enable_M2_volume to run when the Synology shuts down and Synology_HDD_db to run when the Synology boots up, to avoid having to remember to run both scripts after a DSM update. See <a href=how_to_schedule.md/>How to schedule a script in Synology Task Scheduler</a> ## Screenshots Here's the result after running the script and rebooting. Note that the strorage pool is being created in Storage Manager and there's no Online Assembly needed. SHR and JBOD are also available. <p align="center">After reboot I got some notifications saying the M.2 drives can be managed</p> <p align="center"><img src="/images/1b-after-reboot.png"></p> <p align="center">No M2 Storage Pool or Volume yet</p> <p align="center"><img src="/images/2-no-m2-volume-yet.png"></p> <p align="center">Non-Synology M.2 drives</p> <p align="center"><img src="/images/3-non-synology-m2-drives-2.png"></p> <p align="center">Create Storage Pool 2</p> <p align="center"><img src="/images/4-create-storage-pool-3.png"></p> <p align="center">I wonder if RAID 5 and SHR-2 would be available if I had four M.2 drives.</p> <p align="center">RAID choices including SHR and JBOD</p> <p align="center"><img src="/images/5-raid-choices-2.png"></p> <p align="center">Select my non-Synology M.2 drives</p> <p align="center"><img src="/images/7-select-non-synology-drives-2.png"></p> <p align="center">We have an SHR M.2 storage pool</p> <p align="center"><img src="/images/10-we-have-a-m2.storage-pool-2.png"></p> <p align="center">Create Volume 2</p> <p align="center"><img src="/images/11-create-volume-3.png"></p> <p align="center">Finished Creating Volume 2</p> <p align="center"><img src="/images/13-finished-3.png"></p> **Credits** - K4LO from the XPenology forum. - prt1999 for pointing me to K4LO. - capull0 for replacing bc with xargs.
18,657
README
md
en
markdown
text
{"qsc_doc_frac_chars_curly_bracket": 0.0, "qsc_doc_frac_words_redpajama_stop": 0.16017415, "qsc_doc_num_sentences": 308.0, "qsc_doc_num_words": 2828, "qsc_doc_num_chars": 18657.0, "qsc_doc_num_lines": 263.0, "qsc_doc_mean_word_length": 4.04384724, "qsc_doc_frac_words_full_bracket": 0.0, "qsc_doc_frac_lines_end_with_readmore": 0.0, "qsc_doc_frac_lines_start_with_bullet": 0.0, "qsc_doc_frac_words_unique": 0.15452617, "qsc_doc_entropy_unigram": 5.0192587, "qsc_doc_frac_words_all_caps": 0.07424381, "qsc_doc_frac_lines_dupe_lines": 0.04694836, "qsc_doc_frac_chars_dupe_lines": 0.01703578, "qsc_doc_frac_chars_top_2grams": 0.02763204, "qsc_doc_frac_chars_top_3grams": 0.02710738, "qsc_doc_frac_chars_top_4grams": 0.06155999, "qsc_doc_frac_chars_dupe_5grams": 0.57240294, "qsc_doc_frac_chars_dupe_6grams": 0.53454005, "qsc_doc_frac_chars_dupe_7grams": 0.52701994, "qsc_doc_frac_chars_dupe_8grams": 0.47656523, "qsc_doc_frac_chars_dupe_9grams": 0.4418503, "qsc_doc_frac_chars_dupe_10grams": 0.37670514, "qsc_doc_frac_chars_replacement_symbols": 0.0, "qsc_doc_cate_code_related_file_name": 1.0, "qsc_doc_num_chars_sentence_length_mean": 31.61888112, "qsc_doc_frac_chars_hyperlink_html_tag": 0.18866913, "qsc_doc_frac_chars_alphabet": 0.72903594, "qsc_doc_frac_chars_digital": 0.08642327, "qsc_doc_frac_chars_whitespace": 0.24832503, "qsc_doc_frac_chars_hex_words": 0.0}
1
{"qsc_doc_frac_chars_replacement_symbols": 0, "qsc_doc_entropy_unigram": 0, "qsc_doc_frac_chars_top_2grams": 0, "qsc_doc_frac_chars_top_3grams": 0, "qsc_doc_frac_chars_top_4grams": 0, "qsc_doc_frac_chars_dupe_5grams": 0, "qsc_doc_frac_chars_dupe_6grams": 0, "qsc_doc_frac_chars_dupe_7grams": 0, "qsc_doc_frac_chars_dupe_8grams": 0, "qsc_doc_frac_chars_dupe_9grams": 0, "qsc_doc_frac_chars_dupe_10grams": 0, "qsc_doc_frac_chars_dupe_lines": 0, "qsc_doc_frac_lines_dupe_lines": 0, "qsc_doc_frac_lines_end_with_readmore": 0, "qsc_doc_frac_lines_start_with_bullet": 0, "qsc_doc_frac_words_all_caps": 0, "qsc_doc_mean_word_length": 0, "qsc_doc_num_chars": 0, "qsc_doc_num_lines": 0, "qsc_doc_num_sentences": 0, "qsc_doc_num_words": 0, "qsc_doc_frac_chars_hex_words": 0, "qsc_doc_frac_chars_hyperlink_html_tag": 0, "qsc_doc_frac_chars_alphabet": 0, "qsc_doc_frac_chars_digital": 0, "qsc_doc_frac_chars_whitespace": 0}
007revad/Synology_enable_M2_volume
how_to_schedule.md
# How to schedule a script in Synology Task Scheduler To schedule a script to run on your Synology at boot-up or shutdown follow these steps: **Note:** You can setup a schedule task and leave it disabled, so it only runs when you select the task in the Task Scheduler and click on the Run button. 1. Go to **Control Panel** > **Task Scheduler** > click **Create** > and select **Triggered Task**. 2. Select **User-defined script**. 3. Enter a task name. 4. Select **root** as the user (The script needs to run as root). 5. Select **Shutdown** as the event that triggers the task. 6. Leave **Enable** ticked. 7. Click **Task Settings**. 8. Optionally you can tick **Send run details by email** and **Send run details only when the script terminates abnormally** then enter your email address. 9. In the box under **User-defined script** type the path to the script. - e.g. If you saved the script to a shared folder on volume1 called "scripts" you'd type: **/volume1/scripts/syno_enable_m2_volume.sh** 11. Click **OK** to save the settings. Here's some screenshots showing what needs to be set: <p align="leftr"><img src="images/schedule1.png"></p> <p align="leftr"><img src="images/schedule2b.png"></p> <p align="leftr"><img src="images/schedule3.png"></p>
1,269
how_to_schedule
md
en
markdown
text
{"qsc_doc_frac_chars_curly_bracket": 0.0, "qsc_doc_frac_words_redpajama_stop": 0.24595469, "qsc_doc_num_sentences": 28.0, "qsc_doc_num_words": 218, "qsc_doc_num_chars": 1269.0, "qsc_doc_num_lines": 25.0, "qsc_doc_mean_word_length": 4.17431193, "qsc_doc_frac_words_full_bracket": 0.0, "qsc_doc_frac_lines_end_with_readmore": 0.0, "qsc_doc_frac_lines_start_with_bullet": 0.0, "qsc_doc_frac_words_unique": 0.51376147, "qsc_doc_entropy_unigram": 4.41735967, "qsc_doc_frac_words_all_caps": 0.00323625, "qsc_doc_frac_lines_dupe_lines": 0.0, "qsc_doc_frac_chars_dupe_lines": 0.0, "qsc_doc_frac_chars_top_2grams": 0.03956044, "qsc_doc_frac_chars_top_3grams": 0.03626374, "qsc_doc_frac_chars_top_4grams": 0.04615385, "qsc_doc_frac_chars_dupe_5grams": 0.08461538, "qsc_doc_frac_chars_dupe_6grams": 0.08461538, "qsc_doc_frac_chars_dupe_7grams": 0.05934066, "qsc_doc_frac_chars_dupe_8grams": 0.05934066, "qsc_doc_frac_chars_dupe_9grams": 0.0, "qsc_doc_frac_chars_dupe_10grams": 0.0, "qsc_doc_frac_chars_replacement_symbols": 0.0, "qsc_doc_cate_code_related_file_name": 0.0, "qsc_doc_num_chars_sentence_length_mean": 22.96226415, "qsc_doc_frac_chars_hyperlink_html_tag": 0.12608353, "qsc_doc_frac_chars_alphabet": 0.83928571, "qsc_doc_frac_chars_digital": 0.01597744, "qsc_doc_frac_chars_whitespace": 0.16154452, "qsc_doc_frac_chars_hex_words": 0.0}
1
{"qsc_doc_frac_chars_replacement_symbols": 0, "qsc_doc_entropy_unigram": 0, "qsc_doc_frac_chars_top_2grams": 0, "qsc_doc_frac_chars_top_3grams": 0, "qsc_doc_frac_chars_top_4grams": 0, "qsc_doc_frac_chars_dupe_5grams": 0, "qsc_doc_frac_chars_dupe_6grams": 0, "qsc_doc_frac_chars_dupe_7grams": 0, "qsc_doc_frac_chars_dupe_8grams": 0, "qsc_doc_frac_chars_dupe_9grams": 0, "qsc_doc_frac_chars_dupe_10grams": 0, "qsc_doc_frac_chars_dupe_lines": 0, "qsc_doc_frac_lines_dupe_lines": 0, "qsc_doc_frac_lines_end_with_readmore": 0, "qsc_doc_frac_lines_start_with_bullet": 0, "qsc_doc_frac_words_all_caps": 0, "qsc_doc_mean_word_length": 0, "qsc_doc_num_chars": 0, "qsc_doc_num_lines": 0, "qsc_doc_num_sentences": 0, "qsc_doc_num_words": 0, "qsc_doc_frac_chars_hex_words": 0, "qsc_doc_frac_chars_hyperlink_html_tag": 0, "qsc_doc_frac_chars_alphabet": 0, "qsc_doc_frac_chars_digital": 0, "qsc_doc_frac_chars_whitespace": 0}
007revad/Synology_enable_M2_volume
syno_enable_m2_volume.sh
#!/usr/bin/env bash #------------------------------------------------------------------------------ # Enables using non-Synology NVMe drives so you can create a storage pool # and volume on any M.2 drive(s) entirely in DSM Storage Manager. # # Github: https://github.com/007revad/Synology_enable_M2_volume # Script verified at https://www.shellcheck.net/ # Tested on DSM 7.2 and 7.2.1 # # To run in a shell (replace /volume1/scripts/ with path to script): # sudo /volume1/scripts/syno_enable_m2_volume.sh #------------------------------------------------------------------------------ scriptver="v1.1.22" script=Synology_enable_M2_volume repo="007revad/Synology_enable_M2_volume" scriptname=syno_enable_m2_volume # Check BASH variable is bash if [ ! "$(basename "$BASH")" = bash ]; then echo "This is a bash script. Do not run it with $(basename "$BASH")" printf \\a exit 1 fi # Check script is running on a Synology NAS if ! /usr/bin/uname -a | grep -i synology >/dev/null; then echo "This script is NOT running on a Synology NAS!" echo "Copy the script to a folder on the Synology" echo "and run it from there." exit 1 fi ding(){ printf \\a } usage(){ cat <<EOF $script $scriptver - by 007revad Usage: $(basename "$0") [options] Options: -c, --check Check value in file and backup file -r, --restore Restore backup to undo changes -n, --noreboot Don't reboot after script has run -e, --email Disable colored text in output scheduler emails --autoupdate=AGE Auto update script (useful when script is scheduled) AGE is how many days old a release must be before auto-updating. AGE must be a number: 0 or greater -h, --help Show this help message -v, --version Show the script version EOF exit 0 } scriptversion(){ cat <<EOF $script $scriptver - by 007revad See https://github.com/$repo EOF exit 0 } # Save options used args=("$@") # Check for flags with getopt if options="$(getopt -o abcdefghijklmnopqrstuvwxyz0123456789 -l \ check,restore,noreboot,email,autoupdate:,help,version,log,debug -- "$@")"; then eval set -- "$options" while true; do case "${1,,}" in -c|--check) # Check value in file and backup file check=yes ;; -r|--restore) # Restore backup to undo changes restore=yes ;; -e|--email) # Disable colour text in task scheduler emails color=no ;; -n|--noreboot) # Don't reboot after script has run noreboot=yes ;; --autoupdate) # Auto update script autoupdate=yes if [[ $2 =~ ^[0-9]+$ ]]; then delay="$2" shift else delay="0" fi ;; -h|--help) # Show usage options usage ;; -v|--version) # Show script version scriptversion ;; -l|--log) # Log #log=yes ;; -d|--debug) # Show and log debug info debug=yes ;; --) shift break ;; *) # Show usage options echo -e "Invalid option '$1'\n" usage "$1" ;; esac shift done else echo usage fi if [[ $debug == "yes" ]]; then set -x export PS4='`[[ $? == 0 ]] || echo "\e[1;31;40m($?)\e[m\n "`:.$LINENO:' fi # Shell Colors if [[ $color != "no" ]]; then #Black='\e[0;30m' # ${Black} Red='\e[0;31m' # ${Red} #Green='\e[0;32m' # ${Green} Yellow='\e[0;33m' # ${Yellow} #Blue='\e[0;34m' # ${Blue} #Purple='\e[0;35m' # ${Purple} Cyan='\e[0;36m' # ${Cyan} #White='\e[0;37m' # ${White} Error='\e[41m' # ${Error} Off='\e[0m' # ${Off} else echo "" # For task scheduler email readability fi # Check script is running as root if [[ $( whoami ) != "root" ]]; then ding echo -e "${Error}ERROR${Off} This script must be run as sudo or root!" exit 1 fi # Get DSM major version dsm=$(/usr/syno/bin/synogetkeyvalue /etc.defaults/VERSION majorversion) if [[ $dsm -lt "7" ]]; then ding echo "This script only works for DSM 7." exit 1 fi # Show script version #echo -e "$script $scriptver\ngithub.com/$repo\n" echo "$script $scriptver" # Get NAS model model=$(cat /proc/sys/kernel/syno_hw_version) # Get DSM full version productversion=$(/usr/syno/bin/synogetkeyvalue /etc.defaults/VERSION productversion) buildphase=$(/usr/syno/bin/synogetkeyvalue /etc.defaults/VERSION buildphase) buildnumber=$(/usr/syno/bin/synogetkeyvalue /etc.defaults/VERSION buildnumber) smallfixnumber=$(/usr/syno/bin/synogetkeyvalue /etc.defaults/VERSION smallfixnumber) # Show DSM full version and model if [[ $buildphase == GM ]]; then buildphase=""; fi if [[ $smallfixnumber -gt "0" ]]; then smallfix="-$smallfixnumber"; fi echo -e "$model DSM $productversion-$buildnumber$smallfix $buildphase\n" # Get StorageManager version storagemgrver=$(/usr/syno/bin/synopkg version StorageManager) # Show StorageManager version if [[ $storagemgrver ]]; then echo -e "StorageManager $storagemgrver\n"; fi # Show options used echo "Using options: ${args[*]}" #------------------------------------------------------------------------------ # Check latest release with GitHub API syslog_set(){ if [[ ${1,,} == "info" ]] || [[ ${1,,} == "warn" ]] || [[ ${1,,} == "err" ]]; then if [[ $autoupdate == "yes" ]]; then # Add entry to Synology system log /usr/syno/bin/synologset1 sys "$1" 0x11100000 "$2" fi fi } # Get latest release info # Curl timeout options: # https://unix.stackexchange.com/questions/94604/does-curl-have-a-timeout release=$(curl --silent -m 10 --connect-timeout 5 \ "https://api.github.com/repos/$repo/releases/latest") # Release version tag=$(echo "$release" | grep '"tag_name":' | sed -E 's/.*"([^"]+)".*/\1/') shorttag="${tag:1}" # Release published date published=$(echo "$release" | grep '"published_at":' | sed -E 's/.*"([^"]+)".*/\1/') published="${published:0:10}" published=$(date -d "$published" '+%s') # Today's date now=$(date '+%s') # Days since release published age=$(((now - published)/(60*60*24))) # Get script location # https://stackoverflow.com/questions/59895/ source=${BASH_SOURCE[0]} while [ -L "$source" ]; do # Resolve $source until the file is no longer a symlink scriptpath=$( cd -P "$( dirname "$source" )" >/dev/null 2>&1 && pwd ) source=$(readlink "$source") # If $source was a relative symlink, we need to resolve it # relative to the path where the symlink file was located [[ $source != /* ]] && source=$scriptpath/$source done scriptpath=$( cd -P "$( dirname "$source" )" >/dev/null 2>&1 && pwd ) scriptfile=$( basename -- "$source" ) echo "Running from: ${scriptpath}/$scriptfile" # Warn if script located on M.2 drive scriptvol=$(echo "$scriptpath" | cut -d"/" -f2) vg=$(lvdisplay | grep /volume_"${scriptvol#volume}" | cut -d"/" -f3) md=$(pvdisplay | grep -B 1 -E '[ ]'"$vg" | grep /dev/ | cut -d"/" -f3) if cat /proc/mdstat | grep "$md" | grep nvme >/dev/null; then echo -e "${Yellow}WARNING${Off} Don't store this script on an NVMe volume!" fi cleanup_tmp(){ cleanup_err= # Delete downloaded .tar.gz file if [[ -f "/tmp/$script-$shorttag.tar.gz" ]]; then if ! rm "/tmp/$script-$shorttag.tar.gz"; then echo -e "${Error}ERROR${Off} Failed to delete"\ "downloaded /tmp/$script-$shorttag.tar.gz!" >&2 cleanup_err=1 fi fi # Delete extracted tmp files if [[ -d "/tmp/$script-$shorttag" ]]; then if ! rm -r "/tmp/$script-$shorttag"; then echo -e "${Error}ERROR${Off} Failed to delete"\ "downloaded /tmp/$script-$shorttag!" >&2 cleanup_err=1 fi fi # Add warning to DSM log if [[ $cleanup_err ]]; then syslog_set warn "$script update failed to delete tmp files" fi } if ! printf "%s\n%s\n" "$tag" "$scriptver" | sort --check=quiet --version-sort >/dev/null ; then echo -e "\n${Cyan}There is a newer version of this script available.${Off}" echo -e "Current version: ${scriptver}\nLatest version: $tag" scriptdl="$scriptpath/$script-$shorttag" if [[ -f ${scriptdl}.tar.gz ]] || [[ -f ${scriptdl}.zip ]]; then # They have the latest version tar.gz downloaded but are using older version echo "You have the latest version downloaded but are using an older version" sleep 10 elif [[ -d $scriptdl ]]; then # They have the latest version extracted but are using older version echo "You have the latest version extracted but are using an older version" sleep 10 else if [[ $autoupdate == "yes" ]]; then if [[ $age -gt "$delay" ]] || [[ $age -eq "$delay" ]]; then echo "Downloading $tag" reply=y else echo "Skipping as $tag is less than $delay days old." fi else echo -e "${Cyan}Do you want to download $tag now?${Off} [y/n]" read -r -t 30 reply fi if [[ ${reply,,} == "y" ]]; then # Delete previously downloaded .tar.gz file and extracted tmp files cleanup_tmp if cd /tmp; then url="https://github.com/$repo/archive/refs/tags/$tag.tar.gz" if ! curl -JLO -m 30 --connect-timeout 5 "$url"; then echo -e "${Error}ERROR${Off} Failed to download"\ "$script-$shorttag.tar.gz!" syslog_set warn "$script $tag failed to download" else if [[ -f /tmp/$script-$shorttag.tar.gz ]]; then # Extract tar file to /tmp/<script-name> if ! tar -xf "/tmp/$script-$shorttag.tar.gz" -C "/tmp"; then echo -e "${Error}ERROR${Off} Failed to"\ "extract $script-$shorttag.tar.gz!" syslog_set warn "$script failed to extract $script-$shorttag.tar.gz!" else # Set script sh files as executable if ! chmod a+x "/tmp/$script-$shorttag/"*.sh ; then permerr=1 echo -e "${Error}ERROR${Off} Failed to set executable permissions" syslog_set warn "$script failed to set permissions on $tag" fi # Copy new script sh file to script location if ! cp -p "/tmp/$script-$shorttag/${scriptname}.sh" "${scriptpath}/${scriptfile}"; then copyerr=1 echo -e "${Error}ERROR${Off} Failed to copy"\ "$script-$shorttag sh file(s) to:\n $scriptpath/${scriptfile}" syslog_set warn "$script failed to copy $tag to script location" fi # Copy new CHANGES.txt file to script location (if script on a volume) if [[ $scriptpath =~ /volume* ]]; then # Set permissions on CHANGES.txt if ! chmod 664 "/tmp/$script-$shorttag/CHANGES.txt"; then permerr=1 echo -e "${Error}ERROR${Off} Failed to set permissions on:" echo "$scriptpath/CHANGES.txt" fi # Copy new CHANGES.txt file to script location if ! cp -p "/tmp/$script-$shorttag/CHANGES.txt"\ "${scriptpath}/${scriptname}_CHANGES.txt"; then if [[ $autoupdate != "yes" ]]; then copyerr=1; fi echo -e "${Error}ERROR${Off} Failed to copy"\ "$script-$shorttag/CHANGES.txt to:\n $scriptpath" else changestxt=" and changes.txt" fi fi # Delete downloaded tmp files cleanup_tmp # Notify of success (if there were no errors) if [[ $copyerr != 1 ]] && [[ $permerr != 1 ]]; then echo -e "\n$tag ${scriptfile}$changestxt downloaded to: ${scriptpath}\n" syslog_set info "$script successfully updated to $tag" # Reload script printf -- '-%.0s' {1..79}; echo # print 79 - exec "${scriptpath}/$scriptfile" "${args[@]}" else syslog_set warn "$script update to $tag had errors" fi fi else echo -e "${Error}ERROR${Off}"\ "/tmp/$script-$shorttag.tar.gz not found!" #ls /tmp | grep "$script" # debug syslog_set warn "/tmp/$script-$shorttag.tar.gz not found" fi fi cd "$scriptpath" || echo -e "${Error}ERROR${Off} Failed to cd to script location!" else echo -e "${Error}ERROR${Off} Failed to cd to /tmp!" syslog_set warn "$script update failed to cd to /tmp" fi fi fi fi rebootmsg(){ # Reboot prompt echo -e "\n${Cyan}The Synology needs to restart.${Off}" echo -e "Type ${Cyan}yes${Off} to reboot now." echo -e "Type anything else to quit (if you will restart it yourself)." read -r -t 10 answer if [[ ${answer,,} != "yes" ]]; then exit; fi # # Reboot in the background so user can see DSM's "going down" message # reboot & if [[ -x /usr/syno/sbin/synopoweroff ]]; then /usr/syno/sbin/synopoweroff -r || reboot else reboot fi } #---------------------------------------------------------- # Check file exists file="/usr/lib/libhwcontrol.so.1" if [[ ! -f ${file} ]]; then ding echo -e "${Error}ERROR${Off} File not found!" exit 1 fi #---------------------------------------------------------- # Restore from backup file if [[ $restore == "yes" ]]; then if [[ -f ${file}.bak ]]; then # Check if backup size matches file size filesize=$(wc -c "${file}" | awk '{print $1}') filebaksize=$(wc -c "${file}.bak" | awk '{print $1}') if [[ ! $filesize -eq "$filebaksize" ]]; then echo -e "${Yellow}WARNING Backup file size is different to file!${Off}" echo "Do you want to restore this backup? [yes/no]:" read -r answer if [[ $answer != "yes" ]]; then exit fi fi # Restore from backup if cp "$file".bak "$file" ; then echo "Successfully restored from backup." rebootmsg exit else ding echo -e "${Error}ERROR${Off} Backup failed!" exit 1 fi else ding echo -e "${Error}ERROR${Off} Backup file not found!" exit 1 fi fi #---------------------------------------------------------- # Backup file if [[ ! -f ${file}.bak ]]; then if cp "$file" "$file".bak ; then echo "Backup successful." else ding echo -e "${Error}ERROR${Off} Backup failed!" exit 1 fi else # Check if backup size matches file size filesize=$(wc -c "${file}" | awk '{print $1}') filebaksize=$(wc -c "${file}.bak" | awk '{print $1}') if [[ ! $filesize -eq "$filebaksize" ]]; then echo -e "${Yellow}WARNING Backup file size is different to file!${Off}" echo "Maybe you've updated DSM since last running this script?" echo "Renaming file.bak to file.bak.old" mv "${file}.bak" "$file".bak.old if cp "$file" "$file".bak ; then echo "Backup successful." else ding echo -e "${Error}ERROR${Off} Backup failed!" exit 1 fi else echo "File already backed up." fi fi #---------------------------------------------------------- # Edit file findbytes(){ # Get decimal position of matching hex string match=$(od -v -t x1 "$1" | sed 's/[^ ]* *//' | tr '\012' ' ' | grep -b -i -o "$hexstring" | cut -d ':' -f 1 | xargs -I % expr % / 3) # Convert decimal position of matching hex string to hex array=("$match") if [[ ${#array[@]} -gt "1" ]]; then num="0" while [[ $num -lt "${#array[@]}" ]]; do poshex=$(printf "%x" "${array[$num]}") echo "${array[$num]} = $poshex" # debug seek="${array[$num]}" xxd=$(xxd -u -l 12 -s "$seek" "$1") #echo "$xxd" # debug printf %s "$xxd" | cut -d" " -f1-7 bytes=$(printf %s "$xxd" | cut -d" " -f6) #echo "$bytes" # debug num=$((num +1)) done elif [[ -n $match ]]; then poshex=$(printf "%x" "$match") echo "$match = $poshex" # debug seek="$match" xxd=$(xxd -u -l 12 -s "$seek" "$1") #echo "$xxd" # debug printf %s "$xxd" | cut -d" " -f1-7 bytes=$(printf %s "$xxd" | cut -d" " -f6) #echo "$bytes" # debug else bytes="" fi } # Check value in file and backup file if [[ $check == "yes" ]]; then err=0 # Check value in file echo -e "\nChecking value in file." hexstring="80 3E 00 B8 01 00 00 00 90 90 48 8B" findbytes "$file" if [[ $bytes == "9090" ]]; then echo -e "\n${Cyan}File already edited.${Off}" else hexstring="80 3E 00 B8 01 00 00 00 75 2. 48 8B" findbytes "$file" if [[ $bytes =~ "752"[0-9] ]]; then echo -e "\n${Cyan}File is unedited.${Off}" else echo -e "\n${Red}hex string not found!${Off}" err=1 fi fi # Check value in backup file if [[ -f ${file}.bak ]]; then echo -e "\nChecking value in backup file." hexstring="80 3E 00 B8 01 00 00 00 75 2. 48 8B" findbytes "${file}.bak" if [[ $bytes =~ "752"[0-9] ]]; then echo -e "\n${Cyan}Backup file is unedited.${Off}" else hexstring="80 3E 00 B8 01 00 00 00 90 90 48 8B" findbytes "${file}.bak" if [[ $bytes == "9090" ]]; then echo -e "\n${Red}Backup file has been edited!${Off}" else echo -e "\n${Red}hex string not found!${Off}" err=1 fi fi else echo "No backup file found." fi exit "$err" fi echo -e "\nChecking file." # Check if the file is already edited hexstring="80 3E 00 B8 01 00 00 00 90 90 48 8B" findbytes "$file" if [[ $bytes == "9090" ]]; then echo -e "\n${Cyan}File already edited.${Off}" exit else # Check if the file is okay for editing hexstring="80 3E 00 B8 01 00 00 00 75 2. 48 8B" findbytes "$file" if [[ $bytes =~ "752"[0-9] ]]; then echo -e "\nEditing file." else ding echo -e "\n${Red}hex string not found!${Off}" exit 1 fi fi # Replace bytes in file posrep=$(printf "%x\n" $((0x${poshex}+8))) if ! printf %s "${posrep}: 9090" | xxd -r - "$file"; then ding echo -e "${Error}ERROR${Off} Failed to edit file!" exit 1 fi #---------------------------------------------------------- # Check if file was successfully edited echo -e "\nChecking if file was successfully edited." hexstring="80 3E 00 B8 01 00 00 00 90 90 48 8B" findbytes "$file" if [[ $bytes == "9090" ]]; then echo -e "File successfully edited." echo -e "\n${Cyan}You can now create your M.2 storage"\ "pool in Storage Manager.${Off}" edited=yes else ding echo -e "${Error}ERROR${Off} Failed to edit file!" exit 1 fi #-------------------------------------------------------------------- # Enable m2 volume support - DSM 7.1 and later only # Backup synoinfo.conf if needed #if [[ $dsm72 == "yes" ]]; then #if [[ $dsm71 == "yes" ]]; then synoinfo="/etc.defaults/synoinfo.conf" if [[ ! -f ${synoinfo}.bak ]]; then if cp "$synoinfo" "$synoinfo.bak"; then echo -e "\nBacked up $(basename -- "$synoinfo")" >&2 else ding echo -e "\n${Error}ERROR 5${Off} Failed to backup $(basename -- "$synoinfo")!" exit 1 fi fi #fi # Check if m2 volume support is enabled #if [[ $dsm72 == "yes" ]]; then #if [[ $dsm71 == "yes" ]]; then smp=support_m2_pool setting="$(/usr/syno/bin/synogetkeyvalue "$synoinfo" "$smp")" enabled="" if [[ ! $setting ]]; then # Add support_m2_pool="yes" echo 'support_m2_pool="yes"' >> "$synoinfo" enabled="yes" elif [[ $setting == "no" ]]; then # Change support_m2_pool="no" to "yes" #sed -i "s/${smp}=\"no\"/${smp}=\"yes\"/" "$synoinfo" /usr/syno/bin/synosetkeyvalue "$synoinfo" "$smp" "yes" enabled="yes" elif [[ $setting == "yes" ]]; then echo -e "\nM.2 volume support already enabled." fi # Check if we enabled m2 volume support setting="$(/usr/syno/bin/synogetkeyvalue "$synoinfo" "$smp")" if [[ $enabled == "yes" ]]; then if [[ $setting == "yes" ]]; then echo -e "\nEnabled M.2 volume support." else echo -e "\n${Error}ERROR${Off} Failed to enable m2 volume support!" fi fi #fi # Enable creating M.2 storage pool and volume in Storage Manager # for currently installed NVMe drives for nvme in /run/synostorage/disks/nvme*; do if [[ -f "${nvme}/m2_pool_support" ]]; then echo -n 1 > "${nvme}/m2_pool_support" fi done #---------------------------------------------------------- # Reboot # Only show reboot message if $noreboot not set and we patched file if [[ $noreboot != "yes" ]] && [[ $edited == "yes" ]]; then rebootmsg fi exit
23,006
syno_enable_m2_volume
sh
en
shell
code
{"qsc_code_num_words": 2767, "qsc_code_num_chars": 23006.0, "qsc_code_mean_word_length": 4.15468016, "qsc_code_frac_words_unique": 0.17238887, "qsc_code_frac_chars_top_2grams": 0.02348643, "qsc_code_frac_chars_top_3grams": 0.0164405, "qsc_code_frac_chars_top_4grams": 0.02479123, "qsc_code_frac_chars_dupe_5grams": 0.38152401, "qsc_code_frac_chars_dupe_6grams": 0.32759221, "qsc_code_frac_chars_dupe_7grams": 0.29784273, "qsc_code_frac_chars_dupe_8grams": 0.2348643, "qsc_code_frac_chars_dupe_9grams": 0.19841684, "qsc_code_frac_chars_dupe_10grams": 0.17832289, "qsc_code_frac_chars_replacement_symbols": 0.0, "qsc_code_frac_chars_digital": 0.02734451, "qsc_code_frac_chars_whitespace": 0.33395636, "qsc_code_size_file_byte": 23006.0, "qsc_code_num_lines": 705.0, "qsc_code_num_chars_line_max": 112.0, "qsc_code_num_chars_line_mean": 32.63262411, "qsc_code_frac_chars_alphabet": 0.72290022, "qsc_code_frac_chars_comments": 0.20194732, "qsc_code_cate_xml_start": 0.0, "qsc_code_frac_lines_dupe_lines": 0.46481876, "qsc_code_cate_autogen": 0.0, "qsc_code_frac_lines_long_string": 0.01066098, "qsc_code_frac_chars_string_length": 0.297075, "qsc_code_frac_chars_long_word_length": 0.05506836, "qsc_code_frac_lines_string_concat": 0.0, "qsc_code_cate_encoded_data": 0.0, "qsc_code_frac_chars_hex_words": 0.00054469, "qsc_code_frac_lines_prompt_comments": 0.0, "qsc_code_frac_lines_assert": 0.0}
1
{"qsc_code_frac_chars_replacement_symbols": 0, "qsc_code_num_words": 0, "qsc_code_num_chars": 0, "qsc_code_mean_word_length": 0, "qsc_code_frac_chars_top_2grams": 0, "qsc_code_frac_chars_top_3grams": 0, "qsc_code_frac_chars_top_4grams": 0, "qsc_code_frac_chars_dupe_5grams": 0, "qsc_code_frac_chars_dupe_6grams": 0, "qsc_code_frac_chars_dupe_7grams": 0, "qsc_code_frac_chars_dupe_8grams": 0, "qsc_code_frac_chars_dupe_9grams": 0, "qsc_code_frac_chars_dupe_10grams": 0, "qsc_code_frac_lines_dupe_lines": 0, "qsc_code_size_file_byte": 0, "qsc_code_num_lines": 0, "qsc_code_num_chars_line_max": 0, "qsc_code_num_chars_line_mean": 0, "qsc_code_frac_chars_alphabet": 0, "qsc_code_frac_chars_digital": 0, "qsc_code_frac_chars_whitespace": 0, "qsc_code_frac_chars_comments": 0, "qsc_code_cate_xml_start": 0, "qsc_code_cate_autogen": 0, "qsc_code_frac_chars_long_word_length": 0, "qsc_code_cate_encoded_data": 0, "qsc_code_frac_chars_hex_words": 0, "qsc_code_frac_lines_prompt_comments": 0}
007revad/Synology_M2_volume
syno_create_m2_volume.sh
#!/usr/bin/env bash #----------------------------------------------------------------------------------- # Create volume on M.2 drive(s) on Synology models that don't have a GUI option # # Github: https://github.com/007revad/Synology_M2_volume # Script verified at https://www.shellcheck.net/ # Tested on DSM 7.2 and 7.2.1 # # To run in a shell (replace /volume1/scripts/ with path to script): # sudo /volume1/scripts/create_m2_volume.sh # # Resources: # https://academy.pointtosource.com/synology/synology-ds920-nvme-m2-ssd-volume/amp/ # https://www.reddit.com/r/synology/comments/pwrch3/how_to_create_a_usable_poolvolume_to_use_as/ # # Over-Provisioning unnecessary on modern SSDs (since ~2014) # https://easylinuxtipsproject.blogspot.com/p/ssd.html#ID16.2 # # Use synostgpool instead of synopartition, mdadm and lvm # https://www.reddit.com/r/synology/comments/17vn96n/how_to_trigger_the_online_assemble_prompt_without/ #----------------------------------------------------------------------------------- # TODO # Better detection if DSM is using the drive. # Maybe add logging. # Add option to repair damaged array? DSM can probably handle this. # DONE # v2 and later are for DSM 7 only. # For DSM 6 use v1 without the auto update option. # Now shows "M.2 Drive #" the same as storage manager. # Now uses synostgpool command which allows the following: (Thanks to Severe_Pea_2128 on reddit) # Now supports JBOD, SHR, SHR2 and RAID F1. # Added choice of multi-volume or single-volume storage pool. Multi-volume allows overprovisioning. # Added option to skip drive check. # No longer need to reboot after running the script. # No longer need to do an online assemble. # Enables RAID F1 if not enabled and RAID F1 selected. # Removed drive check progress as it was not possible with synostgpool. # Removed dry run mode as it was not possible with synostgpool. # Removed support for SATA M.2 drives. # m2list_assoc contains associative array of [M.2 Drive #]=nvme#n# # m2list array contains list of "M.2 Drive #" # mdisk array contains list of selected nvme#n# scriptver="v2.1.31" script=Synology_M2_volume repo="007revad/Synology_M2_volume" scriptname=syno_create_m2_volume # Check BASH variable is bash if [ ! "$(basename "$BASH")" = bash ]; then echo "This is a bash script. Do not run it with $(basename "$BASH")" printf \\a exit 1 fi # Check script is running on a Synology NAS if ! /usr/bin/uname -a | grep -i synology >/dev/null; then echo "This script is NOT running on a Synology NAS!" echo "Copy the script to a folder on the Synology" echo "and run it from there." exit 1 fi # Shell Colors #Black='\e[0;30m' # ${Black} Red='\e[0;31m' # ${Red} #Green='\e[0;32m' # ${Green} Yellow='\e[0;33m' # ${Yellow} #Blue='\e[0;34m' # ${Blue} #Purple='\e[0;35m' # ${Purple} Cyan='\e[0;36m' # ${Cyan} #White='\e[0;37m' # ${White} Error='\e[41m' # ${Error} Off='\e[0m' # ${Off} ding(){ printf \\a } usage(){ cat <<EOF $script $scriptver - by 007revad Usage: $(basename "$0") [options] Options: -a, --all List all M.2 drives even if detected as active -s, --steps Show the steps to do after running this script -h, --help Show this help message -v, --version Show the script version EOF exit 0 } scriptversion(){ cat <<EOF $script $scriptver - by 007revad See https://github.com/$repo EOF exit 0 } declare -A m2list_assoc=( ) selectdisk(){ if [[ ${#m2list[@]} -gt "0" ]]; then # Only show Done choice when required number of drives selected if [[ $single != "yes" ]] && [[ "${#mdisk[@]}" -ge "$mindisk" ]]; then showDone=" Done" else showDone="" fi select nvmes in "${m2list[@]}"$showDone; do case "$nvmes" in Done) Done="yes" selected_disk="" break ;; Quit) exit ;; nvme*) # if [[ " ${m2list[*]} " =~ " ${nvmes} " ]]; then selected_disk="$nvmes" break # else # echo -e "${Red}Invalid answer!${Off} Try again." >&2 # selected_disk="" # fi ;; "M.2 Drive "*) selected_disk="$nvmes" break ;; *) echo -e "${Red}Invalid answer!${Off} Try again." >&2 #echo -e "There is no menu item $?)" >&2 selected_disk="" ;; esac done if [[ $Done != "yes" ]] && [[ $selected_disk ]]; then #mdisk+=("$selected_disk") mdisk+=("${m2list_assoc["$selected_disk"]}") # Remove selected drive from list of selectable drives remelement "$selected_disk" # Keep track of many drives user selected selected="$((selected +1))" echo -e "You selected ${Cyan}$selected_disk${Off}" >&2 #echo "Drives selected: $selected" >&2 # debug fi echo else Done="yes" fi } showsteps(){ major=$(/usr/syno/bin/synogetkeyvalue /etc.defaults/VERSION major) if [[ $major -gt "6" ]]; then if [[ $pooltype == "single" ]]; then echo -e "\n${Cyan}When storage manager has finished checking the drive(s):${Off}" else echo -e "\n${Cyan}When storage manager has finished creating the storage pool:${Off}" fi cat <<EOF 1. Create the volume as you normally would: Select the new Storage Pool > Create > Create Volume 2. Optionally enable TRIM: Storage Pool > ... > Settings > SSD TRIM EOF echo -e "\n${Error}Important${Off}" >&2 cat <<EOF If you later upgrade DSM and your M.2 drives are shown as unsupported and the storage pool is shown as missing, and online assemble fails, you should run the Synology HDD db script: EOF echo -e "${Cyan}https://github.com/007revad/Synology_HDD_db${Off}\n" >&2 fi #return } # Save options used args=("$@") # Check for flags with getopt # shellcheck disable=SC2034 if options="$(getopt -o abcdefghijklmnopqrstuvwxyz0123456789 -a \ -l all,steps,help,version,log,debug -- "$@")"; then eval set -- "$options" while true; do case "${1,,}" in -a|--all) # List all M.2 drives even if detected as active all=yes ;; -s|--steps) # Show steps remaining after running script showsteps exit ;; -h|--help) # Show usage options usage ;; -v|--version) # Show script version scriptversion ;; -l|--log) # Log log=yes ;; -d|--debug) # Show and log debug info debug=yes ;; --) shift break ;; *) # Show usage options echo -e "Invalid option '$1'\n" usage "$1" ;; esac shift done else echo usage fi if [[ $debug == "yes" ]]; then set -x export PS4='`[[ $? == 0 ]] || echo "\e[1;31;40m($?)\e[m\n "`:.$LINENO:' fi # Check script is running as root if [[ $( whoami ) != "root" ]]; then ding echo -e "${Error}ERROR${Off} This script must be run as sudo or root!" exit 1 fi # Show script version #echo -e "$script $scriptver\ngithub.com/$repo\n" echo "$script $scriptver" # Get DSM major and minor versions dsm=$(/usr/syno/bin/synogetkeyvalue /etc.defaults/VERSION majorversion) dsminor=$(/usr/syno/bin/synogetkeyvalue /etc.defaults/VERSION minorversion) # shellcheck disable=SC2034 if [[ $dsm -gt "6" ]] && [[ $dsminor -gt "1" ]]; then dsm72="yes" fi if [[ $dsm -gt "6" ]] && [[ $dsminor -gt "0" ]]; then dsm71="yes" fi # Get NAS model model=$(cat /proc/sys/kernel/syno_hw_version) hwrevision=$(cat /proc/sys/kernel/syno_hw_revision) if [[ $hwrevision =~ r[0-9] ]]; then showhwrev=" $hwrevision"; fi # Get DSM full version productversion=$(/usr/syno/bin/synogetkeyvalue /etc.defaults/VERSION productversion) buildphase=$(/usr/syno/bin/synogetkeyvalue /etc.defaults/VERSION buildphase) buildnumber=$(/usr/syno/bin/synogetkeyvalue /etc.defaults/VERSION buildnumber) smallfixnumber=$(/usr/syno/bin/synogetkeyvalue /etc.defaults/VERSION smallfixnumber) # Show DSM full version and model if [[ $buildphase == GM ]]; then buildphase=""; fi if [[ $smallfixnumber -gt "0" ]]; then smallfix="-$smallfixnumber"; fi echo -e "${model}$showhwrev DSM $productversion-$buildnumber$smallfix $buildphase\n" # Get StorageManager version storagemgrver=$(/usr/syno/bin/synopkg version StorageManager) # Show StorageManager version if [[ $storagemgrver ]]; then echo -e "StorageManager $storagemgrver\n"; fi # Show options used echo -e "Using options: ${args[*]}\n" #------------------------------------------------------------------------------ # Check latest release with GitHub API # Get latest release info # Curl timeout options: # https://unix.stackexchange.com/questions/94604/does-curl-have-a-timeout release=$(curl --silent -m 10 --connect-timeout 5 \ "https://api.github.com/repos/$repo/releases/latest") # Release version tag=$(echo "$release" | grep '"tag_name":' | sed -E 's/.*"([^"]+)".*/\1/') shorttag="${tag:1}" # Get script location # https://stackoverflow.com/questions/59895/ source=${BASH_SOURCE[0]} while [ -L "$source" ]; do # Resolve $source until the file is no longer a symlink scriptpath=$( cd -P "$( dirname "$source" )" >/dev/null 2>&1 && pwd ) source=$(readlink "$source") # If $source was a relative symlink, we need to resolve it # relative to the path where the symlink file was located [[ $source != /* ]] && source=$scriptpath/$source done scriptpath=$( cd -P "$( dirname "$source" )" >/dev/null 2>&1 && pwd ) scriptfile=$( basename -- "$source" ) echo -e "Running from: ${scriptpath}/$scriptfile\n" #echo "Script location: $scriptpath" # debug #echo "Source: $source" # debug #echo "Script filename: $scriptfile" # debug #echo "tag: $tag" # debug #echo "scriptver: $scriptver" # debug # Warn if script located on M.2 drive scriptvol=$(echo "$scriptpath" | cut -d"/" -f2) vg=$(lvdisplay | grep /volume_"${scriptvol#volume}" | cut -d"/" -f3) md=$(pvdisplay | grep -B 1 -E '[ ]'"$vg" | grep /dev/ | cut -d"/" -f3) if cat /proc/mdstat | grep "$md" | grep nvme >/dev/null; then echo -e "${Yellow}WARNING${Off} Don't store this script on an NVMe volume!" fi cleanup_tmp(){ # Delete downloaded .tar.gz file if [[ -f "/tmp/$script-$shorttag.tar.gz" ]]; then if ! rm "/tmp/$script-$shorttag.tar.gz"; then echo -e "${Error}ERROR${Off} Failed to delete"\ "downloaded /tmp/$script-$shorttag.tar.gz!" >&2 fi fi # Delete extracted tmp files if [[ -d "/tmp/$script-$shorttag" ]]; then if ! rm -r "/tmp/$script-$shorttag"; then echo -e "${Error}ERROR${Off} Failed to delete"\ "downloaded /tmp/$script-$shorttag!" >&2 fi fi } if ! printf "%s\n%s\n" "$tag" "$scriptver" | sort --check=quiet --version-sort >/dev/null ; then echo -e "\n${Cyan}There is a newer version of this script available.${Off}" echo -e "Current version: ${scriptver}\nLatest version: $tag" scriptdl="$scriptpath/$script-$shorttag" if [[ -f ${scriptdl}.tar.gz ]] || [[ -f ${scriptdl}.zip ]]; then # They have the latest version tar.gz downloaded but are using older version echo "You have the latest version downloaded but are using an older version" sleep 10 elif [[ -d $scriptdl ]]; then # They have the latest version extracted but are using older version echo "You have the latest version extracted but are using an older version" sleep 10 else echo -e "${Cyan}Do you want to download $tag now?${Off} [y/n]" read -r -t 30 reply if [[ ${reply,,} == "y" ]]; then # Delete previously downloaded .tar.gz file and extracted tmp files cleanup_tmp if cd /tmp; then url="https://github.com/$repo/archive/refs/tags/$tag.tar.gz" if ! curl -JLO -m 30 --connect-timeout 5 "$url"; then echo -e "${Error}ERROR${Off} Failed to download"\ "$script-$shorttag.tar.gz!" else if [[ -f /tmp/$script-$shorttag.tar.gz ]]; then # Extract tar file to /tmp/<script-name> if ! tar -xf "/tmp/$script-$shorttag.tar.gz" -C "/tmp"; then echo -e "${Error}ERROR${Off} Failed to"\ "extract $script-$shorttag.tar.gz!" else # Set script sh files as executable if ! chmod a+x "/tmp/$script-$shorttag/"*.sh ; then permerr=1 echo -e "${Error}ERROR${Off} Failed to set executable permissions" fi # Copy new script sh file to script location if ! cp -p "/tmp/$script-$shorttag/${scriptname}.sh" "${scriptpath}/${scriptfile}"; then copyerr=1 echo -e "${Error}ERROR${Off} Failed to copy"\ "$script-$shorttag sh file(s) to:\n $scriptpath/${scriptfile}" fi # Copy new CHANGES.txt file to script location (if script on a volume) if [[ $scriptpath =~ /volume* ]]; then # Set permissions on CHANGES.txt if ! chmod 664 "/tmp/$script-$shorttag/CHANGES.txt"; then permerr=1 echo -e "${Error}ERROR${Off} Failed to set permissions on:" echo "$scriptpath/CHANGES.txt" fi # Copy new CHANGES.txt file to script location if ! cp -p "/tmp/$script-$shorttag/CHANGES.txt"\ "${scriptpath}/${scriptname}_CHANGES.txt"; then copyerr=1 echo -e "${Error}ERROR${Off} Failed to copy"\ "$script-$shorttag/CHANGES.txt to:\n $scriptpath" else changestxt=" and changes.txt" fi fi # Delete downloaded tmp files cleanup_tmp # Notify of success (if there were no errors) if [[ $copyerr != 1 ]] && [[ $permerr != 1 ]]; then echo -e "\n$tag ${scriptfile}$changestxt downloaded to: ${scriptpath}\n" # Reload script printf -- '-%.0s' {1..79}; echo # print 79 - exec "${scriptpath}/$scriptfile" "${args[@]}" fi fi else echo -e "${Error}ERROR${Off}"\ "/tmp/$script-$shorttag.tar.gz not found!" #ls /tmp | grep "$script" # debug fi fi cd "$scriptpath" || echo -e "${Error}ERROR${Off} Failed to cd to script location!" else echo -e "${Error}ERROR${Off} Failed to cd to /tmp!" fi fi fi fi #-------------------------------------------------------------------- # Check there's no active resync if grep resync /proc/mdstat >/dev/null ; then ding echo "The Synology is currently doing a RAID resync or data scrub!" exit fi #-------------------------------------------------------------------- # Get list of M.2 drives getm2info(){ local nvme local vendor local pcislot local cardslot nvmemodel=$(cat "$1/device/model") nvmemodel=$(printf "%s" "$nvmemodel" | xargs) # trim leading/trailing space vendor=$(/usr/syno/bin/synonvme --vendor-get "/dev/$(basename -- "${1}")") vendor=" $(printf "%s" "$vendor" | cut -d":" -f2 | xargs)" if nvme=$(/usr/syno/bin/synonvme --get-location "/dev/$(basename -- "${1}")"); then if [[ ! $nvme =~ "PCI Slot: 0" ]]; then pcislot="$(echo "$nvme" | cut -d"," -f2 | awk '{print $NF}')-" fi cardslot="$(echo "$nvme" | awk '{print $NF}')" else nvme_cmd_failed="yes" pcislot="$(basename -- "${1}")" cardslot="" fi #echo "$2 M.2 $(basename -- "${1}") is $nvmemodel" >&2 echo "$(basename -- "${1}") M.2 Drive $pcislot$cardslot -$vendor $nvmemodel" >&2 dev="$(basename -- "${1}")" #echo "/dev/${dev}" >&2 # debug if [[ $all != "yes" ]]; then # Skip listing M.2 drives detected as active if grep -E "active.*${dev}" /proc/mdstat >/dev/null ; then echo -e "${Cyan}Skipping drive as it is being used by DSM${Off}" >&2 echo "" >&2 #active="yes" return fi fi if [[ -e /dev/${dev}p1 ]] && [[ -e /dev/${dev}p2 ]] &&\ [[ -e /dev/${dev}p3 ]]; then echo -e "${Yellow}WARNING ${Cyan}Drive has a volume partition${Off}" >&2 haspartitons="yes" elif [[ ! -e /dev/${dev}p3 ]] && [[ ! -e /dev/${dev}p2 ]] &&\ [[ -e /dev/${dev}p1 ]]; then echo -e "${Yellow}WARNING ${Cyan}Drive has a cache partition${Off}" >&2 haspartitons="yes" elif [[ ! -e /dev/${dev}p3 ]] && [[ ! -e /dev/${dev}p2 ]] &&\ [[ ! -e /dev/${dev}p1 ]]; then echo "No existing partitions on drive" >&2 fi if [[ $nvme_cmd_failed == "yes" ]]; then m2list+=("${dev}") m2list_assoc["$dev"]="$dev" else m2list+=("M.2 Drive $pcislot$cardslot") m2list_assoc["M.2 Drive $pcislot$cardslot"]="$dev" fi echo "" >&2 } for d in /sys/block/*; do case "$(basename -- "${d}")" in nvme*) # M.2 NVMe drives if [[ $d =~ nvme[0-9][0-9]?n[0-9][0-9]?$ ]]; then getm2info "$d" "NVMe" fi ;; nvc*) # M.2 SATA drives (in PCIe card only?) if [[ $d =~ nvc[0-9][0-9]?$ ]]; then #getm2info "$d" "SATA" echo -e "${Cyan}Skipping SATA M.2 drive${Off}" >&2 echo -e "Use Synology_M2_volume v1 instead.\n" >&2 fi ;; *) ;; esac done echo -e "Unused M.2 drives found: ${#m2list[@]}\n" #echo -e "NVMe list: ${m2list[@]}\n" # debug #echo -e "NVMe qty: ${#m2list[@]}\n" # debug if [[ ${#m2list[@]} == "0" ]]; then exit; fi #-------------------------------------------------------------------- # Select RAID type (if multiple M.2 drives found) if [[ ${#m2list[@]} -gt "0" ]]; then PS3="Select the RAID type: " if [[ ${#m2list[@]} -eq "1" ]]; then options=("SHR 1" "Basic" "JBOD") elif [[ ${#m2list[@]} -eq "2" ]]; then options=("SHR 1" "Basic" "JBOD" "RAID 0" "RAID 1") elif [[ ${#m2list[@]} -eq "3" ]]; then options=("SHR 1" "Basic" "JBOD" "RAID 0" "RAID 1" "RAID 5" "RAID F1") elif [[ ${#m2list[@]} -gt "3" ]]; then options=("SHR 1" "SHR 2" "Basic" "JBOD" "RAID 0" "RAID 1" "RAID 5" "RAID 6" "RAID 10" "RAID F1") fi select raid in "${options[@]}"; do case "$raid" in Basic|Single) raidtype="basic" single="yes" mindisk=1 #maxdisk=1 break ;; JBOD) raidtype="linear" mindisk=1 #maxdisk=1 break ;; "SHR 1") raidtype="SHR1" mindisk=1 #maxdisk=1 break ;; "SHR 2") raidtype="SHR2" mindisk=4 #maxdisk=1 break ;; "RAID 0") raidtype="raid0" mindisk=2 #maxdisk=24 break ;; "RAID 1") raidtype="raid1" mindisk=2 #maxdisk=4 break ;; "RAID 5") raidtype="raid5" mindisk=3 #maxdisk=24 break ;; "RAID 6") raidtype="raid6" mindisk=4 #maxdisk=24 break ;; "RAID 10") raidtype="raid10" mindisk=4 #maxdisk=24 break ;; "RAID F1") raidtype="raid_f1" mindisk=3 #maxdisk=24 break ;; Quit) exit ;; *) echo -e "${Red}Invalid answer!${Off} Try again." ;; esac done echo -e "You selected ${Cyan}$raidtype${Off}\n" elif [[ ${#m2list[@]} -eq "1" ]]; then single="yes" fi # Only Basic and RAID 1 have a limit on the number of drives in DSM 7 and 6 # Later we set maxdisk to the number of M.2 drives found if not Single or RAID 1 if [[ $single == "yes" ]]; then maxdisk=1 elif [[ $raidtype == "raid1" ]]; then maxdisk=4 fi # Ask user if they want to create a multi-volume pool echo -e "You have a choice of Multi Volume or Single Volume Storage Pool" echo -e " - Multi Volume Storage Pools allow creating multiple volumes and" echo -e " allow you to over provision to make the NVMe drive(s) last longer." echo -e " - Single Volume Storage Pools are easier to recover data from" echo -e " and perform slightly faster.\n" PS3="Select the storage pool type: " #options=("Multi Volume (default)" "Single Volume (easier recovery)") options=("Multi Volume (DSM 7 default)" "Single Volume") select pool in "${options[@]}"; do case "$pool" in #"Multi Volume (default)") "Multi Volume (DSM 7 default)") pooltype="multi" break ;; #"Single Volume (easier recovery)") "Single Volume") pooltype="single" break ;; Quit) exit ;; *) echo -e "${Red}Invalid answer!${Off} Try again." ;; esac done echo -e "You selected ${Cyan}${pooltype^} Volume${Off} storage pool" echo #-------------------------------------------------------------------- # Selected M.2 drive functions getindex(){ # Get array index from value for i in "${!m2list[@]}"; do if [[ "${m2list[$i]}" == "${1}" ]]; then r="${i}" fi done return "$r" } remelement(){ # Remove selected drive from list of other selectable drives if [[ $1 ]]; then num="0" while [[ $num -lt "${#m2list[@]}" ]]; do if [[ ${m2list[num]} == "$1" ]]; then # Remove selected drive from m2list array unset "m2list[num]" # Rebuild the array to remove empty indices for i in "${!m2list[@]}"; do tmp_array+=( "${m2list[i]}" ) done m2list=("${tmp_array[@]}") unset tmp_array fi num=$((num +1)) done fi } #-------------------------------------------------------------------- # Select M.2 drives mdisk=( ) # Set maxdisk to the number of M.2 drives found if not Single or RAID 1 # Only Basic and RAID 1 have a limit on the number of drives in DSM 7 and 6 if [[ $single != "yes" ]] && [[ $raidtype != "raid1" ]]; then maxdisk="${#m2list[@]}" fi while [[ $selected -lt "$mindisk" ]] || [[ $selected -lt "$maxdisk" ]]; do if [[ $single == "yes" ]]; then PS3="Select the M.2 drive: " else PS3="Select the M.2 drive #$((selected+1)): " fi selectdisk if [[ $Done == "yes" ]]; then break fi done if [[ $selected -lt "$mindisk" ]]; then echo "Drives selected: $selected" echo -e "${Error}ERROR${Off} You need to select $mindisk or more drives for RAID $raidtype" exit fi #-------------------------------------------------------------------- # Ask user if they want to do a drive check echo -e "Do you want perform a drive check? [y/n]" read -r answer if [[ ${answer,,} == "y" ]] || [[ ${answer,,} == "yes" ]]; then drivecheck="yes" fi #-------------------------------------------------------------------- # Let user confirm their choices #if [[ $single == "yes" ]]; then # echo -en "Ready to create storage pool using ${Cyan}${mdisk[*]}${Off}" #else #echo -en "\nReady to create ${Cyan}${raidtype^^}${Off} storage pool using " echo -en "\nReady to create ${Cyan}$raid${Off} storage pool using " echo -e "${Cyan}${mdisk[*]}${Off}" #fi if [[ $haspartitons == "yes" ]]; then echo -e "\n${Red}WARNING${Off} Everything on the selected"\ "M.2 drive(s) will be deleted." fi echo -e "Type ${Cyan}yes${Off} to continue. Type anything else to quit." read -r answer if [[ ${answer,,} != "yes" ]]; then exit; fi #-------------------------------------------------------------------- # Enable m2 volume support - DSM 7.1 and later only # Backup synoinfo.conf if needed #if [[ $dsm72 == "yes" ]]; then if [[ $dsm71 == "yes" ]]; then synoinfo="/etc.defaults/synoinfo.conf" if [[ ! -f ${synoinfo}.bak ]]; then if cp "$synoinfo" "$synoinfo.bak"; then echo -e "\nBacked up $(basename -- "$synoinfo")" >&2 else ding echo -e "\n${Error}ERROR 5${Off} Failed to backup $(basename -- "$synoinfo")!" exit 1 fi fi fi # Check if m2 volume support is enabled #if [[ $dsm72 == "yes" ]]; then if [[ $dsm71 == "yes" ]]; then smp=support_m2_pool setting="$(/usr/syno/bin/synogetkeyvalue "$synoinfo" "$smp")" enabled="" if [[ ! $setting ]]; then # Add support_m2_pool="yes" echo 'support_m2_pool="yes"' >> "$synoinfo" enabled="yes" elif [[ $setting == "no" ]]; then # Change support_m2_pool="no" to "yes" #sed -i "s/${smp}=\"no\"/${smp}=\"yes\"/" "$synoinfo" /usr/syno/bin/synosetkeyvalue "$synoinfo" "$smp" "yes" enabled="yes" elif [[ $setting == "yes" ]]; then echo -e "\nM.2 volume support already enabled." fi # Check if we enabled m2 volume support setting="$(/usr/syno/bin/synogetkeyvalue "$synoinfo" "$smp")" if [[ $enabled == "yes" ]]; then if [[ $setting == "yes" ]]; then echo -e "\nEnabled M.2 volume support." else echo -e "\n${Error}ERROR${Off} Failed to enable M.2 volume support!" fi fi fi # Check if RAID F1 support is enabled if [[ $raidtype == "raid_f1" ]]; then #if [[ $dsm72 == "yes" ]]; then if [[ $dsm71 == "yes" ]]; then srf1=support_diffraid setting="$(/usr/syno/bin/synogetkeyvalue "$synoinfo" "$srf1")" enabled="" if [[ ! $setting ]]; then # Add support_diffraid="yes" echo 'support_diffraid="yes"' >> "$synoinfo" enabled="yes" elif [[ $setting == "no" ]]; then # Change support_diffraid="no" to "yes" #sed -i "s/${srf1}=\"no\"/${srf1}=\"yes\"/" "$synoinfo" /usr/syno/bin/synosetkeyvalue "$synoinfo" "$srf1" "yes" enabled="yes" elif [[ $setting == "yes" ]]; then echo -e "\nRAID F1 support already enabled." fi # Check if we enabled RAID F1 support setting="$(/usr/syno/bin/synogetkeyvalue "$synoinfo" "$srf1")" if [[ $enabled == "yes" ]]; then if [[ $setting == "yes" ]]; then echo -e "\nEnabled RAID F1 support." else echo -e "\n${Error}ERROR${Off} Failed to enable RAID F1 support!" fi fi fi fi #-------------------------------------------------------------------- # Create storage pool on selected M.2 drives # Single volume storage pool (DSM 6 style pool on md#) # synostgpool --create -t single -l basic /dev/nvme0n1 # synostgpool --create -t single -l raid5 /dev/nvme0n1 /dev/nvme1n1 /dev/nvme2n1 # Multiple volume storage pool (DSM 7 style pool on vg#) # synostgpool --create -l basic /dev/nvme0n1 # synostgpool --create -l raid5 /dev/nvme0n1 /dev/nvme1n1 /dev/nvme2n1 partargs=( ) for i in "${mdisk[@]}"; do : partargs+=( /dev/"${i}" ) done if [[ $pooltype == "single" ]]; then # Unset existing arguments while [[ $1 ]]; do shift; done # Set -t single arguments set -- "$@" "-t" set -- "$@" "single" fi echo -e "\nStarting creation of the storage pool." if [[ $drivecheck != "yes" ]]; then /usr/syno/sbin/synostgpool --create "$@" -l "$raidtype" "${partargs[@]}" code="$?" if [[ $code -gt "0" ]] && [[ ! $code -eq "255" ]]; then #ding #echo "$code synostgpool failed to create storage pool!" echo "synostgpool return code: $code" #exit 1 fi else /usr/syno/sbin/synostgpool --create "$@" -l "$raidtype" -c "${partargs[@]}" code="$?" if [[ $code -gt "0" ]] && [[ ! $code -eq "255" ]]; then #ding #echo "$code synostgpool failed to create storage pool!" echo "synostgpool return code: $code" #exit 1 fi fi #-------------------------------------------------------------------- # Notify of remaining steps echo showsteps # Show the final steps to do in DSM
30,257
syno_create_m2_volume
sh
en
shell
code
{"qsc_code_num_words": 3581, "qsc_code_num_chars": 30257.0, "qsc_code_mean_word_length": 4.28008936, "qsc_code_frac_words_unique": 0.16475845, "qsc_code_frac_chars_top_2grams": 0.02055197, "qsc_code_frac_chars_top_3grams": 0.01056958, "qsc_code_frac_chars_top_4grams": 0.01272265, "qsc_code_frac_chars_dupe_5grams": 0.3325504, "qsc_code_frac_chars_dupe_6grams": 0.2778104, "qsc_code_frac_chars_dupe_7grams": 0.23592353, "qsc_code_frac_chars_dupe_8grams": 0.18287989, "qsc_code_frac_chars_dupe_9grams": 0.14803941, "qsc_code_frac_chars_dupe_10grams": 0.11783128, "qsc_code_frac_chars_replacement_symbols": 0.0, "qsc_code_frac_chars_digital": 0.02240286, "qsc_code_frac_chars_whitespace": 0.31695145, "qsc_code_size_file_byte": 30257.0, "qsc_code_num_lines": 921.0, "qsc_code_num_chars_line_max": 112.0, "qsc_code_num_chars_line_mean": 32.85233442, "qsc_code_frac_chars_alphabet": 0.71921421, "qsc_code_frac_chars_comments": 0.27897677, "qsc_code_cate_xml_start": 0.0, "qsc_code_frac_lines_dupe_lines": 0.45117845, "qsc_code_cate_autogen": 0.0, "qsc_code_frac_lines_long_string": 0.0016835, "qsc_code_frac_chars_string_length": 0.27724043, "qsc_code_frac_chars_long_word_length": 0.05069906, "qsc_code_frac_lines_string_concat": 0.0, "qsc_code_cate_encoded_data": 0.0, "qsc_code_frac_chars_hex_words": 0.0, "qsc_code_frac_lines_prompt_comments": 0.00108578, "qsc_code_frac_lines_assert": 0.0}
1
{"qsc_code_frac_chars_replacement_symbols": 0, "qsc_code_num_words": 0, "qsc_code_num_chars": 0, "qsc_code_mean_word_length": 0, "qsc_code_frac_chars_top_2grams": 0, "qsc_code_frac_chars_top_3grams": 0, "qsc_code_frac_chars_top_4grams": 0, "qsc_code_frac_chars_dupe_5grams": 0, "qsc_code_frac_chars_dupe_6grams": 0, "qsc_code_frac_chars_dupe_7grams": 0, "qsc_code_frac_chars_dupe_8grams": 0, "qsc_code_frac_chars_dupe_9grams": 0, "qsc_code_frac_chars_dupe_10grams": 0, "qsc_code_frac_lines_dupe_lines": 0, "qsc_code_size_file_byte": 0, "qsc_code_num_lines": 0, "qsc_code_num_chars_line_max": 0, "qsc_code_num_chars_line_mean": 0, "qsc_code_frac_chars_alphabet": 0, "qsc_code_frac_chars_digital": 0, "qsc_code_frac_chars_whitespace": 0, "qsc_code_frac_chars_comments": 0, "qsc_code_cate_xml_start": 0, "qsc_code_cate_autogen": 0, "qsc_code_frac_chars_long_word_length": 0, "qsc_code_cate_encoded_data": 0, "qsc_code_frac_chars_hex_words": 0, "qsc_code_frac_lines_prompt_comments": 0}
007revad/Synology_M2_volume
README_DSM6.md
# Synology M2 volume <a href="https://github.com/007revad/Synology_M2_volume/releases"><img src="https://img.shields.io/github/release/007revad/Synology_M2_volume.svg"></a> <a href="https://hits.seeyoufarm.com"><img src="https://hits.seeyoufarm.com/api/count/incr/badge.svg?url=https%3A%2F%2Fgithub.com%2F007revad%2FSynology_M2_volume&count_bg=%2379C83D&title_bg=%23555555&icon=&icon_color=%23E7E7E7&title=views&edge_flat=false"/></a> [![](https://img.shields.io/static/v1?label=Sponsor&message=%E2%9D%A4&logo=GitHub&color=%23fe8e86)](https://github.com/sponsors/007revad) [![committers.top badge](https://user-badge.committers.top/australia/007revad.svg)](https://user-badge.committers.top/australia/007revad) ### Description Easily create an M.2 volume on Synology NAS without a lot of typing and no need for any how-to guides. And you ***don't*** need Synology branded NVMe drives. - **DSM 7** This script creates the RAID and storage pool on your NVMe drive(s) so you can then create the volume in the DSM GUI. - **DSM 6** This script creates the RAID, storage pool and volume on your NVMe drive(s) for you. All you have to do is run the script and type yes and 1, 2, 3 or 4 to answer some simple questions. Then reboot, go to Storage Manager, Online Assemble and Create Volume. It also allows you to create a storage pool/volume spanning internal NVMe drives and NVMe drives in a Synology M.2 PCIe card. For Xpenology users the script supports an unlimited number of NVMe drives for RAID 0, 5, 6 and 10. ### RAID levels supported | RAID Level | Drives Required | Maximum Drives | | ----------- |------------------|----------------| | Single | 1 drive | 1 drive | | RAID 0 | 2 or more drives | Unlimited | | RAID 1 | 2 or more drives | 4 drives | | RAID 5 | 3 or more drives | Unlimited | | RAID 6 | 4 or more drives | Unlimited | | RAID 10 | 4 or more drives | Unlimited | ### Confirmed working on <details> <summary>Click here to see list</summary> | Model | DSM version | M.2 card | Notes | | ------------ |--------------------------|-----------|-----------------| | RS2423+ | DSM 7.2-64570 Update 1 | | | DS1823xs+ | DSM 7.2-64561 | M2D20 | | DS923+ | DSM 7.2.1-69057 Update 2 | | | DS923+ | DSM 7.1.1-42962 Update 5 | | | DS723+ | DSM 7.2.1-69057 Update 3 | | | DS723+ | DSM 7.2-64570 Update 1 | | | DS723+ | DSM 7.1.1-42962 Update 4 | | | DS423+ | DSM 7.2.1-69057 Update 3 | | | DS423+ | DSM 7.2-64570 Update 3 | | | DS423+ | DSM 7.1.1-42962 Update 4 | | | DS3622xs+ | DSM 7.2-64216 Beta | E10M20-T1 | | DS3622xs+ | DSM 7.1.1-42962 Update 1 | | | DS2422+ | DSM 7.2.1-69057 Update 4 | E10M20-T1 | | DS1522+ | DSM 7.2.1-69057 Update 4 | | | DS1522+ | DSM 7.2-64570 | | | DS1522+ | DSM 7.1.1-42962 Update 4 | | | DS1821+ | DSM 7.2.1-69057 Update 4 | E10M20-T1 | Also needs [Synology enable_M2_card](https://github.com/007revad/Synology_enable_M2_card) | | DS1821+ | DSM 7.2.1-69057 Update 4 | M2D20 | Also needs [Synology enable_M2_card](https://github.com/007revad/Synology_enable_M2_card) | | DS1821+ | DSM 7.2.1-69057 Update 4 | M2D18 | Also needs [Synology enable_M2_card](https://github.com/007revad/Synology_enable_M2_card) | | DS1821+ | DSM 7.2.1-69057 Update 4 | | | DS1821+ | DSM 7.2.1-69057 Update 3 | | | DS1821+ | DSM 7.2.1-69057 Update 2 | | | DS1821+ | DSM 7.2.1-69057 Update 1 | | | DS1821+ | DSM 7.2.1-69057 | | | DS1821+ | DSM 7.2-64570 Update 3 | | | DS1821+ | DSM 7.2-64570 Update 1 | E10M20-T1 | Also needs [Synology enable_M2_card](https://github.com/007revad/Synology_enable_M2_card) | | DS1821+ | DSM 7.2-64570 Update 1 | M2D18 | Also needs [Synology enable_M2_card](https://github.com/007revad/Synology_enable_M2_card) | | DS1821+ | DSM 7.2-64570 Update 1 | | | DS1821+ | DSM 7.2-64570 | | | DS1821+ | DSM 7.2-64561 | | | DS1821+ | DSM 7.2-64216 Beta | | | DS1821+ | DSM 7.2-64213 Beta | | | DS1821+ | DSM 7.1.1-42962 Update 4 | | | DS1821+ | **DSM 6.2.4**-25556 Update 7 | | | DS1621+ | DSM 7.2-64570 Update 1 | E10M20-T1 | Also needs [Synology enable_M2_card](https://github.com/007revad/Synology_enable_M2_card) | | DS1621+ | DSM 7.2-64570 Update 1 | | | DS1621+ | DSM 7.1.1-42962 Update 4 | | | RS1221+ | DSM 7.2-64570 Update 1 | E10M20-T1 | | RS1221+ | DSM 7.1.1 | E10M20-T1 | | DS1520+ | DSM 7.2.1-69057 Update 2 | | | DS1520+ | DSM 7.2-64570 Update 1 | | | DS1520+ | DSM 7.1.1-42962 Update 4 | | | DS920+ | DSM 7.2.1-69057 Update 4 | | | DS920+ | DSM 7.2.1-69057 Update 3 | | | DS920+ | DSM 7.2.1-69057 Update 2 | | | DS920+ | DSM 7.2.1-69057 update 1 | | | DS920+ | DSM 7.2.1-69057 | | | DS920+ | DSM 7.2-64570 Update 1 | | | DS920+ | DSM 7.2-64561 | | | DS920+ | DSM 7.2-64216 Beta | | | DS920+ | DSM 7.1.1-42962 Update 1 | | | DS920+ | **DSM 6** | | | DS918+ | DSM 7.2-64570 Update 3 | | | RS820+ | DSM 7.2-64570 Update 3 | M2D20 | | DS720+ | DSM 7.2.1-69057 Update 4 | | | DS720+ | DSM 7.2.1-69057 Update 3 | | | DS720+ | DSM 7.2.1-69057 Update 2 | | | DS720+ | DSM 7.2.1-69057 Update 1 | | | DS720+ | DSM 7.2.1-69057 | | | DS720+ | DSM 7.2-64570 Update 3 | | | DS720+ | DSM 7.2-64570 Update 1 | | | DS720+ | DSM 7.2-64570 | | | DS720+ | DSM 7.2-64561 | | | DS720+ | DSM 7.2-64216 Beta | | | DS720+ | **DSM 6.2.4** | | | DS420+ | DSM 7.2-64570 Update 1 | | | DS1819+ | DSM 7.2-64216 Beta | M2D20 | | DS1819+ | DSM 7.1.1 | M2D20 | | DS1019+ | DSM 7.2.1-69057 Update 2 | | | DS1019+ | DSM 7.2-64561 | | | DS1019+ | DSM 7.1.1-42962 Update 4 | | | DS1618+ | DSM 7.1.1 | M2D18 | | DS918+ | DSM 7.2-64561 | | | DS918+ | DSM 7.1.1 | | | DS3617xs | DSM 7.2-64570 | M2D20 | </details> ### Important If you later update DSM and your M.2 drives are shown as unsupported and the storage pool is shown as missing, and online assemble fails, you need to run the <a href="https://github.com/007revad/Synology_HDD_db">Synology_HDD_db</a> script. The <a href="https://github.com/007revad/Synology_HDD_db">Synology_HDD_db</a> script should run after every DSM update. ### Download the script 1. Download the latest version _Source code (zip)_ from https://github.com/007revad/Synology_M2_volume/releases 2. Save the download zip file to a folder on the Synology. 3. Unzip the zip file. ### Video guide Vikash has created a step by step YouTube video here: https://www.youtube.com/watch?v=sclQprHsXQE ### To run the script via SSH [How to enable SSH and login to DSM via SSH](https://kb.synology.com/en-global/DSM/tutorial/How_to_login_to_DSM_with_root_permission_via_SSH_Telnet) ```YAML sudo -s /volume1/scripts/syno_create_m2_volume.sh ``` **Note:** Replace /volume1/scripts/ with the path to where the script is located. ### Troubleshooting If the script won't run check the following: 1. If the path to the script contains any spaces you need to enclose the path/scriptname in double quotes: ```YAML sudo -s "/volume1/my scripts/syno_create_m2_volume.sh" ``` 2. Make sure you unpacked the zip or rar file that you downloaded and are trying to run the syno_create_m2_volume.sh file. 3. Set the syno_create_m2_volume.sh file as executable: ```YAML sudo chmod +x "/volume1/scripts/syno_create_m2_volume.sh" ``` ### Options: ```YAML -a, --all List all M.2 drives even if detected as active -s, --steps Show the steps to do after running this script -h, --help Show this help message -v, --version Show the script version ``` It also has a dry run mode so you can see what it would have done had you run it for real. <p align="center"><img src="/images/create-volume0.png"></p> ### What to do after running the script **DSM 7** 1. Restart the Synology NAS. 2. Go to Storage Manager and select Online Assemble: - Storage Pool > Available Pool > Online Assemble 3. Create the volume as you normally would: - Select the new Storage Pool > Create > Create Volume. - Set the allocated size. - Optionally enter a volume description. Be creative :) - Click Next. - Select the file system (Btrfs or ext4) and click Next. - Optionally enable *Encrypt this volume* and click Next. - Create an encryption password or enter your existing encryption password. - Confirm your settings and click Apply to finish creating your M.2 volume. 4. Optionally enable and schedule TRIM: - Storage Pool > ... > Settings > SSD TRIM - **Note: DSM 7.1.1. has no SSD TRIM setting for M.2 storage pools** - **Note: DSM 7.2 Beta has no SSD TRIM setting for M.2 RAID 0 or RAID 5** **DSM 6** 1. Restart the Synology NAS. ### DSM 7 screen shots <p align="center">Storage Pool available for Online Assemble</p> <p align="center"><img src="/images/create_m2_volume_available_pool.png"></p> <p align="center">Online Assemble step 1</p> <p align="center"><img src="/images/create_m2_volume_online_assemble.png"></p> <p align="center">Online Assemble step 2</p> <p align="center"><img src="/images/create_m2_volume_online_assemble2.png"></p> <p align="center">Create Volume</p> <p align="center"><img src="/images/create-volume1.png"></p> <p align="center">Allocate volume capacity</p> <p align="center"><img src="/images/create-volume2.png"></p> <p align="center">Volume description</p> <p align="center"><img src="/images/create-volume3.png"></p> <p align="center">Select file system</p> <p align="center"><img src="/images/create-volume4.png"></p> <p align="center">Success!</p> <p align="center"><img src="/images/create-volume5.png"></p> <p align="center">Enable TRIM</p> <p align="center"><img src="/images/create_m2_volume_enable_trim.png"></p>
10,910
README_DSM6
md
en
markdown
text
{"qsc_doc_frac_chars_curly_bracket": 0.0, "qsc_doc_frac_words_redpajama_stop": 0.11119573, "qsc_doc_num_sentences": 218.0, "qsc_doc_num_words": 1610, "qsc_doc_num_chars": 10910.0, "qsc_doc_num_lines": 219.0, "qsc_doc_mean_word_length": 3.92546584, "qsc_doc_frac_words_full_bracket": 0.0, "qsc_doc_frac_lines_end_with_readmore": 0.0, "qsc_doc_frac_lines_start_with_bullet": 0.0, "qsc_doc_frac_words_unique": 0.20372671, "qsc_doc_entropy_unigram": 4.84234446, "qsc_doc_frac_words_all_caps": 0.08720487, "qsc_doc_frac_lines_dupe_lines": 0.05714286, "qsc_doc_frac_chars_dupe_lines": 0.00905148, "qsc_doc_frac_chars_top_2grams": 0.04873418, "qsc_doc_frac_chars_top_3grams": 0.04667722, "qsc_doc_frac_chars_top_4grams": 0.02373418, "qsc_doc_frac_chars_dupe_5grams": 0.45791139, "qsc_doc_frac_chars_dupe_6grams": 0.39335443, "qsc_doc_frac_chars_dupe_7grams": 0.34161392, "qsc_doc_frac_chars_dupe_8grams": 0.23164557, "qsc_doc_frac_chars_dupe_9grams": 0.17025316, "qsc_doc_frac_chars_dupe_10grams": 0.14335443, "qsc_doc_frac_chars_replacement_symbols": 0.0, "qsc_doc_cate_code_related_file_name": 0.0, "qsc_doc_num_chars_sentence_length_mean": 23.85421412, "qsc_doc_frac_chars_hyperlink_html_tag": 0.19248396, "qsc_doc_frac_chars_alphabet": 0.66274212, "qsc_doc_frac_chars_digital": 0.13735916, "qsc_doc_frac_chars_whitespace": 0.27598533, "qsc_doc_frac_chars_hex_words": 0.0}
1
{"qsc_doc_frac_chars_replacement_symbols": 0, "qsc_doc_entropy_unigram": 0, "qsc_doc_frac_chars_top_2grams": 0, "qsc_doc_frac_chars_top_3grams": 0, "qsc_doc_frac_chars_top_4grams": 0, "qsc_doc_frac_chars_dupe_5grams": 0, "qsc_doc_frac_chars_dupe_6grams": 0, "qsc_doc_frac_chars_dupe_7grams": 0, "qsc_doc_frac_chars_dupe_8grams": 0, "qsc_doc_frac_chars_dupe_9grams": 0, "qsc_doc_frac_chars_dupe_10grams": 0, "qsc_doc_frac_chars_dupe_lines": 0, "qsc_doc_frac_lines_dupe_lines": 0, "qsc_doc_frac_lines_end_with_readmore": 0, "qsc_doc_frac_lines_start_with_bullet": 0, "qsc_doc_frac_words_all_caps": 0, "qsc_doc_mean_word_length": 0, "qsc_doc_num_chars": 0, "qsc_doc_num_lines": 0, "qsc_doc_num_sentences": 0, "qsc_doc_num_words": 0, "qsc_doc_frac_chars_hex_words": 0, "qsc_doc_frac_chars_hyperlink_html_tag": 0, "qsc_doc_frac_chars_alphabet": 0, "qsc_doc_frac_chars_digital": 0, "qsc_doc_frac_chars_whitespace": 0}
007revad/Synology_M2_volume
my-other-scripts.md
## All my scripts, tools and guides <img src="https://hitscounter.dev/api/hit?url=https%3A%2F%2F007revad.github.io%2F&label=Visitors&icon=github&color=%23198754&message=&style=flat&tz=UTC"> #### Contents - [Plex](#plex) - [Synology docker](#synology-docker) - [Synology recovery](#synology-recovery) - [Other Synology scripts](#other-synology-scripts) - [Synology hardware restrictions](#synology-hardware-restrictions) - [2025 plus models](#2025-plus-models) - [How To Guides](#how-to-guides) - [Synology dev](#synology-dev) *** ### Plex - **<a href="https://github.com/007revad/Synology_Plex_Backup">Synology_Plex_Backup</a>** - A script to backup Plex to a tgz file foror DSM 7 and DSM 6. - Works for Plex Synology package and Plex in docker. - **<a href="https://github.com/007revad/Asustor_Plex_Backup">Asustor_Plex_Backup</a>** - Backup your Asustor's Plex Media Server settings and database. - **<a href="https://github.com/007revad/Linux_Plex_Backup">Linux_Plex_Backup</a>** - Backup your Linux Plex Media Server's settings and database. - **<a href="https://github.com/007revad/Plex_Server_Sync">Plex_Server_Sync</a>** - Sync your main Plex server database & metadata to a backup Plex server. - Works for Synology, Asustor, Linux and supports Plex package or Plex in docker. &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; [Back to Contents](#contents) ### Synology docker - **<a href="https://github.com/007revad/Synology_Docker_Export">Synology_Docker_export</a>** - Export all Synology Container Manager or Docker containers' settings as json files to your docker shared folder. - **<a href="https://github.com/007revad/Synology_ContainerManager_IPv6">Synology_ContainerManager_IPv6</a>** - Enable IPv6 for Container Manager's bridge network. - **<a href="https://github.com/007revad/ContainerManager_for_all_armv8">ContainerManager_for_all_armv8</a>** - Script to install Container Manager on a RS819, DS119j, DS418, DS418j, DS218, DS218play or DS118. - **<a href="https://github.com/007revad/Docker_Autocompose">Docker_Autocompose</a>** - Create .yml files from your docker existing containers. - **<a href="https://github.com/007revad/Synology_docker_cleanup">Synology_docker_cleanup</a>** - Remove orphan docker btrfs subvolumes and images in Synology DSM 7 and DSM 6. &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; [Back to Contents](#contents) ### Synology recovery - **<a href="https://github.com/007revad/Synology_DSM_reinstall">Synology_DSM_reinstall</a>** - Easily re-install the same DSM version without losing any data or settings. - **<a href="https://github.com/007revad/Synology_Recover_Data">Synology_Recover_Data</a>** - A script to make it easy to recover your data from your Synology's drives using a computer. - **<a href="https://github.com/007revad/Synology_clear_drive_error">Synology clear drive error</a>** - Clear drive critical errors so DSM will let you use the drive. - **<a href="https://github.com/007revad/Synology_DSM_Telnet_Password">Synology_DSM_Telnet_Password</a>** - Synology DSM Recovery Telnet Password of the Day generator. - **<a href="https://github.com/007revad/Syno_DSM_Extractor_GUI">Syno_DSM_Extractor_GUI</a>** - Windows GUI for extracting Synology DSM 7 pat files and spk package files. - **<a href="https://github.com/007revad/Synoboot_backup">Synoboot_backup</a>** - Back up synoboot after each DSM update so you can recover from a corrupt USBDOM. &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; [Back to Contents](#contents) ### Other Synology scripts - **<a href="https://github.com/007revad/Synology_app_mover">Synology_app_mover</a>** - Easily move Synology packages from one volume to another volume. - **<a href="https://github.com/007revad/Video_Station_for_DSM_722">Video_Station_for_DSM_722</a>** - Script to install Video Station in DSM 7.2.2 - **<a href="https://github.com/007revad/SS_Motion_Detection">SS_Motion_Detection</a>** - Installs previous Surveillance Station and Advanced Media Extensions versions so motion detection and HEVC are supported. - **<a href="https://github.com/007revad/Synology_Config_Backup">Synology_Config_Backup</a>** - Backup and export your Synology DSM configuration. - **<a href="https://github.com/007revad/Synology_CPU_temperature">Synology_CPU_temperature</a>** - Get and log Synology NAS CPU temperature via SSH. - **<a href="https://github.com/007revad/Synology_SMART_info">Synology_SMART_info</a>** - Show Synology smart test progress or smart health and attributes. - **<a href="https://github.com/007revad/Synology_Cleanup_Coredumps">Synology_Cleanup_Coredumps</a>** - Cleanup memory core dumps from crashed processes. - **<a href="https://github.com/007revad/Synology_toggle_reset_button">Synology_toggle_reset_button</a>** - Script to disable or enable the reset button and show current setting. - **<a href="https://github.com/007revad/Synology_Download_Station_Chrome_Extension">Synology_Download_Station_Chrome_Extension</a>** - Download Station Chrome Extension. - **<a href="https://github.com/007revad/Seagate_lowCurrentSpinup">Seagate_lowCurrentSpinup</a>** - This script avoids the need to buy and install a higher wattage power supply when using multiple large Seagate SATA HDDs. &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; [Back to Contents](#contents) ### Synology hardware restrictions - **<a href="https://github.com/007revad/Synology_HDD_db">Synology_HDD_db</a>** - Add your SATA or SAS HDDs and SSDs plus SATA and NVMe M.2 drives to your Synology's compatible drive databases, including your Synology M.2 PCIe card and Expansion Unit databases. - **<a href="https://github.com/007revad/Synology_enable_M2_volume">Synology_enable_M2_volume</a>** - Enable creating volumes with non-Synology M.2 drives. - Enable Health Info for non-Synology NVMe drives (not in DSM 7.2.1 or later). - **<a href="https://github.com/007revad/Synology_M2_volume">Synology_M2_volume</a>** - Easily create an M.2 volume on Synology NAS. - **<a href="https://github.com/007revad/Synology_enable_M2_card">Synology_enable_M2_card</a>** - Enable Synology M.2 PCIe cards in Synology NAS that don't officially support them. - **<a href="https://github.com/007revad/Synology_enable_eunit">Synology_enable_eunit</a>** - Enable an unsupported Synology eSATA Expansion Unit models. - **<a href="https://github.com/007revad/Synology_enable_Deduplication">Synology_enable_Deduplication</a>** - Enable deduplication with non-Synology SSDs and unsupported NAS models. - **<a href="https://github.com/007revad/Synology_SHR_switch">Synology_SHR_switch</a>** - Easily switch between SHR and RAID Groups, or enable RAID F1. - **<a href="https://github.com/007revad/Synology_enable_sequential_IO">Synology_enable_sequential_IO</a>** - Enables sequential I/O for your SSD caches, like DSM 6 had. - **<a href="https://github.com/007revad/Synology_Information_Wiki">Synology_Information_Wiki</a>** - Information about Synology hardware. &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; [Back to Contents](#contents) ### 2025 plus models - **<a href="https://github.com/007revad/Transcode_for_x25">Transcode_for_x25</a>** - Installs the modules needed for Plex or Jellyfin hardware transcoding in DS425+ and DS225+. - **<a href="https://github.com/007revad/Synology_HDD_db/blob/main/2025_plus_models.md">2025 series or later Plus models</a>** - Unverified 3rd party drive limitations and unofficial solutions. - **<a href="https://github.com/007revad/Synology_HDD_db/blob/main/2025_plus_models.md#setting-up-a-new-2025-or-later-plus-model-with-only-unverified-hdds">Setup with only 3rd party drives</a>** - Setting up a new 2025 or later plus model with only unverified HDDs. - **<a href="https://github.com/007revad/Synology_HDD_db/blob/main/2025_plus_models.md#deleting-and-recreating-your-storage-pool-on-unverified-hdds">Recreating storage pool on migrated drives</a>** - Deleting and recreating your storage pool on unverified HDDs. &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; [Back to Contents](#contents) ### How To Guides - **<a href="https://github.com/007revad/Synology_SSH_key_setup">Synology_SSH_key_setup</a>** - How to setup SSH key authentication for your Synology. &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; [Back to Contents](#contents) ### Synology dev - **<a href="https://github.com/007revad/Download_Synology_Archive">Download_Synology_Archive</a>** - Download all or part of the Synology archive. - **<a href="https://github.com/007revad/Syno_DSM_Extractor_GUI">Syno_DSM_Extractor_GUI</a>** - Windows GUI for extracting Synology DSM 7 pat files and spk package files. - **<a href="https://github.com/007revad/ScriptNotify">ScriptNotify</a>** - DSM 7 package to allow your scripts to send DSM notifications. - **<a href="https://github.com/007revad/DTC_GUI_for_Windows">DTC_GUI_for_Windows</a>** - GUI for DTC.exe for Windows. &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; [Back to Contents](#contents)
9,099
my-other-scripts
md
en
markdown
text
{"qsc_doc_frac_chars_curly_bracket": 0.0, "qsc_doc_frac_words_redpajama_stop": 0.16632653, "qsc_doc_num_sentences": 107.0, "qsc_doc_num_words": 1341, "qsc_doc_num_chars": 9099.0, "qsc_doc_num_lines": 180.0, "qsc_doc_mean_word_length": 4.94630872, "qsc_doc_frac_words_full_bracket": 0.0, "qsc_doc_frac_lines_end_with_readmore": 0.0, "qsc_doc_frac_lines_start_with_bullet": 0.0, "qsc_doc_frac_words_unique": 0.23191648, "qsc_doc_entropy_unigram": 4.76529845, "qsc_doc_frac_words_all_caps": 0.02908163, "qsc_doc_frac_lines_dupe_lines": 0.1025641, "qsc_doc_frac_chars_dupe_lines": 0.10911978, "qsc_doc_frac_chars_top_2grams": 0.05789236, "qsc_doc_frac_chars_top_3grams": 0.06482738, "qsc_doc_frac_chars_top_4grams": 0.10372381, "qsc_doc_frac_chars_dupe_5grams": 0.39981909, "qsc_doc_frac_chars_dupe_6grams": 0.36891301, "qsc_doc_frac_chars_dupe_7grams": 0.34041912, "qsc_doc_frac_chars_dupe_8grams": 0.25569124, "qsc_doc_frac_chars_dupe_9grams": 0.20624152, "qsc_doc_frac_chars_dupe_10grams": 0.15829941, "qsc_doc_frac_chars_replacement_symbols": 0.0, "qsc_doc_cate_code_related_file_name": 0.0, "qsc_doc_num_chars_sentence_length_mean": 30.70731707, "qsc_doc_frac_chars_hyperlink_html_tag": 0.34762062, "qsc_doc_frac_chars_alphabet": 0.79007303, "qsc_doc_frac_chars_digital": 0.03094442, "qsc_doc_frac_chars_whitespace": 0.11210023, "qsc_doc_frac_chars_hex_words": 0.0}
1
{"qsc_doc_frac_chars_replacement_symbols": 0, "qsc_doc_entropy_unigram": 0, "qsc_doc_frac_chars_top_2grams": 0, "qsc_doc_frac_chars_top_3grams": 0, "qsc_doc_frac_chars_top_4grams": 0, "qsc_doc_frac_chars_dupe_5grams": 0, "qsc_doc_frac_chars_dupe_6grams": 0, "qsc_doc_frac_chars_dupe_7grams": 0, "qsc_doc_frac_chars_dupe_8grams": 0, "qsc_doc_frac_chars_dupe_9grams": 0, "qsc_doc_frac_chars_dupe_10grams": 0, "qsc_doc_frac_chars_dupe_lines": 0, "qsc_doc_frac_lines_dupe_lines": 0, "qsc_doc_frac_lines_end_with_readmore": 0, "qsc_doc_frac_lines_start_with_bullet": 0, "qsc_doc_frac_words_all_caps": 0, "qsc_doc_mean_word_length": 0, "qsc_doc_num_chars": 0, "qsc_doc_num_lines": 0, "qsc_doc_num_sentences": 0, "qsc_doc_num_words": 0, "qsc_doc_frac_chars_hex_words": 0, "qsc_doc_frac_chars_hyperlink_html_tag": 0, "qsc_doc_frac_chars_alphabet": 0, "qsc_doc_frac_chars_digital": 0, "qsc_doc_frac_chars_whitespace": 0}
007revad/Synology_M2_volume
README.md
# Synology M2 volume <a href="https://github.com/007revad/Synology_M2_volume/releases"><img src="https://img.shields.io/github/release/007revad/Synology_M2_volume.svg"></a> ![Badge](https://hitscounter.dev/api/hit?url=https%3A%2F%2Fgithub.com%2F007revad%2FSynology_M2_volume&label=Visitors&icon=github&color=%23198754&message=&style=flat&tz=Australia%2FSydney) [![Donate](https://img.shields.io/badge/Donate-PayPal-green.svg)](https://www.paypal.com/paypalme/007revad) [![](https://img.shields.io/static/v1?label=Sponsor&message=%E2%9D%A4&logo=GitHub&color=%23fe8e86)](https://github.com/sponsors/007revad) [![committers.top badge](https://user-badge.committers.top/australia/007revad.svg)](https://user-badge.committers.top/australia/007revad) ### Description Easily create an M.2 volume on Synology NAS without a lot of typing and no need for any how-to guides. And you ***don't*** need Synology branded NVMe drives. This script creates the RAID and storage pool on your NVMe drive(s) so you can then create the volume in the Storage Manager. All you have to do is run the script and type yes and 1, 2, 3 or 4 to answer some simple questions. Then go to Storage Manager and select Create Volume. It also allows you to create a storage pool/volume spanning internal NVMe drives and NVMe drives in a Synology M.2 PCIe card. For Xpenology users the script supports an unlimited number of NVMe drives (except for RAID 1 and Basic). **Supports DSM 7 and later** For [DSM 6 use v1](https://github.com/007revad/Synology_M2_volume/releases/tag/v1.3.25) and run **without** the auto update option. **NEW in v2** - Now shows "M.2 Drive #" the same as storage manager. - Now uses synostgpool command which allows the following: (Thanks to Severe_Pea_2128 on reddit) - Now supports JBOD, SHR, SHR2 and RAID F1. - Added choice of multi-volume or single-volume storage pool. Multi-volume allows overprovisioning. - Added option to skip drive check. - No longer need to reboot after running the script. - No longer need to do an online assemble. - Removed drive check progress as it was not possible with synostgpool. - You can see the drive check progress in Storage Manager. - Removed dry run mode as it was not possible with synostgpool. - Removed support for SATA M.2 drives. - If you have SATA M.2 drives [use v1](https://github.com/007revad/Synology_M2_volume/releases/tag/v1.3.25) and run **without** the auto update option. ### RAID levels supported | RAID Level | Min Drives Required | Maximum Drives | Script version | | ----------- |------------------|----------------|----------------| | SHR 1 | 1 or more drives | Unlimited | v2 and later (DSM 7 only) | | SHR 2 | 4 or more drives | Unlimited | v2 and later (DSM 7 only) | | Basic | 1 drive | 1 drive | all | | JBOD | 1 or more drives | Unlimited | v2 and later (DSM 7 only) | | RAID 0 | 2 or more drives | Unlimited | all | | RAID 1 | 2 or more drives | 4 drives | all | | RAID 5 | 3 or more drives | Unlimited | all | | RAID 6 | 4 or more drives | Unlimited | v1.3.15 and later | | RAID 10 | 4 or more drives | Unlimited | v1.3.15 and later | | RAID F1 | 3 or more drives | Unlimited | v2 and later (DSM 7 only) | If RAID F1 is selected the script enables RAID F1 on Synology models that don't officially support RAID F1. ### Confirmed working on <details> <summary>Click here to see list</summary> | Model | DSM version | M.2 card | Notes | | ------------ |--------------------------|-----------|-----------------| | All | DSM 6 | | [Use v1](https://github.com/007revad/Synology_M2_volume/releases/tag/v1.3.25) run without auto update option | | RS2423+ | DSM 7.2-64570 Update 1 | | | DS1823xs+ | DSM 7.2-64561 | M2D20 | | DS923+ | DSM 7.2.2-72806 Update 3 | | | DS923+ | DSM 7.2.2-72806 Update 2 | | | DS923+ | DSM 7.2.2 72806 Update 1 | | | DS923+ | DSM 7.2.1-69057 Update 5 | | | DS923+ | DSM 7.2.1-69057 Update 2 | | | DS923+ | DSM 7.1.1-42962 Update 5 | | | DS723+ | DSM 7.2.2-72806 Update 2 | | | DS723+ | DSM 7.2.1-69057 Update 3 | | | DS723+ | DSM 7.2-64570 Update 1 | | | DS723+ | DSM 7.1.1-42962 Update 4 | | | DS423+ | DSM 7.2.2-72806 | | | DS423+ | DSM 7.2.1-69057 Update 3 | | | DS423+ | DSM 7.2-64570 Update 3 | | | DS423+ | DSM 7.1.1-42962 Update 4 | | | DS3622xs+ | DSM 7.2-64216 Beta | E10M20-T1 | | DS3622xs+ | DSM 7.1.1-42962 Update 1 | | | DS2422+ | DSM 7.2.1-69057 Update 4 | E10M20-T1 | | DS1522+ | DSM 7.2.1-69057 Update 4 | | | DS1522+ | DSM 7.2-64570 | | | DS1522+ | DSM 7.1.1-42962 Update 4 | | | DS1821+ | DSM 7.2.1-69057 Update 4 | E10M20-T1 | Also needs [Synology enable_M2_card](https://github.com/007revad/Synology_enable_M2_card) | | DS1821+ | DSM 7.2.1-69057 Update 4 | M2D20 | Also needs [Synology enable_M2_card](https://github.com/007revad/Synology_enable_M2_card) | | DS1821+ | DSM 7.2.1-69057 Update 4 | M2D18 | Also needs [Synology enable_M2_card](https://github.com/007revad/Synology_enable_M2_card) | | DS1821+ | DSM 7.2.1-69057 Update 4 | | | DS1821+ | DSM 7.2.1-69057 Update 3 | | | DS1821+ | DSM 7.2.1-69057 Update 2 | | | DS1821+ | DSM 7.2.1-69057 Update 1 | | | DS1821+ | DSM 7.2.1-69057 | | | DS1821+ | DSM 7.2-64570 Update 3 | | | DS1821+ | DSM 7.2-64570 Update 1 | E10M20-T1 | Also needs [Synology enable_M2_card](https://github.com/007revad/Synology_enable_M2_card) | | DS1821+ | DSM 7.2-64570 Update 1 | M2D18 | Also needs [Synology enable_M2_card](https://github.com/007revad/Synology_enable_M2_card) | | DS1821+ | DSM 7.2-64570 Update 1 | | | DS1821+ | DSM 7.2-64570 | | | DS1821+ | DSM 7.2-64561 | | | DS1821+ | DSM 7.2-64216 Beta | | | DS1821+ | DSM 7.2-64213 Beta | | | DS1821+ | DSM 7.1.1-42962 Update 4 | | | DS1621xs+ | DSM 7.2.1-69057 Update 5 | | | DS1621+ | DSM 7.2-64570 Update 1 | E10M20-T1 | Also needs [Synology enable_M2_card](https://github.com/007revad/Synology_enable_M2_card) | | DS1621+ | DSM 7.2-64570 Update 1 | | | DS1621+ | DSM 7.1.1-42962 Update 4 | | | RS1221+ | DSM 7.2-64570 Update 1 | E10M20-T1 | | RS1221+ | DSM 7.1.1 | E10M20-T1 | | DS1520+ | DSM 7.2.1-69057 Update 2 | | | DS1520+ | DSM 7.2-64570 Update 1 | | | DS1520+ | DSM 7.1.1-42962 Update 4 | | | DS920+ | DSM 7.2.2 72806 Update 3 | | | DS920+ | DSM 7.2.2 72806 Update 2 | | | DS920+ | DSM 7.2.2 72806 Update 1 | | | DS920+ | DSM 7.2.2-72806 | | | DS920+ | DSM 7.2.1-69057 Update 5 | | | DS920+ | DSM 7.2.1-69057 Update 4 | | | DS920+ | DSM 7.2.1-69057 Update 3 | | | DS920+ | DSM 7.2.1-69057 Update 2 | | | DS920+ | DSM 7.2.1-69057 update 1 | | | DS920+ | DSM 7.2.1-69057 | | | DS920+ | DSM 7.2-64570 Update 1 | | | DS920+ | DSM 7.2-64561 | | | DS920+ | DSM 7.2-64216 Beta | | | DS920+ | DSM 7.1.1-42962 Update 1 | | | RS1619xs+ | DSM 7.2.2-72806 Update 3 | | | DS918+ | DSM 7.2-64570 Update 3 | | | RS820+ | DSM 7.2-64570 Update 3 | M2D20 | | DS720+ | DSM 7.2.2 72806 Update 3 | | | DS720+ | DSM 7.2.2 72806 Update 2 | | | DS720+ | DSM 7.2.2 72806 Update 1 | | | DS720+ | DSM 7.2.2-72806 | | | DS720+ | DSM 7.2.1-69057 Update 5 | | | DS720+ | DSM 7.2.1-69057 Update 4 | | | DS720+ | DSM 7.2.1-69057 Update 3 | | | DS720+ | DSM 7.2.1-69057 Update 2 | | | DS720+ | DSM 7.2.1-69057 Update 1 | | | DS720+ | DSM 7.2.1-69057 | | | DS720+ | DSM 7.2-64570 Update 3 | | | DS720+ | DSM 7.2-64570 Update 1 | | | DS720+ | DSM 7.2-64570 | | | DS720+ | DSM 7.2-64561 | | | DS720+ | DSM 7.2-64216 Beta | | | DS420+ | DSM 7.2-64570 Update 1 | | | DS1819+ | DSM 7.2-64216 Beta | M2D20 | | DS1819+ | DSM 7.1.1 | M2D20 | | DS1019+ | DSM 7.2.2-72806 | | | DS1019+ | DSM 7.2.1-69057 Update 2 | | | DS1019+ | DSM 7.2-64561 | | | DS1019+ | DSM 7.1.1-42962 Update 4 | | | DS1618+ | DSM 7.1.1 | M2D18 | | DS918+ | DSM 7.2.1-69057 Update 5 | | | DS918+ | DSM 7.2-64561 | | | DS918+ | DSM 7.1.1 | | | DS3617xs | DSM 7.2-64570 | M2D20 | </details> ### Important If you later update DSM and your M.2 drives are shown as unsupported and the storage pool is shown as missing, and online assemble fails, you need to run the <a href="https://github.com/007revad/Synology_HDD_db">Synology_HDD_db</a> script. The <a href="https://github.com/007revad/Synology_HDD_db">Synology_HDD_db</a> script should run after every DSM update. ### Download the script 1. Download the latest version _Source code (zip)_ from https://github.com/007revad/Synology_M2_volume/releases 2. Save the download zip file to a folder on the Synology. 3. Unzip the zip file. ### To run the script via SSH [How to enable SSH and login to DSM via SSH](https://kb.synology.com/en-global/DSM/tutorial/How_to_login_to_DSM_with_root_permission_via_SSH_Telnet) ```YAML sudo -s /volume1/scripts/syno_create_m2_volume.sh ``` **Note:** Replace /volume1/scripts/ with the path to where the script is located. ### Troubleshooting If the script won't run check the following: 1. If the path to the script contains any spaces you need to enclose the path/scriptname in double quotes: ```YAML sudo -s "/volume1/my scripts/syno_create_m2_volume.sh" ``` 2. Make sure you unpacked the zip or rar file that you downloaded and are trying to run the syno_create_m2_volume.sh file. 3. Set the syno_create_m2_volume.sh file as executable: ```YAML sudo chmod +x "/volume1/scripts/syno_create_m2_volume.sh" ``` ### Options: ```YAML -a, --all List all M.2 drives even if detected as active -s, --steps Show the steps to do after running this script -h, --help Show this help message -v, --version Show the script version ``` ### What to do after running the script 1. Create the volume as you normally would: - Select the new Storage Pool > Create > Create Volume. - Set the allocated size. - Optionally enter a volume description. Be creative :) - Click Next. - Select the file system (Btrfs or ext4) and click Next. - Optionally enable *Encrypt this volume* and click Next. - Create an encryption password or enter your existing encryption password. - Confirm your settings and click Apply to finish creating your M.2 volume. 4. Optionally enable and schedule TRIM: - Storage Pool > ... > Settings > SSD TRIM - **Note: DSM 7.2 and later has no SSD TRIM setting for M.2 RAID 0** - **Note: DSM 7.1.1. has no SSD TRIM setting for M.2 storage pools** ----- ### How to repair a NVMe storage pool or upgrade to larger drives - Repair degraded storage pool in DSM 7.2 or later - [Repair NVMe RAID 1 in internal M.2 slots](https://github.com/007revad/Synology_M2_volume/wiki/Repair-M.2-RAID-1-in-internal-M.2-slots) - [Repair NVMe RAID 1 in adaptor card](https://github.com/007revad/Synology_M2_volume/wiki/Repair-M.2-RAID-1-in-adaptor-card) - Upgrade to larger NVMe drives in DSM 7.2 or later - [Replace M.2 RAID 1 with larger drives](https://github.com/007revad/Synology_M2_volume/wiki/Replace-M.2-RAID-1-with-larger-drives) - Repair via SSH for DSM 6 - [How Synology Support repairs RAID in DSM 6](https://github.com/007revad/Synology_M2_volume/wiki/Repair-RAID-via-SSH) ----- ### DSM 7 screen shots <p align="center">Create SHR Storage Pool</p> <p align="center"><img src="/images/create_shr_v2.png"></p> <p align="center">Create Volume</p> <p align="center"><img src="/images/create-volume1.png"></p> <p align="center">Volume description</p> <p align="center"><img src="/images/create-volume3.png"></p> <p align="center">Allocate volume capacity</p> <p align="center"><img src="/images/create-volume2.png"></p> <p align="center">Select file system</p> <p align="center"><img src="/images/create-volume4.png"></p> <p align="center">Success!</p> <p align="center"><img src="/images/create-volume5.png"></p> <p align="center">Enable TRIM</p> <p align="center"><img src="/images/create_m2_volume_enable_trim.png"></p>
13,470
README
md
en
markdown
text
{"qsc_doc_frac_chars_curly_bracket": 0.0, "qsc_doc_frac_words_redpajama_stop": 0.10965978, "qsc_doc_num_sentences": 286.0, "qsc_doc_num_words": 2008, "qsc_doc_num_chars": 13470.0, "qsc_doc_num_lines": 252.0, "qsc_doc_mean_word_length": 3.90039841, "qsc_doc_frac_words_full_bracket": 0.0, "qsc_doc_frac_lines_end_with_readmore": 0.0, "qsc_doc_frac_lines_start_with_bullet": 0.0, "qsc_doc_frac_words_unique": 0.18177291, "qsc_doc_entropy_unigram": 4.87153761, "qsc_doc_frac_words_all_caps": 0.09082625, "qsc_doc_frac_lines_dupe_lines": 0.04784689, "qsc_doc_frac_chars_dupe_lines": 0.00381272, "qsc_doc_frac_chars_top_2grams": 0.05209397, "qsc_doc_frac_chars_top_3grams": 0.05171093, "qsc_doc_frac_chars_top_4grams": 0.02298264, "qsc_doc_frac_chars_dupe_5grams": 0.49272217, "qsc_doc_frac_chars_dupe_6grams": 0.45939734, "qsc_doc_frac_chars_dupe_7grams": 0.4023238, "qsc_doc_frac_chars_dupe_8grams": 0.24885087, "qsc_doc_frac_chars_dupe_9grams": 0.18705312, "qsc_doc_frac_chars_dupe_10grams": 0.17070991, "qsc_doc_frac_chars_replacement_symbols": 0.0, "qsc_doc_cate_code_related_file_name": 1.0, "qsc_doc_num_chars_sentence_length_mean": 23.9462963, "qsc_doc_frac_chars_hyperlink_html_tag": 0.17720861, "qsc_doc_frac_chars_alphabet": 0.66618512, "qsc_doc_frac_chars_digital": 0.14198741, "qsc_doc_frac_chars_whitespace": 0.28054937, "qsc_doc_frac_chars_hex_words": 0.0}
1
{"qsc_doc_frac_chars_replacement_symbols": 0, "qsc_doc_entropy_unigram": 0, "qsc_doc_frac_chars_top_2grams": 0, "qsc_doc_frac_chars_top_3grams": 0, "qsc_doc_frac_chars_top_4grams": 0, "qsc_doc_frac_chars_dupe_5grams": 0, "qsc_doc_frac_chars_dupe_6grams": 0, "qsc_doc_frac_chars_dupe_7grams": 0, "qsc_doc_frac_chars_dupe_8grams": 0, "qsc_doc_frac_chars_dupe_9grams": 0, "qsc_doc_frac_chars_dupe_10grams": 0, "qsc_doc_frac_chars_dupe_lines": 0, "qsc_doc_frac_lines_dupe_lines": 0, "qsc_doc_frac_lines_end_with_readmore": 0, "qsc_doc_frac_lines_start_with_bullet": 0, "qsc_doc_frac_words_all_caps": 0, "qsc_doc_mean_word_length": 0, "qsc_doc_num_chars": 0, "qsc_doc_num_lines": 0, "qsc_doc_num_sentences": 0, "qsc_doc_num_words": 0, "qsc_doc_frac_chars_hex_words": 0, "qsc_doc_frac_chars_hyperlink_html_tag": 0, "qsc_doc_frac_chars_alphabet": 0, "qsc_doc_frac_chars_digital": 0, "qsc_doc_frac_chars_whitespace": 0}
0015/ESP32-OpenCV-Projects
README.md
# ESP32 OpenCV Projects Running OpenCV on ESP32 as a standalone ## Introduction This project is based on joachimBurket/esp32-opencv(https://github.com/joachimBurket/esp32-opencv) Based on what he worked on, I try to not only upgrade all components but also make an OpenCV application for ESP32. ## How to make a build environment First of all, the ESP-IDF development environment should be ready in advance. [Tutorials for the ESP-IDF Visual Studio Code Extension](https://github.com/espressif/vscode-esp-idf-extension/blob/master/docs/tutorial/toc.md) [Running OpenCV on ESP32 (The first thing to be done)](https://youtu.be/7qPIRBY6C8c) [![Foo](https://i.ytimg.com/vi/7qPIRBY6C8c/hqdefault.jpg)](https://youtu.be/7qPIRBY6C8c) ## OpenCV Applications for ESP32 It's RGB Pixel Detector & drawing Histogram. In the image obtained from the camera, the center RGB pixel information is displayed, and the histogram of the entire image is displayed. [RGB Pixel Detector & Histogram](https://youtu.be/DNQuCkPtzYA) [![Foo](https://github.com/0015/ESP32-OpenCV-Projects/blob/main/esp32/examples/color_code/demo/demo.gif)](https://youtu.be/DNQuCkPtzYA) ### Created & Maintained By [Eric Nam](https://github.com/0015) ([Youtube](https://youtube.com/ThatProject)) ([Facebook](https://www.facebook.com/groups/138965931539175))] ### MIT License Copyright (c) 2022 Eric Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
2,393
README
md
en
markdown
text
{"qsc_doc_frac_chars_curly_bracket": 0.0, "qsc_doc_frac_words_redpajama_stop": 0.20077973, "qsc_doc_num_sentences": 25.0, "qsc_doc_num_words": 369, "qsc_doc_num_chars": 2393.0, "qsc_doc_num_lines": 53.0, "qsc_doc_mean_word_length": 5.08672087, "qsc_doc_frac_words_full_bracket": 0.0, "qsc_doc_frac_lines_end_with_readmore": 0.0, "qsc_doc_frac_lines_start_with_bullet": 0.0, "qsc_doc_frac_words_unique": 0.49864499, "qsc_doc_entropy_unigram": 4.80747533, "qsc_doc_frac_words_all_caps": 0.17738791, "qsc_doc_frac_lines_dupe_lines": 0.0, "qsc_doc_frac_chars_dupe_lines": 0.0, "qsc_doc_frac_chars_top_2grams": 0.04688332, "qsc_doc_frac_chars_top_3grams": 0.02983484, "qsc_doc_frac_chars_top_4grams": 0.0213106, "qsc_doc_frac_chars_dupe_5grams": 0.0, "qsc_doc_frac_chars_dupe_6grams": 0.0, "qsc_doc_frac_chars_dupe_7grams": 0.0, "qsc_doc_frac_chars_dupe_8grams": 0.0, "qsc_doc_frac_chars_dupe_9grams": 0.0, "qsc_doc_frac_chars_dupe_10grams": 0.0, "qsc_doc_frac_chars_replacement_symbols": 0.0, "qsc_doc_cate_code_related_file_name": 1.0, "qsc_doc_num_chars_sentence_length_mean": 29.69230769, "qsc_doc_frac_chars_hyperlink_html_tag": 0.21437526, "qsc_doc_frac_chars_alphabet": 0.87770823, "qsc_doc_frac_chars_digital": 0.02599904, "qsc_doc_frac_chars_whitespace": 0.13205182, "qsc_doc_frac_chars_hex_words": 0.0}
1
{"qsc_doc_frac_chars_replacement_symbols": 0, "qsc_doc_entropy_unigram": 0, "qsc_doc_frac_chars_top_2grams": 0, "qsc_doc_frac_chars_top_3grams": 0, "qsc_doc_frac_chars_top_4grams": 0, "qsc_doc_frac_chars_dupe_5grams": 0, "qsc_doc_frac_chars_dupe_6grams": 0, "qsc_doc_frac_chars_dupe_7grams": 0, "qsc_doc_frac_chars_dupe_8grams": 0, "qsc_doc_frac_chars_dupe_9grams": 0, "qsc_doc_frac_chars_dupe_10grams": 0, "qsc_doc_frac_chars_dupe_lines": 0, "qsc_doc_frac_lines_dupe_lines": 0, "qsc_doc_frac_lines_end_with_readmore": 0, "qsc_doc_frac_lines_start_with_bullet": 0, "qsc_doc_frac_words_all_caps": 0, "qsc_doc_mean_word_length": 0, "qsc_doc_num_chars": 0, "qsc_doc_num_lines": 0, "qsc_doc_num_sentences": 0, "qsc_doc_num_words": 0, "qsc_doc_frac_chars_hex_words": 0, "qsc_doc_frac_chars_hyperlink_html_tag": 0, "qsc_doc_frac_chars_alphabet": 0, "qsc_doc_frac_chars_digital": 0, "qsc_doc_frac_chars_whitespace": 0}
0015/ESP32-OpenCV-Projects
esp32/examples/color_code/sdkconfig
# # Automatically generated file. DO NOT EDIT. # Espressif IoT Development Framework (ESP-IDF) Project Configuration # CONFIG_IDF_CMAKE=y CONFIG_IDF_TARGET="esp32" CONFIG_IDF_TARGET_ESP32=y CONFIG_IDF_FIRMWARE_CHIP_ID=0x0000 # # SDK tool configuration # CONFIG_SDK_TOOLPREFIX="xtensa-esp32-elf-" # CONFIG_SDK_TOOLCHAIN_SUPPORTS_TIME_WIDE_64_BITS is not set # end of SDK tool configuration # # Build type # CONFIG_APP_BUILD_TYPE_APP_2NDBOOT=y # CONFIG_APP_BUILD_TYPE_ELF_RAM is not set CONFIG_APP_BUILD_GENERATE_BINARIES=y CONFIG_APP_BUILD_BOOTLOADER=y CONFIG_APP_BUILD_USE_FLASH_SECTIONS=y # end of Build type # # Application manager # CONFIG_APP_COMPILE_TIME_DATE=y # CONFIG_APP_EXCLUDE_PROJECT_VER_VAR is not set # CONFIG_APP_EXCLUDE_PROJECT_NAME_VAR is not set # CONFIG_APP_PROJECT_VER_FROM_CONFIG is not set CONFIG_APP_RETRIEVE_LEN_ELF_SHA=16 # end of Application manager # # Bootloader config # CONFIG_BOOTLOADER_COMPILER_OPTIMIZATION_SIZE=y # CONFIG_BOOTLOADER_COMPILER_OPTIMIZATION_DEBUG is not set # CONFIG_BOOTLOADER_COMPILER_OPTIMIZATION_PERF is not set # CONFIG_BOOTLOADER_COMPILER_OPTIMIZATION_NONE is not set # CONFIG_BOOTLOADER_LOG_LEVEL_NONE is not set # CONFIG_BOOTLOADER_LOG_LEVEL_ERROR is not set # CONFIG_BOOTLOADER_LOG_LEVEL_WARN is not set CONFIG_BOOTLOADER_LOG_LEVEL_INFO=y # CONFIG_BOOTLOADER_LOG_LEVEL_DEBUG is not set # CONFIG_BOOTLOADER_LOG_LEVEL_VERBOSE is not set CONFIG_BOOTLOADER_LOG_LEVEL=3 # CONFIG_BOOTLOADER_SPI_CUSTOM_WP_PIN is not set CONFIG_BOOTLOADER_SPI_WP_PIN=7 CONFIG_BOOTLOADER_VDDSDIO_BOOST_1_9V=y # CONFIG_BOOTLOADER_FACTORY_RESET is not set # CONFIG_BOOTLOADER_APP_TEST is not set CONFIG_BOOTLOADER_WDT_ENABLE=y # CONFIG_BOOTLOADER_WDT_DISABLE_IN_USER_CODE is not set CONFIG_BOOTLOADER_WDT_TIME_MS=9000 # CONFIG_BOOTLOADER_APP_ROLLBACK_ENABLE is not set # CONFIG_BOOTLOADER_SKIP_VALIDATE_IN_DEEP_SLEEP is not set CONFIG_BOOTLOADER_RESERVE_RTC_SIZE=0 # CONFIG_BOOTLOADER_CUSTOM_RESERVE_RTC is not set # end of Bootloader config # # Security features # # CONFIG_SECURE_SIGNED_APPS_NO_SECURE_BOOT is not set # CONFIG_SECURE_BOOT is not set # CONFIG_SECURE_FLASH_ENC_ENABLED is not set # end of Security features # # Serial flasher config # CONFIG_ESPTOOLPY_BAUD_OTHER_VAL=115200 CONFIG_ESPTOOLPY_WITH_STUB=y CONFIG_ESPTOOLPY_FLASHMODE_QIO=y # CONFIG_ESPTOOLPY_FLASHMODE_QOUT is not set # CONFIG_ESPTOOLPY_FLASHMODE_DIO is not set # CONFIG_ESPTOOLPY_FLASHMODE_DOUT is not set CONFIG_ESPTOOLPY_FLASHMODE="dio" CONFIG_ESPTOOLPY_FLASHFREQ_80M=y # CONFIG_ESPTOOLPY_FLASHFREQ_40M is not set # CONFIG_ESPTOOLPY_FLASHFREQ_26M is not set # CONFIG_ESPTOOLPY_FLASHFREQ_20M is not set CONFIG_ESPTOOLPY_FLASHFREQ="80m" # CONFIG_ESPTOOLPY_FLASHSIZE_1MB is not set # CONFIG_ESPTOOLPY_FLASHSIZE_2MB is not set CONFIG_ESPTOOLPY_FLASHSIZE_4MB=y # CONFIG_ESPTOOLPY_FLASHSIZE_8MB is not set # CONFIG_ESPTOOLPY_FLASHSIZE_16MB is not set CONFIG_ESPTOOLPY_FLASHSIZE="4MB" CONFIG_ESPTOOLPY_FLASHSIZE_DETECT=y CONFIG_ESPTOOLPY_BEFORE_RESET=y # CONFIG_ESPTOOLPY_BEFORE_NORESET is not set CONFIG_ESPTOOLPY_BEFORE="default_reset" CONFIG_ESPTOOLPY_AFTER_RESET=y # CONFIG_ESPTOOLPY_AFTER_NORESET is not set CONFIG_ESPTOOLPY_AFTER="hard_reset" # CONFIG_ESPTOOLPY_MONITOR_BAUD_9600B is not set # CONFIG_ESPTOOLPY_MONITOR_BAUD_57600B is not set CONFIG_ESPTOOLPY_MONITOR_BAUD_115200B=y # CONFIG_ESPTOOLPY_MONITOR_BAUD_230400B is not set # CONFIG_ESPTOOLPY_MONITOR_BAUD_921600B is not set # CONFIG_ESPTOOLPY_MONITOR_BAUD_2MB is not set # CONFIG_ESPTOOLPY_MONITOR_BAUD_OTHER is not set CONFIG_ESPTOOLPY_MONITOR_BAUD_OTHER_VAL=115200 CONFIG_ESPTOOLPY_MONITOR_BAUD=115200 # end of Serial flasher config # # Partition Table # # CONFIG_PARTITION_TABLE_SINGLE_APP is not set # CONFIG_PARTITION_TABLE_TWO_OTA is not set CONFIG_PARTITION_TABLE_CUSTOM=y CONFIG_PARTITION_TABLE_CUSTOM_FILENAME="partitions.csv" CONFIG_PARTITION_TABLE_FILENAME="partitions.csv" CONFIG_PARTITION_TABLE_OFFSET=0x8000 CONFIG_PARTITION_TABLE_MD5=y # end of Partition Table # # Compiler options # CONFIG_COMPILER_OPTIMIZATION_DEFAULT=y # CONFIG_COMPILER_OPTIMIZATION_SIZE is not set # CONFIG_COMPILER_OPTIMIZATION_PERF is not set # CONFIG_COMPILER_OPTIMIZATION_NONE is not set CONFIG_COMPILER_OPTIMIZATION_ASSERTIONS_ENABLE=y # CONFIG_COMPILER_OPTIMIZATION_ASSERTIONS_SILENT is not set # CONFIG_COMPILER_OPTIMIZATION_ASSERTIONS_DISABLE is not set CONFIG_COMPILER_CXX_EXCEPTIONS=y CONFIG_COMPILER_CXX_EXCEPTIONS_EMG_POOL_SIZE=512 # CONFIG_COMPILER_CXX_RTTI is not set CONFIG_COMPILER_STACK_CHECK_MODE_NONE=y # CONFIG_COMPILER_STACK_CHECK_MODE_NORM is not set # CONFIG_COMPILER_STACK_CHECK_MODE_STRONG is not set # CONFIG_COMPILER_STACK_CHECK_MODE_ALL is not set # CONFIG_COMPILER_WARN_WRITE_STRINGS is not set # CONFIG_COMPILER_DISABLE_GCC8_WARNINGS is not set # end of Compiler options # # Component config # # # Application Level Tracing # # CONFIG_APPTRACE_DEST_TRAX is not set CONFIG_APPTRACE_DEST_NONE=y CONFIG_APPTRACE_LOCK_ENABLE=y # end of Application Level Tracing # # Bluetooth # # CONFIG_BT_ENABLED is not set CONFIG_BTDM_CTRL_BR_EDR_SCO_DATA_PATH_EFF=0 CONFIG_BTDM_CTRL_PCM_ROLE_EFF=0 CONFIG_BTDM_CTRL_PCM_POLAR_EFF=0 CONFIG_BTDM_CTRL_BLE_MAX_CONN_EFF=0 CONFIG_BTDM_CTRL_BR_EDR_MAX_ACL_CONN_EFF=0 CONFIG_BTDM_CTRL_BR_EDR_MAX_SYNC_CONN_EFF=0 CONFIG_BTDM_CTRL_PINNED_TO_CORE=0 CONFIG_BTDM_BLE_SLEEP_CLOCK_ACCURACY_INDEX_EFF=1 CONFIG_BT_RESERVE_DRAM=0 # end of Bluetooth # # CoAP Configuration # CONFIG_COAP_MBEDTLS_PSK=y # CONFIG_COAP_MBEDTLS_PKI is not set # CONFIG_COAP_MBEDTLS_DEBUG is not set CONFIG_COAP_LOG_DEFAULT_LEVEL=0 # end of CoAP Configuration # # Driver configurations # # # ADC configuration # # CONFIG_ADC_FORCE_XPD_FSM is not set CONFIG_ADC_DISABLE_DAC=y # end of ADC configuration # # SPI configuration # # CONFIG_SPI_MASTER_IN_IRAM is not set CONFIG_SPI_MASTER_ISR_IN_IRAM=y # CONFIG_SPI_SLAVE_IN_IRAM is not set CONFIG_SPI_SLAVE_ISR_IN_IRAM=y # end of SPI configuration # # TWAI configuration # # CONFIG_TWAI_ISR_IN_IRAM is not set # end of TWAI configuration # # UART configuration # # CONFIG_UART_ISR_IN_IRAM is not set # end of UART configuration # # RTCIO configuration # CONFIG_RTCIO_SUPPORT_RTC_GPIO_DESC=y # end of RTCIO configuration # end of Driver configurations # # eFuse Bit Manager # # CONFIG_EFUSE_CUSTOM_TABLE is not set # CONFIG_EFUSE_VIRTUAL is not set # CONFIG_EFUSE_CODE_SCHEME_COMPAT_NONE is not set CONFIG_EFUSE_CODE_SCHEME_COMPAT_3_4=y # CONFIG_EFUSE_CODE_SCHEME_COMPAT_REPEAT is not set CONFIG_EFUSE_MAX_BLK_LEN=192 # end of eFuse Bit Manager # # ESP-TLS # CONFIG_ESP_TLS_USING_MBEDTLS=y # CONFIG_ESP_TLS_USE_SECURE_ELEMENT is not set # CONFIG_ESP_TLS_SERVER is not set # CONFIG_ESP_TLS_PSK_VERIFICATION is not set # end of ESP-TLS # # ESP32-specific # CONFIG_ESP32_ECO3_CACHE_LOCK_FIX=y CONFIG_ESP32_REV_MIN_0=y # CONFIG_ESP32_REV_MIN_1 is not set # CONFIG_ESP32_REV_MIN_2 is not set # CONFIG_ESP32_REV_MIN_3 is not set CONFIG_ESP32_REV_MIN=0 CONFIG_ESP32_DPORT_WORKAROUND=y # CONFIG_ESP32_DEFAULT_CPU_FREQ_80 is not set # CONFIG_ESP32_DEFAULT_CPU_FREQ_160 is not set CONFIG_ESP32_DEFAULT_CPU_FREQ_240=y CONFIG_ESP32_DEFAULT_CPU_FREQ_MHZ=240 CONFIG_ESP32_SPIRAM_SUPPORT=y # # SPI RAM config # CONFIG_SPIRAM_TYPE_AUTO=y # CONFIG_SPIRAM_TYPE_ESPPSRAM16 is not set # CONFIG_SPIRAM_TYPE_ESPPSRAM32 is not set # CONFIG_SPIRAM_TYPE_ESPPSRAM64 is not set CONFIG_SPIRAM_SIZE=-1 # CONFIG_SPIRAM_SPEED_40M is not set CONFIG_SPIRAM_SPEED_80M=y CONFIG_SPIRAM=y CONFIG_SPIRAM_BOOT_INIT=y # CONFIG_SPIRAM_USE_MEMMAP is not set # CONFIG_SPIRAM_USE_CAPS_ALLOC is not set CONFIG_SPIRAM_USE_MALLOC=y CONFIG_SPIRAM_MEMTEST=y CONFIG_SPIRAM_MALLOC_ALWAYSINTERNAL=16384 CONFIG_SPIRAM_TRY_ALLOCATE_WIFI_LWIP=y CONFIG_SPIRAM_MALLOC_RESERVE_INTERNAL=32768 CONFIG_SPIRAM_ALLOW_BSS_SEG_EXTERNAL_MEMORY=y CONFIG_SPIRAM_CACHE_WORKAROUND=y # # SPIRAM cache workaround debugging # CONFIG_SPIRAM_CACHE_WORKAROUND_STRATEGY_MEMW=y # CONFIG_SPIRAM_CACHE_WORKAROUND_STRATEGY_DUPLDST is not set # CONFIG_SPIRAM_CACHE_WORKAROUND_STRATEGY_NOPS is not set # end of SPIRAM cache workaround debugging CONFIG_SPIRAM_BANKSWITCH_ENABLE=y CONFIG_SPIRAM_BANKSWITCH_RESERVE=8 # CONFIG_SPIRAM_ALLOW_STACK_EXTERNAL_MEMORY is not set # CONFIG_SPIRAM_OCCUPY_HSPI_HOST is not set CONFIG_SPIRAM_OCCUPY_VSPI_HOST=y # CONFIG_SPIRAM_OCCUPY_NO_HOST is not set # # PSRAM clock and cs IO for ESP32-DOWD # CONFIG_D0WD_PSRAM_CLK_IO=17 CONFIG_D0WD_PSRAM_CS_IO=16 # end of PSRAM clock and cs IO for ESP32-DOWD # # PSRAM clock and cs IO for ESP32-D2WD # CONFIG_D2WD_PSRAM_CLK_IO=9 CONFIG_D2WD_PSRAM_CS_IO=10 # end of PSRAM clock and cs IO for ESP32-D2WD # # PSRAM clock and cs IO for ESP32-PICO # CONFIG_PICO_PSRAM_CS_IO=10 # end of PSRAM clock and cs IO for ESP32-PICO # CONFIG_SPIRAM_2T_MODE is not set # end of SPI RAM config # CONFIG_ESP32_TRAX is not set CONFIG_ESP32_TRACEMEM_RESERVE_DRAM=0x0 # CONFIG_ESP32_UNIVERSAL_MAC_ADDRESSES_TWO is not set CONFIG_ESP32_UNIVERSAL_MAC_ADDRESSES_FOUR=y CONFIG_ESP32_UNIVERSAL_MAC_ADDRESSES=4 # CONFIG_ESP32_ULP_COPROC_ENABLED is not set CONFIG_ESP32_ULP_COPROC_RESERVE_MEM=0 CONFIG_ESP32_DEBUG_OCDAWARE=y CONFIG_ESP32_BROWNOUT_DET=y CONFIG_ESP32_BROWNOUT_DET_LVL_SEL_0=y # CONFIG_ESP32_BROWNOUT_DET_LVL_SEL_1 is not set # CONFIG_ESP32_BROWNOUT_DET_LVL_SEL_2 is not set # CONFIG_ESP32_BROWNOUT_DET_LVL_SEL_3 is not set # CONFIG_ESP32_BROWNOUT_DET_LVL_SEL_4 is not set # CONFIG_ESP32_BROWNOUT_DET_LVL_SEL_5 is not set # CONFIG_ESP32_BROWNOUT_DET_LVL_SEL_6 is not set # CONFIG_ESP32_BROWNOUT_DET_LVL_SEL_7 is not set CONFIG_ESP32_BROWNOUT_DET_LVL=0 CONFIG_ESP32_REDUCE_PHY_TX_POWER=y CONFIG_ESP32_TIME_SYSCALL_USE_RTC_FRC1=y # CONFIG_ESP32_TIME_SYSCALL_USE_RTC is not set # CONFIG_ESP32_TIME_SYSCALL_USE_FRC1 is not set # CONFIG_ESP32_TIME_SYSCALL_USE_NONE is not set CONFIG_ESP32_RTC_CLK_SRC_INT_RC=y # CONFIG_ESP32_RTC_CLK_SRC_EXT_CRYS is not set # CONFIG_ESP32_RTC_CLK_SRC_EXT_OSC is not set # CONFIG_ESP32_RTC_CLK_SRC_INT_8MD256 is not set CONFIG_ESP32_RTC_CLK_CAL_CYCLES=1024 CONFIG_ESP32_DEEP_SLEEP_WAKEUP_DELAY=2000 CONFIG_ESP32_XTAL_FREQ_40=y # CONFIG_ESP32_XTAL_FREQ_26 is not set # CONFIG_ESP32_XTAL_FREQ_AUTO is not set CONFIG_ESP32_XTAL_FREQ=40 # CONFIG_ESP32_DISABLE_BASIC_ROM_CONSOLE is not set # CONFIG_ESP32_NO_BLOBS is not set # CONFIG_ESP32_COMPATIBLE_PRE_V2_1_BOOTLOADERS is not set # CONFIG_ESP32_COMPATIBLE_PRE_V3_1_BOOTLOADERS is not set # CONFIG_ESP32_USE_FIXED_STATIC_RAM_SIZE is not set CONFIG_ESP32_DPORT_DIS_INTERRUPT_LVL=5 # end of ESP32-specific # # Power Management # # CONFIG_PM_ENABLE is not set # end of Power Management # # ADC-Calibration # CONFIG_ADC_CAL_EFUSE_TP_ENABLE=y CONFIG_ADC_CAL_EFUSE_VREF_ENABLE=y CONFIG_ADC_CAL_LUT_ENABLE=y # end of ADC-Calibration # # Common ESP-related # CONFIG_ESP_ERR_TO_NAME_LOOKUP=y CONFIG_ESP_SYSTEM_EVENT_QUEUE_SIZE=32 CONFIG_ESP_SYSTEM_EVENT_TASK_STACK_SIZE=2304 CONFIG_ESP_MAIN_TASK_STACK_SIZE=3584 CONFIG_ESP_IPC_TASK_STACK_SIZE=1024 CONFIG_ESP_IPC_USES_CALLERS_PRIORITY=y CONFIG_ESP_MINIMAL_SHARED_STACK_SIZE=2048 CONFIG_ESP_CONSOLE_UART_DEFAULT=y # CONFIG_ESP_CONSOLE_UART_CUSTOM is not set # CONFIG_ESP_CONSOLE_UART_NONE is not set CONFIG_ESP_CONSOLE_UART_NUM=0 CONFIG_ESP_CONSOLE_UART_TX_GPIO=1 CONFIG_ESP_CONSOLE_UART_RX_GPIO=3 CONFIG_ESP_CONSOLE_UART_BAUDRATE=115200 CONFIG_ESP_INT_WDT=y CONFIG_ESP_INT_WDT_TIMEOUT_MS=800 CONFIG_ESP_INT_WDT_CHECK_CPU1=y # CONFIG_ESP_TASK_WDT is not set # CONFIG_ESP_PANIC_HANDLER_IRAM is not set CONFIG_ESP_MAC_ADDR_UNIVERSE_WIFI_STA=y CONFIG_ESP_MAC_ADDR_UNIVERSE_WIFI_AP=y CONFIG_ESP_MAC_ADDR_UNIVERSE_BT=y CONFIG_ESP_MAC_ADDR_UNIVERSE_BT_OFFSET=2 CONFIG_ESP_MAC_ADDR_UNIVERSE_ETH=y # end of Common ESP-related # # Ethernet # CONFIG_ETH_ENABLED=y CONFIG_ETH_USE_ESP32_EMAC=y CONFIG_ETH_PHY_INTERFACE_RMII=y # CONFIG_ETH_PHY_INTERFACE_MII is not set CONFIG_ETH_RMII_CLK_INPUT=y # CONFIG_ETH_RMII_CLK_OUTPUT is not set CONFIG_ETH_RMII_CLK_IN_GPIO=0 CONFIG_ETH_DMA_BUFFER_SIZE=512 CONFIG_ETH_DMA_RX_BUFFER_NUM=10 CONFIG_ETH_DMA_TX_BUFFER_NUM=10 CONFIG_ETH_USE_SPI_ETHERNET=y # CONFIG_ETH_SPI_ETHERNET_DM9051 is not set # CONFIG_ETH_USE_OPENETH is not set # end of Ethernet # # Event Loop Library # # CONFIG_ESP_EVENT_LOOP_PROFILING is not set CONFIG_ESP_EVENT_POST_FROM_ISR=y CONFIG_ESP_EVENT_POST_FROM_IRAM_ISR=y # end of Event Loop Library # # GDB Stub # # end of GDB Stub # # ESP HTTP client # CONFIG_ESP_HTTP_CLIENT_ENABLE_HTTPS=y # CONFIG_ESP_HTTP_CLIENT_ENABLE_BASIC_AUTH is not set # end of ESP HTTP client # # HTTP Server # CONFIG_HTTPD_MAX_REQ_HDR_LEN=512 CONFIG_HTTPD_MAX_URI_LEN=512 CONFIG_HTTPD_ERR_RESP_NO_DELAY=y CONFIG_HTTPD_PURGE_BUF_LEN=32 # CONFIG_HTTPD_LOG_PURGE_DATA is not set # CONFIG_HTTPD_WS_SUPPORT is not set # end of HTTP Server # # ESP HTTPS OTA # # CONFIG_OTA_ALLOW_HTTP is not set # end of ESP HTTPS OTA # # ESP HTTPS server # # CONFIG_ESP_HTTPS_SERVER_ENABLE is not set # end of ESP HTTPS server # # ESP NETIF Adapter # CONFIG_ESP_NETIF_IP_LOST_TIMER_INTERVAL=120 CONFIG_ESP_NETIF_TCPIP_LWIP=y # CONFIG_ESP_NETIF_LOOPBACK is not set CONFIG_ESP_NETIF_TCPIP_ADAPTER_COMPATIBLE_LAYER=y # end of ESP NETIF Adapter # # ESP System Settings # # CONFIG_ESP_SYSTEM_PANIC_PRINT_HALT is not set CONFIG_ESP_SYSTEM_PANIC_PRINT_REBOOT=y # CONFIG_ESP_SYSTEM_PANIC_SILENT_REBOOT is not set # CONFIG_ESP_SYSTEM_PANIC_GDBSTUB is not set # end of ESP System Settings # # High resolution timer (esp_timer) # # CONFIG_ESP_TIMER_PROFILING is not set CONFIG_ESP_TIMER_TASK_STACK_SIZE=3584 # CONFIG_ESP_TIMER_IMPL_FRC2 is not set CONFIG_ESP_TIMER_IMPL_TG0_LAC=y # end of High resolution timer (esp_timer) # # Wi-Fi # CONFIG_ESP32_WIFI_STATIC_RX_BUFFER_NUM=10 CONFIG_ESP32_WIFI_DYNAMIC_RX_BUFFER_NUM=32 CONFIG_ESP32_WIFI_STATIC_TX_BUFFER=y CONFIG_ESP32_WIFI_TX_BUFFER_TYPE=0 CONFIG_ESP32_WIFI_STATIC_TX_BUFFER_NUM=16 CONFIG_ESP32_WIFI_CACHE_TX_BUFFER_NUM=32 # CONFIG_ESP32_WIFI_CSI_ENABLED is not set CONFIG_ESP32_WIFI_AMPDU_TX_ENABLED=y CONFIG_ESP32_WIFI_TX_BA_WIN=6 CONFIG_ESP32_WIFI_AMPDU_RX_ENABLED=y CONFIG_ESP32_WIFI_RX_BA_WIN=16 CONFIG_ESP32_WIFI_NVS_ENABLED=y CONFIG_ESP32_WIFI_TASK_PINNED_TO_CORE_0=y # CONFIG_ESP32_WIFI_TASK_PINNED_TO_CORE_1 is not set CONFIG_ESP32_WIFI_SOFTAP_BEACON_MAX_LEN=752 CONFIG_ESP32_WIFI_MGMT_SBUF_NUM=32 # CONFIG_ESP32_WIFI_DEBUG_LOG_ENABLE is not set CONFIG_ESP32_WIFI_IRAM_OPT=y CONFIG_ESP32_WIFI_RX_IRAM_OPT=y # CONFIG_ESP32_WIFI_ENABLE_WPA3_SAE is not set # end of Wi-Fi # # PHY # CONFIG_ESP32_PHY_CALIBRATION_AND_DATA_STORAGE=y # CONFIG_ESP32_PHY_INIT_DATA_IN_PARTITION is not set CONFIG_ESP32_PHY_MAX_WIFI_TX_POWER=20 CONFIG_ESP32_PHY_MAX_TX_POWER=20 # end of PHY # # Core dump # # CONFIG_ESP32_ENABLE_COREDUMP_TO_FLASH is not set # CONFIG_ESP32_ENABLE_COREDUMP_TO_UART is not set CONFIG_ESP32_ENABLE_COREDUMP_TO_NONE=y # end of Core dump # # FAT Filesystem support # # CONFIG_FATFS_CODEPAGE_DYNAMIC is not set CONFIG_FATFS_CODEPAGE_437=y # CONFIG_FATFS_CODEPAGE_720 is not set # CONFIG_FATFS_CODEPAGE_737 is not set # CONFIG_FATFS_CODEPAGE_771 is not set # CONFIG_FATFS_CODEPAGE_775 is not set # CONFIG_FATFS_CODEPAGE_850 is not set # CONFIG_FATFS_CODEPAGE_852 is not set # CONFIG_FATFS_CODEPAGE_855 is not set # CONFIG_FATFS_CODEPAGE_857 is not set # CONFIG_FATFS_CODEPAGE_860 is not set # CONFIG_FATFS_CODEPAGE_861 is not set # CONFIG_FATFS_CODEPAGE_862 is not set # CONFIG_FATFS_CODEPAGE_863 is not set # CONFIG_FATFS_CODEPAGE_864 is not set # CONFIG_FATFS_CODEPAGE_865 is not set # CONFIG_FATFS_CODEPAGE_866 is not set # CONFIG_FATFS_CODEPAGE_869 is not set # CONFIG_FATFS_CODEPAGE_932 is not set # CONFIG_FATFS_CODEPAGE_936 is not set # CONFIG_FATFS_CODEPAGE_949 is not set # CONFIG_FATFS_CODEPAGE_950 is not set CONFIG_FATFS_CODEPAGE=437 CONFIG_FATFS_LFN_NONE=y # CONFIG_FATFS_LFN_HEAP is not set # CONFIG_FATFS_LFN_STACK is not set CONFIG_FATFS_FS_LOCK=0 CONFIG_FATFS_TIMEOUT_MS=10000 CONFIG_FATFS_PER_FILE_CACHE=y CONFIG_FATFS_ALLOC_PREFER_EXTRAM=y # end of FAT Filesystem support # # Modbus configuration # CONFIG_FMB_COMM_MODE_RTU_EN=y CONFIG_FMB_COMM_MODE_ASCII_EN=y CONFIG_FMB_MASTER_TIMEOUT_MS_RESPOND=150 CONFIG_FMB_MASTER_DELAY_MS_CONVERT=200 CONFIG_FMB_QUEUE_LENGTH=20 CONFIG_FMB_SERIAL_TASK_STACK_SIZE=2048 CONFIG_FMB_SERIAL_BUF_SIZE=256 CONFIG_FMB_SERIAL_ASCII_BITS_PER_SYMB=8 CONFIG_FMB_SERIAL_ASCII_TIMEOUT_RESPOND_MS=1000 CONFIG_FMB_SERIAL_TASK_PRIO=10 # CONFIG_FMB_PORT_TASK_AFFINITY_NO_AFFINITY is not set CONFIG_FMB_PORT_TASK_AFFINITY_CPU0=y # CONFIG_FMB_PORT_TASK_AFFINITY_CPU1 is not set CONFIG_FMB_PORT_TASK_AFFINITY=0x0 # CONFIG_FMB_CONTROLLER_SLAVE_ID_SUPPORT is not set CONFIG_FMB_CONTROLLER_NOTIFY_TIMEOUT=20 CONFIG_FMB_CONTROLLER_NOTIFY_QUEUE_SIZE=20 CONFIG_FMB_CONTROLLER_STACK_SIZE=4096 CONFIG_FMB_EVENT_QUEUE_TIMEOUT=20 CONFIG_FMB_TIMER_PORT_ENABLED=y CONFIG_FMB_TIMER_GROUP=0 CONFIG_FMB_TIMER_INDEX=0 # CONFIG_FMB_TIMER_ISR_IN_IRAM is not set # end of Modbus configuration # # FreeRTOS # # CONFIG_FREERTOS_UNICORE is not set CONFIG_FREERTOS_NO_AFFINITY=0x7FFFFFFF CONFIG_FREERTOS_CORETIMER_0=y # CONFIG_FREERTOS_CORETIMER_1 is not set CONFIG_FREERTOS_HZ=1000 CONFIG_FREERTOS_ASSERT_ON_UNTESTED_FUNCTION=y # CONFIG_FREERTOS_CHECK_STACKOVERFLOW_NONE is not set # CONFIG_FREERTOS_CHECK_STACKOVERFLOW_PTRVAL is not set CONFIG_FREERTOS_CHECK_STACKOVERFLOW_CANARY=y # CONFIG_FREERTOS_WATCHPOINT_END_OF_STACK is not set CONFIG_FREERTOS_INTERRUPT_BACKTRACE=y CONFIG_FREERTOS_THREAD_LOCAL_STORAGE_POINTERS=1 CONFIG_FREERTOS_ASSERT_FAIL_ABORT=y # CONFIG_FREERTOS_ASSERT_FAIL_PRINT_CONTINUE is not set # CONFIG_FREERTOS_ASSERT_DISABLE is not set CONFIG_FREERTOS_IDLE_TASK_STACKSIZE=1536 CONFIG_FREERTOS_ISR_STACKSIZE=1536 # CONFIG_FREERTOS_LEGACY_HOOKS is not set CONFIG_FREERTOS_MAX_TASK_NAME_LEN=16 CONFIG_FREERTOS_SUPPORT_STATIC_ALLOCATION=y # CONFIG_FREERTOS_ENABLE_STATIC_TASK_CLEAN_UP is not set CONFIG_FREERTOS_TIMER_TASK_PRIORITY=1 CONFIG_FREERTOS_TIMER_TASK_STACK_DEPTH=2048 CONFIG_FREERTOS_TIMER_QUEUE_LENGTH=10 CONFIG_FREERTOS_QUEUE_REGISTRY_SIZE=0 # CONFIG_FREERTOS_USE_TRACE_FACILITY is not set # CONFIG_FREERTOS_GENERATE_RUN_TIME_STATS is not set CONFIG_FREERTOS_TASK_FUNCTION_WRAPPER=y CONFIG_FREERTOS_CHECK_MUTEX_GIVEN_BY_OWNER=y # CONFIG_FREERTOS_CHECK_PORT_CRITICAL_COMPLIANCE is not set CONFIG_FREERTOS_DEBUG_OCDAWARE=y # CONFIG_FREERTOS_FPU_IN_ISR is not set # end of FreeRTOS # # Heap memory debugging # CONFIG_HEAP_POISONING_DISABLED=y # CONFIG_HEAP_POISONING_LIGHT is not set # CONFIG_HEAP_POISONING_COMPREHENSIVE is not set CONFIG_HEAP_TRACING_OFF=y # CONFIG_HEAP_TRACING_STANDALONE is not set # CONFIG_HEAP_TRACING_TOHOST is not set # CONFIG_HEAP_ABORT_WHEN_ALLOCATION_FAILS is not set # end of Heap memory debugging # # jsmn # # CONFIG_JSMN_PARENT_LINKS is not set # CONFIG_JSMN_STRICT is not set # end of jsmn # # libsodium # # end of libsodium # # Log output # # CONFIG_LOG_DEFAULT_LEVEL_NONE is not set # CONFIG_LOG_DEFAULT_LEVEL_ERROR is not set # CONFIG_LOG_DEFAULT_LEVEL_WARN is not set CONFIG_LOG_DEFAULT_LEVEL_INFO=y # CONFIG_LOG_DEFAULT_LEVEL_DEBUG is not set # CONFIG_LOG_DEFAULT_LEVEL_VERBOSE is not set CONFIG_LOG_DEFAULT_LEVEL=3 CONFIG_LOG_COLORS=y CONFIG_LOG_TIMESTAMP_SOURCE_RTOS=y # CONFIG_LOG_TIMESTAMP_SOURCE_SYSTEM is not set # end of Log output # # LWIP # CONFIG_LWIP_LOCAL_HOSTNAME="espressif" CONFIG_LWIP_DNS_SUPPORT_MDNS_QUERIES=y # CONFIG_LWIP_L2_TO_L3_COPY is not set # CONFIG_LWIP_IRAM_OPTIMIZATION is not set CONFIG_LWIP_TIMERS_ONDEMAND=y CONFIG_LWIP_MAX_SOCKETS=10 # CONFIG_LWIP_USE_ONLY_LWIP_SELECT is not set # CONFIG_LWIP_SO_LINGER is not set CONFIG_LWIP_SO_REUSE=y CONFIG_LWIP_SO_REUSE_RXTOALL=y # CONFIG_LWIP_SO_RCVBUF is not set # CONFIG_LWIP_NETBUF_RECVINFO is not set CONFIG_LWIP_IP4_FRAG=y CONFIG_LWIP_IP6_FRAG=y # CONFIG_LWIP_IP4_REASSEMBLY is not set # CONFIG_LWIP_IP6_REASSEMBLY is not set # CONFIG_LWIP_IP_FORWARD is not set # CONFIG_LWIP_STATS is not set # CONFIG_LWIP_ETHARP_TRUST_IP_MAC is not set CONFIG_LWIP_ESP_GRATUITOUS_ARP=y CONFIG_LWIP_GARP_TMR_INTERVAL=60 CONFIG_LWIP_TCPIP_RECVMBOX_SIZE=32 CONFIG_LWIP_DHCP_DOES_ARP_CHECK=y # CONFIG_LWIP_DHCP_DISABLE_CLIENT_ID is not set # CONFIG_LWIP_DHCP_RESTORE_LAST_IP is not set # # DHCP server # CONFIG_LWIP_DHCPS_LEASE_UNIT=60 CONFIG_LWIP_DHCPS_MAX_STATION_NUM=8 # end of DHCP server # CONFIG_LWIP_AUTOIP is not set # CONFIG_LWIP_IPV6_AUTOCONFIG is not set CONFIG_LWIP_NETIF_LOOPBACK=y CONFIG_LWIP_LOOPBACK_MAX_PBUFS=8 # # TCP # CONFIG_LWIP_TCP_ISN_HOOK=y CONFIG_LWIP_MAX_ACTIVE_TCP=16 CONFIG_LWIP_MAX_LISTENING_TCP=16 CONFIG_LWIP_TCP_HIGH_SPEED_RETRANSMISSION=y CONFIG_LWIP_TCP_MAXRTX=12 CONFIG_LWIP_TCP_SYNMAXRTX=6 CONFIG_LWIP_TCP_MSS=1436 CONFIG_LWIP_TCP_TMR_INTERVAL=250 CONFIG_LWIP_TCP_MSL=60000 CONFIG_LWIP_TCP_SND_BUF_DEFAULT=5744 CONFIG_LWIP_TCP_WND_DEFAULT=5744 CONFIG_LWIP_TCP_RECVMBOX_SIZE=6 CONFIG_LWIP_TCP_QUEUE_OOSEQ=y # CONFIG_LWIP_TCP_SACK_OUT is not set # CONFIG_LWIP_TCP_KEEP_CONNECTION_WHEN_IP_CHANGES is not set CONFIG_LWIP_TCP_OVERSIZE_MSS=y # CONFIG_LWIP_TCP_OVERSIZE_QUARTER_MSS is not set # CONFIG_LWIP_TCP_OVERSIZE_DISABLE is not set # CONFIG_LWIP_WND_SCALE is not set CONFIG_LWIP_TCP_RTO_TIME=1500 # end of TCP # # UDP # CONFIG_LWIP_MAX_UDP_PCBS=16 CONFIG_LWIP_UDP_RECVMBOX_SIZE=6 # end of UDP CONFIG_LWIP_TCPIP_TASK_STACK_SIZE=3072 CONFIG_LWIP_TCPIP_TASK_AFFINITY_NO_AFFINITY=y # CONFIG_LWIP_TCPIP_TASK_AFFINITY_CPU0 is not set # CONFIG_LWIP_TCPIP_TASK_AFFINITY_CPU1 is not set CONFIG_LWIP_TCPIP_TASK_AFFINITY=0x7FFFFFFF # CONFIG_LWIP_PPP_SUPPORT is not set CONFIG_LWIP_IPV6_MEMP_NUM_ND6_QUEUE=3 CONFIG_LWIP_IPV6_ND6_NUM_NEIGHBORS=5 # # ICMP # # CONFIG_LWIP_MULTICAST_PING is not set # CONFIG_LWIP_BROADCAST_PING is not set # end of ICMP # # LWIP RAW API # CONFIG_LWIP_MAX_RAW_PCBS=16 # end of LWIP RAW API # # SNTP # CONFIG_LWIP_DHCP_MAX_NTP_SERVERS=1 CONFIG_LWIP_SNTP_UPDATE_DELAY=3600000 # end of SNTP CONFIG_LWIP_ESP_LWIP_ASSERT=y # end of LWIP # # mbedTLS # CONFIG_MBEDTLS_INTERNAL_MEM_ALLOC=y # CONFIG_MBEDTLS_EXTERNAL_MEM_ALLOC is not set # CONFIG_MBEDTLS_DEFAULT_MEM_ALLOC is not set # CONFIG_MBEDTLS_CUSTOM_MEM_ALLOC is not set CONFIG_MBEDTLS_ASYMMETRIC_CONTENT_LEN=y CONFIG_MBEDTLS_SSL_IN_CONTENT_LEN=16384 CONFIG_MBEDTLS_SSL_OUT_CONTENT_LEN=4096 # CONFIG_MBEDTLS_DYNAMIC_BUFFER is not set # CONFIG_MBEDTLS_DEBUG is not set # # Certificate Bundle # CONFIG_MBEDTLS_CERTIFICATE_BUNDLE=y CONFIG_MBEDTLS_CERTIFICATE_BUNDLE_DEFAULT_FULL=y # CONFIG_MBEDTLS_CERTIFICATE_BUNDLE_DEFAULT_CMN is not set # CONFIG_MBEDTLS_CERTIFICATE_BUNDLE_DEFAULT_NONE is not set # CONFIG_MBEDTLS_CUSTOM_CERTIFICATE_BUNDLE is not set # end of Certificate Bundle # CONFIG_MBEDTLS_ECP_RESTARTABLE is not set # CONFIG_MBEDTLS_CMAC_C is not set CONFIG_MBEDTLS_HARDWARE_AES=y CONFIG_MBEDTLS_HARDWARE_MPI=y CONFIG_MBEDTLS_HARDWARE_SHA=y # CONFIG_MBEDTLS_ATCA_HW_ECDSA_SIGN is not set # CONFIG_MBEDTLS_ATCA_HW_ECDSA_VERIFY is not set CONFIG_MBEDTLS_HAVE_TIME=y # CONFIG_MBEDTLS_HAVE_TIME_DATE is not set CONFIG_MBEDTLS_ECDSA_DETERMINISTIC=y CONFIG_MBEDTLS_SHA512_C=y CONFIG_MBEDTLS_TLS_SERVER_AND_CLIENT=y # CONFIG_MBEDTLS_TLS_SERVER_ONLY is not set # CONFIG_MBEDTLS_TLS_CLIENT_ONLY is not set # CONFIG_MBEDTLS_TLS_DISABLED is not set CONFIG_MBEDTLS_TLS_SERVER=y CONFIG_MBEDTLS_TLS_CLIENT=y CONFIG_MBEDTLS_TLS_ENABLED=y # # TLS Key Exchange Methods # CONFIG_MBEDTLS_PSK_MODES=y CONFIG_MBEDTLS_KEY_EXCHANGE_PSK=y CONFIG_MBEDTLS_KEY_EXCHANGE_DHE_PSK=y CONFIG_MBEDTLS_KEY_EXCHANGE_ECDHE_PSK=y CONFIG_MBEDTLS_KEY_EXCHANGE_RSA_PSK=y CONFIG_MBEDTLS_KEY_EXCHANGE_RSA=y CONFIG_MBEDTLS_KEY_EXCHANGE_DHE_RSA=y CONFIG_MBEDTLS_KEY_EXCHANGE_ELLIPTIC_CURVE=y CONFIG_MBEDTLS_KEY_EXCHANGE_ECDHE_RSA=y CONFIG_MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA=y CONFIG_MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA=y CONFIG_MBEDTLS_KEY_EXCHANGE_ECDH_RSA=y # end of TLS Key Exchange Methods CONFIG_MBEDTLS_SSL_RENEGOTIATION=y # CONFIG_MBEDTLS_SSL_PROTO_SSL3 is not set CONFIG_MBEDTLS_SSL_PROTO_TLS1=y CONFIG_MBEDTLS_SSL_PROTO_TLS1_1=y CONFIG_MBEDTLS_SSL_PROTO_TLS1_2=y CONFIG_MBEDTLS_SSL_PROTO_DTLS=y CONFIG_MBEDTLS_SSL_ALPN=y CONFIG_MBEDTLS_CLIENT_SSL_SESSION_TICKETS=y CONFIG_MBEDTLS_SERVER_SSL_SESSION_TICKETS=y # # Symmetric Ciphers # CONFIG_MBEDTLS_AES_C=y # CONFIG_MBEDTLS_CAMELLIA_C is not set # CONFIG_MBEDTLS_DES_C is not set CONFIG_MBEDTLS_RC4_DISABLED=y # CONFIG_MBEDTLS_RC4_ENABLED_NO_DEFAULT is not set # CONFIG_MBEDTLS_RC4_ENABLED is not set # CONFIG_MBEDTLS_BLOWFISH_C is not set # CONFIG_MBEDTLS_XTEA_C is not set CONFIG_MBEDTLS_CCM_C=y CONFIG_MBEDTLS_GCM_C=y # end of Symmetric Ciphers # CONFIG_MBEDTLS_RIPEMD160_C is not set # # Certificates # CONFIG_MBEDTLS_PEM_PARSE_C=y CONFIG_MBEDTLS_PEM_WRITE_C=y CONFIG_MBEDTLS_X509_CRL_PARSE_C=y CONFIG_MBEDTLS_X509_CSR_PARSE_C=y # end of Certificates CONFIG_MBEDTLS_ECP_C=y CONFIG_MBEDTLS_ECDH_C=y CONFIG_MBEDTLS_ECDSA_C=y # CONFIG_MBEDTLS_ECJPAKE_C is not set CONFIG_MBEDTLS_ECP_DP_SECP192R1_ENABLED=y CONFIG_MBEDTLS_ECP_DP_SECP224R1_ENABLED=y CONFIG_MBEDTLS_ECP_DP_SECP256R1_ENABLED=y CONFIG_MBEDTLS_ECP_DP_SECP384R1_ENABLED=y CONFIG_MBEDTLS_ECP_DP_SECP521R1_ENABLED=y CONFIG_MBEDTLS_ECP_DP_SECP192K1_ENABLED=y CONFIG_MBEDTLS_ECP_DP_SECP224K1_ENABLED=y CONFIG_MBEDTLS_ECP_DP_SECP256K1_ENABLED=y CONFIG_MBEDTLS_ECP_DP_BP256R1_ENABLED=y CONFIG_MBEDTLS_ECP_DP_BP384R1_ENABLED=y CONFIG_MBEDTLS_ECP_DP_BP512R1_ENABLED=y CONFIG_MBEDTLS_ECP_DP_CURVE25519_ENABLED=y CONFIG_MBEDTLS_ECP_NIST_OPTIM=y # CONFIG_MBEDTLS_POLY1305_C is not set # CONFIG_MBEDTLS_CHACHA20_C is not set # CONFIG_MBEDTLS_HKDF_C is not set # CONFIG_MBEDTLS_THREADING_C is not set # CONFIG_MBEDTLS_SECURITY_RISKS is not set # end of mbedTLS # # mDNS # CONFIG_MDNS_MAX_SERVICES=10 CONFIG_MDNS_TASK_PRIORITY=1 CONFIG_MDNS_TASK_STACK_SIZE=4096 # CONFIG_MDNS_TASK_AFFINITY_NO_AFFINITY is not set CONFIG_MDNS_TASK_AFFINITY_CPU0=y # CONFIG_MDNS_TASK_AFFINITY_CPU1 is not set CONFIG_MDNS_TASK_AFFINITY=0x0 CONFIG_MDNS_SERVICE_ADD_TIMEOUT_MS=2000 # CONFIG_MDNS_STRICT_MODE is not set CONFIG_MDNS_TIMER_PERIOD_MS=100 # end of mDNS # # ESP-MQTT Configurations # CONFIG_MQTT_PROTOCOL_311=y CONFIG_MQTT_TRANSPORT_SSL=y CONFIG_MQTT_TRANSPORT_WEBSOCKET=y CONFIG_MQTT_TRANSPORT_WEBSOCKET_SECURE=y # CONFIG_MQTT_USE_CUSTOM_CONFIG is not set # CONFIG_MQTT_TASK_CORE_SELECTION_ENABLED is not set # CONFIG_MQTT_CUSTOM_OUTBOX is not set # end of ESP-MQTT Configurations # # Newlib # CONFIG_NEWLIB_STDOUT_LINE_ENDING_CRLF=y # CONFIG_NEWLIB_STDOUT_LINE_ENDING_LF is not set # CONFIG_NEWLIB_STDOUT_LINE_ENDING_CR is not set # CONFIG_NEWLIB_STDIN_LINE_ENDING_CRLF is not set # CONFIG_NEWLIB_STDIN_LINE_ENDING_LF is not set CONFIG_NEWLIB_STDIN_LINE_ENDING_CR=y # CONFIG_NEWLIB_NANO_FORMAT is not set # end of Newlib # # NVS # # end of NVS # # OpenSSL # # CONFIG_OPENSSL_DEBUG is not set CONFIG_OPENSSL_ASSERT_DO_NOTHING=y # CONFIG_OPENSSL_ASSERT_EXIT is not set # end of OpenSSL # # PThreads # CONFIG_PTHREAD_TASK_PRIO_DEFAULT=5 CONFIG_PTHREAD_TASK_STACK_SIZE_DEFAULT=3072 CONFIG_PTHREAD_STACK_MIN=768 CONFIG_PTHREAD_DEFAULT_CORE_NO_AFFINITY=y # CONFIG_PTHREAD_DEFAULT_CORE_0 is not set # CONFIG_PTHREAD_DEFAULT_CORE_1 is not set CONFIG_PTHREAD_TASK_CORE_DEFAULT=-1 CONFIG_PTHREAD_TASK_NAME_DEFAULT="pthread" # end of PThreads # # SPI Flash driver # # CONFIG_SPI_FLASH_VERIFY_WRITE is not set # CONFIG_SPI_FLASH_ENABLE_COUNTERS is not set CONFIG_SPI_FLASH_ROM_DRIVER_PATCH=y CONFIG_SPI_FLASH_DANGEROUS_WRITE_ABORTS=y # CONFIG_SPI_FLASH_DANGEROUS_WRITE_FAILS is not set # CONFIG_SPI_FLASH_DANGEROUS_WRITE_ALLOWED is not set # CONFIG_SPI_FLASH_USE_LEGACY_IMPL is not set # CONFIG_SPI_FLASH_SHARE_SPI1_BUS is not set # CONFIG_SPI_FLASH_BYPASS_BLOCK_ERASE is not set CONFIG_SPI_FLASH_YIELD_DURING_ERASE=y CONFIG_SPI_FLASH_ERASE_YIELD_DURATION_MS=20 CONFIG_SPI_FLASH_ERASE_YIELD_TICKS=1 # CONFIG_SPI_FLASH_SIZE_OVERRIDE is not set # # Auto-detect flash chips # CONFIG_SPI_FLASH_SUPPORT_ISSI_CHIP=y CONFIG_SPI_FLASH_SUPPORT_MXIC_CHIP=y CONFIG_SPI_FLASH_SUPPORT_GD_CHIP=y # end of Auto-detect flash chips CONFIG_SPI_FLASH_ENABLE_ENCRYPTED_READ_WRITE=y # end of SPI Flash driver # # SPIFFS Configuration # CONFIG_SPIFFS_MAX_PARTITIONS=3 # # SPIFFS Cache Configuration # CONFIG_SPIFFS_CACHE=y CONFIG_SPIFFS_CACHE_WR=y # CONFIG_SPIFFS_CACHE_STATS is not set # end of SPIFFS Cache Configuration CONFIG_SPIFFS_PAGE_CHECK=y CONFIG_SPIFFS_GC_MAX_RUNS=10 # CONFIG_SPIFFS_GC_STATS is not set CONFIG_SPIFFS_PAGE_SIZE=256 CONFIG_SPIFFS_OBJ_NAME_LEN=32 # CONFIG_SPIFFS_FOLLOW_SYMLINKS is not set CONFIG_SPIFFS_USE_MAGIC=y CONFIG_SPIFFS_USE_MAGIC_LENGTH=y CONFIG_SPIFFS_META_LENGTH=4 CONFIG_SPIFFS_USE_MTIME=y # # Debug Configuration # # CONFIG_SPIFFS_DBG is not set # CONFIG_SPIFFS_API_DBG is not set # CONFIG_SPIFFS_GC_DBG is not set # CONFIG_SPIFFS_CACHE_DBG is not set # CONFIG_SPIFFS_CHECK_DBG is not set # CONFIG_SPIFFS_TEST_VISUALISATION is not set # end of Debug Configuration # end of SPIFFS Configuration # # TinyUSB # # # Descriptor configuration # CONFIG_USB_DESC_CUSTOM_VID=0x1234 CONFIG_USB_DESC_CUSTOM_PID=0x5678 # end of Descriptor configuration # end of TinyUSB # # Unity unit testing library # CONFIG_UNITY_ENABLE_FLOAT=y CONFIG_UNITY_ENABLE_DOUBLE=y # CONFIG_UNITY_ENABLE_COLOR is not set CONFIG_UNITY_ENABLE_IDF_TEST_RUNNER=y # CONFIG_UNITY_ENABLE_FIXTURE is not set # CONFIG_UNITY_ENABLE_BACKTRACE_ON_FAIL is not set # end of Unity unit testing library # # Virtual file system # CONFIG_VFS_SUPPORT_IO=y CONFIG_VFS_SUPPORT_DIR=y CONFIG_VFS_SUPPORT_SELECT=y CONFIG_VFS_SUPPRESS_SELECT_DEBUG_OUTPUT=y CONFIG_VFS_SUPPORT_TERMIOS=y # # Host File System I/O (Semihosting) # CONFIG_VFS_SEMIHOSTFS_MAX_MOUNT_POINTS=1 CONFIG_VFS_SEMIHOSTFS_HOST_PATH_MAX_LEN=128 # end of Host File System I/O (Semihosting) # end of Virtual file system # # Wear Levelling # # CONFIG_WL_SECTOR_SIZE_512 is not set CONFIG_WL_SECTOR_SIZE_4096=y CONFIG_WL_SECTOR_SIZE=4096 # end of Wear Levelling # # Wi-Fi Provisioning Manager # CONFIG_WIFI_PROV_SCAN_MAX_ENTRIES=16 CONFIG_WIFI_PROV_AUTOSTOP_TIMEOUT=30 # end of Wi-Fi Provisioning Manager # # Supplicant # CONFIG_WPA_MBEDTLS_CRYPTO=y # CONFIG_WPA_DEBUG_PRINT is not set # CONFIG_WPA_TESTING_OPTIONS is not set # CONFIG_WPA_WPS_STRICT is not set # end of Supplicant # # Camera configuration # CONFIG_OV2640_SUPPORT=y # CONFIG_OV7725_SUPPORT is not set CONFIG_OV3660_SUPPORT=y CONFIG_OV5640_SUPPORT=y CONFIG_SCCB_HARDWARE_I2C=y # CONFIG_SCCB_HARDWARE_I2C_PORT0 is not set CONFIG_SCCB_HARDWARE_I2C_PORT1=y CONFIG_CAMERA_CORE0=y # CONFIG_CAMERA_CORE1 is not set # CONFIG_CAMERA_NO_AFFINITY is not set # end of Camera configuration # end of Component config # # Compatibility options # # CONFIG_LEGACY_INCLUDE_COMMON_HEADERS is not set # end of Compatibility options # Deprecated options for backward compatibility CONFIG_TOOLPREFIX="xtensa-esp32-elf-" # CONFIG_LOG_BOOTLOADER_LEVEL_NONE is not set # CONFIG_LOG_BOOTLOADER_LEVEL_ERROR is not set # CONFIG_LOG_BOOTLOADER_LEVEL_WARN is not set CONFIG_LOG_BOOTLOADER_LEVEL_INFO=y # CONFIG_LOG_BOOTLOADER_LEVEL_DEBUG is not set # CONFIG_LOG_BOOTLOADER_LEVEL_VERBOSE is not set CONFIG_LOG_BOOTLOADER_LEVEL=3 # CONFIG_APP_ROLLBACK_ENABLE is not set # CONFIG_FLASH_ENCRYPTION_ENABLED is not set CONFIG_FLASHMODE_QIO=y # CONFIG_FLASHMODE_QOUT is not set # CONFIG_FLASHMODE_DIO is not set # CONFIG_FLASHMODE_DOUT is not set # CONFIG_MONITOR_BAUD_9600B is not set # CONFIG_MONITOR_BAUD_57600B is not set CONFIG_MONITOR_BAUD_115200B=y # CONFIG_MONITOR_BAUD_230400B is not set # CONFIG_MONITOR_BAUD_921600B is not set # CONFIG_MONITOR_BAUD_2MB is not set # CONFIG_MONITOR_BAUD_OTHER is not set CONFIG_MONITOR_BAUD_OTHER_VAL=115200 CONFIG_MONITOR_BAUD=115200 CONFIG_COMPILER_OPTIMIZATION_LEVEL_DEBUG=y # CONFIG_COMPILER_OPTIMIZATION_LEVEL_RELEASE is not set CONFIG_OPTIMIZATION_ASSERTIONS_ENABLED=y # CONFIG_OPTIMIZATION_ASSERTIONS_SILENT is not set # CONFIG_OPTIMIZATION_ASSERTIONS_DISABLED is not set CONFIG_CXX_EXCEPTIONS=y CONFIG_CXX_EXCEPTIONS_EMG_POOL_SIZE=512 CONFIG_STACK_CHECK_NONE=y # CONFIG_STACK_CHECK_NORM is not set # CONFIG_STACK_CHECK_STRONG is not set # CONFIG_STACK_CHECK_ALL is not set # CONFIG_WARN_WRITE_STRINGS is not set # CONFIG_DISABLE_GCC8_WARNINGS is not set # CONFIG_ESP32_APPTRACE_DEST_TRAX is not set CONFIG_ESP32_APPTRACE_DEST_NONE=y CONFIG_ESP32_APPTRACE_LOCK_ENABLE=y CONFIG_BTDM_CONTROLLER_BLE_MAX_CONN_EFF=0 CONFIG_BTDM_CONTROLLER_BR_EDR_MAX_ACL_CONN_EFF=0 CONFIG_BTDM_CONTROLLER_BR_EDR_MAX_SYNC_CONN_EFF=0 CONFIG_BTDM_CONTROLLER_PINNED_TO_CORE=0 CONFIG_ADC2_DISABLE_DAC=y CONFIG_SPIRAM_SUPPORT=y CONFIG_WIFI_LWIP_ALLOCATION_FROM_SPIRAM_FIRST=y CONFIG_TRACEMEM_RESERVE_DRAM=0x0 # CONFIG_TWO_UNIVERSAL_MAC_ADDRESS is not set CONFIG_FOUR_UNIVERSAL_MAC_ADDRESS=y CONFIG_NUMBER_OF_UNIVERSAL_MAC_ADDRESS=4 # CONFIG_ULP_COPROC_ENABLED is not set CONFIG_ULP_COPROC_RESERVE_MEM=0 CONFIG_BROWNOUT_DET=y CONFIG_BROWNOUT_DET_LVL_SEL_0=y # CONFIG_BROWNOUT_DET_LVL_SEL_1 is not set # CONFIG_BROWNOUT_DET_LVL_SEL_2 is not set # CONFIG_BROWNOUT_DET_LVL_SEL_3 is not set # CONFIG_BROWNOUT_DET_LVL_SEL_4 is not set # CONFIG_BROWNOUT_DET_LVL_SEL_5 is not set # CONFIG_BROWNOUT_DET_LVL_SEL_6 is not set # CONFIG_BROWNOUT_DET_LVL_SEL_7 is not set CONFIG_BROWNOUT_DET_LVL=0 CONFIG_REDUCE_PHY_TX_POWER=y CONFIG_ESP32_RTC_CLOCK_SOURCE_INTERNAL_RC=y # CONFIG_ESP32_RTC_CLOCK_SOURCE_EXTERNAL_CRYSTAL is not set # CONFIG_ESP32_RTC_CLOCK_SOURCE_EXTERNAL_OSC is not set # CONFIG_ESP32_RTC_CLOCK_SOURCE_INTERNAL_8MD256 is not set # CONFIG_DISABLE_BASIC_ROM_CONSOLE is not set # CONFIG_NO_BLOBS is not set # CONFIG_COMPATIBLE_PRE_V2_1_BOOTLOADERS is not set CONFIG_SYSTEM_EVENT_QUEUE_SIZE=32 CONFIG_SYSTEM_EVENT_TASK_STACK_SIZE=2304 CONFIG_MAIN_TASK_STACK_SIZE=3584 CONFIG_IPC_TASK_STACK_SIZE=1024 CONFIG_CONSOLE_UART_DEFAULT=y # CONFIG_CONSOLE_UART_CUSTOM is not set # CONFIG_CONSOLE_UART_NONE is not set CONFIG_CONSOLE_UART_NUM=0 CONFIG_CONSOLE_UART_TX_GPIO=1 CONFIG_CONSOLE_UART_RX_GPIO=3 CONFIG_CONSOLE_UART_BAUDRATE=115200 CONFIG_INT_WDT=y CONFIG_INT_WDT_TIMEOUT_MS=800 CONFIG_INT_WDT_CHECK_CPU1=y # CONFIG_TASK_WDT is not set # CONFIG_EVENT_LOOP_PROFILING is not set CONFIG_POST_EVENTS_FROM_ISR=y CONFIG_POST_EVENTS_FROM_IRAM_ISR=y # CONFIG_ESP32S2_PANIC_PRINT_HALT is not set CONFIG_ESP32S2_PANIC_PRINT_REBOOT=y # CONFIG_ESP32S2_PANIC_SILENT_REBOOT is not set # CONFIG_ESP32S2_PANIC_GDBSTUB is not set CONFIG_TIMER_TASK_STACK_SIZE=3584 CONFIG_MB_MASTER_TIMEOUT_MS_RESPOND=150 CONFIG_MB_MASTER_DELAY_MS_CONVERT=200 CONFIG_MB_QUEUE_LENGTH=20 CONFIG_MB_SERIAL_TASK_STACK_SIZE=2048 CONFIG_MB_SERIAL_BUF_SIZE=256 CONFIG_MB_SERIAL_TASK_PRIO=10 # CONFIG_MB_CONTROLLER_SLAVE_ID_SUPPORT is not set CONFIG_MB_CONTROLLER_NOTIFY_TIMEOUT=20 CONFIG_MB_CONTROLLER_NOTIFY_QUEUE_SIZE=20 CONFIG_MB_CONTROLLER_STACK_SIZE=4096 CONFIG_MB_EVENT_QUEUE_TIMEOUT=20 CONFIG_MB_TIMER_PORT_ENABLED=y CONFIG_MB_TIMER_GROUP=0 CONFIG_MB_TIMER_INDEX=0 CONFIG_SUPPORT_STATIC_ALLOCATION=y # CONFIG_ENABLE_STATIC_TASK_CLEAN_UP_HOOK is not set CONFIG_TIMER_TASK_PRIORITY=1 CONFIG_TIMER_TASK_STACK_DEPTH=2048 CONFIG_TIMER_QUEUE_LENGTH=10 # CONFIG_L2_TO_L3_COPY is not set # CONFIG_USE_ONLY_LWIP_SELECT is not set CONFIG_ESP_GRATUITOUS_ARP=y CONFIG_GARP_TMR_INTERVAL=60 CONFIG_TCPIP_RECVMBOX_SIZE=32 CONFIG_TCP_MAXRTX=12 CONFIG_TCP_SYNMAXRTX=6 CONFIG_TCP_MSS=1436 CONFIG_TCP_MSL=60000 CONFIG_TCP_SND_BUF_DEFAULT=5744 CONFIG_TCP_WND_DEFAULT=5744 CONFIG_TCP_RECVMBOX_SIZE=6 CONFIG_TCP_QUEUE_OOSEQ=y # CONFIG_ESP_TCP_KEEP_CONNECTION_WHEN_IP_CHANGES is not set CONFIG_TCP_OVERSIZE_MSS=y # CONFIG_TCP_OVERSIZE_QUARTER_MSS is not set # CONFIG_TCP_OVERSIZE_DISABLE is not set CONFIG_UDP_RECVMBOX_SIZE=6 CONFIG_TCPIP_TASK_STACK_SIZE=3072 CONFIG_TCPIP_TASK_AFFINITY_NO_AFFINITY=y # CONFIG_TCPIP_TASK_AFFINITY_CPU0 is not set # CONFIG_TCPIP_TASK_AFFINITY_CPU1 is not set CONFIG_TCPIP_TASK_AFFINITY=0x7FFFFFFF # CONFIG_PPP_SUPPORT is not set CONFIG_ESP32_PTHREAD_TASK_PRIO_DEFAULT=5 CONFIG_ESP32_PTHREAD_TASK_STACK_SIZE_DEFAULT=3072 CONFIG_ESP32_PTHREAD_STACK_MIN=768 CONFIG_ESP32_DEFAULT_PTHREAD_CORE_NO_AFFINITY=y # CONFIG_ESP32_DEFAULT_PTHREAD_CORE_0 is not set # CONFIG_ESP32_DEFAULT_PTHREAD_CORE_1 is not set CONFIG_ESP32_PTHREAD_TASK_CORE_DEFAULT=-1 CONFIG_ESP32_PTHREAD_TASK_NAME_DEFAULT="pthread" CONFIG_SPI_FLASH_WRITING_DANGEROUS_REGIONS_ABORTS=y # CONFIG_SPI_FLASH_WRITING_DANGEROUS_REGIONS_FAILS is not set # CONFIG_SPI_FLASH_WRITING_DANGEROUS_REGIONS_ALLOWED is not set CONFIG_SUPPRESS_SELECT_DEBUG_OUTPUT=y CONFIG_SUPPORT_TERMIOS=y CONFIG_SEMIHOSTFS_MAX_MOUNT_POINTS=1 CONFIG_SEMIHOSTFS_HOST_PATH_MAX_LEN=128 # End of deprecated options
36,126
sdkconfig
en
unknown
unknown
{}
0
{}
0015/ESP32-OpenCV-Projects
esp32/examples/color_code/sdkconfig.defaults
CONFIG_ESPTOOLPY_PORT="/dev/ttyUSB0" CONFIG_ESPTOOLPY_BAUD_115200B= CONFIG_ESPTOOLPY_BAUD_230400B= CONFIG_ESPTOOLPY_BAUD_921600B=y CONFIG_ESPTOOLPY_BAUD_2MB= CONFIG_ESPTOOLPY_BAUD_OTHER= CONFIG_ESPTOOLPY_BAUD_OTHER_VAL=115200 CONFIG_ESPTOOLPY_BAUD=921600 CONFIG_ESPTOOLPY_COMPRESSED=y CONFIG_FLASHMODE_QIO=y CONFIG_FLASHMODE_QOUT= CONFIG_FLASHMODE_DIO= CONFIG_FLASHMODE_DOUT= CONFIG_ESPTOOLPY_FLASHMODE="dio" CONFIG_ESPTOOLPY_FLASHFREQ_80M=y CONFIG_ESPTOOLPY_FLASHFREQ_40M= CONFIG_ESPTOOLPY_FLASHFREQ_26M= CONFIG_ESPTOOLPY_FLASHFREQ_20M= CONFIG_ESPTOOLPY_FLASHFREQ="80m" CONFIG_ESPTOOLPY_FLASHSIZE_1MB= CONFIG_ESPTOOLPY_FLASHSIZE_2MB= CONFIG_ESPTOOLPY_FLASHSIZE_4MB=y CONFIG_ESPTOOLPY_FLASHSIZE_8MB= CONFIG_ESPTOOLPY_FLASHSIZE_16MB= CONFIG_ESPTOOLPY_FLASHSIZE="4MB" CONFIG_ESPTOOLPY_FLASHSIZE_DETECT=y CONFIG_ESPTOOLPY_BEFORE_RESET=y CONFIG_ESPTOOLPY_BEFORE_NORESET= CONFIG_ESPTOOLPY_BEFORE="default_reset" CONFIG_ESPTOOLPY_AFTER_RESET=y CONFIG_ESPTOOLPY_AFTER_NORESET= CONFIG_ESPTOOLPY_AFTER="hard_reset" CONFIG_MONITOR_BAUD_9600B= CONFIG_MONITOR_BAUD_57600B= CONFIG_MONITOR_BAUD_115200B=y CONFIG_MONITOR_BAUD_230400B= CONFIG_MONITOR_BAUD_921600B= CONFIG_MONITOR_BAUD_2MB= CONFIG_MONITOR_BAUD_OTHER= CONFIG_MONITOR_BAUD_OTHER_VAL=115200 CONFIG_MONITOR_BAUD=115200 # # Partition Table # CONFIG_PARTITION_TABLE_SINGLE_APP= CONFIG_PARTITION_TABLE_TWO_OTA= CONFIG_PARTITION_TABLE_CUSTOM=y CONFIG_PARTITION_TABLE_CUSTOM_FILENAME="partitions.csv" CONFIG_PARTITION_TABLE_FILENAME="partitions.csv" CONFIG_PARTITION_TABLE_OFFSET=0x8000 CONFIG_PARTITION_TABLE_MD5=y # # Camera configuration # CONFIG_ENABLE_TEST_PATTERN= CONFIG_OV2640_SUPPORT=y CONFIG_OV7725_SUPPORT= # # ESP32-specific # CONFIG_ESP32_DEFAULT_CPU_FREQ_80= CONFIG_ESP32_DEFAULT_CPU_FREQ_160= CONFIG_ESP32_DEFAULT_CPU_FREQ_240=y CONFIG_ESP32_DEFAULT_CPU_FREQ_MHZ=240 CONFIG_SPIRAM_SUPPORT=y # # SPI RAM config # CONFIG_SPIRAM_BOOT_INIT=y CONFIG_SPIRAM_IGNORE_NOTFOUND= CONFIG_SPIRAM_USE_MEMMAP= CONFIG_SPIRAM_USE_CAPS_ALLOC=y CONFIG_SPIRAM_USE_MALLOC= CONFIG_SPIRAM_TYPE_AUTO=y CONFIG_SPIRAM_TYPE_ESPPSRAM32= CONFIG_SPIRAM_TYPE_ESPPSRAM64= CONFIG_SPIRAM_SIZE=-1 CONFIG_SPIRAM_SPEED_40M= CONFIG_SPIRAM_SPEED_80M=y CONFIG_SPIRAM_MEMTEST=y CONFIG_SPIRAM_CACHE_WORKAROUND=y CONFIG_SPIRAM_BANKSWITCH_ENABLE=y CONFIG_SPIRAM_BANKSWITCH_RESERVE=8 CONFIG_WIFI_LWIP_ALLOCATION_FROM_SPIRAM_FIRST= CONFIG_SPIRAM_ALLOW_BSS_SEG_EXTERNAL_MEMORY= CONFIG_TASK_WDT= # # FreeRTOS # CONFIG_FREERTOS_HZ=1000
2,448
sdkconfig
defaults
en
unknown
unknown
{}
0
{}
0015/ESP32-OpenCV-Projects
esp32/examples/color_code/main/app_screen.cpp
#include "app_screen.h" #include "esp32/rom/tjpgd.h" #include <errno.h> #include <sys/stat.h> #include <string.h> #include "esp_freertos_hooks.h" #include "freertos/FreeRTOS.h" #include "freertos/task.h" #include "esp_system.h" #include "esp_log.h" #include "lwip/sockets.h" #include "board_def.h" #define TAG "[Screen]" CEspLcd *tft = NULL; int image_debug = 0; // === Special coordinates constants === typedef struct __attribute__((__packed__)) { uint8_t r; uint8_t g; uint8_t b; } color_t; typedef struct { uint16_t x1; uint16_t y1; uint16_t x2; uint16_t y2; } dispWin_t; dispWin_t dispWin = { .x1 = 0, .y1 = 0, .x2 = TFT_WITDH, .y2 = TFT_HEIGHT, }; typedef struct { FILE *fhndl; // File handler for input function int x; // image top left point X position int y; // image top left point Y position int s; bool found_header; uint8_t *membuff; // memory buffer containing the image uint32_t bufsize; // size of the memory buffer uint32_t bufptr; // memory buffer current position color_t *linbuf[2]; // memory buffer used for display output uint8_t linbuf_idx; } JPGIODEV; // User defined call-back function to input JPEG data from file //--------------------- static UINT tjd_s_input( JDEC *jd, // Decompression object BYTE *buff, // Pointer to the read buffer (NULL:skip) UINT nd // Number of bytes to read/skip from input stream ) { int rb = 0; char recv_buf[16]; // Device identifier for the session (5th argument of jd_prepare function) JPGIODEV *dev = (JPGIODEV *)jd->device; while (!dev->found_header) { rb += read(dev->s, recv_buf, 1); putchar(recv_buf[0]); // debug if (recv_buf[0] == '\r') { rb += read(dev->s, recv_buf, 3); putchar(recv_buf[0]); putchar(recv_buf[1]); putchar(recv_buf[2]); // debug if ((recv_buf[0] == '\n') && (recv_buf[1] == '\r') && (recv_buf[2] == '\n')) { ESP_LOGI("TFT", "Found header ended at %d", rb); dev->found_header = true; } } } if (buff) { // Read nd bytes from the input strem rb = read(dev->s, buff, nd); // ESP_LOGI("TFT", "Socket read %d, actual %d", nd, rb); return rb; // Returns actual number of bytes read } else { // Remove nd bytes from the input stream int seek_size = nd; while (seek_size) { if (seek_size > sizeof(recv_buf)) { rb = read(dev->s, recv_buf, sizeof(recv_buf)); } else { rb = read(dev->s, recv_buf, seek_size); } seek_size -= rb; } return nd; // Returns actual number of bytes read // if (fseek(dev->fhndl, nd, SEEK_CUR) >= 0) return nd; // else return 0; } } // User defined call-back function to input JPEG data from file //--------------------- static UINT tjd_input( JDEC *jd, // Decompression object BYTE *buff, // Pointer to the read buffer (NULL:skip) UINT nd // Number of bytes to read/skip from input stream ) { int rb = 0; // Device identifier for the session (5th argument of jd_prepare function) JPGIODEV *dev = (JPGIODEV *)jd->device; if (buff) { // Read nd bytes from the input strem rb = fread(buff, 1, nd, dev->fhndl); return rb; // Returns actual number of bytes read } else { // Remove nd bytes from the input stream if (fseek(dev->fhndl, nd, SEEK_CUR) >= 0) return nd; else return 0; } } // User defined call-back function to input JPEG data from memory buffer //------------------------- static UINT tjd_buf_input( JDEC *jd, // Decompression object BYTE *buff, // Pointer to the read buffer (NULL:skip) UINT nd // Number of bytes to read/skip from input stream ) { // Device identifier for the session (5th argument of jd_prepare function) JPGIODEV *dev = (JPGIODEV *)jd->device; if (!dev->membuff) return 0; if (dev->bufptr >= (dev->bufsize + 2)) return 0; // end of stream if ((dev->bufptr + nd) > (dev->bufsize + 2)) nd = (dev->bufsize + 2) - dev->bufptr; if (buff) { // Read nd bytes from the input strem memcpy(buff, dev->membuff + dev->bufptr, nd); dev->bufptr += nd; return nd; // Returns number of bytes read } else { // Remove nd bytes from the input stream dev->bufptr += nd; return nd; } } // User defined call-back function to output RGB bitmap to display device //---------------------- static UINT tjd_output( JDEC *jd, // Decompression object of current session void *bitmap, // Bitmap data to be output JRECT *rect // Rectangular region to output ) { // Device identifier for the session (5th argument of jd_prepare function) JPGIODEV *dev = (JPGIODEV *)jd->device; // ** Put the rectangular into the display device ** int x; int y; int dleft, dtop, dright, dbottom; BYTE *src = (BYTE *)bitmap; int left = rect->left + dev->x; int top = rect->top + dev->y; int right = rect->right + dev->x; int bottom = rect->bottom + dev->y; if ((left > dispWin.x2) || (top > dispWin.y2)) return 1; // out of screen area, return if ((right < dispWin.x1) || (bottom < dispWin.y1)) return 1; // out of screen area, return if (left < dispWin.x1) dleft = dispWin.x1; else dleft = left; if (top < dispWin.y1) dtop = dispWin.y1; else dtop = top; if (right > dispWin.x2) dright = dispWin.x2; else dright = right; if (bottom > dispWin.y2) dbottom = dispWin.y2; else dbottom = bottom; if ((dleft > dispWin.x2) || (dtop > dispWin.y2)) return 1; // out of screen area, return if ((dright < dispWin.x1) || (dbottom < dispWin.y1)) return 1; // out of screen area, return uint32_t len = ((dright - dleft + 1) * (dbottom - dtop + 1)); // calculate length of data if ((len > 0) && (len <= JPG_IMAGE_LINE_BUF_SIZE)) { uint8_t *dest = (uint8_t *)(dev->linbuf[dev->linbuf_idx]); for (y = top; y <= bottom; y++) { for (x = left; x <= right; x++) { // Clip to display area if ((x >= dleft) && (y >= dtop) && (x <= dright) && (y <= dbottom)) { *dest++ = (*src++) & 0xFC; *dest++ = (*src++) & 0xFC; *dest++ = (*src++) & 0xFC; } else src += 3; // skip } } // ESP_LOGI(TAG, "x1:%d x2:%d y1:%d y2:%d\n", dleft, dright, dtop, dbottom); tft->setAddrWindow(dleft, dtop, dright, dbottom); uint16_t *p = (uint16_t *)malloc(sizeof(uint16_t) * len); if (!p) { ESP_LOGE(TAG, "malloc fail"); return 0; } for (uint32_t i = 0; i < len; i++) { p[i] = tft->color565(dev->linbuf[dev->linbuf_idx][i].r, dev->linbuf[dev->linbuf_idx][i].g, dev->linbuf[dev->linbuf_idx][i].b); } tft->_fastSendBuf(p, len, true); // TODO: Swapping bytes directly in the camera register could enhance display free(p); dev->linbuf_idx = ((dev->linbuf_idx + 1) & 1); } else { ESP_LOGE(TAG, "Data size error: %d jpg: (%d,%d,%d,%d) disp: (%d,%d,%d,%d)\r\n", len, left, top, right, bottom, dleft, dtop, dright, dbottom); return 0; // stop decompression } return 1; // Continue to decompression } //================================================================================== void TFT_jpg_image(int x, int y, uint8_t scale, int s, char *fname, uint8_t *buf, int size) { JPGIODEV dev; struct stat sb; char *work = NULL; // Pointer to the working buffer (must be 4-byte aligned) UINT sz_work = 3800; // Size of the working buffer (must be power of 2) JDEC jd; // Decompression object (70 bytes) JRESULT rc; dev.linbuf[0] = NULL; dev.linbuf[1] = NULL; dev.linbuf_idx = 0; dev.fhndl = NULL; dev.s = s; if (s >= 0) { // image from socket dev.membuff = NULL; dev.found_header = false; dev.bufsize = 0; dev.bufptr = 0; } else if (fname == NULL) { // image from buffer dev.membuff = buf; dev.bufsize = size; dev.bufptr = 0; } else { // image from file dev.membuff = NULL; dev.bufsize = 0; dev.bufptr = 0; if (stat(fname, &sb) != 0) { if (image_debug) printf("File error: %ss\r\n", strerror(errno)); goto exit; } dev.fhndl = fopen(fname, "r"); if (!dev.fhndl) { if (image_debug) printf("Error opening file: %s\r\n", strerror(errno)); goto exit; } } if (scale > 3) scale = 3; work = (char *)malloc(sz_work); if (work) { if (dev.s >= 0) rc = jd_prepare(&jd, tjd_s_input, (void *)work, sz_work, &dev); else if (dev.membuff) rc = jd_prepare(&jd, tjd_buf_input, (void *)work, sz_work, &dev); else rc = jd_prepare(&jd, tjd_input, (void *)work, sz_work, &dev); if (rc == JDR_OK) { if (x == CENTER) x = ((dispWin.x2 - dispWin.x1 + 1 - (int)(jd.width >> scale)) / 2) + dispWin.x1; else if (x == RIGHT) x = dispWin.x2 + 1 - (int)(jd.width >> scale); if (y == CENTER) y = ((dispWin.y2 - dispWin.y1 + 1 - (int)(jd.height >> scale)) / 2) + dispWin.y1; else if (y == BOTTOM) y = dispWin.y2 + 1 - (int)(jd.height >> scale); if (x < ((dispWin.x2 - 1) * -1)) x = (dispWin.x2 - 1) * -1; if (y < ((dispWin.y2 - 1)) * -1) y = (dispWin.y2 - 1) * -1; if (x > (dispWin.x2 - 1)) x = dispWin.x2 - 1; if (y > (dispWin.y2 - 1)) y = dispWin.y2 - 1; dev.x = x; dev.y = y; dev.linbuf[0] = (color_t *)heap_caps_malloc(JPG_IMAGE_LINE_BUF_SIZE * 3, MALLOC_CAP_DMA); if (dev.linbuf[0] == NULL) { if (image_debug) printf("Error allocating line buffer #0\r\n"); goto exit; } dev.linbuf[1] = (color_t *)heap_caps_malloc(JPG_IMAGE_LINE_BUF_SIZE * 3, MALLOC_CAP_DMA); if (dev.linbuf[1] == NULL) { if (image_debug) printf("Error allocating line buffer #1\r\n"); goto exit; } // Start to decode the JPEG file rc = jd_decomp(&jd, tjd_output, scale); if (rc != JDR_OK) { if (image_debug) printf("jpg decompression error %d\r\n", rc); } if (image_debug) printf("Jpg size: %dx%d, position; %d,%d, scale: %d, bytes used: %d\r\n", jd.width, jd.height, x, y, scale, jd.sz_pool); } else { if (image_debug) printf("jpg prepare error %d\r\n", rc); } } else { if (image_debug) printf("work buffer allocation error\r\n"); } exit: if (work) free(work); // free work buffer if (dev.linbuf[0]) free(dev.linbuf[0]); if (dev.linbuf[1]) free(dev.linbuf[1]); if (dev.fhndl) fclose(dev.fhndl); // close input file } // ===================================================================================================================== // lvgl // ===================================================================================================================== #include "lvgl.h" /* lvgl internal graphics buffers */ #define DISP_BUF_SIZE LV_HOR_RES_MAX * 24 // Horizontal resolution * number of lines sent to the driver static lv_disp_buf_t disp_buf; static lv_color_t buf_1[DISP_BUF_SIZE]; static lv_color_t buf_2[DISP_BUF_SIZE]; /*Write the internal buffer to the display. 'lv_flush_ready()' has to be called when finished*/ static void ex_disp_flush(lv_disp_drv_t *disp_drv, const lv_area_t *area, lv_color_t *color_p) { tft->drawBitmap((int16_t)area->x1, (int16_t)area->y1, (const uint16_t *)color_p, (int16_t)(area->x2 - area->x1 + 1), (int16_t)(area->y2 - area->y1 + 1)); /* IMPORTANT!!! * Inform the graphics library that you are ready with the flushing*/ lv_disp_t *disp = _lv_refr_get_disp_refreshing(); lv_disp_flush_ready(&disp->driver); } void lvgl_lcd_hal_init() { lcd_conf_t lcd_pins = { .lcd_model = LCD_MOD_ST7789, .pin_num_miso = TFT_MISO, .pin_num_mosi = TFT_MOSI, .pin_num_clk = TFT_SCLK, .pin_num_cs = TFT_CS, .pin_num_dc = TFT_DC, .pin_num_rst = TFT_RST, .pin_num_bckl = TFT_BK, .clk_freq = 26 * 1000 * 1000, .rst_active_level = 0, .bckl_active_level = 1, .spi_host = HSPI_HOST, .init_spi_bus = true, }; /*Initialize SPI Handler*/ if (tft == NULL) { tft = new CEspLcd(&lcd_pins, TFT_HEIGHT, TFT_WITDH); } /*screen initialize*/ tft->invertDisplay(true); tft->setRotation(0); tft->fillScreen(COLOR_BLACK); /* init lvgl display buffers */ lv_disp_buf_init(&disp_buf, buf_1, buf_2, DISP_BUF_SIZE); /* lvgl screen driver */ lv_disp_drv_t disp_drv; /*Descriptor of a display driver*/ lv_disp_drv_init(&disp_drv); /*Basic initialization*/ disp_drv.flush_cb = ex_disp_flush; disp_drv.buffer = &disp_buf; /* Finally register the driver */ lv_disp_drv_register(&disp_drv); }
12,104
app_screen
cpp
en
cpp
code
{"qsc_code_num_words": 1840, "qsc_code_num_chars": 12104.0, "qsc_code_mean_word_length": 3.88532609, "qsc_code_frac_words_unique": 0.16847826, "qsc_code_frac_chars_top_2grams": 0.02643726, "qsc_code_frac_chars_top_3grams": 0.01342845, "qsc_code_frac_chars_top_4grams": 0.02014268, "qsc_code_frac_chars_dupe_5grams": 0.37347881, "qsc_code_frac_chars_dupe_6grams": 0.29640509, "qsc_code_frac_chars_dupe_7grams": 0.23555742, "qsc_code_frac_chars_dupe_8grams": 0.22828368, "qsc_code_frac_chars_dupe_9grams": 0.22800392, "qsc_code_frac_chars_dupe_10grams": 0.19974822, "qsc_code_frac_chars_replacement_symbols": 0.0, "qsc_code_frac_chars_digital": 0.02291818, "qsc_code_frac_chars_whitespace": 0.20332122, "qsc_code_size_file_byte": 12104.0, "qsc_code_num_lines": 476.0, "qsc_code_num_chars_line_max": 155.0, "qsc_code_num_chars_line_mean": 25.42857143, "qsc_code_frac_chars_alphabet": 0.71844862, "qsc_code_frac_chars_comments": 0.28841705, "qsc_code_cate_xml_start": 0.0, "qsc_code_frac_lines_dupe_lines": 0.20175439, "qsc_code_cate_autogen": 0.0, "qsc_code_frac_lines_long_string": 0.00584795, "qsc_code_frac_chars_string_length": 0.0599164, "qsc_code_frac_chars_long_word_length": 0.0, "qsc_code_frac_lines_string_concat": 0.0, "qsc_code_cate_encoded_data": 0.0, "qsc_code_frac_chars_hex_words": 0.0013934, "qsc_code_frac_lines_prompt_comments": 0.00210084, "qsc_code_frac_lines_assert": 0.0, "qsc_codecpp_frac_lines_preprocessor_directives": 0.05555556, "qsc_codecpp_frac_lines_func_ratio": 0.02631579, "qsc_codecpp_cate_bitsstdc": 0.0, "qsc_codecpp_nums_lines_main": 0.0, "qsc_codecpp_frac_lines_goto": 0.01169591, "qsc_codecpp_cate_var_zero": 0.0, "qsc_codecpp_score_lines_no_logic": 0.09649123, "qsc_codecpp_frac_lines_print": 0.02339181}
1
{"qsc_code_frac_chars_replacement_symbols": 0, "qsc_code_num_words": 0, "qsc_code_num_chars": 0, "qsc_code_mean_word_length": 0, "qsc_code_frac_chars_top_2grams": 0, "qsc_code_frac_chars_top_3grams": 0, "qsc_code_frac_chars_top_4grams": 0, "qsc_code_frac_chars_dupe_5grams": 0, "qsc_code_frac_chars_dupe_6grams": 0, "qsc_code_frac_chars_dupe_7grams": 0, "qsc_code_frac_chars_dupe_8grams": 0, "qsc_code_frac_chars_dupe_9grams": 0, "qsc_code_frac_chars_dupe_10grams": 0, "qsc_code_frac_lines_dupe_lines": 0, "qsc_code_size_file_byte": 0, "qsc_code_num_lines": 0, "qsc_code_num_chars_line_max": 0, "qsc_code_num_chars_line_mean": 0, "qsc_code_frac_chars_alphabet": 0, "qsc_code_frac_chars_digital": 0, "qsc_code_frac_chars_whitespace": 0, "qsc_code_frac_chars_comments": 0, "qsc_code_cate_xml_start": 0, "qsc_code_cate_autogen": 0, "qsc_code_frac_lines_long_string": 0, "qsc_code_frac_chars_string_length": 0, "qsc_code_frac_chars_long_word_length": 0, "qsc_code_cate_encoded_data": 0, "qsc_code_frac_chars_hex_words": 0, "qsc_code_frac_lines_prompt_comments": 0, "qsc_code_frac_lines_assert": 0, "qsc_codecpp_frac_lines_func_ratio": 0, "qsc_codecpp_nums_lines_main": 0, "qsc_codecpp_score_lines_no_logic": 0, "qsc_codecpp_frac_lines_preprocessor_directives": 0, "qsc_codecpp_frac_lines_print": 0}
0015/Grid_Board
grid_board_app/.metadata
# This file tracks properties of this Flutter project. # Used by Flutter tool to assess capabilities and perform upgrades etc. # # This file should be version controlled and should not be manually edited. version: revision: "d7b523b356d15fb81e7d340bbe52b47f93937323" channel: "stable" project_type: app # Tracks metadata for the flutter migrate command migration: platforms: - platform: root create_revision: d7b523b356d15fb81e7d340bbe52b47f93937323 base_revision: d7b523b356d15fb81e7d340bbe52b47f93937323 - platform: android create_revision: d7b523b356d15fb81e7d340bbe52b47f93937323 base_revision: d7b523b356d15fb81e7d340bbe52b47f93937323 - platform: ios create_revision: d7b523b356d15fb81e7d340bbe52b47f93937323 base_revision: d7b523b356d15fb81e7d340bbe52b47f93937323 # User provided section # List of Local paths (relative to this file) that should be # ignored by the migrate tool. # # Files that are not part of the templates will be ignored by default. unmanaged_files: - 'lib/main.dart' - 'ios/Runner.xcodeproj/project.pbxproj'
1,114
.metadata
metadata
en
xpages
data
{"qsc_code_num_words": 114, "qsc_code_num_chars": 1114.0, "qsc_code_mean_word_length": 7.54385965, "qsc_code_frac_words_unique": 0.57017544, "qsc_code_frac_chars_top_2grams": 0.39069767, "qsc_code_frac_chars_top_3grams": 0.18837209, "qsc_code_frac_chars_top_4grams": 0.20232558, "qsc_code_frac_chars_dupe_5grams": 0.38837209, "qsc_code_frac_chars_dupe_6grams": 0.38837209, "qsc_code_frac_chars_dupe_7grams": 0.26511628, "qsc_code_frac_chars_dupe_8grams": 0.0, "qsc_code_frac_chars_dupe_9grams": 0.0, "qsc_code_frac_chars_dupe_10grams": 0.0, "qsc_code_frac_chars_replacement_symbols": 0.0, "qsc_code_frac_chars_digital": 0.20543478, "qsc_code_frac_chars_whitespace": 0.17414722, "qsc_code_size_file_byte": 1114.0, "qsc_code_num_lines": 33.0, "qsc_code_num_chars_line_max": 76.0, "qsc_code_num_chars_line_mean": 33.75757576, "qsc_code_frac_chars_alphabet": 0.72934783, "qsc_code_frac_chars_comments": 1.0, "qsc_code_cate_xml_start": 0.0, "qsc_code_frac_lines_dupe_lines": null, "qsc_code_cate_autogen": 0.0, "qsc_code_frac_lines_long_string": null, "qsc_code_frac_chars_string_length": null, "qsc_code_frac_chars_long_word_length": null, "qsc_code_frac_lines_string_concat": null, "qsc_code_cate_encoded_data": 0.0, "qsc_code_frac_chars_hex_words": null, "qsc_code_frac_lines_prompt_comments": 0.0, "qsc_code_frac_lines_assert": null}
0
{"qsc_code_frac_chars_replacement_symbols": 0, "qsc_code_num_words": 0, "qsc_code_num_chars": 0, "qsc_code_mean_word_length": 0, "qsc_code_frac_words_unique": 0, "qsc_code_frac_chars_top_2grams": 1, "qsc_code_frac_chars_top_3grams": 1, "qsc_code_frac_chars_top_4grams": 1, "qsc_code_frac_chars_dupe_5grams": 0, "qsc_code_frac_chars_dupe_6grams": 0, "qsc_code_frac_chars_dupe_7grams": 0, "qsc_code_frac_chars_dupe_8grams": 0, "qsc_code_frac_chars_dupe_9grams": 0, "qsc_code_frac_chars_dupe_10grams": 0, "qsc_code_frac_lines_dupe_lines": 0, "qsc_code_size_file_byte": 0, "qsc_code_num_lines": 0, "qsc_code_num_chars_line_max": 0, "qsc_code_num_chars_line_mean": 0, "qsc_code_frac_chars_alphabet": 0, "qsc_code_frac_chars_digital": 1, "qsc_code_frac_chars_whitespace": 0, "qsc_code_frac_chars_comments": 1, "qsc_code_cate_xml_start": 0, "qsc_code_cate_autogen": 0, "qsc_code_frac_chars_long_word_length": 0, "qsc_code_cate_encoded_data": 0, "qsc_code_frac_chars_hex_words": 0}
0015/Grid_Board
grid_board_app/README.md
# GRID BOARD APP A Flutter app for sending customizable text and emoji grids via BLE (Bluetooth Low Energy) to ESP32-P4 Device. Create, save, and reload messages in a 12×5 grid—perfect for smart displays and IoT dashboards. --- ## Features - 12×5 customizable grid (text and emoji supported) - Fast BLE connection (uses [flutter_blue_plus](https://pub.dev/packages/flutter_blue_plus)) - Save/load unlimited grid messages (local storage) - Emoji picker, clear grid, auto-uppercase, and more! - Automatic BLE reconnect and robust error handling --- ## Getting Started ### 1. **Install dependencies** ```bash flutter pub get ``` ### 2. **(Re)generate platform folders (if needed)** If the `ios/` or `android/` folders are missing, run: ```bash flutter create . ``` --- ## Permissions & Platform Setup ### iOS **Required: Add Bluetooth Usage Description to Info.plist** Open `ios/Runner/Info.plist` and add: ```xml <key>NSBluetoothAlwaysUsageDescription</key> <string>This app uses Bluetooth to connect to your Grid Board display.</string> ``` > ⚠️ Without this, iOS will deny BLE access and your app won't see any devices. --- ### Android **Required: Bluetooth Permissions in AndroidManifest.xml** Add these inside `<manifest><application>...</application></manifest>`: ```xml <uses-permission android:name="android.permission.BLUETOOTH"/> <uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/> <uses-permission android:name="android.permission.BLUETOOTH_SCAN"/> <uses-permission android:name="android.permission.BLUETOOTH_CONNECT"/> <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/> <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/> ``` For **Android 12+** you must also request runtime permissions; see [flutter_blue_plus docs](https://pub.dev/packages/flutter_blue_plus#android-permissions) for examples. --- ## Running the App ```bash flutter run ``` - The app will scan for your Grid Board BLE device (default: `"Grid_Board"`). - Tap any grid cell and start typing or long-press to insert emoji. - Use the Send button to transmit the grid to your ESP32. - Save and reload grid messages for later use! --- ## Notes - All user input is forced to uppercase except for emoji. - Emojis are limited to those supported by both your ESP32 font and app. - The app automatically tries to reconnect if BLE connection drops. --- ## Dependencies - [flutter_blue_plus](https://pub.dev/packages/flutter_blue_plus) - [shared_preferences](https://pub.dev/packages/shared_preferences) --- ## License MIT License. ---
2,598
README
md
en
markdown
text
{"qsc_doc_frac_chars_curly_bracket": 0.0, "qsc_doc_frac_words_redpajama_stop": 0.15213358, "qsc_doc_num_sentences": 37.0, "qsc_doc_num_words": 363, "qsc_doc_num_chars": 2598.0, "qsc_doc_num_lines": 98.0, "qsc_doc_mean_word_length": 5.2892562, "qsc_doc_frac_words_full_bracket": 0.0, "qsc_doc_frac_lines_end_with_readmore": 0.0, "qsc_doc_frac_lines_start_with_bullet": 0.0, "qsc_doc_frac_words_unique": 0.44628099, "qsc_doc_entropy_unigram": 4.71359152, "qsc_doc_frac_words_all_caps": 0.03896104, "qsc_doc_frac_lines_dupe_lines": 0.28787879, "qsc_doc_frac_chars_dupe_lines": 0.030012, "qsc_doc_frac_chars_top_2grams": 0.034375, "qsc_doc_frac_chars_top_3grams": 0.046875, "qsc_doc_frac_chars_top_4grams": 0.078125, "qsc_doc_frac_chars_dupe_5grams": 0.225, "qsc_doc_frac_chars_dupe_6grams": 0.225, "qsc_doc_frac_chars_dupe_7grams": 0.225, "qsc_doc_frac_chars_dupe_8grams": 0.05104167, "qsc_doc_frac_chars_dupe_9grams": 0.05104167, "qsc_doc_frac_chars_dupe_10grams": 0.05104167, "qsc_doc_frac_chars_replacement_symbols": 0.0, "qsc_doc_cate_code_related_file_name": 1.0, "qsc_doc_num_chars_sentence_length_mean": 17.97080292, "qsc_doc_frac_chars_hyperlink_html_tag": 0.265204, "qsc_doc_frac_chars_alphabet": 0.8409393, "qsc_doc_frac_chars_digital": 0.00753212, "qsc_doc_frac_chars_whitespace": 0.13125481, "qsc_doc_frac_chars_hex_words": 0.0}
1
{"qsc_doc_frac_chars_replacement_symbols": 0, "qsc_doc_entropy_unigram": 0, "qsc_doc_frac_chars_top_2grams": 0, "qsc_doc_frac_chars_top_3grams": 0, "qsc_doc_frac_chars_top_4grams": 0, "qsc_doc_frac_chars_dupe_5grams": 0, "qsc_doc_frac_chars_dupe_6grams": 0, "qsc_doc_frac_chars_dupe_7grams": 0, "qsc_doc_frac_chars_dupe_8grams": 0, "qsc_doc_frac_chars_dupe_9grams": 0, "qsc_doc_frac_chars_dupe_10grams": 0, "qsc_doc_frac_chars_dupe_lines": 0, "qsc_doc_frac_lines_dupe_lines": 0, "qsc_doc_frac_lines_end_with_readmore": 0, "qsc_doc_frac_lines_start_with_bullet": 0, "qsc_doc_frac_words_all_caps": 0, "qsc_doc_mean_word_length": 0, "qsc_doc_num_chars": 0, "qsc_doc_num_lines": 0, "qsc_doc_num_sentences": 0, "qsc_doc_num_words": 0, "qsc_doc_frac_chars_hex_words": 0, "qsc_doc_frac_chars_hyperlink_html_tag": 0, "qsc_doc_frac_chars_alphabet": 0, "qsc_doc_frac_chars_digital": 0, "qsc_doc_frac_chars_whitespace": 0}
007gzs/dingtalk-sdk
dingtalk/client/api/workrecord.py
# encoding: utf-8 from __future__ import absolute_import, unicode_literals import datetime import time from optionaldict import optionaldict from dingtalk.client.api.base import DingTalkBaseAPI from dingtalk.model.field import FieldBase class WorkRecord(DingTalkBaseAPI): def add(self, userid, create_time, title, url, form_item_dict, originator_user_id='', source_name=''): """ 新增待办事项 :param userid: 用户id :param create_time: 待办时间。Unix时间戳 :param title: 标题 :param url: 待办跳转url :param form_item_dict: 表单列表 OrderedDict((('标题1', '内容1'),('标题2', '内容2'))) :param originator_user_id: manager7078 :param source_name: 待办来源名称 """ if isinstance(create_time, (datetime.date, datetime.datetime)): create_time = int(time.mktime(create_time.timetuple()) * 1000) form_item_list = [{'title': k, 'content': v}for k, v in form_item_dict.items()] return self._top_request( "dingtalk.oapi.workrecord.add", { "userid": userid, "create_time": create_time, "title": title, "url": url, "formItemList": form_item_list, "originator_user_id": originator_user_id, "source_name": source_name }, result_processor=lambda x: x['record_id'] ) def update(self, userid, record_id): """ 更新待办事项状态 :param userid: 用户id :param record_id: 待办事项唯一id """ return self._top_request( "dingtalk.oapi.workrecord.update", {"userid": userid, "record_id": record_id} ) def getbyuserid(self, userid, status, offset=0, limit=50): """ 获取用户的待办事项 :param userid: 用户唯一ID :param offset: 分页游标,从0开始,如返回结果中has_more为true,则表示还有数据,offset再传上一次的offset+limit :param limit: 分页大小,最多50 :param status: 待办事项状态,0表示未完成,1表示完成 """ return self._top_request( "dingtalk.oapi.workrecord.getbyuserid", { "userid": userid, "offset": offset, "limit": limit, "status": status }, result_processor=lambda x: x['records'] ) def process_save(self, name, description, form_component_list=(), process_code=None, agentid=None): """ 保存审批模板 :param name: 模板名称 :param description: 模板描述 :param form_component_list: 表单列表 :param process_code: 模板的唯一码 :param agentid: 企业微应用标识 """ form_component_list = [form.get_dict() if isinstance(form, FieldBase) else form for form in form_component_list] return self._top_request( "dingtalk.oapi.process.save", { "saveProcessRequest": optionaldict({ "agentid": agentid, "process_code": process_code, "name": name, "description": description, "fake_mode": True, "form_component_list": form_component_list }) }, result_processor=lambda x: x['process_code'] ) def process_delete(self, process_code, agentid=''): """ 删除创建的审批模板 :param process_code: 模板的唯一码 :param agentid: 微应用agentId,ISV必填 """ return self._top_request( "dingtalk.oapi.process.delete", { "request": { "process_code": process_code, "agentid": agentid } } ) def process_workrecord_create( self, process_code, originator_user_id, form_component_values, url, agentid='', title='' ): """ 发起不带流程的审批实例 :param process_code: 审批模板唯一码 :param originator_user_id: 审批发起人 :param form_component_values: 表单参数列表 :param url: 实例跳转链接 :param agentid: 应用id :param title: 实例标题 """ if isinstance(form_component_values, dict): form_component_values = [{"name": name, "value": value} for name, value in form_component_values.items()] return self._top_request( "dingtalk.oapi.process.workrecord.create", { "request": { "process_code": process_code, "originator_user_id": originator_user_id, "form_component_values": form_component_values, "url": url, "agentid": agentid, "title": title } }, result_processor=lambda x: x['process_instance_id'] ) def process_workrecord_update( self, process_instance_id, status, result, agentid='' ): """ 同步待办实例状态 :param process_instance_id: 实例id :param status: 实例状态,分为COMPLETED, TERMINATED :param result: 实例结果, 如果实例状态是COMPLETED,需要设置result,分为agree和refuse :param agentid: 应用id """ return self._top_request( "dingtalk.oapi.process.workrecord.update", { "request": { "process_instance_id": process_instance_id, "status": status, "result": result, "agentid": agentid } } ) def process_workrecord_task_create( self, process_instance_id, tasks, agentid='', activity_id='' ): """ 创建待办任务 :param process_instance_id: 实例id :param tasks: 任务列表 :param agentid: 应用id :param activity_id: 节点id """ return self._top_request( "dingtalk.oapi.process.workrecord.task.create", { "request": { "process_instance_id": process_instance_id, "tasks": tasks, "agentid": agentid, "activity_id": activity_id } }, result_processor=lambda x: x['tasks'] ) def dingtalk_oapi_process_workrecord_task_update( self, process_instance_id, tasks, agentid='' ): """ 更新待办任务状态 :param process_instance_id: 实例id :param tasks: 任务列表 :param agentid: 应用id """ return self._top_request( "dingtalk.oapi.process.workrecord.task.update", { "request": { "process_instance_id": process_instance_id, "tasks": tasks, "agentid": agentid } }, result_processor=lambda x: x['tasks'] ) def process_workrecord_taskgroup_cancel( self, process_instance_id, activity_id, agentid='' ): """ 批量取消任务 :param process_instance_id: 实例id :param activity_id: 任务组id :param agentid: 应用id """ return self._top_request( "dingtalk.oapi.process.workrecord.taskgroup.cancel", { "request": { "process_instance_id": process_instance_id, "activity_id": activity_id, "agentid": agentid } } )
7,646
workrecord
py
en
python
code
{"qsc_code_num_words": 668, "qsc_code_num_chars": 7646.0, "qsc_code_mean_word_length": 5.60628743, "qsc_code_frac_words_unique": 0.2260479, "qsc_code_frac_chars_top_2grams": 0.06809079, "qsc_code_frac_chars_top_3grams": 0.07716956, "qsc_code_frac_chars_top_4grams": 0.05340454, "qsc_code_frac_chars_dupe_5grams": 0.42536716, "qsc_code_frac_chars_dupe_6grams": 0.34979973, "qsc_code_frac_chars_dupe_7grams": 0.23951936, "qsc_code_frac_chars_dupe_8grams": 0.15487316, "qsc_code_frac_chars_dupe_9grams": 0.12763685, "qsc_code_frac_chars_dupe_10grams": 0.11241656, "qsc_code_frac_chars_replacement_symbols": 0.0, "qsc_code_frac_chars_digital": 0.0045376, "qsc_code_frac_chars_whitespace": 0.39471619, "qsc_code_size_file_byte": 7646.0, "qsc_code_num_lines": 259.0, "qsc_code_num_chars_line_max": 121.0, "qsc_code_num_chars_line_mean": 29.52123552, "qsc_code_frac_chars_alphabet": 0.80466724, "qsc_code_frac_chars_comments": 0.17106984, "qsc_code_cate_xml_start": 0.0, "qsc_code_frac_lines_dupe_lines": 0.37888199, "qsc_code_cate_autogen": 0.0, "qsc_code_frac_lines_long_string": 0.0, "qsc_code_frac_chars_string_length": 0.1556938, "qsc_code_frac_chars_long_word_length": 0.06652843, "qsc_code_frac_lines_string_concat": 0.0, "qsc_code_cate_encoded_data": 0.0, "qsc_code_frac_chars_hex_words": 0.0, "qsc_code_frac_lines_prompt_comments": 0.0, "qsc_code_frac_lines_assert": 0.0, "qsc_codepython_cate_ast": 1.0, "qsc_codepython_frac_lines_func_ratio": 0.0621118, "qsc_codepython_cate_var_zero": false, "qsc_codepython_frac_lines_pass": 0.0, "qsc_codepython_frac_lines_import": 0.03726708, "qsc_codepython_frac_lines_simplefunc": 0.0, "qsc_codepython_score_lines_no_logic": 0.16770186, "qsc_codepython_frac_lines_print": 0.0}
1
{"qsc_code_frac_chars_replacement_symbols": 0, "qsc_code_num_words": 0, "qsc_code_num_chars": 0, "qsc_code_mean_word_length": 0, "qsc_code_frac_chars_top_2grams": 0, "qsc_code_frac_chars_top_3grams": 0, "qsc_code_frac_chars_top_4grams": 0, "qsc_code_frac_chars_dupe_5grams": 0, "qsc_code_frac_chars_dupe_6grams": 0, "qsc_code_frac_chars_dupe_7grams": 0, "qsc_code_frac_chars_dupe_8grams": 0, "qsc_code_frac_chars_dupe_9grams": 0, "qsc_code_frac_chars_dupe_10grams": 0, "qsc_code_frac_lines_dupe_lines": 0, "qsc_code_size_file_byte": 0, "qsc_code_num_lines": 0, "qsc_code_num_chars_line_max": 0, "qsc_code_num_chars_line_mean": 0, "qsc_code_frac_chars_alphabet": 0, "qsc_code_frac_chars_digital": 0, "qsc_code_frac_chars_whitespace": 0, "qsc_code_frac_chars_comments": 0, "qsc_code_cate_xml_start": 0, "qsc_code_cate_autogen": 0, "qsc_code_frac_lines_long_string": 0, "qsc_code_frac_chars_string_length": 0, "qsc_code_frac_chars_long_word_length": 0, "qsc_code_cate_encoded_data": 0, "qsc_code_frac_chars_hex_words": 0, "qsc_code_frac_lines_prompt_comments": 0, "qsc_code_frac_lines_assert": 0, "qsc_codepython_cate_ast": 0, "qsc_codepython_frac_lines_func_ratio": 0, "qsc_codepython_cate_var_zero": 0, "qsc_codepython_frac_lines_pass": 0, "qsc_codepython_frac_lines_import": 0, "qsc_codepython_frac_lines_simplefunc": 0, "qsc_codepython_score_lines_no_logic": 0, "qsc_codepython_frac_lines_print": 0}
007gzs/dingtalk-sdk
dingtalk/client/api/ext.py
# -*- coding: utf-8 -*- from __future__ import absolute_import, unicode_literals import six from dingtalk.client.api.base import DingTalkBaseAPI from dingtalk.core.utils import json_loads class Ext(DingTalkBaseAPI): def listlabelgroups(self, offset=0, size=100): """ 标签列表 :param offset: 偏移位置 :param size: 分页大小,最大100 :return: """ return self._top_request( 'dingtalk.corp.ext.listlabelgroups', {'offset': offset, 'size': size}, result_processor=lambda x: json_loads(x) if isinstance(x, six.string_types) else x ) def list(self, offset=0, size=100): """ 外部联系人列表 :param offset: 偏移位置 :param size: 分页大小,最大100 :return: """ return self._top_request( 'dingtalk.corp.ext.list', {'offset': offset, 'size': size}, result_processor=lambda x: json_loads(x) if isinstance(x, six.string_types) else x ) def add(self, name, follower_userid, label_ids, mobile, state_code='86', title=None, share_deptids=(), remark=None, address=None, company_name=None, share_userids=()): """ 添加企业外部联系人 :param name: 名称 :param follower_userid: 负责人userId :param state_code: 手机号国家码 :param mobile: 手机号 :param label_ids: 标签列表 :param title: 职位 :param share_deptids: 共享给的部门ID :param remark: 备注 :param address: 地址 :param company_name: 企业名 :param share_userids: 共享给的员工userId列表 :return: """ return self._top_request( 'dingtalk.corp.ext.add', { 'contact': { 'name': name, 'follower_user': follower_userid, 'state_code': state_code, 'mobile': mobile, 'label_ids': label_ids, 'title': title, 'share_deptids': share_deptids, 'remark': remark, 'address': address, 'company_name': company_name, 'share_userid': share_userids } }, result_processor=lambda x: x['userid'] )
2,292
ext
py
en
python
code
{"qsc_code_num_words": 230, "qsc_code_num_chars": 2292.0, "qsc_code_mean_word_length": 5.11304348, "qsc_code_frac_words_unique": 0.34347826, "qsc_code_frac_chars_top_2grams": 0.02721088, "qsc_code_frac_chars_top_3grams": 0.04081633, "qsc_code_frac_chars_top_4grams": 0.04846939, "qsc_code_frac_chars_dupe_5grams": 0.33928571, "qsc_code_frac_chars_dupe_6grams": 0.30867347, "qsc_code_frac_chars_dupe_7grams": 0.30867347, "qsc_code_frac_chars_dupe_8grams": 0.30867347, "qsc_code_frac_chars_dupe_9grams": 0.27380952, "qsc_code_frac_chars_dupe_10grams": 0.27380952, "qsc_code_frac_chars_replacement_symbols": 0.0, "qsc_code_frac_chars_digital": 0.01168385, "qsc_code_frac_chars_whitespace": 0.36518325, "qsc_code_size_file_byte": 2292.0, "qsc_code_num_lines": 77.0, "qsc_code_num_chars_line_max": 107.0, "qsc_code_num_chars_line_mean": 29.76623377, "qsc_code_frac_chars_alphabet": 0.79656357, "qsc_code_frac_chars_comments": 0.18673647, "qsc_code_cate_xml_start": 0.0, "qsc_code_frac_lines_dupe_lines": 0.18421053, "qsc_code_cate_autogen": 0.0, "qsc_code_frac_lines_long_string": 0.0, "qsc_code_frac_chars_string_length": 0.12606061, "qsc_code_frac_chars_long_word_length": 0.04606061, "qsc_code_frac_lines_string_concat": 0.0, "qsc_code_cate_encoded_data": 0.0, "qsc_code_frac_chars_hex_words": 0.0, "qsc_code_frac_lines_prompt_comments": 0.0, "qsc_code_frac_lines_assert": 0.0, "qsc_codepython_cate_ast": 1.0, "qsc_codepython_frac_lines_func_ratio": 0.07894737, "qsc_codepython_cate_var_zero": false, "qsc_codepython_frac_lines_pass": 0.0, "qsc_codepython_frac_lines_import": 0.10526316, "qsc_codepython_frac_lines_simplefunc": 0.0, "qsc_codepython_score_lines_no_logic": 0.28947368, "qsc_codepython_frac_lines_print": 0.0}
1
{"qsc_code_frac_chars_replacement_symbols": 0, "qsc_code_num_words": 0, "qsc_code_num_chars": 0, "qsc_code_mean_word_length": 0, "qsc_code_frac_chars_top_2grams": 0, "qsc_code_frac_chars_top_3grams": 0, "qsc_code_frac_chars_top_4grams": 0, "qsc_code_frac_chars_dupe_5grams": 0, "qsc_code_frac_chars_dupe_6grams": 0, "qsc_code_frac_chars_dupe_7grams": 0, "qsc_code_frac_chars_dupe_8grams": 0, "qsc_code_frac_chars_dupe_9grams": 0, "qsc_code_frac_chars_dupe_10grams": 0, "qsc_code_frac_lines_dupe_lines": 0, "qsc_code_size_file_byte": 0, "qsc_code_num_lines": 0, "qsc_code_num_chars_line_max": 0, "qsc_code_num_chars_line_mean": 0, "qsc_code_frac_chars_alphabet": 0, "qsc_code_frac_chars_digital": 0, "qsc_code_frac_chars_whitespace": 0, "qsc_code_frac_chars_comments": 0, "qsc_code_cate_xml_start": 0, "qsc_code_cate_autogen": 0, "qsc_code_frac_lines_long_string": 0, "qsc_code_frac_chars_string_length": 0, "qsc_code_frac_chars_long_word_length": 0, "qsc_code_cate_encoded_data": 0, "qsc_code_frac_chars_hex_words": 0, "qsc_code_frac_lines_prompt_comments": 0, "qsc_code_frac_lines_assert": 0, "qsc_codepython_cate_ast": 0, "qsc_codepython_frac_lines_func_ratio": 0, "qsc_codepython_cate_var_zero": 0, "qsc_codepython_frac_lines_pass": 0, "qsc_codepython_frac_lines_import": 0, "qsc_codepython_frac_lines_simplefunc": 0, "qsc_codepython_score_lines_no_logic": 0, "qsc_codepython_frac_lines_print": 0}
007gzs/dingtalk-sdk
dingtalk/client/api/callback.py
# -*- coding: utf-8 -*- from __future__ import absolute_import, unicode_literals from dingtalk.client.api.base import DingTalkBaseAPI class Callback(DingTalkBaseAPI): ALL_CALL_BACK_TAGS = ( 'user_add_org', 'user_modify_org', 'user_leave_org', 'user_active_org', 'org_admin_add', 'org_admin_remove', 'org_dept_create', 'org_dept_modify', 'org_dept_remove', 'org_change', 'org_remove', 'label_user_change', 'label_conf_add', 'label_conf_modify', 'label_conf_del', 'edu_user_insert', 'edu_user_update', 'edu_user_delete', 'edu_user_relation_insert', 'edu_user_relation_update', 'edu_user_relation_delete', 'edu_dept_insert', 'edu_dept_update', 'edu_dept_delete', 'chat_add_member', 'chat_remove_member', 'chat_quit', 'chat_update_owner', 'chat_update_title', 'chat_disband', 'check_in', 'bpms_task_change', 'bpms_instance_change', 'attendance_check_record', 'attendance_schedule_change', 'attendance_overtime_duration', 'meetingroom_book', 'meetingroom_room_info' ) def register_call_back(self, call_back_tags, token, aes_key, url): """ 注册事件回调接口 :param call_back_tags: 需要监听的事件类型 :param token: 加解密需要用到的token :param aes_key: 数据加密密钥 :param url: 接收事件回调的url :return: """ call_back_tag = [] for k in call_back_tags: if k in self.ALL_CALL_BACK_TAGS: call_back_tag.append(k) return self._post( '/call_back/register_call_back', { "call_back_tag": call_back_tag, "token": token, "aes_key": aes_key, "url": url } ) def get_call_back(self): """ 查询事件回调接口 :return: """ return self._get('/call_back/get_call_back') def update_call_back(self, call_back_tags, token, aes_key, url): """ 更新事件回调接口 :param call_back_tags: 需要监听的事件类型 :param token: 加解密需要用到的token :param aes_key: 数据加密密钥 :param url: 接收事件回调的url :return: """ call_back_tag = [] for k in call_back_tags: if k in self.ALL_CALL_BACK_TAGS: call_back_tag.append(k) return self._post( '/call_back/update_call_back', { "call_back_tag": call_back_tag, "token": token, "aes_key": aes_key, "url": url } ) def delete_call_back(self): """ 删除事件回调接口 :return: """ return self._get('/call_back/delete_call_back') def get_call_back_failed_result(self): """ 获取回调失败的结果 :return: """ return self._get('/call_back/get_call_back_failed_result')
2,855
callback
py
en
python
code
{"qsc_code_num_words": 330, "qsc_code_num_chars": 2855.0, "qsc_code_mean_word_length": 4.61212121, "qsc_code_frac_words_unique": 0.26060606, "qsc_code_frac_chars_top_2grams": 0.16819974, "qsc_code_frac_chars_top_3grams": 0.07095926, "qsc_code_frac_chars_top_4grams": 0.02956636, "qsc_code_frac_chars_dupe_5grams": 0.46123522, "qsc_code_frac_chars_dupe_6grams": 0.43823916, "qsc_code_frac_chars_dupe_7grams": 0.42049934, "qsc_code_frac_chars_dupe_8grams": 0.42049934, "qsc_code_frac_chars_dupe_9grams": 0.42049934, "qsc_code_frac_chars_dupe_10grams": 0.37056505, "qsc_code_frac_chars_replacement_symbols": 0.0, "qsc_code_frac_chars_digital": 0.00050505, "qsc_code_frac_chars_whitespace": 0.30647986, "qsc_code_size_file_byte": 2855.0, "qsc_code_num_lines": 92.0, "qsc_code_num_chars_line_max": 120.0, "qsc_code_num_chars_line_mean": 31.0326087, "qsc_code_frac_chars_alphabet": 0.76818182, "qsc_code_frac_chars_comments": 0.11628722, "qsc_code_cate_xml_start": 0.0, "qsc_code_frac_lines_dupe_lines": 0.36, "qsc_code_cate_autogen": 0.0, "qsc_code_frac_lines_long_string": 0.0, "qsc_code_frac_chars_string_length": 0.35649153, "qsc_code_frac_chars_long_word_length": 0.13677812, "qsc_code_frac_lines_string_concat": 0.0, "qsc_code_cate_encoded_data": 0.0, "qsc_code_frac_chars_hex_words": 0.0, "qsc_code_frac_lines_prompt_comments": 0.0, "qsc_code_frac_lines_assert": 0.0, "qsc_codepython_cate_ast": 1.0, "qsc_codepython_frac_lines_func_ratio": 0.1, "qsc_codepython_cate_var_zero": false, "qsc_codepython_frac_lines_pass": 0.0, "qsc_codepython_frac_lines_import": 0.04, "qsc_codepython_frac_lines_simplefunc": 0.0, "qsc_codepython_score_lines_no_logic": 0.28, "qsc_codepython_frac_lines_print": 0.0}
1
{"qsc_code_frac_chars_replacement_symbols": 0, "qsc_code_num_words": 0, "qsc_code_num_chars": 0, "qsc_code_mean_word_length": 0, "qsc_code_frac_chars_top_2grams": 0, "qsc_code_frac_chars_top_3grams": 0, "qsc_code_frac_chars_top_4grams": 0, "qsc_code_frac_chars_dupe_5grams": 0, "qsc_code_frac_chars_dupe_6grams": 0, "qsc_code_frac_chars_dupe_7grams": 0, "qsc_code_frac_chars_dupe_8grams": 0, "qsc_code_frac_chars_dupe_9grams": 0, "qsc_code_frac_chars_dupe_10grams": 0, "qsc_code_frac_lines_dupe_lines": 0, "qsc_code_size_file_byte": 0, "qsc_code_num_lines": 0, "qsc_code_num_chars_line_max": 0, "qsc_code_num_chars_line_mean": 0, "qsc_code_frac_chars_alphabet": 0, "qsc_code_frac_chars_digital": 0, "qsc_code_frac_chars_whitespace": 0, "qsc_code_frac_chars_comments": 0, "qsc_code_cate_xml_start": 0, "qsc_code_cate_autogen": 0, "qsc_code_frac_lines_long_string": 0, "qsc_code_frac_chars_string_length": 0, "qsc_code_frac_chars_long_word_length": 0, "qsc_code_cate_encoded_data": 0, "qsc_code_frac_chars_hex_words": 0, "qsc_code_frac_lines_prompt_comments": 0, "qsc_code_frac_lines_assert": 0, "qsc_codepython_cate_ast": 0, "qsc_codepython_frac_lines_func_ratio": 0, "qsc_codepython_cate_var_zero": 0, "qsc_codepython_frac_lines_pass": 0, "qsc_codepython_frac_lines_import": 0, "qsc_codepython_frac_lines_simplefunc": 0, "qsc_codepython_score_lines_no_logic": 0, "qsc_codepython_frac_lines_print": 0}
0015/Grid_Board
main/grid_board.cpp
#include "grid_board.hpp" #include "esp_log.h" #include "esp_random.h" #include <algorithm> #include <random> #include <cstring> static const char *TAG = "LVGL"; // Static character sets const char *GridBoard::card_chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ.,:;!?@#$%&*()-+=/\\\"'<>[]{}|_^~ °±•…×÷−≠≤≥€£¥™®©"; const char *GridBoard::emoji_chars[] = { "✅", "✔", "✖", "❌", "❤", "️", "📀", "📁", "📂", "📃", "📄", "📅", "📆", "📇", "📈", "📉", "📊", "📋", "📌", "📍", "📎", "📏", "📐", "📑", "📒", "📓", "📔", "📕", "📖", "📗", "📘", "📙", "📚", "📛", "📜", "📝", "📞", "📟", "📠", "📡", "📢", "📣", "📤", "📥", "📦", "📧", "📨", "📩", "📪", "📫", "📬", "📭", "📮", "📯", "📰", "📱", "📲", "📳", "📴", "📵", "📶", "📷", "📸", "📹", "📺", "📻", "📼", "📽", "📿", "😀", "😁", "😂", "😃", "😄", "😅", "😆", "😇", "😈", "😉", "😊", "😋", "😌", "😍", "😎", "😏", "😐", "😑", "😒", "😓", "😔", "😕", "😖", "😗", "😘", "😙", "😚", "😛", "😜", "😝", "😞", "😟", "😠", "😡", "😢", "😣", "😤", "😥", "😦", "😧", "😨", "😩", "😪", "😫", "😬", "😭", "😮", "😯", "😰", "😱", "😲", "😳", "😴", "😵", "😶", "😷", "😸", "😹", "😺", "😻", "😼", "😽", "😾", "😿", "🙀", "🙁", "🙂", "🙃", "🙄", "🙅", "🙆", "🙇", "🙈", "🙉", "🙊", "🙋", "🙌", "🙍", "🙎", "🙏", "🚀", "🚁", "🚂", "🚃", "🚄", "🚅", "🚆", "🚇", "🚈", "🚉", "🚊", "🚋", "🚌", "🚍", "🚎", "🚏", "🚐", "🚑", "🚒", "🚓", "🚔", "🚕", "🚖", "🚗", "🚘", "🚙", "🚚", "🚛", "🚜", "🚝", "🚞", "🚟", "🚠", "🚡", "🚢", "🚣", "🚤", "🚥", "🚦", "🚧", "🚨", "🚩", "🚪", "🚫", "🚬", "🚭", "🚮", "🚯", "🚰", "🚱", "🚲", "🚳", "🚴", "🚵", "🚶", "🚷", "🚸", "🚹", "🚺", "🚻", "🚼", "🚽", "🚾", "🚿", "🛀", "🛁", "🛂", "🛃", "🛄", "🛅", "🛋", "🛌", "🛍", "🛎", "🛏", "🛐", "🛑", "🛒", "🛕", "🛖", "🛗", "🛜", "🛝", "🛞", "🛟", "🛠", "🛡", "🛢", "🛣", "🛤", "🛥", "🛩", "🛫", "🛬", "🛰", "🛳", "🛴", "🛵", "🛶", "🛷", "🛸", "🛹", "🛺", "🛻", "🛼"}; const int GridBoard::total_emoji_cards = sizeof(GridBoard::emoji_chars) / sizeof(GridBoard::emoji_chars[0]); const int GridBoard::total_cards = strlen(GridBoard::card_chars); static std::random_device rd; static std::mt19937 g(rd()); static GridBoard *g_grid_instance = nullptr; GridBoard *get_grid_board_instance() { return g_grid_instance; } // Utility function for typographic quotes replacement static void replace_typographic_quotes(char *str) { if (!str) return; unsigned char *p = (unsigned char *)str; char *out = str; while (*p) { // UTF-8 for ' (U+2018): 0xE2 0x80 0x98 if (p[0] == 0xE2 && p[1] == 0x80 && p[2] == 0x98) { *out++ = '\''; p += 3; } // UTF-8 for ' (U+2019): 0xE2 0x80 0x99 else if (p[0] == 0xE2 && p[1] == 0x80 && p[2] == 0x99) { *out++ = '\''; p += 3; } else { *out++ = *p++; } } *out = 0; } // UTF-8 helper function static uint32_t utf8_next(const char **txt) { const unsigned char *ptr = (const unsigned char *)(*txt); uint32_t codepoint = 0; if (*ptr < 0x80) { codepoint = *ptr; (*txt)++; } else if ((*ptr & 0xE0) == 0xC0) { codepoint = ((*ptr & 0x1F) << 6) | (*(ptr + 1) & 0x3F); (*txt) += 2; } else if ((*ptr & 0xF0) == 0xE0) { codepoint = ((*ptr & 0x0F) << 12) | ((*(ptr + 1) & 0x3F) << 6) | (*(ptr + 2) & 0x3F); (*txt) += 3; } else if ((*ptr & 0xF8) == 0xF0) { codepoint = ((*ptr & 0x07) << 18) | ((*(ptr + 1) & 0x3F) << 12) | ((*(ptr + 2) & 0x3F) << 6) | (*(ptr + 3) & 0x3F); (*txt) += 4; } else { codepoint = *ptr; (*txt)++; } return codepoint; } GridBoard::GridBoard() : running_animations(0), start_card_flip_sound_task(nullptr), stop_card_flip_sound_task(nullptr) { for (int row = 0; row < GRID_ROWS; row++) { for (int col = 0; col < GRID_COLS; col++) { slots[row][col] = nullptr; } } g_grid_instance = this; } GridBoard::~GridBoard() { if (g_grid_instance == this) { g_grid_instance = nullptr; } } void GridBoard::initialize(lv_obj_t *parent) { create_grid(parent); } void GridBoard::set_sound_callback(void (*on_start)(), void (*on_end)()) { start_card_flip_sound_task = on_start; stop_card_flip_sound_task = on_end; } void GridBoard::create_grid(lv_obj_t *parent) { lv_obj_set_style_bg_color(parent, lv_color_hex(0x1A1A1A), 0); int total_width = GRID_COLS * GRID_SLOT_WIDTH + (GRID_COLS - 1) * GRID_GAP; int total_height = GRID_ROWS * GRID_SLOT_HEIGHT + (GRID_ROWS - 1) * GRID_GAP; int x_start = (GRID_SCREEN_WIDTH - total_width) / 2; int y_start = (GRID_SCREEN_HEIGHT - total_height) / 2; for (int row = 0; row < GRID_ROWS; row++) { for (int col = 0; col < GRID_COLS; col++) { int x = x_start + col * (GRID_SLOT_WIDTH + GRID_GAP); int y = y_start + row * (GRID_SLOT_HEIGHT + GRID_GAP); lv_obj_t *slot = lv_obj_create(parent); lv_obj_set_size(slot, GRID_SLOT_WIDTH, GRID_SLOT_HEIGHT); lv_obj_set_pos(slot, x, y); lv_obj_clear_flag(slot, LV_OBJ_FLAG_SCROLLABLE); lv_obj_set_layout(slot, LV_LAYOUT_NONE); lv_obj_set_style_pad_all(slot, 0, 0); lv_obj_set_style_border_width(slot, 1, 0); lv_obj_set_style_border_color(slot, lv_color_hex(0x3A3A3A), 0); lv_obj_set_style_bg_color(slot, lv_color_hex(0x2A2A2A), 0); lv_obj_set_style_radius(slot, 0, 0); slots[row][col] = slot; } } } lv_obj_t *GridBoard::create_card(lv_obj_t *slot, const char *text, const lv_font_t *font) { if (slot == nullptr) { ESP_LOGE(TAG, "Attempted to create card on NULL slot for '%s'", text); return nullptr; } lv_obj_t *card = lv_obj_create(slot); lv_obj_set_size(card, GRID_SLOT_WIDTH, GRID_SLOT_HEIGHT); lv_obj_clear_flag(card, LV_OBJ_FLAG_SCROLLABLE); lv_obj_set_style_bg_color(card, lv_color_hex(0x121212), 0); lv_obj_set_style_border_width(card, 0, 0); lv_obj_set_style_radius(card, 0, 0); lv_obj_set_style_pad_all(card, 0, 0); lv_obj_align(card, LV_ALIGN_TOP_MID, 0, -GRID_SLOT_HEIGHT); lv_obj_t *label = lv_label_create(card); lv_label_set_text(label, text); // Set emoji color if (strcmp(text, "❤") == 0 || strcmp(text, "❤️") == 0) { lv_obj_set_style_text_color(label, lv_color_hex(0xFF4444), 0); // Red heart } else if (font == &NotoEmoji64) { // Random color for other emojis uint8_t r = esp_random() % 200 + 55; uint8_t g = esp_random() % 200 + 55; uint8_t b = esp_random() % 200 + 55; lv_obj_set_style_text_color(label, lv_color_make(r, g, b), 0); } else { lv_obj_set_style_text_color(label, lv_color_white(), 0); } lv_obj_center(label); lv_obj_set_style_text_font(label, font, 0); return card; } bool GridBoard::is_emoji(const char *utf8_char) { const char *tmp = utf8_char; uint32_t cp = utf8_next(&tmp); return ( (cp >= 0x1F600 && cp <= 0x1F64F) || (cp >= 0x1F680 && cp <= 0x1F6FF) || (cp >= 0x1F4C0 && cp <= 0x1F4FF) || cp == 0x2764 || cp == 0x2705 || cp == 0x2714 || cp == 0x274C || cp == 0x2716); } void GridBoard::utf8_to_upper_ascii(char *utf8_char) { // Only handle single-byte ASCII lowercase letters if ((uint8_t)utf8_char[0] >= 'a' && (uint8_t)utf8_char[0] <= 'z') { utf8_char[0] = utf8_char[0] - 32; } } int GridBoard::utf8_char_len(unsigned char c) { if ((c & 0x80) == 0x00) return 1; // ASCII if ((c & 0xE0) == 0xC0) return 2; // 2-byte UTF-8 if ((c & 0xF0) == 0xE0) return 3; // 3-byte UTF-8 if ((c & 0xF8) == 0xF0) return 4; // 4-byte UTF-8 return 1; // fallback } void GridBoard::animate_card_to_slot(lv_obj_t *card, const char *target) { if (start_card_flip_sound_task) { start_card_flip_sound_task(); } lv_anim_t a; lv_anim_init(&a); lv_anim_set_var(&a, card); lv_anim_set_exec_cb(&a, (lv_anim_exec_xcb_t)lv_obj_set_y); lv_anim_set_time(&a, 333); lv_coord_t start_y = -GRID_SLOT_HEIGHT * 2; lv_coord_t end_y = GRID_SLOT_HEIGHT * 1.2; // go beyond bottom lv_anim_set_values(&a, start_y, end_y); lv_anim_set_path_cb(&a, lv_anim_path_ease_out); lv_anim_set_ready_cb(&a, animation_ready_callback); lv_anim_start(&a); } void GridBoard::animation_ready_callback(lv_anim_t *a) { lv_obj_t *card = (lv_obj_t *)a->var; lv_obj_set_y(card, 0); // reset to top before next retry GridBoard *instance = get_grid_board_instance(); if (instance) { instance->on_card_dropped(card); } } void GridBoard::on_card_dropped(lv_obj_t *card) { if (!card) return; lv_obj_t *slot = lv_obj_get_parent(card); GridCharacterSlot *slot_info = (GridCharacterSlot *)lv_obj_get_user_data(card); if (!slot_info || !slot) return; const char *target = slot_info->utf8_char; const char *txt = lv_label_get_text(lv_obj_get_child(card, 0)); if (!target || !txt) return; const int MAX_RETRY_PER_CARD = 30; // 1. If match: show final static card, finish if (strcmp(txt, target) == 0) { running_animations--; lv_obj_t *final_card; if (is_emoji(target)) { final_card = create_card(slot, target, &NotoEmoji64); } else { final_card = create_card(slot, target, &ShareTech140); } lv_obj_set_y(final_card, 0); delete slot_info; lv_obj_del(card); if (running_animations <= 0 && animation_queue.empty()) { if (stop_card_flip_sound_task) { stop_card_flip_sound_task(); } } start_animation_batch(); return; } // 2. If retry count exceeded: force correct answer and finish if (slot_info->retry_index > MAX_RETRY_PER_CARD) { running_animations--; lv_obj_t *final_card; if (is_emoji(target)) { final_card = create_card(slot, target, &NotoEmoji64); } else { final_card = create_card(slot, target, &ShareTech140); } lv_obj_set_y(final_card, 0); delete slot_info; lv_obj_del(card); if (running_animations <= 0 && animation_queue.empty()) { if (stop_card_flip_sound_task) { stop_card_flip_sound_task(); } } start_animation_batch(); return; } // 3. Not matched, keep spinning with next candidate lv_obj_del(card); lv_obj_t *next_card; if (is_emoji(target)) { // Use per-slot shuffled emoji order if present, otherwise random if (!slot_info->shuffled_emojis.empty()) { int i = slot_info->retry_index % slot_info->shuffled_emojis.size(); next_card = create_card(slot, slot_info->shuffled_emojis[i], &NotoEmoji64); } else { next_card = create_card(slot, emoji_chars[esp_random() % total_emoji_cards], &NotoEmoji64); } } else { // Use per-slot shuffled char order if present, otherwise random if (!slot_info->shuffled_chars.empty()) { int i = slot_info->retry_index % slot_info->shuffled_chars.size(); char buf[2] = {slot_info->shuffled_chars[i], '\0'}; next_card = create_card(slot, buf, &ShareTech140); } else { int i = slot_info->retry_index % total_cards; char buf[2] = {card_chars[i], '\0'}; next_card = create_card(slot, buf, &ShareTech140); } } slot_info->retry_index++; lv_obj_set_user_data(next_card, slot_info); animate_card_to_slot(next_card, target); } void GridBoard::timer_callback(lv_timer_t *t) { lv_obj_t *card = (lv_obj_t *)lv_timer_get_user_data(t); GridCharacterSlot *info = (GridCharacterSlot *)lv_obj_get_user_data(card); GridBoard *instance = get_grid_board_instance(); if (instance) { instance->animate_card_to_slot(card, info->utf8_char); } lv_timer_del(t); } void GridBoard::start_animation_batch() { while (running_animations < MAX_PARALLEL_ANIMATIONS && !animation_queue.empty()) { GridCharacterSlot slot_info = animation_queue.back(); animation_queue.pop_back(); running_animations++; GridCharacterSlot *info = new GridCharacterSlot(slot_info); // allocate per-slot lv_obj_t *slot = slots[info->row][info->col]; if (!slot) { delete info; continue; } lv_obj_t *card; if (is_emoji(info->utf8_char)) { card = create_card(slot, emoji_chars[esp_random() % total_emoji_cards], &NotoEmoji64); } else { int i = info->retry_index++ % total_cards; char buf[2] = {card_chars[i], '\0'}; card = create_card(slot, buf, &ShareTech140); } lv_obj_set_user_data(card, info); int delay_ms = (esp_random() % 200) + 100; // between 100–300ms delay lv_timer_t *timer = lv_timer_create_basic(); lv_timer_set_repeat_count(timer, 1); // one-shot lv_timer_set_period(timer, delay_ms); lv_timer_set_user_data(timer, card); lv_timer_set_cb(timer, timer_callback); } } bool GridBoard::is_animation_running() const { return running_animations > 0 || !animation_queue.empty(); } void GridBoard::clear_display() { animation_queue.clear(); running_animations = 0; // Clear grid for (int row = 0; row < GRID_ROWS; row++) { for (int col = 0; col < GRID_COLS; col++) { if (slots[row][col]) { lv_obj_clean(slots[row][col]); } } } } void GridBoard::process_text_and_animate(const std::string &new_text) { clear_display(); if (new_text.empty()) { ESP_LOGI(TAG, "New text is empty, clearing display."); return; } int i = 0; int char_index = 0; while (i < new_text.size() && char_index < GRID_ROWS * GRID_COLS) { int char_len = utf8_char_len((unsigned char)new_text[i]); if (char_len < 1 || i + char_len > new_text.size()) break; char utf8[8] = {0}; memcpy(utf8, &new_text[i], char_len); replace_typographic_quotes(utf8); i += char_len; int row = char_index / GRID_COLS; int col = char_index % GRID_COLS; char_index++; GridCharacterSlot slot{}; memcpy(slot.utf8_char, utf8, sizeof(slot.utf8_char)); slot.row = row; slot.col = col; slot.retry_index = esp_random() % total_cards; // Spaces are static/transparent if (strcmp(slot.utf8_char, " ") == 0) { if (slots[row][col]) { lv_obj_t *space_card = lv_obj_create(slots[row][col]); lv_obj_set_size(space_card, GRID_SLOT_WIDTH, GRID_SLOT_HEIGHT); lv_obj_clear_flag(space_card, LV_OBJ_FLAG_SCROLLABLE); lv_obj_set_style_bg_opa(space_card, LV_OPA_TRANSP, 0); lv_obj_set_style_border_width(space_card, 0, 0); lv_obj_set_y(space_card, 0); } continue; } // Prepare animation sequence for letters/emojis if (is_emoji(slot.utf8_char)) { std::vector<const char *> emojis(emoji_chars, emoji_chars + total_emoji_cards); std::shuffle(emojis.begin(), emojis.end(), g); slot.shuffled_emojis = emojis; } else { std::vector<char> chars(card_chars, card_chars + total_cards); std::shuffle(chars.begin(), chars.end(), g); slot.shuffled_chars = chars; } animation_queue.push_back(slot); } // Fill any missing slots with static blank for (; char_index < GRID_ROWS * GRID_COLS; char_index++) { int row = char_index / GRID_COLS; int col = char_index % GRID_COLS; if (slots[row][col]) { lv_obj_t *space_card = lv_obj_create(slots[row][col]); lv_obj_set_size(space_card, GRID_SLOT_WIDTH, GRID_SLOT_HEIGHT); lv_obj_clear_flag(space_card, LV_OBJ_FLAG_SCROLLABLE); lv_obj_set_style_bg_opa(space_card, LV_OPA_TRANSP, 0); lv_obj_set_style_border_width(space_card, 0, 0); lv_obj_set_y(space_card, 0); } } std::shuffle(animation_queue.begin(), animation_queue.end(), g); start_animation_batch(); }
16,714
grid_board
cpp
hr
cpp
code
{"qsc_code_num_words": 2302, "qsc_code_num_chars": 16714.0, "qsc_code_mean_word_length": 3.73935708, "qsc_code_frac_words_unique": 0.23848827, "qsc_code_frac_chars_top_2grams": 0.04356413, "qsc_code_frac_chars_top_3grams": 0.02973978, "qsc_code_frac_chars_top_4grams": 0.02718401, "qsc_code_frac_chars_dupe_5grams": 0.37012082, "qsc_code_frac_chars_dupe_6grams": 0.31238383, "qsc_code_frac_chars_dupe_7grams": 0.27195632, "qsc_code_frac_chars_dupe_8grams": 0.25487918, "qsc_code_frac_chars_dupe_9grams": 0.24163569, "qsc_code_frac_chars_dupe_10grams": 0.20236989, "qsc_code_frac_chars_replacement_symbols": 0.0, "qsc_code_frac_chars_digital": 0.03245083, "qsc_code_frac_chars_whitespace": 0.27910734, "qsc_code_size_file_byte": 16714.0, "qsc_code_num_lines": 540.0, "qsc_code_num_chars_line_max": 1275.0, "qsc_code_num_chars_line_mean": 30.95185185, "qsc_code_frac_chars_alphabet": 0.65897585, "qsc_code_frac_chars_comments": 0.05492402, "qsc_code_cate_xml_start": 0.0, "qsc_code_frac_lines_dupe_lines": 0.19463087, "qsc_code_cate_autogen": 0.0, "qsc_code_frac_lines_long_string": 0.01118568, "qsc_code_frac_chars_string_length": 0.028235, "qsc_code_frac_chars_long_word_length": 0.00360851, "qsc_code_frac_lines_string_concat": 0.0, "qsc_code_cate_encoded_data": 0.0, "qsc_code_frac_chars_hex_words": 0.01468726, "qsc_code_frac_lines_prompt_comments": 0.0, "qsc_code_frac_lines_assert": 0.0, "qsc_codecpp_frac_lines_preprocessor_directives": 0.01342282, "qsc_codecpp_frac_lines_func_ratio": 0.01118568, "qsc_codecpp_cate_bitsstdc": 0.0, "qsc_codecpp_nums_lines_main": 0.0, "qsc_codecpp_frac_lines_goto": 0.0, "qsc_codecpp_cate_var_zero": 0.0, "qsc_codecpp_score_lines_no_logic": 0.049217, "qsc_codecpp_frac_lines_print": 0.0}
0
{"qsc_code_frac_chars_replacement_symbols": 0, "qsc_code_num_words": 0, "qsc_code_num_chars": 0, "qsc_code_mean_word_length": 0, "qsc_code_frac_chars_top_2grams": 0, "qsc_code_frac_chars_top_3grams": 0, "qsc_code_frac_chars_top_4grams": 0, "qsc_code_frac_chars_dupe_5grams": 0, "qsc_code_frac_chars_dupe_6grams": 0, "qsc_code_frac_chars_dupe_7grams": 0, "qsc_code_frac_chars_dupe_8grams": 0, "qsc_code_frac_chars_dupe_9grams": 0, "qsc_code_frac_chars_dupe_10grams": 0, "qsc_code_frac_lines_dupe_lines": 0, "qsc_code_size_file_byte": 0, "qsc_code_num_lines": 0, "qsc_code_num_chars_line_max": 1, "qsc_code_num_chars_line_mean": 0, "qsc_code_frac_chars_alphabet": 0, "qsc_code_frac_chars_digital": 0, "qsc_code_frac_chars_whitespace": 0, "qsc_code_frac_chars_comments": 0, "qsc_code_cate_xml_start": 0, "qsc_code_cate_autogen": 0, "qsc_code_frac_lines_long_string": 0, "qsc_code_frac_chars_string_length": 0, "qsc_code_frac_chars_long_word_length": 0, "qsc_code_cate_encoded_data": 0, "qsc_code_frac_chars_hex_words": 0, "qsc_code_frac_lines_prompt_comments": 0, "qsc_code_frac_lines_assert": 0, "qsc_codecpp_frac_lines_func_ratio": 0, "qsc_codecpp_nums_lines_main": 0, "qsc_codecpp_score_lines_no_logic": 0, "qsc_codecpp_frac_lines_preprocessor_directives": 0, "qsc_codecpp_frac_lines_print": 0}
0015/Grid_Board
main/ble_server.c
#include "ble_server.h" #include "esp_log.h" #include "nvs_flash.h" #include "host/util/util.h" #include "nimble/nimble_port.h" #include "nimble/nimble_port_freertos.h" #include "host/ble_hs.h" #include "services/gap/ble_svc_gap.h" #include "services/gatt/ble_svc_gatt.h" #include "bleprph.h" static void (*conn_cb)(bool) = NULL; static void (*write_cb)(const uint8_t *, uint16_t) = NULL; static int ble_gap_event_cb(struct ble_gap_event *event, void *arg); static void ble_host_task(void *param) { nimble_port_run(); nimble_port_freertos_deinit(); } static void ble_on_sync(void) { int rc = ble_hs_util_ensure_addr(0); assert(rc == 0); uint8_t addr_val[6]; ble_hs_id_copy_addr(BLE_OWN_ADDR_PUBLIC, addr_val, NULL); ESP_LOGI("BLE_SERVER", "Device Address: %02X:%02X:%02X:%02X:%02X:%02X", addr_val[5], addr_val[4], addr_val[3], addr_val[2], addr_val[1], addr_val[0]); struct ble_gap_adv_params adv_params = {0}; struct ble_hs_adv_fields fields = {0}; fields.flags = BLE_HS_ADV_F_DISC_GEN | BLE_HS_ADV_F_BREDR_UNSUP; fields.tx_pwr_lvl_is_present = 1; fields.tx_pwr_lvl = BLE_HS_ADV_TX_PWR_LVL_AUTO; const char *name = ble_svc_gap_device_name(); fields.name = (uint8_t *)name; fields.name_len = strlen(name); fields.name_is_complete = 1; ble_gap_adv_set_fields(&fields); adv_params.conn_mode = BLE_GAP_CONN_MODE_UND; adv_params.disc_mode = BLE_GAP_DISC_MODE_GEN; ble_gap_adv_start(BLE_OWN_ADDR_PUBLIC, NULL, BLE_HS_FOREVER, &adv_params, ble_gap_event_cb, NULL); } static void ble_on_reset(int reason) { ESP_LOGE("BLE_SERVER", "Resetting state; reason=%d", reason); } static int ble_gap_event_cb(struct ble_gap_event *event, void *arg) { switch (event->type) { case BLE_GAP_EVENT_CONNECT: if (conn_cb) conn_cb(event->connect.status == 0); if (event->connect.status != 0) ble_on_sync(); break; case BLE_GAP_EVENT_DISCONNECT: if (conn_cb) conn_cb(false); ble_on_sync(); break; default: break; } return 0; } void ble_server_register_callbacks(void (*on_connect)(bool), void (*on_write)(const uint8_t *, uint16_t)) { conn_cb = on_connect; write_cb = on_write; gatt_svr_set_write_callback(write_cb); } void ble_server_start(const char *device_name) { nimble_port_init(); ble_hs_cfg.reset_cb = ble_on_reset; ble_hs_cfg.sync_cb = ble_on_sync; ble_hs_cfg.gatts_register_cb = gatt_svr_register_cb; ble_hs_cfg.store_status_cb = ble_store_util_status_rr; gatt_svr_init(); ble_svc_gap_init(); ble_svc_gatt_init(); if (device_name) { ble_svc_gap_device_name_set(device_name); } nimble_port_freertos_init(ble_host_task); }
2,806
ble_server
c
en
c
code
{"qsc_code_num_words": 453, "qsc_code_num_chars": 2806.0, "qsc_code_mean_word_length": 3.88300221, "qsc_code_frac_words_unique": 0.24503311, "qsc_code_frac_chars_top_2grams": 0.03411029, "qsc_code_frac_chars_top_3grams": 0.04377487, "qsc_code_frac_chars_top_4grams": 0.02217169, "qsc_code_frac_chars_dupe_5grams": 0.15804434, "qsc_code_frac_chars_dupe_6grams": 0.08413872, "qsc_code_frac_chars_dupe_7grams": 0.05798749, "qsc_code_frac_chars_dupe_8grams": 0.05798749, "qsc_code_frac_chars_dupe_9grams": 0.05798749, "qsc_code_frac_chars_dupe_10grams": 0.05798749, "qsc_code_frac_chars_replacement_symbols": 0.0, "qsc_code_frac_chars_digital": 0.01573427, "qsc_code_frac_chars_whitespace": 0.18460442, "qsc_code_size_file_byte": 2806.0, "qsc_code_num_lines": 103.0, "qsc_code_num_chars_line_max": 106.0, "qsc_code_num_chars_line_mean": 27.24271845, "qsc_code_frac_chars_alphabet": 0.75305944, "qsc_code_frac_chars_comments": 0.0, "qsc_code_cate_xml_start": 0.0, "qsc_code_frac_lines_dupe_lines": 0.08139535, "qsc_code_cate_autogen": 0.0, "qsc_code_frac_lines_long_string": 0.0, "qsc_code_frac_chars_string_length": 0.09405059, "qsc_code_frac_chars_long_word_length": 0.03990025, "qsc_code_frac_lines_string_concat": 0.0, "qsc_code_cate_encoded_data": 0.0, "qsc_code_frac_chars_hex_words": 0.0, "qsc_code_frac_lines_prompt_comments": 0.0, "qsc_code_frac_lines_assert": 0.01162791, "qsc_codec_frac_lines_func_ratio": 0.08139535, "qsc_codec_cate_bitsstdc": 0.0, "qsc_codec_nums_lines_main": 0, "qsc_codec_frac_lines_goto": 0.0, "qsc_codec_cate_var_zero": 0.0, "qsc_codec_score_lines_no_logic": 0.20930233, "qsc_codec_frac_lines_print": 0.0, "qsc_codec_frac_lines_preprocessor_directives": 0.1627907}
1
{"qsc_code_frac_chars_replacement_symbols": 0, "qsc_code_num_words": 0, "qsc_code_num_chars": 0, "qsc_code_mean_word_length": 0, "qsc_code_frac_chars_top_2grams": 0, "qsc_code_frac_chars_top_3grams": 0, "qsc_code_frac_chars_top_4grams": 0, "qsc_code_frac_chars_dupe_5grams": 0, "qsc_code_frac_chars_dupe_6grams": 0, "qsc_code_frac_chars_dupe_7grams": 0, "qsc_code_frac_chars_dupe_8grams": 0, "qsc_code_frac_chars_dupe_9grams": 0, "qsc_code_frac_chars_dupe_10grams": 0, "qsc_code_size_file_byte": 0, "qsc_code_num_lines": 0, "qsc_code_num_chars_line_max": 0, "qsc_code_num_chars_line_mean": 0, "qsc_code_frac_chars_alphabet": 0, "qsc_code_frac_chars_digital": 0, "qsc_code_frac_chars_whitespace": 0, "qsc_code_frac_chars_comments": 0, "qsc_code_cate_xml_start": 0, "qsc_code_frac_lines_dupe_lines": 0, "qsc_code_cate_autogen": 0, "qsc_code_frac_lines_long_string": 0, "qsc_code_frac_chars_string_length": 0, "qsc_code_frac_chars_long_word_length": 0, "qsc_code_cate_encoded_data": 0, "qsc_code_frac_chars_hex_words": 0, "qsc_code_frac_lines_prompt_comments": 0, "qsc_code_frac_lines_assert": 0, "qsc_codec_frac_lines_func_ratio": 0, "qsc_codec_nums_lines_main": 0, "qsc_codec_score_lines_no_logic": 0, "qsc_codec_frac_lines_preprocessor_directives": 0, "qsc_codec_frac_lines_print": 0}
007gzs/dingtalk-sdk
dingtalk/client/api/extcontact.py
# -*- coding: utf-8 -*- from __future__ import absolute_import, unicode_literals from dingtalk.client.api.base import DingTalkBaseAPI class ExtContact(DingTalkBaseAPI): def listlabelgroups(self, offset=0, size=100): """ 获取外部联系人标签列表 :param size: 分页大小,最大100 :param offset: 偏移位置 """ return self._top_request( "dingtalk.oapi.extcontact.listlabelgroups", {"size": size, "offset": offset} ) def list(self, offset=0, size=100): """ 获取外部联系人列表 :param size: 分页大小, 最大100 :param offset: 偏移位置 """ return self._top_request( "dingtalk.oapi.extcontact.list", {"size": size, "offset": offset} ) def get(self, user_id): """ 获取企业外部联系人详情 :param user_id: userId """ return self._top_request( "dingtalk.oapi.extcontact.get", {"user_id": user_id} ) def create(self, name, follower_user_id, label_ids, mobile, state_code='86', title=None, share_dept_ids=(), remark=None, address=None, company_name=None, share_user_ids=()): """ 添加外部联系人 :param name: 名称 :param follower_user_id: 负责人userId :param state_code: 手机号国家码 :param mobile: 手机号 :param label_ids: 标签列表 :param title: 职位 :param share_dept_ids: 共享给的部门ID :param remark: 备注 :param address: 地址 :param company_name: 企业名 :param share_user_ids: 共享给的员工userId列表 :return: """ if not isinstance(label_ids, (list, tuple, set)): label_ids = (label_ids, ) if not isinstance(share_dept_ids, (list, tuple, set)): share_dept_ids = (share_dept_ids, ) if not isinstance(share_user_ids, (list, tuple, set)): share_user_ids = (share_user_ids, ) return self._top_request( "dingtalk.oapi.extcontact.create", { "contact": { 'name': name, 'follower_user_id': follower_user_id, 'state_code': state_code, 'mobile': mobile, 'label_ids': label_ids, 'title': title, 'share_dept_ids': share_dept_ids, 'remark': remark, 'address': address, 'company_name': company_name, 'share_user_ids': share_user_ids } }, result_processor=lambda x: x['userid'] ) def update(self, user_id, name, follower_user_id, label_ids, mobile, state_code='86', title=None, share_dept_ids=(), remark=None, address=None, company_name=None, share_user_ids=()): """ 更新外部联系人 :param user_id: 该外部联系人的userId :param name: 名称 :param follower_user_id: 负责人userId :param state_code: 手机号国家码 :param mobile: 手机号 :param label_ids: 标签列表 :param title: 职位 :param share_dept_ids: 共享给的部门ID :param remark: 备注 :param address: 地址 :param company_name: 企业名 :param share_user_ids: 共享给的员工userId列表 :return: """ if not isinstance(label_ids, (list, tuple, set)): label_ids = (label_ids, ) if not isinstance(share_dept_ids, (list, tuple, set)): share_dept_ids = (share_dept_ids, ) if not isinstance(share_user_ids, (list, tuple, set)): share_user_ids = (share_user_ids, ) return self._top_request( "dingtalk.oapi.extcontact.update", { "contact": { "user_id": user_id, 'name': name, 'follower_user_id': follower_user_id, 'state_code': state_code, 'mobile': mobile, 'label_ids': label_ids, 'title': title, 'share_dept_ids': share_dept_ids, 'remark': remark, 'address': address, 'company_name': company_name, 'share_user_ids': share_user_ids } } ) def delete(self, user_id): """ 删除外部联系人 :param user_id: 用户id """ return self._top_request( "dingtalk.oapi.extcontact.delete", {"user_id": user_id} )
4,510
extcontact
py
en
python
code
{"qsc_code_num_words": 460, "qsc_code_num_chars": 4510.0, "qsc_code_mean_word_length": 4.82173913, "qsc_code_frac_words_unique": 0.18043478, "qsc_code_frac_chars_top_2grams": 0.0541028, "qsc_code_frac_chars_top_3grams": 0.07574391, "qsc_code_frac_chars_top_4grams": 0.0541028, "qsc_code_frac_chars_dupe_5grams": 0.79981966, "qsc_code_frac_chars_dupe_6grams": 0.76284941, "qsc_code_frac_chars_dupe_7grams": 0.76284941, "qsc_code_frac_chars_dupe_8grams": 0.72497746, "qsc_code_frac_chars_dupe_9grams": 0.72497746, "qsc_code_frac_chars_dupe_10grams": 0.72497746, "qsc_code_frac_chars_replacement_symbols": 0.0, "qsc_code_frac_chars_digital": 0.00676397, "qsc_code_frac_chars_whitespace": 0.37716186, "qsc_code_size_file_byte": 4510.0, "qsc_code_num_lines": 142.0, "qsc_code_num_chars_line_max": 112.0, "qsc_code_num_chars_line_mean": 31.76056338, "qsc_code_frac_chars_alphabet": 0.78284087, "qsc_code_frac_chars_comments": 0.17804878, "qsc_code_cate_xml_start": 0.0, "qsc_code_frac_lines_dupe_lines": 0.62337662, "qsc_code_cate_autogen": 0.0, "qsc_code_frac_lines_long_string": 0.0, "qsc_code_frac_chars_string_length": 0.13885542, "qsc_code_frac_chars_long_word_length": 0.05722892, "qsc_code_frac_lines_string_concat": 0.0, "qsc_code_cate_encoded_data": 0.0, "qsc_code_frac_chars_hex_words": 0.0, "qsc_code_frac_lines_prompt_comments": 0.0, "qsc_code_frac_lines_assert": 0.0, "qsc_codepython_cate_ast": 1.0, "qsc_codepython_frac_lines_func_ratio": 0.07792208, "qsc_codepython_cate_var_zero": false, "qsc_codepython_frac_lines_pass": 0.0, "qsc_codepython_frac_lines_import": 0.02597403, "qsc_codepython_frac_lines_simplefunc": 0.0, "qsc_codepython_score_lines_no_logic": 0.19480519, "qsc_codepython_frac_lines_print": 0.0}
0
{"qsc_code_frac_chars_replacement_symbols": 0, "qsc_code_num_words": 0, "qsc_code_num_chars": 0, "qsc_code_mean_word_length": 0, "qsc_code_frac_chars_top_2grams": 0, "qsc_code_frac_chars_top_3grams": 0, "qsc_code_frac_chars_top_4grams": 0, "qsc_code_frac_chars_dupe_5grams": 0, "qsc_code_frac_chars_dupe_6grams": 1, "qsc_code_frac_chars_dupe_7grams": 1, "qsc_code_frac_chars_dupe_8grams": 1, "qsc_code_frac_chars_dupe_9grams": 1, "qsc_code_frac_chars_dupe_10grams": 1, "qsc_code_frac_lines_dupe_lines": 0, "qsc_code_size_file_byte": 0, "qsc_code_num_lines": 0, "qsc_code_num_chars_line_max": 0, "qsc_code_num_chars_line_mean": 0, "qsc_code_frac_chars_alphabet": 0, "qsc_code_frac_chars_digital": 0, "qsc_code_frac_chars_whitespace": 0, "qsc_code_frac_chars_comments": 0, "qsc_code_cate_xml_start": 0, "qsc_code_cate_autogen": 0, "qsc_code_frac_lines_long_string": 0, "qsc_code_frac_chars_string_length": 0, "qsc_code_frac_chars_long_word_length": 0, "qsc_code_cate_encoded_data": 0, "qsc_code_frac_chars_hex_words": 0, "qsc_code_frac_lines_prompt_comments": 0, "qsc_code_frac_lines_assert": 0, "qsc_codepython_cate_ast": 0, "qsc_codepython_frac_lines_func_ratio": 0, "qsc_codepython_cate_var_zero": 0, "qsc_codepython_frac_lines_pass": 0, "qsc_codepython_frac_lines_import": 0, "qsc_codepython_frac_lines_simplefunc": 0, "qsc_codepython_score_lines_no_logic": 0, "qsc_codepython_frac_lines_print": 0}
007gzs/meeting
server/apps/meetings/serializer.py
# encoding: utf-8 from __future__ import absolute_import, unicode_literals from rest_framework import serializers from apps.wechat.models import User from apps.wechat.serializer import UserSerializer from core import utils from . import models class RoomSerializer(utils.BaseSerializer): class Meta: model = models.Room fields = ('id', 'name', 'description') class RoomDetailSerializer(utils.BaseSerializer): is_follow = serializers.SerializerMethodField("func_is_follow") def func_is_follow(self, obj): assert isinstance(self.request.user, User) return models.UserFollowRoom.objects.filter(user_id=self.request.user.pk, room_id=obj.pk).exists() class Meta: model = models.Room fields = ('id', 'name', 'description', 'qr_code', 'create_user', 'is_follow', 'create_user_manager') class MeetingSerializer(utils.BaseSerializer): class Meta: model = models.Meeting fields = ('id', 'user', 'room', 'date', 'start_time', 'end_time', 'name', 'description') class MeetingDetailSerializer(utils.BaseSerializer): user = UserSerializer(many=False, read_only=True) room = RoomSerializer(many=False, read_only=True) attendees = UserSerializer(many=True, read_only=True) is_manager = serializers.SerializerMethodField("func_is_manager") def func_is_manager(self, obj): if self.request is None or not isinstance(self.request.user, User): return False return self.request.user.pk == obj.user_id or ( obj.room.create_user_manager and self.request.user.pk == obj.room.create_user_id ) class Meta: model = models.Meeting fields = ( 'id', 'user', 'room', 'date', 'start_time', 'end_time', 'attendees', 'name', 'description', 'is_manager' )
1,831
serializer
py
en
python
code
{"qsc_code_num_words": 219, "qsc_code_num_chars": 1831.0, "qsc_code_mean_word_length": 5.59817352, "qsc_code_frac_words_unique": 0.31506849, "qsc_code_frac_chars_top_2grams": 0.05383361, "qsc_code_frac_chars_top_3grams": 0.06117455, "qsc_code_frac_chars_top_4grams": 0.06525285, "qsc_code_frac_chars_dupe_5grams": 0.33442088, "qsc_code_frac_chars_dupe_6grams": 0.2675367, "qsc_code_frac_chars_dupe_7grams": 0.17944535, "qsc_code_frac_chars_dupe_8grams": 0.17944535, "qsc_code_frac_chars_dupe_9grams": 0.17944535, "qsc_code_frac_chars_dupe_10grams": 0.10277325, "qsc_code_frac_chars_replacement_symbols": 0.0, "qsc_code_frac_chars_digital": 0.00067843, "qsc_code_frac_chars_whitespace": 0.19497542, "qsc_code_size_file_byte": 1831.0, "qsc_code_num_lines": 54.0, "qsc_code_num_chars_line_max": 117.0, "qsc_code_num_chars_line_mean": 33.90740741, "qsc_code_frac_chars_alphabet": 0.83107191, "qsc_code_frac_chars_comments": 0.00819224, "qsc_code_cate_xml_start": 0.0, "qsc_code_frac_lines_dupe_lines": 0.21052632, "qsc_code_cate_autogen": 0.0, "qsc_code_frac_lines_long_string": 0.0, "qsc_code_frac_chars_string_length": 0.12238148, "qsc_code_frac_chars_long_word_length": 0.0, "qsc_code_frac_lines_string_concat": 0.0, "qsc_code_cate_encoded_data": 0.0, "qsc_code_frac_chars_hex_words": 0.0, "qsc_code_frac_lines_prompt_comments": 0.0, "qsc_code_frac_lines_assert": 0.02631579, "qsc_codepython_cate_ast": 1.0, "qsc_codepython_frac_lines_func_ratio": 0.05263158, "qsc_codepython_cate_var_zero": false, "qsc_codepython_frac_lines_pass": 0.0, "qsc_codepython_frac_lines_import": 0.15789474, "qsc_codepython_frac_lines_simplefunc": 0.0, "qsc_codepython_score_lines_no_logic": 0.63157895, "qsc_codepython_frac_lines_print": 0.0}
1
{"qsc_code_frac_chars_replacement_symbols": 0, "qsc_code_num_words": 0, "qsc_code_num_chars": 0, "qsc_code_mean_word_length": 0, "qsc_code_frac_chars_top_2grams": 0, "qsc_code_frac_chars_top_3grams": 0, "qsc_code_frac_chars_top_4grams": 0, "qsc_code_frac_chars_dupe_5grams": 0, "qsc_code_frac_chars_dupe_6grams": 0, "qsc_code_frac_chars_dupe_7grams": 0, "qsc_code_frac_chars_dupe_8grams": 0, "qsc_code_frac_chars_dupe_9grams": 0, "qsc_code_frac_chars_dupe_10grams": 0, "qsc_code_frac_lines_dupe_lines": 0, "qsc_code_size_file_byte": 0, "qsc_code_num_lines": 0, "qsc_code_num_chars_line_max": 0, "qsc_code_num_chars_line_mean": 0, "qsc_code_frac_chars_alphabet": 0, "qsc_code_frac_chars_digital": 0, "qsc_code_frac_chars_whitespace": 0, "qsc_code_frac_chars_comments": 0, "qsc_code_cate_xml_start": 0, "qsc_code_cate_autogen": 0, "qsc_code_frac_lines_long_string": 0, "qsc_code_frac_chars_string_length": 0, "qsc_code_frac_chars_long_word_length": 0, "qsc_code_cate_encoded_data": 0, "qsc_code_frac_chars_hex_words": 0, "qsc_code_frac_lines_prompt_comments": 0, "qsc_code_frac_lines_assert": 0, "qsc_codepython_cate_ast": 0, "qsc_codepython_frac_lines_func_ratio": 0, "qsc_codepython_cate_var_zero": 0, "qsc_codepython_frac_lines_pass": 0, "qsc_codepython_frac_lines_import": 0, "qsc_codepython_frac_lines_simplefunc": 0, "qsc_codepython_score_lines_no_logic": 0, "qsc_codepython_frac_lines_print": 0}
007gzs/meeting
server/apps/meetings/views.py
# encoding: utf-8 from __future__ import absolute_import, unicode_literals import datetime import json from cool.views import ViewSite, CoolAPIException, ErrorCode, mixins from cool.views.fields import SplitCharField from rest_framework import fields from constance import config from django.db import transaction from django.db.models import Q from apps.wechat import biz from apps.wechat.views import UserBaseView from core import utils, constants as core_constants from . import models, serializer, constants site = ViewSite(name='meetings', app_name='meetings') class BaseView(UserBaseView): @staticmethod def get_room_follow(room_id, user_id): follow, _ = models.UserFollowRoom.default_manager.get_or_create( room_id=room_id, user_id=user_id ) return follow @classmethod def response_info_date_time_settings(cls): return { 'start_time': '开始时间', 'end_time': '结束时间', 'start_date': '开始日期', 'end_date': '结束日期', 'history_start_date': '历史开始日期', 'history_end_date': '历史结束日期' } @staticmethod def get_date_time_settings(): today = datetime.date.today() return { 'start_time': config.RESERVE_START_TIME, 'end_time': config.RESERVE_END_TIME, 'start_date': today, 'end_date': today + datetime.timedelta(days=config.SELECT_DATE_DAYS), 'history_start_date': today - datetime.timedelta(days=config.MAX_HISTORY_DAYS), 'history_end_date': today } def get_context(self, request, *args, **kwargs): raise NotImplementedError class Meta: path = '/' @site class Config(BaseView): name = "配置信息" def get_context(self, request, *args, **kwargs): return { 'reserve_start_time': config.RESERVE_START_TIME, 'reserve_end_time': config.RESERVE_END_TIME, 'select_date_days': config.SELECT_DATE_DAYS } @site class RoomCreate(mixins.AddMixin, BaseView): model = models.Room response_info_serializer_class = serializer.RoomSerializer add_fields = ['name', 'description', 'create_user_manager'] def init_fields(self, request, obj): obj.create_user_id = request.user.pk super().init_fields(request, obj) def save_obj(self, request, obj): super().save_obj(request, obj) try: obj.qr_code = biz.get_wxa_code_unlimited_file( "room_%d.jpg" % obj.pk, scene="room_id=%d" % obj.pk, page="pages/room/detail" ) obj.save(update_fields=['qr_code', ], force_update=True) except Exception: utils.exception_logging.exception("get_wxa_code_unlimited_file", extra={'request': request}) self.get_room_follow(obj.pk, request.user.pk) class RoomBase(BaseView): check_manager = False def check_api_permissions(self, request, *args, **kwargs): super(RoomBase, self).check_api_permissions(request, *args, **kwargs) room = models.Room.get_obj_by_pk_from_cache(request.params.room_id) if room is None: raise CoolAPIException(ErrorCode.ERR_MEETING_ROOM_NOT_FOUND) setattr(self, 'room', room) if self.check_manager: if room.create_user_id != request.user.pk: raise CoolAPIException(ErrorCode.ERROR_PERMISSION) def get_context(self, request, *args, **kwargs): raise NotImplementedError class Meta: path = '/' param_fields = ( ('room_id', fields.IntegerField(label='会议室ID')), ) @site class RoomEdit(RoomBase): name = "修改会议室" check_manager = True response_info_serializer_class = serializer.RoomSerializer def get_context(self, request, *args, **kwargs): self.room.name = request.params.name self.room.description = request.params.description update_fields = ['name', 'description'] if request.params.create_user_manager is not None: self.room.create_user_manager = request.params.create_user_manager update_fields.append('create_user_manager') self.room.save(force_update=True, update_fields=update_fields) return self.room class Meta: param_fields = ( ('name', fields.CharField(label='名称', max_length=64)), ('description', fields.CharField(label='描述', max_length=255, allow_blank=True, default="")), ('create_user_manager', fields.NullBooleanField(label='创建人管理权限', default=None)), ) @site class RoomDelete(RoomBase): name = "删除会议室" check_manager = True def get_context(self, request, *args, **kwargs): self.room.delete() return {} @site class RoomInfo(RoomBase): name = "会议室信息" response_info_serializer_class = serializer.RoomDetailSerializer def get_context(self, request, *args, **kwargs): return self.room @site class RoomFollow(BaseView): name = "关注会议室" def get_context(self, request, *args, **kwargs): if len(request.params.room_id) > 50: raise CoolAPIException(ErrorCode.ERROR_BAD_PARAMETER) for room_id in request.params.room_id: self.get_room_follow(room_id, request.user.pk).un_delete() return {} class Meta: param_fields = ( ('room_id', SplitCharField(label='会议室ID列表', sep=',', child=fields.IntegerField())), ) @site class RoomUnFollow(BaseView): name = "取消关注会议室" def get_context(self, request, *args, **kwargs): follow = models.UserFollowRoom.objects.filter(room_id=request.params.room_id, user_id=request.user.pk).first() if follow is None: raise CoolAPIException(ErrorCode.ERROR_BAD_PARAMETER) follow.delete() return {} class Meta: param_fields = ( ('room_id', fields.IntegerField(label='会议室ID')), ) @site class FollowRooms(BaseView): name = "已关注会议室列表" response_info_serializer_class = serializer.RoomSerializer response_many = True def get_context(self, request, *args, **kwargs): return models.Room.objects.filter( follows__user_id=request.user.pk, follows__delete_status=core_constants.DeleteCode.NORMAL.code ) @site class CreateRooms(BaseView): name = "创建会议室列表" response_info_serializer_class = serializer.RoomSerializer response_many = True def get_context(self, request, *args, **kwargs): return models.Room.objects.filter(create_user_id=request.user.pk) @site class RoomMeetings(BaseView): name = "会议室预约列表" @classmethod def response_info_data(cls): from cool.views.utils import get_serializer_info ret = cls.response_info_date_time_settings() ret.update({ 'rooms': get_serializer_info(serializer.RoomSerializer(), True), 'meetings': get_serializer_info(serializer.MeetingSerializer(), True) }) return ret def get_context(self, request, *args, **kwargs): if len(request.params.room_ids) > 10: raise CoolAPIException(ErrorCode.ERROR_BAD_PARAMETER) d = datetime.date.today() if request.params.date is not None: d = request.params.date rooms = list(sorted(models.Room.objects.filter( id__in=request.params.room_ids), key=lambda x: request.params.room_ids.index(x.id) )) meetings = models.Meeting.objects.filter(room_id__in=request.params.room_ids, date=d).order_by('start_time') ret = self.get_date_time_settings() ret.update({ 'rooms': serializer.RoomSerializer(rooms, request=request, many=True).data, 'meetings': serializer.MeetingSerializer(meetings, request=request, many=True).data }) return ret class Meta: param_fields = ( ('room_ids', SplitCharField(label='会议室ID列表', sep=',', child=fields.IntegerField())), ('date', utils.DateField(label='日期', default=None)), ) @site class HistoryMeetings(RoomBase): name = "会议室预约历史" check_manager = True @classmethod def response_info_data(cls): from cool.views.utils import get_serializer_info ret = cls.response_info_date_time_settings() ret.update({'meetings': get_serializer_info(serializer.MeetingSerializer(), True)}) return ret def get_context(self, request, *args, **kwargs): meetings = models.Meeting.objects.filter( room_id=self.room.pk, date__gte=request.params.start_date, date__lte=request.params.end_date ).order_by('date', 'start_time') ret = self.get_date_time_settings() ret.update({'meetings': serializer.MeetingSerializer(meetings, request=request, many=True).data}) return ret class Meta: param_fields = ( ('start_date', utils.DateField(label='开始日期')), ('end_date', utils.DateField(label='结束日期')), ) @site class MyMeetings(BaseView): name = "我参与的会议列表" @classmethod def response_info_data(cls): from cool.views.utils import get_serializer_info ret = cls.response_info_date_time_settings() ret.update({ 'rooms': get_serializer_info(serializer.RoomSerializer(), True), 'meetings': get_serializer_info(serializer.MeetingSerializer(), True) }) return ret def get_context(self, request, *args, **kwargs): d = datetime.date.today() if request.params.date is not None: d = request.params.date meetings = list(models.Meeting.objects.filter( id__in=models.MeetingAttendee.objects.filter( user_id=request.user.pk, meeting__date=d ).values_list('meeting', flat=True) )) rooms = list(models.Room.objects.filter(id__in=set(map(lambda x: x.room_id, meetings)))) ret = self.get_date_time_settings() ret.update({ 'rooms': serializer.RoomSerializer(rooms, request=request, many=True).data, 'meetings': serializer.MeetingSerializer(meetings, request=request, many=True).data }) return ret class Meta: param_fields = ( ('date', utils.DateField(label='日期', default=None)), ) @site class Reserve(BaseView): name = "预约会议" response_info_serializer_class = serializer.MeetingDetailSerializer @staticmethod def time_ok(t): return t.second == 0 and t.microsecond == 0 and t.minute in (0, 30) def get_context(self, request, *args, **kwargs): if request.params.start_time >= request.params.end_time: raise CoolAPIException(ErrorCode.ERROR_BAD_PARAMETER) if not self.time_ok(request.params.start_time) or not self.time_ok(request.params.end_time): raise CoolAPIException(ErrorCode.ERROR_BAD_PARAMETER) now = datetime.datetime.now() if request.params.date == now.date() and request.params.start_time < now.time(): raise CoolAPIException(ErrorCode.ERR_MEETING_ROOM_TIMEOVER) with transaction.atomic(): if models.Meeting.objects.filter(room_id=request.params.room_id, date=request.params.date).filter( (Q(start_time__lte=request.params.start_time) & Q(end_time__gt=request.params.start_time)) | (Q(start_time__lt=request.params.end_time) & Q(end_time__gte=request.params.end_time)) | (Q(start_time__lte=request.params.start_time) & Q(start_time__gt=request.params.end_time)) | (Q(end_time__lt=request.params.start_time) & Q(end_time__gte=request.params.end_time)) ).select_for_update().exists(): raise CoolAPIException(ErrorCode.ERR_MEETING_ROOM_INUSE) meeting = models.Meeting.objects.create( user_id=request.user.pk, room_id=request.params.room_id, name=request.params.name, description=request.params.description, date=request.params.date, start_time=request.params.start_time, end_time=request.params.end_time, ) models.MeetingAttendee.objects.create( user_id=request.user.pk, meeting_id=meeting.pk ) self.get_room_follow(request.params.room_id, request.user.pk) return meeting class Meta: param_fields = ( ('room_id', fields.IntegerField(label='会议室ID')), ('name', fields.CharField(label='名称', max_length=64)), ('description', fields.CharField(label='描述', max_length=255, allow_blank=True, default="")), ('date', fields.DateField(label='预定日期')), ('start_time', fields.TimeField(label='开始时间')), ('end_time', fields.TimeField(label='结束时间')), ) class MeetingBase(BaseView): check_manager = False check_meeting_time = True response_info_serializer_class = serializer.MeetingDetailSerializer def check_api_permissions(self, request, *args, **kwargs): super(MeetingBase, self).check_api_permissions(request, *args, **kwargs) meeting = models.Meeting.get_obj_by_pk_from_cache(request.params.meeting_id) if meeting is None: raise CoolAPIException(ErrorCode.ERR_MEETING_NOT_FOUND) setattr(self, 'meeting', meeting) if self.check_manager: if meeting.user_id != request.user.pk and ( not meeting.room.create_user_manager or request.user.pk != meeting.room.create_user_id ): raise CoolAPIException(ErrorCode.ERROR_PERMISSION) if self.check_meeting_time: if datetime.datetime.combine(meeting.date, meeting.end_time) < datetime.datetime.now(): raise CoolAPIException(ErrorCode.ERR_MEETING_FINISHED) def get_context(self, request, *args, **kwargs): raise NotImplementedError class Meta: path = '/' param_fields = ( ('meeting_id', fields.IntegerField(label='会议ID')), ) @site class Info(MeetingBase): name = "会议详情" check_meeting_time = False def get_context(self, request, *args, **kwargs): return self.meeting @site class Edit(MeetingBase): name = "会议修改" check_manager = True def get_context(self, request, *args, **kwargs): data = dict() update_fields = list() if self.meeting.name != request.params.name: data['name'] = {'from': self.meeting.name, 'to': request.params.name} update_fields.append('name') self.meeting.name = request.params.name if self.meeting.description != request.params.description: data['description'] = {'from': self.meeting.description, 'to': request.params.description} update_fields.append('description') self.meeting.description = request.params.description if update_fields: with transaction.atomic(): self.meeting.save(force_update=True, update_fields=update_fields) models.MeetingTrace.objects.create( meeting_id=self.meeting.pk, user_id=request.user.pk, owner=request.user.pk == self.meeting.user_id, type=constants.MeetingTraceTypeCode.EDIT.code, data=json.dumps(data, ensure_ascii=False) ) return self.meeting class Meta: param_fields = ( ('name', fields.CharField(label='名称', max_length=64)), ('description', fields.CharField(label='描述', max_length=255, allow_blank=True, default="")), ) @site class Cancel(MeetingBase): name = "取消会议" check_manager = True response_info_serializer_class = None def get_context(self, request, *args, **kwargs): with transaction.atomic(): self.meeting.delete() models.MeetingTrace.objects.create( meeting_id=self.meeting.pk, user_id=request.user.pk, owner=request.user.pk == self.meeting.user_id, type=constants.MeetingTraceTypeCode.DELETE.code ) return {} @site class Join(MeetingBase): name = "参加会议" def get_context(self, request, *args, **kwargs): attendee, _ = models.MeetingAttendee.default_manager.get_or_create( meeting_id=request.params.meeting_id, user_id=request.user.pk ) attendee.un_delete() self.get_room_follow(self.meeting.room_id, request.user.pk) return self.meeting @site class Leave(MeetingBase): name = "取消参加会议" def get_context(self, request, *args, **kwargs): attendee = models.MeetingAttendee.objects.filter( meeting_id=request.params.meeting_id, user_id=request.user.pk ) if attendee is None: raise CoolAPIException(ErrorCode.ERROR_BAD_PARAMETER) attendee.delete() return self.meeting urlpatterns = site.urlpatterns app_name = site.app_name
17,211
views
py
en
python
code
{"qsc_code_num_words": 1968, "qsc_code_num_chars": 17211.0, "qsc_code_mean_word_length": 5.4004065, "qsc_code_frac_words_unique": 0.13058943, "qsc_code_frac_chars_top_2grams": 0.0611592, "qsc_code_frac_chars_top_3grams": 0.03838916, "qsc_code_frac_chars_top_4grams": 0.04347008, "qsc_code_frac_chars_dupe_5grams": 0.62881069, "qsc_code_frac_chars_dupe_6grams": 0.55955965, "qsc_code_frac_chars_dupe_7grams": 0.4556831, "qsc_code_frac_chars_dupe_8grams": 0.3913248, "qsc_code_frac_chars_dupe_9grams": 0.34823109, "qsc_code_frac_chars_dupe_10grams": 0.30438464, "qsc_code_frac_chars_replacement_symbols": 0.0, "qsc_code_frac_chars_digital": 0.00193095, "qsc_code_frac_chars_whitespace": 0.24774853, "qsc_code_size_file_byte": 17211.0, "qsc_code_num_lines": 498.0, "qsc_code_num_chars_line_max": 119.0, "qsc_code_num_chars_line_mean": 34.56024096, "qsc_code_frac_chars_alphabet": 0.8189542, "qsc_code_frac_chars_comments": 0.00087154, "qsc_code_cate_xml_start": 0.0, "qsc_code_frac_lines_dupe_lines": 0.45049505, "qsc_code_cate_autogen": 0.0, "qsc_code_frac_lines_long_string": 0.0, "qsc_code_frac_chars_string_length": 0.05036641, "qsc_code_frac_chars_long_word_length": 0.00157032, "qsc_code_frac_lines_string_concat": 0.0, "qsc_code_cate_encoded_data": 0.0, "qsc_code_frac_chars_hex_words": 0.0, "qsc_code_frac_lines_prompt_comments": 0.0, "qsc_code_frac_lines_assert": 0.0, "qsc_codepython_cate_ast": 1.0, "qsc_codepython_frac_lines_func_ratio": 0.07673267, "qsc_codepython_cate_var_zero": false, "qsc_codepython_frac_lines_pass": 0.0, "qsc_codepython_frac_lines_import": 0.03960396, "qsc_codepython_frac_lines_simplefunc": 0.017326732673267328, "qsc_codepython_score_lines_no_logic": 0.3490099, "qsc_codepython_frac_lines_print": 0.0}
1
{"qsc_code_frac_chars_replacement_symbols": 0, "qsc_code_num_words": 0, "qsc_code_num_chars": 0, "qsc_code_mean_word_length": 0, "qsc_code_frac_chars_top_2grams": 0, "qsc_code_frac_chars_top_3grams": 0, "qsc_code_frac_chars_top_4grams": 0, "qsc_code_frac_chars_dupe_5grams": 0, "qsc_code_frac_chars_dupe_6grams": 0, "qsc_code_frac_chars_dupe_7grams": 0, "qsc_code_frac_chars_dupe_8grams": 0, "qsc_code_frac_chars_dupe_9grams": 0, "qsc_code_frac_chars_dupe_10grams": 0, "qsc_code_frac_lines_dupe_lines": 0, "qsc_code_size_file_byte": 0, "qsc_code_num_lines": 0, "qsc_code_num_chars_line_max": 0, "qsc_code_num_chars_line_mean": 0, "qsc_code_frac_chars_alphabet": 0, "qsc_code_frac_chars_digital": 0, "qsc_code_frac_chars_whitespace": 0, "qsc_code_frac_chars_comments": 0, "qsc_code_cate_xml_start": 0, "qsc_code_cate_autogen": 0, "qsc_code_frac_lines_long_string": 0, "qsc_code_frac_chars_string_length": 0, "qsc_code_frac_chars_long_word_length": 0, "qsc_code_cate_encoded_data": 0, "qsc_code_frac_chars_hex_words": 0, "qsc_code_frac_lines_prompt_comments": 0, "qsc_code_frac_lines_assert": 0, "qsc_codepython_cate_ast": 0, "qsc_codepython_frac_lines_func_ratio": 0, "qsc_codepython_cate_var_zero": 0, "qsc_codepython_frac_lines_pass": 0, "qsc_codepython_frac_lines_import": 0, "qsc_codepython_frac_lines_simplefunc": 0, "qsc_codepython_score_lines_no_logic": 0, "qsc_codepython_frac_lines_print": 0}
007gzs/meeting
miniprogram/components/time_table.wxml
<!--components/time_table.wxml--> <view class='time_table'> <view class="table"> <view class='thead'> <view class="tr"> <view class="th label" bindtap='title_label_click'> {{title_label}} </view> <view class="th" wx:for="{{titles}}" wx:key="id" id="{{item.id}}" bindtap='title_click'> <text class="title_name">{{item.name}}</text> </view> <view class="th" wx:if='{{titles.length == 0}}'> {{no_title_desc}} </view> </view> </view> <scroll-view scroll-y class="tbody"> <view class="tr" wx:for="{{labels}}" wx:key="id" wx:for-item="label"> <view class="td label {{label.text ? 'top' : 'buttom'}}" id="{{label.id}}" bindtap='label_click'> <view class="label_item"> {{label.text}} </view> </view> <view class="td {{td_data[title.id][label.id].clazz}}" wx:for="{{titles}}" wx:key="id" wx:for-item="title" bindtap="data_click" data-title="{{title.id}}" data-label="{{label.id}}" data-data="{{td_data[title.id][label.id].meeting_id}}"> {{td_data[title.id][label.id].text}} </view> <view class="td" wx:if='{{titles.length == 0}}'> </view> </view> </scroll-view> </view> </view>
1,361
time_table
wxml
en
unknown
unknown
{}
0
{}
007gzs/meeting
miniprogram/components/time_table.wxss
/* components/time_table.wxss */ .time_table{ height: 100%; } .table { position: relative; overflow: hidden; width: 100%; height: 100%; font-size: 32rpx; line-height: 32rpx; border-right: 1rpx solid #ddd; border-bottom: 1rpx solid #ddd; } .table .thead{ height: 48rpx; } .table .tbody{ position: absolute; top: 49rpx; bottom: 0; width: 100%; overflow: auto; } .table .tr{ display:-webkit-box; display:-webkit-flex; display:flex; } .table .th, .table .td{ -webkit-box-flex:1; -webkit-flex:1; flex:1; text-align: center; vertical-align: middle; overflow: hidden; margin-right:-1rpx; margin-bottom:-1rpx; } .table .th { font-weight: bold; border: 1rpx solid #ddd; background-color: #f5fafe; line-height: 48rpx; height: 48rpx; } .table .td { border-left: 1rpx solid #ddd; border-right: 1rpx solid #ddd; height: 36rpx; } .table .td.expire{ border-top: 1rpx solid #f5f5f5; background-color: #f5f5f5; } .table .td.in_use{ border-top: 1rpx solid #fcf8e3; background-color: #fcf8e3; } .table .td.selected{ border-top: 1rpx solid #dfffd8; background-color: #dfffd8; } .table .td.top{ border-top: 1rpx solid #ddd; } .table .td.bottom{ border-bottom: 1rpx solid #ddd; } .label_item{ font-size: 28rpx; } view.label{ -webkit-box-flex:none!important; -webkit-flex:none!important; flex:none!important; width: 100rpx; background-color: #f5fafe; float: left; }
1,441
time_table
wxss
en
unknown
unknown
{}
0
{}
007gzs/meeting
miniprogram/components/time_table.js
// components/time_table.js Component({ /** * 组件的属性列表 */ properties: { no_title_desc: String, title_label: String }, /** * 组件的初始数据 */ data: { titles: [], labels: [], td_data: {}, }, /** * 组件的方法列表 */ methods: { set_data: function({titles, labels, td_data} = {}){ let data = {} if (titles !== undefined) { data['titles'] = titles } if (labels !== undefined) { data['labels'] = labels } if (td_data !== undefined) { data['td_data'] = td_data } this.setData(data) }, event: function(event, data = {}){ this.triggerEvent(event, data, {}) }, title_label_click: function(e){ this.event('title_label_click') }, title_click: function (e) { this.event('title_click', { title_id: e.currentTarget.id }) }, label_click: function (e) { this.event('label_click', { label_id: e.currentTarget.id }) }, data_click: function(e){ this.event('data_click', { title_id: e.currentTarget.dataset.title, label_id: e.currentTarget.dataset.label, data_id: e.currentTarget.dataset.data, }) } } })
1,240
time_table
js
en
javascript
code
{"qsc_code_num_words": 125, "qsc_code_num_chars": 1240.0, "qsc_code_mean_word_length": 5.016, "qsc_code_frac_words_unique": 0.264, "qsc_code_frac_chars_top_2grams": 0.04784689, "qsc_code_frac_chars_top_3grams": 0.12759171, "qsc_code_frac_chars_top_4grams": 0.11483254, "qsc_code_frac_chars_dupe_5grams": 0.261563, "qsc_code_frac_chars_dupe_6grams": 0.14194577, "qsc_code_frac_chars_dupe_7grams": 0.0, "qsc_code_frac_chars_dupe_8grams": 0.0, "qsc_code_frac_chars_dupe_9grams": 0.0, "qsc_code_frac_chars_dupe_10grams": 0.0, "qsc_code_frac_chars_replacement_symbols": 0.0, "qsc_code_frac_chars_digital": 0.0, "qsc_code_frac_chars_whitespace": 0.31532258, "qsc_code_size_file_byte": 1240.0, "qsc_code_num_lines": 61.0, "qsc_code_num_chars_line_max": 56.0, "qsc_code_num_chars_line_mean": 20.32786885, "qsc_code_frac_chars_alphabet": 0.7385159, "qsc_code_frac_chars_comments": 0.075, "qsc_code_cate_xml_start": 0.0, "qsc_code_frac_lines_dupe_lines": 0.08163265, "qsc_code_cate_autogen": 0.0, "qsc_code_frac_lines_long_string": 0.0, "qsc_code_frac_chars_string_length": 0.05928509, "qsc_code_frac_chars_long_word_length": 0.0, "qsc_code_frac_lines_string_concat": 0.0, "qsc_code_cate_encoded_data": 0.0, "qsc_code_frac_chars_hex_words": 0.0, "qsc_code_frac_lines_prompt_comments": 0.0, "qsc_code_frac_lines_assert": 0.0, "qsc_codejavascript_cate_ast": 1.0, "qsc_codejavascript_cate_var_zero": 0.0, "qsc_codejavascript_frac_lines_func_ratio": 0.0, "qsc_codejavascript_num_statement_line": 0.02040816, "qsc_codejavascript_score_lines_no_logic": 0.0, "qsc_codejavascript_frac_words_legal_var_name": 1.0, "qsc_codejavascript_frac_words_legal_func_name": null, "qsc_codejavascript_frac_words_legal_class_name": null, "qsc_codejavascript_frac_lines_print": 0.0}
1
{"qsc_code_frac_chars_replacement_symbols": 0, "qsc_code_num_words": 0, "qsc_code_num_chars": 0, "qsc_code_mean_word_length": 0, "qsc_code_frac_chars_top_2grams": 0, "qsc_code_frac_chars_top_3grams": 0, "qsc_code_frac_chars_top_4grams": 0, "qsc_code_frac_chars_dupe_5grams": 0, "qsc_code_frac_chars_dupe_6grams": 0, "qsc_code_frac_chars_dupe_7grams": 0, "qsc_code_frac_chars_dupe_8grams": 0, "qsc_code_frac_chars_dupe_9grams": 0, "qsc_code_frac_chars_dupe_10grams": 0, "qsc_code_size_file_byte": 0, "qsc_code_num_lines": 0, "qsc_code_num_chars_line_max": 0, "qsc_code_num_chars_line_mean": 0, "qsc_code_frac_chars_alphabet": 0, "qsc_code_frac_chars_digital": 0, "qsc_code_frac_chars_whitespace": 0, "qsc_code_frac_chars_comments": 0, "qsc_code_cate_xml_start": 0, "qsc_code_frac_lines_dupe_lines": 0, "qsc_code_cate_autogen": 0, "qsc_code_frac_lines_long_string": 0, "qsc_code_frac_chars_string_length": 0, "qsc_code_frac_chars_long_word_length": 0, "qsc_code_cate_encoded_data": 0, "qsc_code_frac_chars_hex_words": 0, "qsc_code_frac_lines_prompt_comments": 0, "qsc_code_frac_lines_assert": 0, "qsc_codejavascript_cate_ast": 0, "qsc_codejavascript_cate_var_zero": 0, "qsc_codejavascript_frac_lines_func_ratio": 0, "qsc_codejavascript_score_lines_no_logic": 0, "qsc_codejavascript_frac_lines_print": 0}
007gzs/meeting
miniprogram/components/date_select.js
// components/date_select.js const weekStr = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'] const app = getApp() Component({ /** * 组件的属性列表 */ properties: { }, /** * 组件的初始数据 */ data: { start_date: '', end_date: '', select_date: '', date_range: [] }, lifetimes: { // 生命周期函数,可以为函数,或一个在methods段中定义的方法名 attached: function () { }, }, /** * 组件的方法列表 */ methods: { setDateRange: function(start_date, end_date){ let select_date_ok = false start_date = new Date(start_date) if (isNaN(start_date)) { start_date = app.nowDate() } end_date = new Date(end_date) if (isNaN(end_date)) { end_date = this.addDay(start_date, 19) } start_date = new Date(this.dateId(start_date)) end_date = new Date(this.dateId(end_date)) let date_range = [] let current_date = start_date while (current_date <= end_date) { select_date_ok = select_date_ok || this.data.select_date == this.dateId(current_date) date_range.push({ id: this.dateId(current_date), show: this.dateShow(current_date), desc: this.dateDesc(current_date), }) current_date = this.addDay(current_date, 1) } let set_data = { date_range: date_range, start_date: this.dateId(start_date), end_date: this.dateId(end_date)} if (!select_date_ok) { set_data.select_date = this.dateId(start_date) } this.setData(set_data) }, change: function(){ this.triggerEvent('change', { select_date: this.data.select_date }, { }) }, tap: function(e){ this.setData({select_date: e.currentTarget.id}) this.change() }, addDay: function(date, day){ return new Date(Date.parse(date) + 86400000 * day) }, formatNumber: function(n) { n = n.toString() return n[1] ? n : '0' + n }, dateId: function(date){ const year = date.getFullYear() const month = date.getMonth() + 1 const day = date.getDate() return [year, month, day].map(this.formatNumber).join('-') }, dateShow: function (date) { const month = date.getMonth() + 1 const day = date.getDate() return [month, day].map(this.formatNumber).join('/') }, dateDesc: function (date) { const now = app.nowDate() if(this.dateId(now) == this.dateId(date)){ return "今天" } return weekStr[date.getDay()] } } })
2,491
date_select
js
en
javascript
code
{"qsc_code_num_words": 292, "qsc_code_num_chars": 2491.0, "qsc_code_mean_word_length": 4.74315068, "qsc_code_frac_words_unique": 0.26369863, "qsc_code_frac_chars_top_2grams": 0.08447653, "qsc_code_frac_chars_top_3grams": 0.05559567, "qsc_code_frac_chars_top_4grams": 0.04620939, "qsc_code_frac_chars_dupe_5grams": 0.26353791, "qsc_code_frac_chars_dupe_6grams": 0.15740072, "qsc_code_frac_chars_dupe_7grams": 0.11263538, "qsc_code_frac_chars_dupe_8grams": 0.06931408, "qsc_code_frac_chars_dupe_9grams": 0.06931408, "qsc_code_frac_chars_dupe_10grams": 0.06931408, "qsc_code_frac_chars_replacement_symbols": 0.0, "qsc_code_frac_chars_digital": 0.00829646, "qsc_code_frac_chars_whitespace": 0.27418707, "qsc_code_size_file_byte": 2491.0, "qsc_code_num_lines": 92.0, "qsc_code_num_chars_line_max": 117.0, "qsc_code_num_chars_line_mean": 27.07608696, "qsc_code_frac_chars_alphabet": 0.75774336, "qsc_code_frac_chars_comments": 0.05178643, "qsc_code_cate_xml_start": 0.0, "qsc_code_frac_lines_dupe_lines": 0.07594937, "qsc_code_cate_autogen": 0.0, "qsc_code_frac_lines_long_string": 0.0, "qsc_code_frac_chars_string_length": 0.01058425, "qsc_code_frac_chars_long_word_length": 0.0, "qsc_code_frac_lines_string_concat": 0.0, "qsc_code_cate_encoded_data": 0.0, "qsc_code_frac_chars_hex_words": 0.0, "qsc_code_frac_lines_prompt_comments": 0.0, "qsc_code_frac_lines_assert": 0.0, "qsc_codejavascript_cate_ast": 1.0, "qsc_codejavascript_cate_var_zero": 0.0, "qsc_codejavascript_frac_lines_func_ratio": 0.0, "qsc_codejavascript_num_statement_line": 0.03797468, "qsc_codejavascript_score_lines_no_logic": 0.03797468, "qsc_codejavascript_frac_words_legal_var_name": 0.66666667, "qsc_codejavascript_frac_words_legal_func_name": null, "qsc_codejavascript_frac_words_legal_class_name": null, "qsc_codejavascript_frac_lines_print": 0.0}
1
{"qsc_code_frac_chars_replacement_symbols": 0, "qsc_code_num_words": 0, "qsc_code_num_chars": 0, "qsc_code_mean_word_length": 0, "qsc_code_frac_chars_top_2grams": 0, "qsc_code_frac_chars_top_3grams": 0, "qsc_code_frac_chars_top_4grams": 0, "qsc_code_frac_chars_dupe_5grams": 0, "qsc_code_frac_chars_dupe_6grams": 0, "qsc_code_frac_chars_dupe_7grams": 0, "qsc_code_frac_chars_dupe_8grams": 0, "qsc_code_frac_chars_dupe_9grams": 0, "qsc_code_frac_chars_dupe_10grams": 0, "qsc_code_size_file_byte": 0, "qsc_code_num_lines": 0, "qsc_code_num_chars_line_max": 0, "qsc_code_num_chars_line_mean": 0, "qsc_code_frac_chars_alphabet": 0, "qsc_code_frac_chars_digital": 0, "qsc_code_frac_chars_whitespace": 0, "qsc_code_frac_chars_comments": 0, "qsc_code_cate_xml_start": 0, "qsc_code_frac_lines_dupe_lines": 0, "qsc_code_cate_autogen": 0, "qsc_code_frac_lines_long_string": 0, "qsc_code_frac_chars_string_length": 0, "qsc_code_frac_chars_long_word_length": 0, "qsc_code_cate_encoded_data": 0, "qsc_code_frac_chars_hex_words": 0, "qsc_code_frac_lines_prompt_comments": 0, "qsc_code_frac_lines_assert": 0, "qsc_codejavascript_cate_ast": 0, "qsc_codejavascript_cate_var_zero": 0, "qsc_codejavascript_frac_lines_func_ratio": 0, "qsc_codejavascript_score_lines_no_logic": 0, "qsc_codejavascript_frac_lines_print": 0}
007gzs/meeting
miniprogram/weui/weui.wxss
/*! * WeUI v1.1.1 (https://github.com/weui/weui-wxss) * Copyright 2017 Tencent, Inc. * Licensed under the MIT license */ page{line-height:1.6;font-family:-apple-system-font,Helvetica Neue,sans-serif}icon{vertical-align:middle}.weui-cells{position:relative;margin-top:1.17647059em;background-color:#fff;line-height:1.41176471;font-size:34rpx}.weui-cells:before{top:0;border-top:1rpx solid #d9d9d9}.weui-cells:after,.weui-cells:before{content:" ";position:absolute;left:0;right:0;height:2rpx;color:#d9d9d9}.weui-cells:after{bottom:0;border-bottom:1rpx solid #d9d9d9}.weui-cells__title{margin-top:.77em;margin-bottom:.3em;padding-left:30rpx;padding-right:30rpx;color:#999;font-size:28rpx}.weui-cells_after-title{margin-top:0}.weui-cells__tips{margin-top:.3em;color:#999;padding-left:30rpx;padding-right:30rpx;font-size:28rpx}.weui-cell{padding:20rpx 30rpx;position:relative;display:-webkit-box;display:-webkit-flex;display:flex;-webkit-box-align:center;-webkit-align-items:center;align-items:center}.weui-cell:before{content:" ";position:absolute;left:0;top:0;right:0;height:2rpx;border-top:1rpx solid #d9d9d9;color:#d9d9d9;left:30rpx}.weui-cell:first-child:before{display:none}.weui-cell_active{background-color:#ececec}.weui-cell_primary{-webkit-box-align:start;-webkit-align-items:flex-start;align-items:flex-start}.weui-cell__bd{-webkit-box-flex:1;-webkit-flex:1;flex:1}.weui-cell__ft{text-align:right;color:#999}.weui-cell_access{color:inherit}.weui-cell__ft_in-access{padding-right:26rpx;position:relative}.weui-cell__ft_in-access:after{content:" ";display:inline-block;height:12rpx;width:12rpx;border-width:4rpx 4rpx 0 0;border-color:#c8c8cd;border-style:solid;-webkit-transform:matrix(.71,.71,-.71,.71,0,0);transform:matrix(.71,.71,-.71,.71,0,0);position:relative;top:-4rpx;position:absolute;top:50%;margin-top:-8rpx;right:4rpx}.weui-cell_link{color:#586c94;font-size:28rpx}.weui-cell_link:active{background-color:#ececec}.weui-cell_link:first-child:before{display:block}.weui-icon-radio{margin-left:6.4rpx;margin-right:6.4rpx}.weui-icon-checkbox_circle,.weui-icon-checkbox_success{margin-left:9.2rpx;margin-right:9.2rpx}.weui-check__label:active{background-color:#ececec}.weui-check{position:absolute;left:-9999rpx}.weui-check__hd_in-checkbox{padding-right:.35em}.weui-cell__ft_in-radio{padding-left:.35em}.weui-cell_input{padding-top:0;padding-bottom:0}.weui-label{width:210rpx;word-wrap:break-word;word-break:break-all}.weui-input{height:2.58823529em;min-height:2.58823529em;line-height:2.58823529em}.weui-toptips{position:fixed;-webkit-transform:translateZ(0);transform:translateZ(0);top:0;left:0;right:0;padding:10rpx;font-size:28rpx;text-align:center;color:#fff;z-index:5000;word-wrap:break-word;word-break:break-all}.weui-toptips_warn{background-color:#e64340}.weui-textarea{display:block;width:100%}.weui-textarea-counter{color:#b2b2b2;text-align:right}.weui-cell_warn,.weui-textarea-counter_warn{color:#e64340}.weui-form-preview{position:relative;background-color:#fff}.weui-form-preview:before{top:0;border-top:1rpx solid #d9d9d9}.weui-form-preview:after,.weui-form-preview:before{content:" ";position:absolute;left:0;right:0;height:2rpx;color:#d9d9d9}.weui-form-preview:after{bottom:0;border-bottom:1rpx solid #d9d9d9}.weui-form-preview__value{font-size:28rpx}.weui-form-preview__value_in-hd{font-size:52rpx}.weui-form-preview__hd{position:relative;padding:20rpx 30rpx;text-align:right;line-height:2.5em}.weui-form-preview__hd:after{content:" ";position:absolute;left:0;bottom:0;right:0;height:2rpx;border-bottom:1rpx solid #d9d9d9;color:#d9d9d9;left:30rpx}.weui-form-preview__bd{padding:20rpx 30rpx;font-size:.9em;text-align:right;color:#999;line-height:2}.weui-form-preview__ft{position:relative;line-height:100rpx;display:-webkit-box;display:-webkit-flex;display:flex}.weui-form-preview__ft:after{content:" ";position:absolute;left:0;top:0;right:0;height:2rpx;border-top:1rpx solid #d5d5d6;color:#d5d5d6}.weui-form-preview__item{overflow:hidden}.weui-form-preview__label{float:left;margin-right:1em;min-width:4em;color:#999;text-align:justify;text-align-last:justify}.weui-form-preview__value{display:block;overflow:hidden;word-break:normal;word-wrap:break-word}.weui-form-preview__btn{position:relative;display:block;-webkit-box-flex:1;-webkit-flex:1;flex:1;color:#3cc51f;text-align:center}.weui-form-preview__btn:after{content:" ";position:absolute;left:0;top:0;width:2rpx;bottom:0;border-left:1rpx solid #d5d5d6;color:#d5d5d6}.weui-form-preview__btn:first-child:after{display:none}.weui-form-preview__btn_active{background-color:#eee}.weui-form-preview__btn_default{color:#999}.weui-form-preview__btn_primary{color:#0bb20c}.weui-cell_select{padding:0}.weui-select{position:relative;padding-left:30rpx;padding-right:60rpx;height:2.58823529em;min-height:2.58823529em;line-height:2.58823529em;border-right:1rpx solid #d9d9d9}.weui-select:before{content:" ";display:inline-block;height:12rpx;width:12rpx;border-width:4rpx 4rpx 0 0;border-color:#c8c8cd;border-style:solid;-webkit-transform:matrix(.71,.71,-.71,.71,0,0);transform:matrix(.71,.71,-.71,.71,0,0);position:relative;top:-4rpx;position:absolute;top:50%;right:30rpx;margin-top:-8rpx}.weui-select_in-select-after{padding-left:0}.weui-cell__bd_in-select-before,.weui-cell__hd_in-select-after{padding-left:30rpx}.weui-cell_vcode{padding-right:0}.weui-vcode-btn,.weui-vcode-img{margin-left:10rpx;height:2.58823529em;vertical-align:middle}.weui-vcode-btn{display:inline-block;padding:0 .6em 0 .7em;border-left:1rpx solid #e5e5e5;line-height:2.58823529em;font-size:34rpx;color:#3cc51f;white-space:nowrap}.weui-vcode-btn:active{color:#52a341}.weui-cell_switch{padding-top:12rpx;padding-bottom:12rpx}.weui-uploader__hd{display:-webkit-box;display:-webkit-flex;display:flex;padding-bottom:20rpx;-webkit-box-align:center;-webkit-align-items:center;align-items:center}.weui-uploader__title{-webkit-box-flex:1;-webkit-flex:1;flex:1}.weui-uploader__info{color:#b2b2b2}.weui-uploader__bd{margin-bottom:-8rpx;margin-right:-18rpx;overflow:hidden}.weui-uploader__file{float:left;margin-right:18rpx;margin-bottom:18rpx}.weui-uploader__img{display:block;width:158rpx;height:158rpx}.weui-uploader__file_status{position:relative}.weui-uploader__file_status:before{content:" ";position:absolute;top:0;right:0;bottom:0;left:0;background-color:rgba(0,0,0,.5)}.weui-uploader__file-content{position:absolute;top:50%;left:50%;-webkit-transform:translate(-50%,-50%);transform:translate(-50%,-50%);color:#fff}.weui-uploader__input-box{float:left;position:relative;margin-right:18rpx;margin-bottom:18rpx;width:154rpx;height:154rpx;border:1rpx solid #d9d9d9}.weui-uploader__input-box:after,.weui-uploader__input-box:before{content:" ";position:absolute;top:50%;left:50%;-webkit-transform:translate(-50%,-50%);transform:translate(-50%,-50%);background-color:#d9d9d9}.weui-uploader__input-box:before{width:4rpx;height:79rpx}.weui-uploader__input-box:after{width:79rpx;height:4rpx}.weui-uploader__input-box:active{border-color:#999}.weui-uploader__input-box:active:after,.weui-uploader__input-box:active:before{background-color:#999}.weui-uploader__input{position:absolute;z-index:1;top:0;left:0;width:100%;height:100%;opacity:0}.weui-article{padding:40rpx 30rpx;font-size:30rpx}.weui-article__section{margin-bottom:1.5em}.weui-article__h1{font-size:36rpx;font-weight:400;margin-bottom:.9em}.weui-article__h2{font-size:32rpx;font-weight:400;margin-bottom:.34em}.weui-article__h3{font-weight:400;font-size:30rpx;margin-bottom:.34em}.weui-article__p{margin:0 0 .8em}.weui-msg{padding-top:72rpx;text-align:center}.weui-msg__link{display:inline;color:#586c94}.weui-msg__icon-area{margin-bottom:60rpx}.weui-msg__text-area{margin-bottom:50rpx;padding:0 40rpx}.weui-msg__title{margin-bottom:10rpx;font-weight:400;font-size:40rpx}.weui-msg__desc{font-size:28rpx;color:#999}.weui-msg__opr-area{margin-bottom:100rpx}.weui-msg__extra-area{margin-bottom:30rpx;font-size:28rpx;color:#999}@media screen and (min-height:876rpx){.weui-msg__extra-area{position:fixed;left:0;bottom:0;width:100%;text-align:center}}.weui-flex{display:-webkit-box;display:-webkit-flex;display:flex}.weui-flex__item{-webkit-box-flex:1;-webkit-flex:1;flex:1}.weui-btn{margin-top:30rpx}.weui-btn:first-child{margin-top:0}.weui-btn-area{margin:1.17647059em 30rpx .3em}.weui-agree{display:block;padding:.5em 30rpx;font-size:26rpx}.weui-agree__text{color:#999}.weui-agree__link{display:inline;color:#586c94}.weui-agree__checkbox{position:absolute;left:-9999rpx}.weui-agree__checkbox-icon{position:relative;top:4rpx;display:inline-block;border:1rpx solid #d1d1d1;background-color:#fff;border-radius:6rpx;width:22rpx;height:22rpx}.weui-agree__checkbox-icon-check{position:absolute;top:2rpx;left:2rpx}.weui-footer{color:#999;font-size:28rpx;text-align:center}.weui-footer_fixed-bottom{position:fixed;bottom:.52em;left:0;right:0}.weui-footer__links{font-size:0}.weui-footer__link{display:inline-block;vertical-align:top;margin:0 .62em;position:relative;font-size:28rpx;color:#586c94}.weui-footer__link:before{content:" ";position:absolute;left:0;top:0;width:2rpx;bottom:0;border-left:1rpx solid #c7c7c7;color:#c7c7c7;left:-.65em;top:.36em;bottom:.36em}.weui-footer__link:first-child:before{display:none}.weui-footer__text{padding:0 .34em;font-size:24rpx}.weui-grids{border-top:1rpx solid #d9d9d9;border-left:1rpx solid #d9d9d9;overflow:hidden}.weui-grid{position:relative;float:left;padding:40rpx 20rpx;width:33.33333333%;box-sizing:border-box;border-right:1rpx solid #d9d9d9;border-bottom:1rpx solid #d9d9d9}.weui-grid_active{background-color:#ececec}.weui-grid__icon{display:block;width:56rpx;height:56rpx;margin:0 auto}.weui-grid__label{margin-top:10rpx;display:block;text-align:center;color:#000;font-size:28rpx;white-space:nowrap;text-overflow:ellipsis;overflow:hidden}.weui-loading{margin:0 10rpx;width:40rpx;height:40rpx;display:inline-block;vertical-align:middle;-webkit-animation:a 1s steps(12) infinite;animation:a 1s steps(12) infinite;background:transparent url(data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSIxMjAiIGhlaWdodD0iMTIwIiB2aWV3Qm94PSIwIDAgMTAwIDEwMCI+PHBhdGggZmlsbD0ibm9uZSIgZD0iTTAgMGgxMDB2MTAwSDB6Ii8+PHJlY3Qgd2lkdGg9IjciIGhlaWdodD0iMjAiIHg9IjQ2LjUiIHk9IjQwIiBmaWxsPSIjRTlFOUU5IiByeD0iNSIgcnk9IjUiIHRyYW5zZm9ybT0idHJhbnNsYXRlKDAgLTMwKSIvPjxyZWN0IHdpZHRoPSI3IiBoZWlnaHQ9IjIwIiB4PSI0Ni41IiB5PSI0MCIgZmlsbD0iIzk4OTY5NyIgcng9IjUiIHJ5PSI1IiB0cmFuc2Zvcm09InJvdGF0ZSgzMCAxMDUuOTggNjUpIi8+PHJlY3Qgd2lkdGg9IjciIGhlaWdodD0iMjAiIHg9IjQ2LjUiIHk9IjQwIiBmaWxsPSIjOUI5OTlBIiByeD0iNSIgcnk9IjUiIHRyYW5zZm9ybT0icm90YXRlKDYwIDc1Ljk4IDY1KSIvPjxyZWN0IHdpZHRoPSI3IiBoZWlnaHQ9IjIwIiB4PSI0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jUiIHJ5PSI1IiB0cmFuc2Zvcm09InJvdGF0ZSgtNjAgMjQuMDIgNjUpIi8+PHJlY3Qgd2lkdGg9IjciIGhlaWdodD0iMjAiIHg9IjQ2LjUiIHk9IjQwIiBmaWxsPSIjRTJFMkUyIiByeD0iNSIgcnk9IjUiIHRyYW5zZm9ybT0icm90YXRlKC0zMCAtNS45OCA2NSkiLz48L3N2Zz4=) no-repeat;background-size:100%}.weui-loading.weui-loading_transparent{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='120' height='120' viewBox='0 0 100 100'%3E%3Cpath fill='none' d='M0 0h100v100H0z'/%3E%3Crect xmlns='http://www.w3.org/2000/svg' width='7' height='20' x='46.5' y='40' fill='rgba(255,255,255,.56)' rx='5' ry='5' transform='translate(0 -30)'/%3E%3Crect width='7' height='20' x='46.5' y='40' fill='rgba(255,255,255,.5)' rx='5' ry='5' transform='rotate(30 105.98 65)'/%3E%3Crect width='7' height='20' x='46.5' y='40' fill='rgba(255,255,255,.43)' rx='5' ry='5' transform='rotate(60 75.98 65)'/%3E%3Crect width='7' height='20' x='46.5' y='40' fill='rgba(255,255,255,.38)' rx='5' ry='5' transform='rotate(90 65 65)'/%3E%3Crect width='7' height='20' x='46.5' y='40' fill='rgba(255,255,255,.32)' rx='5' ry='5' transform='rotate(120 58.66 65)'/%3E%3Crect width='7' height='20' x='46.5' y='40' fill='rgba(255,255,255,.28)' rx='5' ry='5' transform='rotate(150 54.02 65)'/%3E%3Crect width='7' height='20' x='46.5' y='40' fill='rgba(255,255,255,.25)' rx='5' ry='5' transform='rotate(180 50 65)'/%3E%3Crect width='7' height='20' x='46.5' y='40' fill='rgba(255,255,255,.2)' rx='5' ry='5' transform='rotate(-150 45.98 65)'/%3E%3Crect width='7' height='20' x='46.5' y='40' fill='rgba(255,255,255,.17)' rx='5' ry='5' transform='rotate(-120 41.34 65)'/%3E%3Crect width='7' height='20' x='46.5' y='40' fill='rgba(255,255,255,.14)' rx='5' ry='5' transform='rotate(-90 35 65)'/%3E%3Crect width='7' height='20' x='46.5' y='40' fill='rgba(255,255,255,.1)' rx='5' ry='5' transform='rotate(-60 24.02 65)'/%3E%3Crect width='7' height='20' x='46.5' y='40' fill='rgba(255,255,255,.03)' rx='5' ry='5' transform='rotate(-30 -5.98 65)'/%3E%3C/svg%3E")}@-webkit-keyframes a{0%{-webkit-transform:rotate(0deg);transform:rotate(0deg)}to{-webkit-transform:rotate(1turn);transform:rotate(1turn)}}@keyframes a{0%{-webkit-transform:rotate(0deg);transform:rotate(0deg)}to{-webkit-transform:rotate(1turn);transform:rotate(1turn)}}.weui-badge{display:inline-block;padding:.15em .4em;min-width:16rpx;border-radius:36rpx;background-color:#e64340;color:#fff;line-height:1.2;text-align:center;font-size:24rpx;vertical-align:middle}.weui-badge_dot{padding:.4em;min-width:0}.weui-loadmore{width:65%;margin:1.5em auto;line-height:1.6em;font-size:28rpx;text-align:center}.weui-loadmore__tips{display:inline-block;vertical-align:middle}.weui-loadmore_line{border-top:1rpx solid #e5e5e5;margin-top:2.4em}.weui-loadmore__tips_in-line{position:relative;top:-.9em;padding:0 .55em;background-color:#fff;color:#999}.weui-loadmore__tips_in-dot{position:relative;padding:0 .16em;width:8rpx;height:1.6em}.weui-loadmore__tips_in-dot:before{content:" ";position:absolute;top:50%;left:50%;margin-top:-2rpx;margin-left:-4rpx;width:8rpx;height:8rpx;border-radius:50%;background-color:#e5e5e5}.weui-panel{background-color:#fff;margin-top:20rpx;position:relative;overflow:hidden}.weui-panel:first-child{margin-top:0}.weui-panel:before{top:0;border-top:1rpx solid #e5e5e5}.weui-panel:after,.weui-panel:before{content:" ";position:absolute;left:0;right:0;height:2rpx;color:#e5e5e5}.weui-panel:after{bottom:0;border-bottom:1rpx solid #e5e5e5}.weui-panel__hd{padding:28rpx 30rpx 20rpx;color:#999;font-size:26rpx;position:relative}.weui-panel__hd:after{content:" ";position:absolute;left:0;bottom:0;right:0;height:2rpx;border-bottom:1rpx solid #e5e5e5;color:#e5e5e5;left:30rpx}.weui-media-box{padding:30rpx;position:relative}.weui-media-box:before{content:" ";position:absolute;left:0;top:0;right:0;height:2rpx;border-top:1rpx solid #e5e5e5;color:#e5e5e5;left:30rpx}.weui-media-box:first-child:before{display:none}.weui-media-box__title{font-weight:400;font-size:34rpx;width:auto;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;word-wrap:normal;word-wrap:break-word;word-break:break-all}.weui-media-box__desc{color:#999;font-size:26rpx;line-height:1.2;overflow:hidden;text-overflow:ellipsis;display:-webkit-box;-webkit-box-orient:vertical;-webkit-line-clamp:2}.weui-media-box__info{margin-top:30rpx;padding-bottom:10rpx;font-size:26rpx;color:#cecece;line-height:1em;list-style:none;overflow:hidden}.weui-media-box__info__meta{float:left;padding-right:1em}.weui-media-box__info__meta_extra{padding-left:1em;border-left:1rpx solid #cecece}.weui-media-box__title_in-text{margin-bottom:16rpx}.weui-media-box_appmsg{display:-webkit-box;display:-webkit-flex;display:flex;-webkit-box-align:center;-webkit-align-items:center;align-items:center}.weui-media-box__thumb{width:100%;height:100%;vertical-align:top}.weui-media-box__hd_in-appmsg{margin-right:.8em;width:120rpx;height:120rpx;line-height:120rpx;text-align:center}.weui-media-box__bd_in-appmsg{-webkit-box-flex:1;-webkit-flex:1;flex:1;min-width:0}.weui-media-box_small-appmsg{padding:0}.weui-cells_in-small-appmsg{margin-top:0}.weui-cells_in-small-appmsg:before{display:none}.weui-progress{display:-webkit-box;display:-webkit-flex;display:flex;-webkit-box-align:center;-webkit-align-items:center;align-items:center}.weui-progress__bar{-webkit-box-flex:1;-webkit-flex:1;flex:1}.weui-progress__opr{margin-left:30rpx;font-size:0}.weui-navbar{display:-webkit-box;display:-webkit-flex;display:flex;position:absolute;z-index:500;top:0;width:100%;border-bottom:1rpx solid #ccc}.weui-navbar__item{position:relative;display:block;-webkit-box-flex:1;-webkit-flex:1;flex:1;padding:26rpx 0;text-align:center;font-size:0}.weui-navbar__item.weui-bar__item_on{color:#1aad19}.weui-navbar__slider{position:absolute;content:" ";left:0;bottom:0;width:6em;height:6rpx;background-color:#1aad19;-webkit-transition:-webkit-transform .3s;transition:-webkit-transform .3s;transition:transform .3s;transition:transform .3s,-webkit-transform .3s}.weui-navbar__title{display:inline-block;font-size:30rpx;max-width:8em;width:auto;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;word-wrap:normal}.weui-tab{position:relative;height:100%}.weui-tab__panel{box-sizing:border-box;height:100%;padding-top:100rpx;overflow:auto;-webkit-overflow-scrolling:touch}.weui-search-bar{position:relative;padding:16rpx 20rpx;display:-webkit-box;display:-webkit-flex;display:flex;box-sizing:border-box;background-color:#efeff4;border-top:1rpx solid #d7d6dc;border-bottom:1rpx solid #d7d6dc}.weui-icon-search{margin-right:16rpx;font-size:inherit}.weui-icon-search_in-box{position:absolute;left:20rpx;top:14rpx}.weui-search-bar__text{display:inline-block;font-size:28rpx;vertical-align:middle}.weui-search-bar__form{position:relative;-webkit-box-flex:1;-webkit-flex:auto;flex:auto;border-radius:10rpx;background:#fff;border:1rpx solid #e6e6ea}.weui-search-bar__box{position:relative;padding-left:60rpx;padding-right:60rpx;width:100%;box-sizing:border-box;z-index:1}.weui-search-bar__input{height:56rpx;line-height:56rpx;font-size:28rpx}.weui-icon-clear{position:absolute;top:0;right:0;padding:14rpx 16rpx;font-size:0}.weui-search-bar__label{position:absolute;top:0;right:0;bottom:0;left:0;z-index:2;border-radius:6rpx;text-align:center;color:#9b9b9b;background:#fff;line-height:56rpx}.weui-search-bar__cancel-btn{margin-left:20rpx;line-height:56rpx;color:#09bb07;white-space:nowrap}
19,071
weui
wxss
en
unknown
unknown
{}
0
{}
007gzs/meeting
miniprogram/utils/api.js
"use strict"; const request = require('./request'); const server = 'http://127.0.0.1:8000'; const ERROR_CODE = { SUCCESS: 0, // 返回成功 ERROR_UNKNOWN: -1, // 未知错误 ERROR_SYSTEM: -2, // 系统错误 ERROR_BAD_PARAMETER: -11, // 参数错误 ERROR_BAD_FORMAT: -12, // 格式错误 ERROR_PERMISSION: -13, // 权限错误 ERR_WECHAT_LOGIN: 10001, // 需要登录 ERR_MEETING_ROOM_TIMEOVER: 20001, // 时间已过 ERR_MEETING_ROOM_INUSE: 20002, // 时间冲突 ERR_MEETING_ROOM_NOT_FOUND: 20003, // 会议室未找到 ERR_MEETING_NOT_FOUND: 20004 // 会议室未找到 } // 小程序登录 const api_wechat_login = function({ js_code // 小程序登录code } = {}) { return request({ server: server, path: '/api/wechat/login', method: 'GET', data: { js_code: js_code }, header: { 'Content-Type': 'application/x-www-form-urlencoded' } }) } // 小程序用户信息 const api_wechat_user_info = function({ encrypted_data, // 完整用户信息的加密数据 iv // 加密算法的初始向量 } = {}) { return request({ server: server, path: '/api/wechat/user/info', method: 'POST', data: { encrypted_data: encrypted_data, iv: iv }, header: { 'Content-Type': 'application/x-www-form-urlencoded' } }) } // 配置信息 const api_meeting_config = function() { return request({ server: server, path: '/api/meeting/config', method: 'GET', data: {}, header: { 'Content-Type': 'application/x-www-form-urlencoded' } }) } // 创建会议室 const api_meeting_room_create = function({ name, // 名称 description, // 描述 create_user_manager // 创建人管理权限 } = {}) { return request({ server: server, path: '/api/meeting/room/create', method: 'POST', data: { name: name, description: description, create_user_manager: create_user_manager }, header: { 'Content-Type': 'application/x-www-form-urlencoded' } }) } // 修改会议室 const api_meeting_room_edit = function({ room_id, // 会议室ID name, // 名称 description, // 描述 create_user_manager // 创建人管理权限 } = {}) { return request({ server: server, path: '/api/meeting/room/edit', method: 'POST', data: { room_id: room_id, name: name, description: description, create_user_manager: create_user_manager }, header: { 'Content-Type': 'application/x-www-form-urlencoded' } }) } // 删除会议室 const api_meeting_room_delete = function({ room_id // 会议室ID } = {}) { return request({ server: server, path: '/api/meeting/room/delete', method: 'GET', data: { room_id: room_id }, header: { 'Content-Type': 'application/x-www-form-urlencoded' } }) } // 会议室信息 const api_meeting_room_info = function({ room_id // 会议室ID } = {}) { return request({ server: server, path: '/api/meeting/room/info', method: 'GET', data: { room_id: room_id }, header: { 'Content-Type': 'application/x-www-form-urlencoded' } }) } // 关注会议室 const api_meeting_room_follow = function({ room_id // 会议室ID列表 } = {}) { return request({ server: server, path: '/api/meeting/room/follow', method: 'GET', data: { room_id: room_id }, header: { 'Content-Type': 'application/x-www-form-urlencoded' } }) } // 取消关注会议室 const api_meeting_room_un_follow = function({ room_id // 会议室ID } = {}) { return request({ server: server, path: '/api/meeting/room/un/follow', method: 'GET', data: { room_id: room_id }, header: { 'Content-Type': 'application/x-www-form-urlencoded' } }) } // 已关注会议室列表 const api_meeting_follow_rooms = function() { return request({ server: server, path: '/api/meeting/follow/rooms', method: 'GET', data: {}, header: { 'Content-Type': 'application/x-www-form-urlencoded' } }) } // 创建会议室列表 const api_meeting_create_rooms = function() { return request({ server: server, path: '/api/meeting/create/rooms', method: 'GET', data: {}, header: { 'Content-Type': 'application/x-www-form-urlencoded' } }) } // 会议室预约列表 const api_meeting_room_meetings = function({ room_ids, // 会议室ID列表 date // 日期 } = {}) { return request({ server: server, path: '/api/meeting/room/meetings', method: 'GET', data: { room_ids: room_ids, date: date }, header: { 'Content-Type': 'application/x-www-form-urlencoded' } }) } // 会议室预约历史 const api_meeting_history_meetings = function({ room_id, // 会议室ID start_date, // 开始日期 end_date // 结束日期 } = {}) { return request({ server: server, path: '/api/meeting/history/meetings', method: 'GET', data: { room_id: room_id, start_date: start_date, end_date: end_date }, header: { 'Content-Type': 'application/x-www-form-urlencoded' } }) } // 我参与的会议列表 const api_meeting_my_meetings = function({ date // 日期 } = {}) { return request({ server: server, path: '/api/meeting/my/meetings', method: 'GET', data: { date: date }, header: { 'Content-Type': 'application/x-www-form-urlencoded' } }) } // 预约会议 const api_meeting_reserve = function({ room_id, // 会议室ID name, // 名称 description, // 描述 date, // 预定日期 start_time, // 开始时间 end_time // 结束时间 } = {}) { return request({ server: server, path: '/api/meeting/reserve', method: 'POST', data: { room_id: room_id, name: name, description: description, date: date, start_time: start_time, end_time: end_time }, header: { 'Content-Type': 'application/x-www-form-urlencoded' } }) } // 会议详情 const api_meeting_info = function({ meeting_id // 会议ID } = {}) { return request({ server: server, path: '/api/meeting/info', method: 'GET', data: { meeting_id: meeting_id }, header: { 'Content-Type': 'application/x-www-form-urlencoded' } }) } // 会议修改 const api_meeting_edit = function({ meeting_id, // 会议ID name, // 名称 description // 描述 } = {}) { return request({ server: server, path: '/api/meeting/edit', method: 'POST', data: { meeting_id: meeting_id, name: name, description: description }, header: { 'Content-Type': 'application/x-www-form-urlencoded' } }) } // 取消会议 const api_meeting_cancel = function({ meeting_id // 会议ID } = {}) { return request({ server: server, path: '/api/meeting/cancel', method: 'GET', data: { meeting_id: meeting_id }, header: { 'Content-Type': 'application/x-www-form-urlencoded' } }) } // 参加会议 const api_meeting_join = function({ meeting_id // 会议ID } = {}) { return request({ server: server, path: '/api/meeting/join', method: 'GET', data: { meeting_id: meeting_id }, header: { 'Content-Type': 'application/x-www-form-urlencoded' } }) } // 取消参加会议 const api_meeting_leave = function({ meeting_id // 会议ID } = {}) { return request({ server: server, path: '/api/meeting/leave', method: 'GET', data: { meeting_id: meeting_id }, header: { 'Content-Type': 'application/x-www-form-urlencoded' } }) } module.exports = { ERROR_CODE: ERROR_CODE, api_wechat_login: api_wechat_login, api_wechat_user_info: api_wechat_user_info, api_meeting_config: api_meeting_config, api_meeting_room_create: api_meeting_room_create, api_meeting_room_edit: api_meeting_room_edit, api_meeting_room_delete: api_meeting_room_delete, api_meeting_room_info: api_meeting_room_info, api_meeting_room_follow: api_meeting_room_follow, api_meeting_room_un_follow: api_meeting_room_un_follow, api_meeting_follow_rooms: api_meeting_follow_rooms, api_meeting_create_rooms: api_meeting_create_rooms, api_meeting_room_meetings: api_meeting_room_meetings, api_meeting_history_meetings: api_meeting_history_meetings, api_meeting_my_meetings: api_meeting_my_meetings, api_meeting_reserve: api_meeting_reserve, api_meeting_info: api_meeting_info, api_meeting_edit: api_meeting_edit, api_meeting_cancel: api_meeting_cancel, api_meeting_join: api_meeting_join, api_meeting_leave: api_meeting_leave }
8,012
api
js
zh
javascript
code
{"qsc_code_num_words": 1028, "qsc_code_num_chars": 8012.0, "qsc_code_mean_word_length": 4.72373541, "qsc_code_frac_words_unique": 0.12937743, "qsc_code_frac_chars_top_2grams": 0.14827018, "qsc_code_frac_chars_top_3grams": 0.08072488, "qsc_code_frac_chars_top_4grams": 0.1029654, "qsc_code_frac_chars_dupe_5grams": 0.76276771, "qsc_code_frac_chars_dupe_6grams": 0.65362438, "qsc_code_frac_chars_dupe_7grams": 0.62644152, "qsc_code_frac_chars_dupe_8grams": 0.51729819, "qsc_code_frac_chars_dupe_9grams": 0.45819605, "qsc_code_frac_chars_dupe_10grams": 0.37541186, "qsc_code_frac_chars_replacement_symbols": 0.0, "qsc_code_frac_chars_digital": 0.00701083, "qsc_code_frac_chars_whitespace": 0.21667499, "qsc_code_size_file_byte": 8012.0, "qsc_code_num_lines": 382.0, "qsc_code_num_chars_line_max": 68.0, "qsc_code_num_chars_line_mean": 20.97382199, "qsc_code_frac_chars_alphabet": 0.7667304, "qsc_code_frac_chars_comments": 0.06215676, "qsc_code_cate_xml_start": 0.0, "qsc_code_frac_lines_dupe_lines": 0.56739812, "qsc_code_cate_autogen": 0.0, "qsc_code_frac_lines_long_string": 0.0, "qsc_code_frac_chars_string_length": 0.1918829, "qsc_code_frac_chars_long_word_length": 0.12681304, "qsc_code_frac_lines_string_concat": 0.0, "qsc_code_cate_encoded_data": 0.0, "qsc_code_frac_chars_hex_words": 0.0, "qsc_code_frac_lines_prompt_comments": 0.0, "qsc_code_frac_lines_assert": 0.0, "qsc_codejavascript_cate_ast": 1.0, "qsc_codejavascript_cate_var_zero": 0.0, "qsc_codejavascript_frac_lines_func_ratio": 0.06269592, "qsc_codejavascript_num_statement_line": 0.07836991, "qsc_codejavascript_score_lines_no_logic": 0.06583072, "qsc_codejavascript_frac_words_legal_var_name": 0.66666667, "qsc_codejavascript_frac_words_legal_func_name": 0.0, "qsc_codejavascript_frac_words_legal_class_name": null, "qsc_codejavascript_frac_lines_print": 0.0}
1
{"qsc_code_frac_chars_replacement_symbols": 0, "qsc_code_num_words": 0, "qsc_code_num_chars": 0, "qsc_code_mean_word_length": 0, "qsc_code_frac_chars_top_2grams": 0, "qsc_code_frac_chars_top_3grams": 0, "qsc_code_frac_chars_top_4grams": 0, "qsc_code_frac_chars_dupe_5grams": 0, "qsc_code_frac_chars_dupe_6grams": 0, "qsc_code_frac_chars_dupe_7grams": 0, "qsc_code_frac_chars_dupe_8grams": 0, "qsc_code_frac_chars_dupe_9grams": 0, "qsc_code_frac_chars_dupe_10grams": 0, "qsc_code_size_file_byte": 0, "qsc_code_num_lines": 0, "qsc_code_num_chars_line_max": 0, "qsc_code_num_chars_line_mean": 0, "qsc_code_frac_chars_alphabet": 0, "qsc_code_frac_chars_digital": 0, "qsc_code_frac_chars_whitespace": 0, "qsc_code_frac_chars_comments": 0, "qsc_code_cate_xml_start": 0, "qsc_code_frac_lines_dupe_lines": 0, "qsc_code_cate_autogen": 0, "qsc_code_frac_lines_long_string": 0, "qsc_code_frac_chars_string_length": 0, "qsc_code_frac_chars_long_word_length": 0, "qsc_code_cate_encoded_data": 0, "qsc_code_frac_chars_hex_words": 0, "qsc_code_frac_lines_prompt_comments": 0, "qsc_code_frac_lines_assert": 0, "qsc_codejavascript_cate_ast": 0, "qsc_codejavascript_cate_var_zero": 0, "qsc_codejavascript_frac_lines_func_ratio": 0, "qsc_codejavascript_score_lines_no_logic": 0, "qsc_codejavascript_frac_lines_print": 0}
000haoji/deep-student
src-tauri/Cargo.toml
[package] name = "ai-mistake-manager" version = "0.1.0" description = "A Tauri App" authors = ["you"] edition = "2021" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html [lib] # The `_lib` suffix may seem redundant but it is necessary # to make the lib name unique and wouldn't conflict with the bin name. # This seems to be only an issue on Windows, see https://github.com/rust-lang/cargo/issues/8519 name = "ai_mistake_manager_lib" crate-type = ["cdylib", "rlib"] [build-dependencies] tauri-build = { version = "2", features = [] } [dependencies] tauri = { version = "2", features = ["rustls-tls", "devtools"] } tauri-plugin-opener = "2" tauri-plugin-dialog = "2" serde = { version = "1.0", features = ["derive", "rc"] } serde_json = { version = "1.0", features = ["preserve_order"] } uuid = { version = "1.0", features = ["v4", "serde"] } reqwest = { version = "0.11", features = ["json", "rustls-tls", "stream"] } tokio = { version = "1.0", features = ["full"] } rusqlite = { version = "0.29", features = ["bundled"] } base64 = "0.21" chrono = { version = "0.4", features = ["serde"] } anyhow = "1.0" futures-util = "0.3" regex = "1.0" aes-gcm = "0.10" rand = "0.8" blake3 = "1.5" keyring = "2.0" zip = "0.6" url = "2.4" image = "0.24" # RAG文档处理依赖 pdf-extract = "0.7" docx-rs = "0.4" # 向量搜索依赖 - 暂时移除sqlite-vss,使用基础SQLite + 应用层向量计算 # sqlite-vss = { version = "0.1", features = ["download-libs"] } # Windows平台不支持 # Neo4j图数据库依赖 neo4rs = "0.7" # 优化编译速度的配置 [profile.dev] opt-level = 0 # 无优化,快速编译 debug = true # 保留调试信息 incremental = true # 启用增量编译 lto = false # 禁用链接时优化 [profile.release] opt-level = "s" # 优化大小 lto = true # 链接时优化 codegen-units = 1 # 减少代码生成单元以提高优化效果
1,772
Cargo
toml
en
toml
data
{"qsc_code_num_words": 249, "qsc_code_num_chars": 1772.0, "qsc_code_mean_word_length": 4.42570281, "qsc_code_frac_words_unique": 0.61445783, "qsc_code_frac_chars_top_2grams": 0.01270417, "qsc_code_frac_chars_top_3grams": 0.03266788, "qsc_code_frac_chars_top_4grams": 0.06170599, "qsc_code_frac_chars_dupe_5grams": 0.0, "qsc_code_frac_chars_dupe_6grams": 0.0, "qsc_code_frac_chars_dupe_7grams": 0.0, "qsc_code_frac_chars_dupe_8grams": 0.0, "qsc_code_frac_chars_dupe_9grams": 0.0, "qsc_code_frac_chars_dupe_10grams": 0.0, "qsc_code_frac_chars_replacement_symbols": 0.0, "qsc_code_frac_chars_digital": 0.05034965, "qsc_code_frac_chars_whitespace": 0.19300226, "qsc_code_size_file_byte": 1772.0, "qsc_code_num_lines": 61.0, "qsc_code_num_chars_line_max": 97.0, "qsc_code_num_chars_line_mean": 29.04918033, "qsc_code_frac_chars_alphabet": 0.72027972, "qsc_code_frac_chars_comments": 0.30756208, "qsc_code_cate_xml_start": 0.0, "qsc_code_frac_lines_dupe_lines": 0.0, "qsc_code_cate_autogen": 0.0, "qsc_code_frac_lines_long_string": 0.0, "qsc_code_frac_chars_string_length": 0.1867863, "qsc_code_frac_chars_long_word_length": 0.01794454, "qsc_code_frac_lines_string_concat": 0.0, "qsc_code_cate_encoded_data": 0.0, "qsc_code_frac_chars_hex_words": 0.0, "qsc_code_frac_lines_prompt_comments": 0.0, "qsc_code_frac_lines_assert": 0.0}
1
{"qsc_code_frac_chars_replacement_symbols": 0, "qsc_code_num_words": 0, "qsc_code_num_chars": 0, "qsc_code_mean_word_length": 0, "qsc_code_frac_words_unique": 0, "qsc_code_frac_chars_top_2grams": 0, "qsc_code_frac_chars_top_3grams": 0, "qsc_code_frac_chars_top_4grams": 0, "qsc_code_frac_chars_dupe_5grams": 0, "qsc_code_frac_chars_dupe_6grams": 0, "qsc_code_frac_chars_dupe_7grams": 0, "qsc_code_frac_chars_dupe_8grams": 0, "qsc_code_frac_chars_dupe_9grams": 0, "qsc_code_frac_chars_dupe_10grams": 0, "qsc_code_frac_lines_dupe_lines": 0, "qsc_code_size_file_byte": 0, "qsc_code_num_lines": 0, "qsc_code_num_chars_line_max": 0, "qsc_code_num_chars_line_mean": 0, "qsc_code_frac_chars_alphabet": 0, "qsc_code_frac_chars_digital": 0, "qsc_code_frac_chars_whitespace": 0, "qsc_code_frac_chars_comments": 0, "qsc_code_cate_xml_start": 0, "qsc_code_cate_autogen": 0, "qsc_code_frac_chars_long_word_length": 0, "qsc_code_cate_encoded_data": 0, "qsc_code_frac_chars_hex_words": 0}
000haoji/deep-student
src/DeepStudent.css
/* Deep Student Design - 简洁优雅的侧边栏布局 */ /* 紧急修复:彻底禁用所有旧tooltip相关的伪元素 */ .tooltip-container, .tooltip-container::before, .tooltip-container::after, .tooltip-container.tooltip-right::before, .tooltip-container.tooltip-right::after, .tooltip-container.tooltip-left::before, .tooltip-container.tooltip-left::after, .tooltip-container.tooltip-bottom::before, .tooltip-container.tooltip-bottom::after, .tooltip-container.tooltip-success::before, .tooltip-container.tooltip-success::after, .tooltip-container.tooltip-warning::before, .tooltip-container.tooltip-warning::after, .tooltip-container.tooltip-info::before, .tooltip-container.tooltip-info::after, /* 增强清理:清除任何可能的选择器 */ *[class*="tooltip-container"]::before, *[class*="tooltip-container"]::after, *[data-tooltip]:not(.tooltip-test)::before, *[data-tooltip]:not(.tooltip-test)::after { display: none !important; content: none !important; opacity: 0 !important; visibility: hidden !important; position: static !important; background: none !important; border: none !important; box-shadow: none !important; width: 0 !important; height: 0 !important; margin: 0 !important; padding: 0 !important; } /* 自定义标题栏样式 */ .custom-titlebar { height: 32px; background: linear-gradient(180deg, #ffffff 0%, #f8f9fa 100%); border-bottom: 1px solid #e2e8f0; display: flex; align-items: center; justify-content: space-between; padding: 0; user-select: none; position: relative; z-index: 1000; box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05); } .titlebar-content { display: flex; align-items: center; justify-content: space-between; width: 100%; height: 100%; } .titlebar-left { display: flex; align-items: center; gap: 8px; padding-left: 12px; flex: 1; } .app-icon { font-size: 16px; width: 20px; height: 20px; display: flex; align-items: center; justify-content: center; } .app-title { font-size: 13px; font-weight: 500; color: #2d3748; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; } .titlebar-controls { display: flex; height: 100%; } .titlebar-button { width: 48px; height: 32px; border: none; background: transparent; display: flex; align-items: center; justify-content: center; cursor: pointer; transition: background-color 0.2s ease; color: #4a5568; } .titlebar-button:hover { background: rgba(0, 0, 0, 0.05); } .titlebar-button.close:hover { background: #e53e3e; color: white; } .titlebar-button svg { flex-shrink: 0; } /* 窗口控制按钮样式 - 强制显示 */ .window-controls { position: fixed !important; top: 0 !important; right: 0 !important; display: flex !important; z-index: 999999 !important; /* 🎯 修复:使用最高z-index确保窗口控制按钮始终可见 */ background: rgba(255, 255, 255, 0.95) !important; backdrop-filter: blur(10px) !important; border-bottom-left-radius: 8px !important; /* 🎯 修复:强制确保窗口控制按钮不被隐藏 */ visibility: visible !important; opacity: 1 !important; pointer-events: auto !important; width: auto !important; height: auto !important; transform: none !important; clip: none !important; overflow: visible !important; } .window-button { width: 46px; height: 32px; border: none; background: transparent; display: flex; align-items: center; justify-content: center; cursor: pointer; transition: background-color 0.2s ease; color: #4a5568; border-radius: 0; /* 🎯 修复:确保窗口按钮始终可见 */ visibility: visible !important; opacity: 1 !important; pointer-events: auto !important; position: relative; z-index: 10001; } .window-button:hover { background: rgba(0, 0, 0, 0.08); } .window-button.close:hover { background: #e53e3e; color: white; } .window-button:first-child { border-bottom-left-radius: 8px; } .window-button:last-child { border-top-right-radius: 0; } .window-button svg { flex-shrink: 0; /* 🎯 修复:确保SVG图标正常显示 */ display: block !important; visibility: visible !important; opacity: 1 !important; pointer-events: none; } /* 确保header可拖拽 */ .sidebar-header { cursor: grab; user-select: none; } .sidebar-header:active { cursor: grabbing; } .content-header { cursor: grab; user-select: none; } .content-header:active { cursor: grabbing; } /* 确保按钮不受拖拽影响 */ .sidebar-toggle { pointer-events: auto; z-index: 10; } .window-controls { pointer-events: auto; z-index: 10000; /* 🎯 修复:确保窗口控制按钮在最上层 */ } .window-button { pointer-events: auto; z-index: 10001; /* 🎯 修复:确保窗口按钮在最上层 */ position: relative; } .sidebar-toggle { pointer-events: auto; z-index: 11; position: relative; } /* 隐藏调试信息和开发者工具覆盖层 */ [data-tauri-debug], [data-debug], .debug-overlay, .size-indicator, .resize-indicator, .window-size-indicator, .dimension-overlay, *[class*="debug"], *[id*="debug"], *[class*="dev-tools"], *[class*="devtools"], *[class*="resize-info"], *[class*="size-info"] { display: none !important; visibility: hidden !important; opacity: 0 !important; pointer-events: none !important; } /* 特别针对右上角的调试信息 - 排除窗口控制按钮 */ body::after, html::after, *:not(.window-controls):not(.window-button)::after, *:not(.window-controls):not(.window-button)::before { content: none !important; } /* 隐藏任何可能的固定定位调试元素 - 更精确的选择器 */ div[style*="position: fixed"][style*="top: 0"][style*="right: 0"][class*="debug"]:not(.window-controls), div[style*="position: absolute"][style*="top: 0"][style*="right: 0"][class*="debug"]:not(.window-controls), div[style*="position: fixed"][style*="top: 0"][style*="right: 0"][id*="debug"]:not(.window-controls), div[style*="position: absolute"][style*="top: 0"][style*="right: 0"][id*="debug"]:not(.window-controls) { display: none !important; } /* 全局样式重置 */ * { margin: 0; padding: 0; box-sizing: border-box; } /* 主应用容器 */ .app { display: flex !important; flex-direction: row !important; height: 100vh !important; background-color: #f8f9fa; font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', sans-serif; color: #2d3748; transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1); /* CSS变量用于动态设置侧边栏宽度 */ --sidebar-width: 240px; --sidebar-collapsed-width: 60px; /* 确保CSS变量变化时也有过渡效果 */ --transition-timing: 0.3s cubic-bezier(0.4, 0, 0.2, 1); } /* 应用主体区域(整个应用内容) */ .app-body { display: flex; height: 100vh; /* 🎯 修复:确保主体内容区域从窗口顶部开始,适配自定义标题栏 */ padding-top: 0; /* 🎯 修复:移除最小宽度限制,解决响应式布局在小窗口下的突变问题 */ flex-direction: row !important; flex: 1 !important; overflow: auto !important; /* MODIFIED: Allow scrolling if content overflows */ } /* 侧边栏 */ .app-sidebar { width: var(--sidebar-width); min-width: var(--sidebar-width); background: #ffffff; border-right: 1px solid #e2e8f0; display: flex; flex-direction: column; transition: width 0.3s cubic-bezier(0.4, 0, 0.2, 1), min-width 0.3s cubic-bezier(0.4, 0, 0.2, 1); box-shadow: 0 0 0 1px rgba(0, 0, 0, 0.05); /* overflow: visible !important; -- This was part of the problematic block, sidebar itself should not scroll */ } .app-sidebar.collapsed { width: var(--sidebar-collapsed-width); min-width: var(--sidebar-collapsed-width); } /* 侧边栏头部 */ .sidebar-header { padding: 0.75rem 1rem; border-bottom: 1px solid #e2e8f0; display: flex; align-items: center; justify-content: space-between; background: #ffffff !important; height: 48px; box-sizing: border-box; } .app-logo { display: flex; align-items: center; gap: 0.75rem; justify-content: center; } /* 侧边栏展开时,logo靠左1/3 */ .app-sidebar:not(.collapsed) .app-logo { justify-content: flex-start; padding-left: 1.5rem; } .logo-icon { width: 32px; height: 32px; border-radius: 8px; object-fit: contain; } .logo-full { height: 32px; max-width: 200px; object-fit: contain; object-position: left center; margin-left: 0; } .logo-text { font-size: 1rem; font-weight: 600; color: #2d3748; white-space: nowrap; } .sidebar-toggle { width: 28px; height: 28px; border: none; background: #f7fafc; border-radius: 6px; cursor: pointer; display: flex; align-items: center; justify-content: center; transition: all 0.2s ease; color: #718096; font-size: 0.875rem; } .sidebar-toggle:hover { background: #edf2f7; color: #4a5568; } /* 导航区域 */ .sidebar-nav { flex: 1; padding: 1rem 0.75rem; overflow-y: auto !important; /* MODIFIED: Ensure this scrolls */ min-height: 0; /* ADDED: Good practice for flex children that scroll */ } .nav-section { margin-bottom: 1.5rem; /* overflow: visible !important; -- This was part of the problematic block */ } .nav-label { font-size: 0.75rem; font-weight: 600; color: #000000 !important; text-transform: uppercase; letter-spacing: 0.05em; margin-bottom: 0.5rem; padding-left: 0.75rem; } .nav-item { width: 100%; padding: 0.75rem; border: none; background: transparent; border-radius: 8px; cursor: pointer; display: flex; align-items: center; gap: 0.75rem; font-size: 0.875rem; font-weight: 500; color: #000000 !important; text-align: left; transition: all 0.2s ease; margin-bottom: 0.25rem; position: relative; /* overflow: visible !important; -- This was part of the problematic block */ } .nav-item:hover { background: #f7fafc; color: #000000 !important; } .nav-item.active { background: #ebf8ff; color: #000000 !important; font-weight: 600; } .nav-item.active::before { content: ''; position: absolute; left: 0; top: 50%; transform: translateY(-50%); width: 3px; height: 20px; background: #3182ce; border-radius: 0 2px 2px 0; } .nav-icon { font-size: 1.125rem; width: 20px; display: flex; align-items: center; justify-content: center; flex-shrink: 0; } .nav-text { white-space: nowrap; overflow: hidden; } /* 侧边栏底部 */ .sidebar-footer { padding: 0.75rem; border-top: 1px solid #e2e8f0; background: #ffffff !important; } .sidebar-footer .nav-item { background: transparent !important; color: #000000 !important; } /* 主内容区域 */ .app-content { flex: 1 !important; display: flex !important; flex-direction: column !important; overflow: auto !important; /* MODIFIED: Allow scrolling */ background: #ffffff; min-width: 0; /* ADDED: Prevent flexbox overflow */ } /* 内容头部 */ .content-header { padding: 0.75rem 2rem; border-bottom: 1px solid #e2e8f0; display: flex; align-items: center; justify-content: space-between; background: #ffffff; box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05); height: 48px; box-sizing: border-box; } .content-title { font-size: 1.5rem; font-weight: 600; color: #2d3748; margin: 0; } .content-header-left { display: flex; align-items: center; gap: 1rem; } .content-header .sidebar-toggle { width: 32px; height: 32px; border: none; background: #f7fafc; border-radius: 8px; cursor: pointer; display: flex; align-items: center; justify-content: center; transition: all 0.2s ease; color: #718096; margin-right: 0.5rem; } .content-header .sidebar-toggle svg { flex-shrink: 0; } .content-header .sidebar-toggle:hover { background: #edf2f7; color: #4a5568; transform: scale(1.05); } /* 返回按钮 */ .back-button { padding: 0.5rem 1rem; border: 1px solid #e2e8f0; background: #ffffff; border-radius: 8px; cursor: pointer; font-size: 0.875rem; color: #4a5568; transition: all 0.2s ease; display: flex; align-items: center; gap: 0.5rem; font-weight: 500; } .back-button svg { flex-shrink: 0; } .back-button:hover { background: #f7fafc; border-color: #cbd5e0; color: #2d3748; transform: translateX(-2px); } /* 全屏切换按钮 */ .fullscreen-toggle { padding: 0.5rem 1rem; border: 1px solid #e2e8f0; background: #ffffff; border-radius: 8px; cursor: pointer; font-size: 1rem; color: #4a5568; transition: all 0.2s ease; display: flex; align-items: center; gap: 0.5rem; } .fullscreen-toggle:hover { background: #f7fafc; border-color: #cbd5e0; color: #2d3748; } /* 内容主体 */ .content-body { flex: 1; padding: 2rem; overflow-y: auto; /* MODIFIED */ background: #f8f9fa; display: flex; flex-direction: column; min-height: 0; /* ADDED */ } /* 分析视图特殊布局 */ .content-body .analysis-layout { display: flex !important; flex-direction: row !important; flex: 1 !important; min-height: 0 !important; /* ADDED */ } /* 聊天区域全屏增强 */ .chat-container { position: relative; background: #ffffff; border-radius: 24px; border: 1px solid #e2e8f0; transition: all 0.3s cubic-bezier(0.25, 0.1, 0.25, 1), transform 0.3s cubic-bezier(0.25, 0.1, 0.25, 1), position 0.3s cubic-bezier(0.25, 0.1, 0.25, 1), top 0.3s cubic-bezier(0.25, 0.1, 0.25, 1), left 0.3s cubic-bezier(0.25, 0.1, 0.25, 1), right 0.3s cubic-bezier(0.25, 0.1, 0.25, 1), bottom 0.3s cubic-bezier(0.25, 0.1, 0.25, 1), width 0.3s cubic-bezier(0.25, 0.1, 0.25, 1), height 0.3s cubic-bezier(0.25, 0.1, 0.25, 1); box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05); display: flex; flex-direction: column; flex: 1; min-height: 0; /* 设置变换原点为右下角,实现自然缩放 */ transform-origin: bottom right; } /* 聊天容器全屏样式 - 直接过渡无动画 */ .chat-container.chat-fullscreen { position: fixed !important; top: 48px !important; /* content-header高度 */ /* 动态计算left值,根据侧边栏是否收缩调整 */ left: var(--sidebar-width, 240px) !important; right: 0 !important; bottom: 0 !important; z-index: 999 !important; /* 低于窗口控制按钮 */ border-radius: 0 !important; border: none !important; box-shadow: 0 0 20px rgba(0, 0, 0, 0.1) !important; background: #ffffff !important; /* 保持变换原点为右下角 */ transform-origin: bottom right !important; display: flex !important; flex-direction: column !important; height: calc(100vh - 48px) !important; /* 减去content-header高度 */ min-height: unset !important; max-height: unset !important; width: auto !important; flex: none !important; /* 使用统一的transition,不使用动画 */ } /* Removed chat-header styles since chat-header is no longer used */ .chat-fullscreen-toggle { padding: 0.75rem 1rem; border: 1px solid #e2e8f0; background: #ffffff; border-radius: 8px; cursor: pointer; font-size: 1rem; color: #4a5568; transition: all 0.2s ease; display: flex; align-items: center; justify-content: center; min-width: 44px; } .chat-fullscreen-toggle:hover { background: #f7fafc; border-color: #cbd5e0; color: #2d3748; transform: scale(1.05); } .chat-history { flex: 1; overflow-y: auto; padding: 1rem; min-height: 0; border-radius: 0; /* 移除圆角 */ } .chat-container.chat-fullscreen .chat-history { padding: 2rem !important; flex: 1 !important; overflow-y: auto !important; max-height: none !important; min-height: 0 !important; height: auto !important; border-radius: 0 !important; /* 全屏时移除圆角 */ } .chat-input { padding: 0.75rem 1.5rem; border-top: 1px solid #e2e8f0; background: #ffffff; border-radius: 0; display: flex; flex-direction: row; gap: 0.75rem; align-items: center; flex-wrap: nowrap; } /* Removed duplicate chat-history definition */ .chat-container.chat-fullscreen .chat-input { border-radius: 0 !important; padding: 1rem 2rem !important; background: #ffffff !important; border-top: 1px solid #e2e8f0 !important; box-shadow: 0 -2px 4px rgba(0, 0, 0, 0.05) !important; flex-shrink: 0 !important; } .chat-input input { flex: 1; padding: 0.75rem 1rem; border: 1px solid #e2e8f0; border-radius: 8px; font-size: 0.875rem; outline: none; transition: border-color 0.2s ease; } .chat-input input:focus { border-color: #3182ce; box-shadow: 0 0 0 3px rgba(49, 130, 206, 0.1); } .send-button { padding: 0.75rem 1rem; background: #3182ce; color: white; border: none; border-radius: 8px; cursor: pointer; font-size: 1rem; transition: all 0.2s ease; display: flex; align-items: center; justify-content: center; min-width: 44px; } .send-button:hover:not(:disabled) { background: #2c5aa0; transform: translateY(-1px); } .send-button:disabled { background: #a0aec0; cursor: not-allowed; transform: none; } /* 分析界面布局 */ .analysis-layout { display: flex !important; flex-direction: row !important; gap: 1.5rem !important; flex: 1 !important; min-height: 0 !important; align-items: stretch !important; padding: 1.5rem; background: #f8fafc; max-width: 100%; box-sizing: border-box; overflow: visible; /* Allow content to be visible */ } .left-panel { flex: 0 0 450px; /* 🎯 修复:固定宽度,防止突然收缩 */ min-width: 400px; /* 🎯 修复:提高最小宽度,确保稳定显示 */ display: flex; flex-direction: column; gap: 1rem; background: transparent; max-width: 450px; /* 🎯 修复:限制最大宽度 */ box-sizing: border-box; } .right-panel { flex: 1 1 auto; /* 🎯 修复:改为更稳定的flex设置,占据剩余空间 */ display: flex; flex-direction: column; min-width: 300px; /* 🎯 修复:设置合理的最小宽度 */ overflow: hidden; /* Keep hidden here to manage its own content */ height: 100%; } .upload-section { background: rgba(255, 255, 255, 0.72) !important; backdrop-filter: saturate(180%) blur(12px) !important; border: 1px solid rgba(255, 255, 255, 0.3) !important; padding: 1.5rem; box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05); /* 🎯 美化修复:让上传区域始终填满左侧面板,确保与右侧面板下边缘对齐 */ flex: 1; min-height: 0; display: flex; flex-direction: column; /* 🎯 修复:确保上传区域不超出容器 */ max-width: 100%; box-sizing: border-box; overflow: hidden; } .upload-section h3 { margin: 0 0 1.5rem 0; color: #2d3748; font-size: 1.35rem !important; font-weight: 700 !important; /* 🎯 美化:添加底部边框和更好的间距 */ padding-bottom: 0.75rem; border-bottom: 2px solid #f0f4f8; display: flex; align-items: center; gap: 0.5rem; } .form-group { margin-bottom: 1.5rem; /* 🎯 修复:确保表单组件不超出容器 */ max-width: 100%; box-sizing: border-box; } .form-group label { display: block; margin-bottom: 0.75rem; font-weight: 600; color: #2d3748; font-size: 0.9rem; /* 🎯 美化:添加更好的标签样式 */ text-transform: uppercase; letter-spacing: 0.5px; } .form-group select, .form-group input, .form-group textarea { width: 100%; padding: 0.875rem 1rem; border: 2px solid #e2e8f0; border-radius: 10px; font-size: 0.9rem; transition: all 0.2s ease; /* 🎯 美化:添加更好的输入框样式 */ background: #ffffff; box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05); } .form-group select:focus, .form-group input:focus, .form-group textarea:focus { outline: none; border-color: #667eea; box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1), 0 2px 8px rgba(0, 0, 0, 0.1); /* 🎯 美化:添加轻微的向上移动效果 */ transform: translateY(-1px); } .image-preview { display: grid; grid-template-columns: repeat(auto-fill, minmax(100px, 1fr)); gap: 0.5rem; margin-top: 0.5rem; } .preview-image { width: 100%; height: 80px; object-fit: cover; border-radius: 6px; border: 1px solid #e2e8f0; } .analyze-button { width: 100%; padding: 0.875rem 1rem; background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; border: none; border-radius: 10px; font-size: 1rem; font-weight: 600; cursor: pointer; transition: all 0.2s ease, transform 0.15s ease, box-shadow 0.15s ease; display: flex; align-items: center; justify-content: center; gap: 0.5rem; margin-top: auto; flex-shrink: 0; /* 🎯 美化:添加更好的视觉效果 */ box-shadow: 0 2px 8px rgba(102, 126, 234, 0.2); } .analyze-button:hover:not(:disabled) { transform: translateY(-2px); box-shadow: 0 6px 16px rgba(0, 0, 0, 0.08); } .analyze-button:disabled { background: #a0aec0; cursor: not-allowed; transform: none; } .action-buttons { display: flex; gap: 0.75rem; margin-top: 1.5rem; /* 🎯 美化:添加顶部边框分隔 */ padding-top: 1.5rem; border-top: 1px solid #f0f4f8; } .save-button, .reset-button { flex: 1; padding: 0.875rem 1rem; border: none; border-radius: 10px; font-size: 0.9rem; font-weight: 600; cursor: pointer; transition: all 0.2s ease, transform 0.15s ease, box-shadow 0.15s ease; /* 🎯 美化:添加阴影和更好的视觉效果 */ box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1); display: flex; align-items: center; justify-content: center; gap: 0.5rem; } .save-button { background: linear-gradient(135deg, #38a169 0%, #2f855a 100%); color: white; } .save-button:hover { background: linear-gradient(135deg, #2f855a 0%, #276749 100%); transform: translateY(-2px); box-shadow: 0 6px 16px rgba(0, 0, 0, 0.08); } .reset-button { background: #f7fafc; color: #4a5568; border: 2px solid #e2e8f0; } .reset-button:hover { background: #edf2f7; border-color: #cbd5e0; transform: translateY(-2px); box-shadow: 0 6px 16px rgba(0, 0, 0, 0.08); } .empty-result { display: flex; flex-direction: column; align-items: center; justify-content: center; height: 100%; text-align: center; color: #718096; /* 🎯 美化:添加背景和边框,与左侧面板保持一致 */ background: #ffffff; border-radius: 12px; border: 1px solid #e2e8f0; box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05); padding: 2rem; } .empty-icon { font-size: 3rem; margin-bottom: 1rem; } .empty-logo { width: 64px; height: 64px; object-fit: contain; opacity: 0.6; border-radius: 12px; } .analysis-result { background: #ffffff; border-radius: 24px; border: 1px solid #e2e8f0; height: 100%; display: flex; flex-direction: column; box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05); } .result-header { padding: 1.5rem; border-bottom: 1px solid #e2e8f0; display: flex; align-items: center; justify-content: space-between; } .result-header h3 { margin: 0; color: #2d3748; font-size: 1.125rem; font-weight: 600; } .analyzing-indicator { display: flex; align-items: center; gap: 0.5rem; color: #667eea; font-size: 0.875rem; } .spinner { animation: spin 1s linear infinite; } @keyframes spin { from { transform: rotate(0deg); } to { transform: rotate(360deg); } } .result-info { padding: 1rem 1.5rem; border-bottom: 1px solid #e2e8f0; } .info-item { margin-bottom: 0.75rem; display: flex; gap: 0.5rem; align-items: flex-start; } .info-item strong { color: #4a5568; min-width: 80px; font-weight: 600; } .info-value { color: #2d3748; } .tags { display: flex; flex-wrap: wrap; gap: 0.5rem; } .tag { background: #ebf8ff; color: #3182ce; padding: 0.25rem 0.75rem; border-radius: 16px; font-size: 0.75rem; font-weight: 500; } .ocr-text { background: #f7fafc; padding: 0.75rem; border-radius: 6px; border: 1px solid #e2e8f0; font-size: 0.875rem; line-height: 1.5; color: #2d3748; max-height: 120px; overflow-y: auto; } /* 响应式设计 */ @media (max-width: 1200px) { .analysis-layout { flex-direction: column !important; gap: 1rem !important; padding: 1rem !important; } .left-panel { flex: 0 0 auto; /* 🎯 修复:在小屏幕上也保持固定尺寸 */ min-width: 350px; /* 🎯 修复:在小屏幕上适当减小但保持稳定 */ max-width: 100%; /* 🎯 修复:确保不超出容器 */ } .right-panel { flex: 1 1 auto; /* 🎯 修复:占据剩余空间,但不会过度扩展 */ min-width: 250px; /* 🎯 修复:设置合理的最小宽度 */ } } /* 渐进式响应式断点设计 - 谨慎优化 */ /* 中等窗口尺寸:适度缩小侧边栏宽度 */ @media (max-width: 1200px) { :root { --sidebar-width: 200px; /* 从240px减少到200px */ } /* 确保聊天容器全屏模式适应新的侧边栏宽度 */ .chat-container.chat-fullscreen { left: 200px !important; } } /* 较小窗口尺寸:进一步缩小侧边栏 */ @media (max-width: 900px) { :root { --sidebar-width: 180px; /* 进一步减少到180px */ } .chat-container.chat-fullscreen { left: 180px !important; } } /* 小窗口尺寸:显著缩小但保持可读性 */ @media (max-width: 700px) { :root { --sidebar-width: 160px; /* 减少到160px */ } .chat-container.chat-fullscreen { left: 160px !important; } } /* 极小窗口尺寸:切换到收缩模式(移动设备) */ @media (max-width: 500px) { .app-sidebar { width: 60px; /* 确保过渡动画仍然有效 */ transition: width 0.3s cubic-bezier(0.4, 0, 0.2, 1), min-width 0.3s cubic-bezier(0.4, 0, 0.2, 1); } .app-sidebar:not(.collapsed) { position: absolute; width: 240px; z-index: 100; box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1); } .content-header { padding: 0.5rem 1rem; } .content-body { padding: 1rem; } /* 确保聊天容器在移动设备上正确调整 */ .chat-container.chat-fullscreen { left: 60px !important; } } /* 动画效果 */ @keyframes slideIn { from { opacity: 0; transform: translateX(-20px); } to { opacity: 1; transform: translateX(0); } } .nav-item { animation: slideIn 0.3s ease; } /* 主题色彩优化 */ :root { --cherry-primary: #3182ce; --cherry-primary-light: #ebf8ff; --cherry-secondary: #667eea; --cherry-gray-50: #f8f9fa; --cherry-gray-100: #f7fafc; --cherry-gray-200: #edf2f7; --cherry-gray-300: #e2e8f0; --cherry-gray-400: #cbd5e0; --cherry-gray-500: #a0aec0; --cherry-gray-600: #718096; --cherry-gray-700: #4a5568; --cherry-gray-800: #2d3748; --cherry-gray-900: #1a202c; } /* 滚动条美化 */ .sidebar-nav::-webkit-scrollbar, .content-body::-webkit-scrollbar { width: 6px; } .sidebar-nav::-webkit-scrollbar-track, .content-body::-webkit-scrollbar-track { background: transparent; } .sidebar-nav::-webkit-scrollbar-thumb, .content-body::-webkit-scrollbar-thumb { background: #cbd5e0; border-radius: 3px; } .sidebar-nav::-webkit-scrollbar-thumb:hover, .content-body::-webkit-scrollbar-thumb:hover { background: #a0aec0; } /* 美化文件上传区域 */ .file-upload-area { position: relative; border: 2px dashed var(--primary-color, #8b5cf6) !important; border-radius: 8px !important; padding: 2rem; text-align: center; background: linear-gradient(145deg, rgba(139, 92, 246, 0.05) 0%, rgba(59, 130, 246, 0.05) 100%) !important; transition: all 0.25s ease !important; cursor: pointer; /* 🎯 修复:确保上传区域不超出容器 */ max-width: 100%; box-sizing: border-box; } .file-upload-area:hover { background: linear-gradient(145deg, rgba(139, 92, 246, 0.10) 0%, rgba(59, 130, 246, 0.10) 100%) !important; box-shadow: 0 8px 20px rgba(139, 92, 246, 0.15) !important; transform: translateY(-2px) !important; border-color: var(--primary-color, #7c3aed) !important; } .file-upload-area.drag-over { background: linear-gradient(145deg, rgba(139, 92, 246, 0.12) 0%, rgba(59, 130, 246, 0.12) 100%) !important; border-color: var(--primary-color, #7c3aed) !important; animation: pulseBorder 1.2s infinite ease-in-out !important; } @keyframes pulseBorder { 0% { box-shadow: 0 0 0 0 rgba(139, 92, 246, 0.4); } 70% { box-shadow: 0 0 0 6px rgba(139, 92, 246, 0); } 100% { box-shadow: 0 0 0 0 rgba(139, 92, 246, 0); } } .upload-content { display: flex; flex-direction: column; align-items: center; gap: 0.75rem; /* 🎯 修复:确保上传内容不超出容器 */ max-width: 100%; box-sizing: border-box; } .upload-icon { font-size: 2.5rem !important; color: var(--primary-color, #6d28d9) !important; } .upload-text { font-size: 0.95rem !important; color: #4b5563 !important; } .file-input { position: absolute; top: 0; left: 0; width: 100%; height: 100%; opacity: 0; cursor: pointer; } .image-preview { display: grid; grid-template-columns: repeat(auto-fill, minmax(120px, 1fr)); gap: 0.75rem; margin-top: 1rem; padding: 1rem; background: #ffffff; border-radius: 8px; border: 1px solid #e2e8f0; } /* 新的图片画廊样式 */ .image-gallery { margin-top: 1rem; } .image-list { display: flex; gap: 1rem; overflow-x: auto; padding: 1rem; background: #ffffff; border-radius: 12px; border: 1px solid #e2e8f0; scroll-behavior: smooth; } .image-list::-webkit-scrollbar { height: 6px; } .image-list::-webkit-scrollbar-track { background: #f1f1f1; border-radius: 3px; } .image-list::-webkit-scrollbar-thumb { background: #cbd5e0; border-radius: 3px; } .image-list::-webkit-scrollbar-thumb:hover { background: #a0aec0; } .image-item { position: relative; flex-shrink: 0; width: 120px; height: 120px; border-radius: 8px; overflow: hidden; border: 2px solid #e2e8f0; transition: all 0.2s ease; } .image-item:hover { border-color: #667eea; transform: translateY(-2px); box-shadow: 0 4px 12px rgba(102, 126, 234, 0.2); } .gallery-image { width: 100%; height: 100%; object-fit: cover; cursor: pointer; transition: transform 0.2s ease; } .gallery-image:hover { transform: scale(1.05); } .remove-image { position: absolute; top: 4px; right: 4px; width: 24px; height: 24px; border: none; border-radius: 50%; background: rgba(239, 68, 68, 0.9); color: white; font-size: 16px; font-weight: bold; cursor: pointer; display: flex; align-items: center; justify-content: center; transition: all 0.2s ease; backdrop-filter: blur(4px); } .remove-image:hover { background: rgba(239, 68, 68, 1); transform: scale(1.1); } .add-image-btn { flex-shrink: 0; width: 120px; height: 120px; border: 2px dashed #cbd5e0; border-radius: 8px; display: flex; align-items: center; justify-content: center; cursor: pointer; transition: all 0.2s ease; position: relative; background: #f8f9fa; } .add-image-btn:hover { border-color: #667eea; background: #f0f8ff; transform: translateY(-2px); } .add-content { display: flex; flex-direction: column; align-items: center; gap: 0.5rem; color: #718096; } .add-icon { font-size: 2rem; font-weight: 300; } .add-text { font-size: 0.875rem; font-weight: 500; } .preview-image { width: 100%; height: 100px; object-fit: cover; border-radius: 6px; border: 1px solid #e2e8f0; transition: transform 0.2s ease; } .preview-image:hover { transform: scale(1.05); } /* 图片错误显示优化 */ .image-error { display: flex; flex-direction: column; align-items: center; justify-content: center; min-height: 120px; background: #f8f9fa; border: 2px dashed #cbd5e0; border-radius: 8px; padding: 1rem; text-align: center; color: #6c757d; font-size: 0.9rem; } .error-path { margin-top: 0.5rem; font-size: 0.75rem; color: #a0aec0; word-break: break-all; max-width: 100%; } /* 🎯 现代化简约按钮样式 */ .btn { display: inline-flex; align-items: center; justify-content: center; padding: 0.625rem 1.25rem; font-size: 0.875rem; font-weight: 500; border-radius: 8px; border: 1px solid transparent; cursor: pointer; transition: all 0.15s ease; text-decoration: none; gap: 0.5rem; background: #ffffff; position: relative; overflow: hidden; } .btn:disabled { opacity: 0.5; cursor: not-allowed; transform: none !important; } .btn-primary { background: #f8fafc; color: #1e293b; border-color: #e2e8f0; box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05); } .btn-primary:hover:not(:disabled) { background: #f1f5f9; border-color: #cbd5e1; box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1); } .btn-success { background: #f0fdf4; color: #166534; border-color: #bbf7d0; box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05); } .btn-success:hover:not(:disabled) { background: #dcfce7; border-color: #86efac; box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1); } .btn-secondary { background: #f8fafc; color: #64748b; border-color: #e2e8f0; box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05); } .btn-secondary:hover:not(:disabled) { background: #f1f5f9; border-color: #cbd5e1; color: #475569; box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1); } .btn-danger { background: #fef2f2; color: #dc2626; border-color: #fecaca; box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05); } .btn-danger:hover:not(:disabled) { background: #fee2e2; border-color: #fca5a5; box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1); } /* 标签页按钮美化 */ .tab { padding: 0.75rem 1.5rem; background: #f7fafc; color: #4a5568; border: 1px solid #e2e8f0; border-radius: 8px 8px 0 0; cursor: pointer; font-weight: 500; transition: all 0.2s ease; border-bottom: none; } .tab:hover { background: #edf2f7; color: #2d3748; } .tab.active { background: #ffffff; color: #3182ce; border-color: #3182ce; border-bottom: 2px solid #3182ce; font-weight: 600; } /* 返回按钮美化 */ .back-button { display: inline-flex; align-items: center; gap: 0.5rem; padding: 0.5rem 1rem; background: #f7fafc; color: #4a5568; border: 1px solid #e2e8f0; border-radius: 6px; cursor: pointer; font-size: 0.9rem; font-weight: 500; transition: all 0.2s ease; text-decoration: none; } .back-button:hover { background: #edf2f7; color: #2d3748; border-color: #cbd5e0; transform: translateX(-2px); } /* 多图片网格显示样式 */ .image-grid-container { margin-top: 0.75rem; border: 1px solid #e2e8f0; border-radius: 8px; background: #f8f9fa; padding: 0.75rem; /* 🎯 修复:确保图片网格容器不超出父容器 */ max-width: 100%; box-sizing: border-box; overflow: hidden; } .image-grid-scroll { display: flex; gap: 0.75rem; overflow-x: auto; overflow-y: hidden; padding: 0.25rem; scroll-behavior: smooth; /* 🎯 修复:确保水平滚动正常工作 */ width: 100%; min-width: 0; } .image-grid-scroll::-webkit-scrollbar { height: 6px; } .image-grid-scroll::-webkit-scrollbar-track { background: #f1f1f1; border-radius: 3px; } .image-grid-scroll::-webkit-scrollbar-thumb { background: #c1c1c1; border-radius: 3px; } .image-grid-scroll::-webkit-scrollbar-thumb:hover { background: #a1a1a1; } .image-thumbnail-container { position: relative; flex-shrink: 0; width: 120px; height: 120px; border-radius: 10px !important; overflow: hidden !important; background: white; cursor: pointer; transition: all 0.2s ease; } .image-thumbnail-container:hover { border-color: #4299e1; transform: translateY(-2px); box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1); } .image-thumbnail { width: 100%; height: 100%; object-fit: cover; transition: transform 0.2s ease; } .image-thumbnail-container:hover .image-thumbnail { transform: scale(1.05) !important; } .remove-image-btn { position: absolute; top: 4px; right: 4px; width: 24px; height: 24px; border: none; background: rgba(239, 68, 68, 0.9); color: white; border-radius: 50%; cursor: pointer; display: flex; align-items: center; justify-content: center; font-size: 12px; font-weight: bold; transition: all 0.2s ease; opacity: 0; } .image-thumbnail-container:hover .remove-image-btn { opacity: 1; } .remove-image-btn:hover { background: rgba(220, 38, 38, 1); transform: scale(1.1); } .add-image-placeholder { flex-shrink: 0; width: 120px; height: 120px; border: 2px dashed #cbd5e0; border-radius: 8px; display: flex; flex-direction: column; align-items: center; justify-content: center; cursor: pointer; transition: all 0.2s ease; background: #f8f9fa; } .add-image-placeholder:hover { border-color: #4299e1; background: #f0f8ff; } .add-image-input { display: none; } .add-image-label { display: flex; flex-direction: column; align-items: center; justify-content: center; width: 100%; height: 100%; cursor: pointer; color: #718096; transition: color 0.2s ease; } .add-image-placeholder:hover .add-image-label { color: #4299e1; } .add-image-icon { font-size: 24px; margin-bottom: 4px; } .add-image-text { font-size: 12px; font-weight: 500; text-align: center; } /* 拖拽状态样式 */ .file-upload-area.drag-over { border-color: #4299e1; background: #f0f8ff; transform: scale(1.02); } .file-upload-area.drag-over .upload-icon { transform: scale(1.1); color: #4299e1; } .file-upload-area.drag-over .upload-text { color: #4299e1; font-weight: 600; } .image-grid-container.drag-over { border-color: #4299e1; background: #f0f8ff; transform: scale(1.01); box-shadow: 0 0 10px rgba(66, 153, 225, 0.3); } /* Cherry Studio 风格的现代化 Tooltip */ /* 自定义 tooltip 容器 */ .tooltip-container { position: relative; display: inline-block; } /* 已禁用 - 这些选择器被替换为tooltip-test */ /* 已禁用 - 旧的tooltip-container选择器 .tooltip-container[data-tooltip]:not([data-tooltip=""])::before { content: attr(data-tooltip); position: absolute; bottom: calc(100% + 8px); left: 50%; background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; padding: 8px 12px; border-radius: 12px; font-size: 13px; font-weight: 500; line-height: 1.4; white-space: nowrap; z-index: 1000; box-shadow: 0 8px 32px rgba(102, 126, 234, 0.25), 0 4px 16px rgba(0, 0, 0, 0.1), inset 0 1px 0 rgba(255, 255, 255, 0.2); backdrop-filter: blur(10px); border: 1px solid rgba(255, 255, 255, 0.1); letter-spacing: 0.025em; } 已禁用 */ /* 已禁用 - 继续注释旧代码 .tooltip-container[data-tooltip]:not([data-tooltip=""])::after { content: ''; position: absolute; bottom: calc(100% + 2px); left: 50%; width: 0; height: 0; border: 6px solid transparent; border-top: 6px solid #667eea; z-index: 999; filter: drop-shadow(0 2px 4px rgba(0, 0, 0, 0.1)); } 已禁用 */ /* 已禁用 - 全部旧tooltip代码开始 .tooltip-container[data-tooltip]:not([data-tooltip=""]):hover::before, .tooltip-container[data-tooltip]:not([data-tooltip=""]):hover::after { opacity: 1; transform: translate(-50%, 0) scale(1); } /* 不同位置的 tooltip */ .tooltip-container.tooltip-right[data-tooltip]:not([data-tooltip=""])::before { bottom: auto; top: 50%; left: calc(100% + 8px); transform: translate(0, -50%) scale(0.8); transform-origin: left center; } .tooltip-container.tooltip-right[data-tooltip]:not([data-tooltip=""])::after { bottom: auto; top: 50%; left: calc(100% + 2px); border: 6px solid transparent; border-right: 6px solid #667eea; border-top: 6px solid transparent; transform: translate(0, -50%) scale(0.8); transform-origin: left center; } .tooltip-container.tooltip-right[data-tooltip]:not([data-tooltip=""]):hover::before, .tooltip-container.tooltip-right[data-tooltip]:not([data-tooltip=""]):hover::after { opacity: 1; transform: translate(0, -50%) scale(1); } .tooltip-container.tooltip-left[data-tooltip]:not([data-tooltip=""])::before { bottom: auto; top: 50%; left: auto; right: calc(100% + 8px); transform: translate(0, -50%) scale(0.8); transform-origin: right center; } .tooltip-container.tooltip-left[data-tooltip]:not([data-tooltip=""])::after { bottom: auto; top: 50%; left: auto; right: calc(100% + 2px); border: 6px solid transparent; border-left: 6px solid #667eea; border-top: 6px solid transparent; transform: translate(0, -50%) scale(0.8); transform-origin: right center; } .tooltip-container.tooltip-left[data-tooltip]:not([data-tooltip=""]):hover::before, .tooltip-container.tooltip-left[data-tooltip]:not([data-tooltip=""]):hover::after { opacity: 1; transform: translate(0, -50%) scale(1); } .tooltip-container.tooltip-bottom[data-tooltip]:not([data-tooltip=""])::before { bottom: auto; top: calc(100% + 8px); left: 50%; transform: translate(-50%, 0) scale(0.8); transform-origin: bottom center; } .tooltip-container.tooltip-bottom[data-tooltip]:not([data-tooltip=""])::after { bottom: auto; top: calc(100% + 2px); left: 50%; border: 6px solid transparent; border-bottom: 6px solid #667eea; border-top: 6px solid transparent; transform: translate(-50%, 0) scale(0.8); transform-origin: bottom center; } .tooltip-container.tooltip-bottom[data-tooltip]:not([data-tooltip=""]):hover::before, .tooltip-container.tooltip-bottom[data-tooltip]:not([data-tooltip=""]):hover::after { opacity: 1; transform: translate(-50%, 0) scale(1); } /* 特殊主题的 tooltip */ .tooltip-container.tooltip-success[data-tooltip]:not([data-tooltip=""])::before { background: linear-gradient(135deg, #4ecdc4 0%, #44a08d 100%); } .tooltip-container.tooltip-success[data-tooltip]:not([data-tooltip=""])::after { border-top-color: #4ecdc4; } .tooltip-container.tooltip-warning[data-tooltip]:not([data-tooltip=""])::before { background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%); } .tooltip-container.tooltip-warning[data-tooltip]:not([data-tooltip=""])::after { border-top-color: #f093fb; } .tooltip-container.tooltip-info[data-tooltip]:not([data-tooltip=""])::before { background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%); } .tooltip-container.tooltip-info[data-tooltip]:not([data-tooltip=""])::after { border-top-color: #4facfe; } /* 动画关键帧 */ @keyframes tooltipFadeIn { 0% { opacity: 0; transform: translate(-50%, 8px) scale(0.8); } 100% { opacity: 1; transform: translate(-50%, 0) scale(1); } } /* 响应式调整 */ @media (max-width: 768px) { .tooltip-container[data-tooltip]:not([data-tooltip=""])::before { font-size: 12px; padding: 6px 10px; border-radius: 10px; } .tooltip-container[data-tooltip]:not([data-tooltip=""])::after { border-width: 5px; } } */ /* 简化的tooltip功能 - 为侧边栏导航设计 */ .tooltip-test { position: relative !important; display: block !important; } /* 清理所有不需要的伪元素 */ .tooltip-test:not(:hover)::before, .tooltip-test:not(:hover)::after { display: none !important; content: none !important; opacity: 0 !important; visibility: hidden !important; } /* 清理空的data-tooltip的伪元素 */ .tooltip-test[data-tooltip=""]::before, .tooltip-test[data-tooltip=""]::after, .tooltip-test:not([data-tooltip])::before, .tooltip-test:not([data-tooltip])::after { display: none !important; content: none !important; opacity: 0 !important; visibility: hidden !important; } /* 默认tooltip (上方显示) - 动画优化 */ .tooltip-test[data-tooltip]:not([data-tooltip=""]):hover::before { content: attr(data-tooltip) !important; position: absolute !important; bottom: calc(100% + 10px) !important; left: 50% !important; transform: translateX(-50%) scale(1) !important; background: linear-gradient(135deg, #667eea 0%, #764ba2 100%) !important; color: white !important; padding: 8px 12px !important; border-radius: 12px !important; font-size: 13px !important; font-weight: 500 !important; white-space: nowrap !important; z-index: 10000 !important; box-shadow: 0 8px 32px rgba(102, 126, 234, 0.25), 0 4px 16px rgba(0, 0, 0, 0.1), inset 0 1px 0 rgba(255, 255, 255, 0.2) !important; backdrop-filter: blur(10px) !important; border: 1px solid rgba(255, 255, 255, 0.1) !important; opacity: 1 !important; visibility: visible !important; pointer-events: none !important; animation: tooltipFadeIn 0.2s cubic-bezier(0.68, -0.55, 0.265, 1.55) !important; } .tooltip-test[data-tooltip]:not([data-tooltip=""]):hover::after { content: '' !important; position: absolute !important; bottom: calc(100% + 4px) !important; left: 50% !important; transform: translateX(-50%) scale(1) !important; border: 6px solid transparent !important; border-top: 6px solid #667eea !important; z-index: 9999 !important; opacity: 1 !important; visibility: visible !important; pointer-events: none !important; filter: drop-shadow(0 2px 4px rgba(0, 0, 0, 0.1)) !important; animation: tooltipFadeIn 0.2s cubic-bezier(0.68, -0.55, 0.265, 1.55) !important; } /* 侧边栏收起时的右侧tooltip - 相对于按钮定位 */ .app-sidebar.collapsed .tooltip-test[data-tooltip]:not([data-tooltip=""]):hover::before { content: attr(data-tooltip) !important; position: absolute !important; top: 50% !important; left: calc(100% + 12px) !important; bottom: auto !important; right: auto !important; transform: translateY(-50%) scale(1) !important; background: linear-gradient(135deg, #667eea 0%, #764ba2 100%) !important; color: white !important; padding: 6px 10px !important; border-radius: 8px !important; font-size: 12px !important; font-weight: 500 !important; white-space: nowrap !important; min-width: max-content !important; max-width: none !important; overflow: visible !important; z-index: 999999 !important; box-shadow: 0 4px 20px rgba(102, 126, 234, 0.3), 0 2px 8px rgba(0, 0, 0, 0.15) !important; backdrop-filter: blur(8px) !important; border: 1px solid rgba(255, 255, 255, 0.2) !important; opacity: 1 !important; visibility: visible !important; pointer-events: none !important; animation: tooltipFadeIn 0.15s cubic-bezier(0.68, -0.55, 0.265, 1.55) !important; } .app-sidebar.collapsed .tooltip-test[data-tooltip]:not([data-tooltip=""]):hover::after { content: '' !important; position: absolute !important; top: 50% !important; left: calc(100% + 6px) !important; bottom: auto !important; right: auto !important; transform: translateY(-50%) scale(1) !important; border: 5px solid transparent !important; border-right: 5px solid #667eea !important; border-left: none !important; border-top: 5px solid transparent !important; border-bottom: 5px solid transparent !important; z-index: 999998 !important; opacity: 1 !important; visibility: visible !important; pointer-events: none !important; filter: drop-shadow(0 1px 3px rgba(0, 0, 0, 0.1)) !important; animation: tooltipFadeIn 0.15s cubic-bezier(0.68, -0.55, 0.265, 1.55) !important; } /* 全局清理:防止不明黑框 - 排除窗口控制按钮 */ /* 清理所有可能的伪元素黑框 */ *:not(.tooltip-test):not(.window-controls):not(.window-button)::before, *:not(.tooltip-test):not(.window-controls):not(.window-button)::after { /* 确保非tooltip元素的伪元素不会意外显示 */ display: none !important; content: none !important; } /* 特别清理:确保没有遗留的tooltip相关伪元素 */ .tooltip-container:not(.tooltip-test)::before, .tooltip-container:not(.tooltip-test)::after { display: none !important; content: none !important; opacity: 0 !important; visibility: hidden !important; position: static !important; } /* 清理旧的tooltip-container样式 */ .tooltip-container:not(.tooltip-test) { position: static !important; } /* 清理任何可能的复杂选择器的伪元素 */ .tooltip-container.tooltip-right:not(.tooltip-test)::before, .tooltip-container.tooltip-right:not(.tooltip-test)::after, .tooltip-container.tooltip-left:not(.tooltip-test)::before, .tooltip-container.tooltip-left:not(.tooltip-test)::after, .tooltip-container.tooltip-bottom:not(.tooltip-test)::before, .tooltip-container.tooltip-bottom:not(.tooltip-test)::after, .tooltip-container.tooltip-success:not(.tooltip-test)::before, .tooltip-container.tooltip-success:not(.tooltip-test)::after, .tooltip-container.tooltip-warning:not(.tooltip-test)::before, .tooltip-container.tooltip-warning:not(.tooltip-test)::after, .tooltip-container.tooltip-info:not(.tooltip-test)::before, .tooltip-container.tooltip-info:not(.tooltip-test)::after { display: none !important; content: none !important; opacity: 0 !important; visibility: hidden !important; position: static !important; } /* 确保只有hover时才显示tooltip */ .tooltip-test:not(:hover)::before, .tooltip-test:not(:hover)::after { opacity: 0 !important; visibility: hidden !important; transform: scale(0) !important; display: none !important; } /* 精确清理:只针对可能出现问题的元素 */ /* 特别针对可能出现在底部的框 */ body::before, body::after, html::before, html::after, #root::before, #root::after, .app::before, .app::after, .app-body::before, .app-body::after { display: none !important; content: none !important; opacity: 0 !important; visibility: hidden !important; } /* ============================================================= ⚡ FINAL OVERRIDES – ensure new upload page style wins ============================================================= */ .upload-section { background: rgba(255, 255, 255, 0.72) !important; backdrop-filter: saturate(180%) blur(12px) !important; border: 1px solid rgba(255, 255, 255, 0.3) !important; } .upload-section h3 { font-size: 1.35rem !important; font-weight: 700 !important; } .file-upload-area { border: 2px dashed var(--primary-color, #8b5cf6) !important; background: linear-gradient(145deg, rgba(139, 92, 246, 0.05) 0%, rgba(59, 130, 246, 0.05) 100%) !important; transition: all 0.25s ease !important; } .file-upload-area:hover { background: linear-gradient(145deg, rgba(139, 92, 246, 0.10) 0%, rgba(59, 130, 246, 0.10) 100%) !important; box-shadow: 0 8px 20px rgba(139, 92, 246, 0.15) !important; transform: translateY(-2px) !important; border-color: var(--primary-color, #7c3aed) !important; } .file-upload-area.drag-over { background: linear-gradient(145deg, rgba(139, 92, 246, 0.12) 0%, rgba(59, 130, 246, 0.12) 100%) !important; border-color: var(--primary-color, #7c3aed) !important; animation: pulseBorder 1.2s infinite ease-in-out !important; } .upload-icon { font-size: 2.5rem !important; color: var(--primary-color, #6d28d9) !important; } .upload-text { font-size: 0.95rem !important; color: #4b5563 !important; } .image-thumbnail-container { border-radius: 10px !important; overflow: hidden !important; } .image-thumbnail-container:hover .image-thumbnail { transform: scale(1.05) !important; } .analyze-button, .save-button, .reset-button { border-radius: 10px !important; font-weight: 600 !important; transition: transform 0.15s ease, box-shadow 0.15s ease !important; } .analyze-button:hover:not(:disabled), .save-button:hover:not(:disabled), .reset-button:hover:not(:disabled) { transform: translateY(-2px) !important; box-shadow: 0 6px 16px rgba(0, 0, 0, 0.08) !important; } /* ============================================================= */ /* ============================================================= 🎛️ Modern Select (Subject Picker) – improved native look ============================================================= */ .form-group select { /* Remove default OS / browser styling */ appearance: none !important; -webkit-appearance: none !important; -moz-appearance: none !important; /* Modern colors */ background-color: #f9fafb !important; /* Custom arrow icon */ background-image: url("data:image/svg+xml,%3Csvg fill='none' stroke='%23667eea' stroke-width='2' viewBox='0 0 24 24' xmlns='http://www.w3.org/2000/svg'%3E%3Cpath d='M6 9l6 6 6-6'/%3E%3C/svg%3E") !important; background-repeat: no-repeat !important; background-position: right 1rem center !important; background-size: 1rem !important; padding-right: 3rem !important; /* space for arrow */ cursor: pointer !important; border: 2px solid #e2e8f0 !important; border-radius: 10px !important; font-weight: 500 !important; transition: all 0.2s ease !important; } /* Hover & focus states */ .form-group select:hover { border-color: #667eea !important; } .form-group select:focus { outline: none !important; border-color: #667eea !important; box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.15) !important; } /* Remove legacy IE arrow */ .form-group select::-ms-expand { display: none !important; } /* Disabled state keeping modern look */ .form-group select:disabled { background-color: #edf2f7 !important; cursor: not-allowed !important; opacity: 0.6 !important; } /* ============================================================= */
50,281
DeepStudent
css
zh
css
data
{"qsc_code_num_words": 7137, "qsc_code_num_chars": 50281.0, "qsc_code_mean_word_length": 4.67157069, "qsc_code_frac_words_unique": 0.10718789, "qsc_code_frac_chars_top_2grams": 0.00785819, "qsc_code_frac_chars_top_3grams": 0.00692841, "qsc_code_frac_chars_top_4grams": 0.00431901, "qsc_code_frac_chars_dupe_5grams": 0.62649591, "qsc_code_frac_chars_dupe_6grams": 0.53513692, "qsc_code_frac_chars_dupe_7grams": 0.49428631, "qsc_code_frac_chars_dupe_8grams": 0.42755166, "qsc_code_frac_chars_dupe_9grams": 0.38790078, "qsc_code_frac_chars_dupe_10grams": 0.3299841, "qsc_code_frac_chars_replacement_symbols": 0.0, "qsc_code_frac_chars_digital": 0.07564809, "qsc_code_frac_chars_whitespace": 0.16606671, "qsc_code_size_file_byte": 50281.0, "qsc_code_num_lines": 2271.0, "qsc_code_num_chars_line_max": 209.0, "qsc_code_num_chars_line_mean": 22.14046675, "qsc_code_frac_chars_alphabet": 0.71856145, "qsc_code_frac_chars_comments": 0.0, "qsc_code_cate_xml_start": 0.0, "qsc_code_frac_lines_dupe_lines": 0.51953908, "qsc_code_cate_autogen": 0.0, "qsc_code_frac_lines_long_string": 0.000501, "qsc_code_frac_chars_string_length": 0.00807462, "qsc_code_frac_chars_long_word_length": 0.00049721, "qsc_code_frac_lines_string_concat": 0.0, "qsc_code_cate_encoded_data": 0.0, "qsc_code_frac_chars_hex_words": 0.0, "qsc_code_frac_lines_prompt_comments": 0.0, "qsc_code_frac_lines_assert": 0.0}
0
{"qsc_code_frac_chars_replacement_symbols": 0, "qsc_code_num_words": 0, "qsc_code_num_chars": 1, "qsc_code_mean_word_length": 0, "qsc_code_frac_words_unique": 1, "qsc_code_frac_chars_top_2grams": 0, "qsc_code_frac_chars_top_3grams": 0, "qsc_code_frac_chars_top_4grams": 0, "qsc_code_frac_chars_dupe_5grams": 0, "qsc_code_frac_chars_dupe_6grams": 0, "qsc_code_frac_chars_dupe_7grams": 0, "qsc_code_frac_chars_dupe_8grams": 0, "qsc_code_frac_chars_dupe_9grams": 0, "qsc_code_frac_chars_dupe_10grams": 0, "qsc_code_frac_lines_dupe_lines": 0, "qsc_code_size_file_byte": 0, "qsc_code_num_lines": 0, "qsc_code_num_chars_line_max": 0, "qsc_code_num_chars_line_mean": 0, "qsc_code_frac_chars_alphabet": 0, "qsc_code_frac_chars_digital": 0, "qsc_code_frac_chars_whitespace": 0, "qsc_code_frac_chars_comments": 0, "qsc_code_cate_xml_start": 0, "qsc_code_cate_autogen": 0, "qsc_code_frac_chars_long_word_length": 0, "qsc_code_cate_encoded_data": 0, "qsc_code_frac_chars_hex_words": 0}
000haoji/deep-student
src/App.css
/* 全局样式 */ * { margin: 0; padding: 0; box-sizing: border-box; } /* 页面保活机制样式 - 确保隐藏的组件不影响布局 */ .page-container { width: 100%; } .page-container[style*="display: none"] { position: absolute; visibility: hidden; pointer-events: none; } /* 模态框样式 */ .modal-overlay { position: fixed; top: 0; left: 0; right: 0; bottom: 0; background-color: rgba(0, 0, 0, 0.5); display: flex; justify-content: center; align-items: center; z-index: 1000; } .modal-dialog { background: white; border-radius: 12px; box-shadow: 0 4px 20px rgba(0, 0, 0, 0.3); max-width: 90vw; max-height: 90vh; width: 90%; /* Use percentage for flexibility */ max-width: 800px; /* Keep a max-width for larger screens */ overflow: hidden; display: flex; flex-direction: column; } .modal-header { padding: 1.5rem; border-bottom: 1px solid #e0e0e0; display: flex; justify-content: space-between; align-items: center; background: #f8f9fa; } .modal-header h3 { margin: 0; font-size: 1.25rem; color: #333; } .modal-content { flex: 1; overflow-y: auto; padding: 1.5rem; } .modal-footer { padding: 1.5rem; border-top: 1px solid #e0e0e0; background: #f8f9fa; display: flex; justify-content: space-between; align-items: center; } .close-button { background: none; border: none; font-size: 1.5rem; cursor: pointer; color: #666; padding: 0.25rem 0.5rem; border-radius: 4px; transition: background-color 0.2s; } .close-button:hover { background-color: #e0e0e0; color: #333; } /* AI Chat Interface Styles */ .ai-chat-interface { display: flex; flex-direction: column; height: 100%; background: white; border-radius: 8px; box-shadow: 0 2px 8px rgba(0,0,0,0.1); overflow: hidden; } .chat-messages { flex: 1; overflow-y: auto; padding: 1rem; display: flex; flex-direction: column; gap: 1rem; max-height: 600px; } .message { display: flex; flex-direction: column; gap: 0.5rem; } .message.user { align-items: flex-end; background: none !important; } .message.assistant { align-items: flex-start; background: none !important; } .message-header { display: flex; align-items: center; gap: 0.5rem; font-size: 0.8rem; color: #666; } .message.user .message-header { flex-direction: row-reverse; } .role { font-weight: 600; color: #4a5568; } .timestamp { color: #a0aec0; } .message-content { max-width: 80%; padding: 0.75rem 1rem; border-radius: 12px; background: #f7fafc; border: 1px solid #e2e8f0; } .message.user .message-content { background: #f0f9ff; color: #0369a1; border-color: #e0f2fe; } .user-message { word-wrap: break-word; } .loading-indicator { display: flex; align-items: center; gap: 0.5rem; color: #666; font-style: italic; } .typing-dots { display: flex; gap: 4px; } .typing-dots span { width: 8px; height: 8px; border-radius: 50%; background: #4299e1; animation: typing 1.4s infinite ease-in-out; } .typing-dots span:nth-child(1) { animation-delay: -0.32s; } .typing-dots span:nth-child(2) { animation-delay: -0.16s; } @keyframes typing { 0%, 80%, 100% { transform: scale(0); opacity: 0.5; } 40% { transform: scale(1); opacity: 1; } } .error-message { padding: 1rem; background: #fed7d7; border: 1px solid #feb2b2; border-radius: 8px; margin: 0.5rem 0; } .error-content { display: flex; align-items: center; gap: 0.5rem; } .error-icon { font-size: 1.2rem; } .error-text { flex: 1; color: #c53030; font-weight: 500; } .retry-button { padding: 0.25rem 0.75rem; background: #e53e3e; color: white; border: none; border-radius: 4px; cursor: pointer; font-size: 0.8rem; transition: background-color 0.2s; } .retry-button:hover { background: #c53030; } .chat-input-form { border-top: 1px solid #e2e8f0; padding: 1rem; background: #f7fafc; } .input-container { display: flex; flex-direction: column; gap: 0.75rem; } .chat-input { width: 100%; padding: 0.75rem; border: 1px solid #cbd5e0; border-radius: 8px; font-family: inherit; font-size: 0.9rem; resize: vertical; min-height: 60px; transition: border-color 0.2s, box-shadow 0.2s; } .chat-input:focus { outline: none; border-color: #0369a1; box-shadow: 0 0 0 3px rgba(3, 105, 161, 0.1); } .chat-input:disabled { background: #edf2f7; cursor: not-allowed; } .input-actions { display: flex; gap: 0.5rem; justify-content: flex-end; } .send-button, .stop-button, .clear-button { padding: 0.5rem 1rem; border: 1px solid transparent; border-radius: 8px; font-weight: 500; cursor: pointer; transition: all 0.15s ease; font-size: 0.9rem; box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05); } .send-button { background: #eff6ff; color: #2563eb; border-color: #dbeafe; } .send-button:hover:not(:disabled) { background: #dbeafe; border-color: #93c5fd; box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1); } .send-button:disabled { background: #f8fafc; color: #94a3b8; border-color: #e2e8f0; cursor: not-allowed; opacity: 0.5; } .stop-button { background: #fef2f2; color: #dc2626; border-color: #fecaca; } .stop-button:hover { background: #fee2e2; border-color: #fca5a5; box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1); } .clear-button { background: #f8fafc; color: #64748b; border-color: #e2e8f0; } .clear-button:hover:not(:disabled) { background: #f1f5f9; border-color: #cbd5e1; color: #475569; box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1); } .clear-button:disabled { opacity: 0.5; cursor: not-allowed; } .chat-controls { display: flex; justify-content: space-between; align-items: center; padding: 0.75rem 1rem; background: #edf2f7; border-top: 1px solid #e2e8f0; font-size: 0.8rem; } .chain-of-thought-toggle { display: flex; align-items: center; gap: 0.5rem; cursor: pointer; color: #4a5568; } .chain-of-thought-toggle input[type="checkbox"] { margin: 0; transform: scale(1.1); } .chat-stats { display: flex; gap: 1rem; color: #718096; } .analyzing { color: #4299e1; font-weight: 500; } /* Analysis with AI SDK Styles */ .analysis-with-ai-sdk { padding: 1.5rem; max-width: 1200px; margin: 0 auto; } .analysis-header { text-align: center; margin-bottom: 2rem; padding-bottom: 1rem; border-bottom: 2px solid #e2e8f0; } .analysis-header h2 { color: #2d3748; font-size: 1.8rem; font-weight: 600; margin-bottom: 0.5rem; } .analysis-description { color: #718096; font-size: 1rem; } .analysis-content { display: flex; flex-direction: column; gap: 2rem; } .section-header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 1rem; } .section-header h3 { color: #2d3748; font-size: 1.2rem; font-weight: 600; } .select-image-button { padding: 0.5rem 1rem; background: #4299e1; color: white; border: none; border-radius: 6px; cursor: pointer; font-weight: 500; transition: background-color 0.2s; } .select-image-button:hover:not(:disabled) { background: #3182ce; } .select-image-button:disabled { background: #a0aec0; cursor: not-allowed; } .image-section, .input-section, .analysis-results, .chat-section { background: white; padding: 1.5rem; border-radius: 12px; box-shadow: 0 2px 8px rgba(0,0,0,0.1); border: 1px solid #e2e8f0; } .image-preview { margin-top: 1rem; } .analysis-image { max-width: 100%; max-height: 400px; border-radius: 8px; box-shadow: 0 4px 12px rgba(0,0,0,0.15); } .analysis-input { width: 100%; padding: 1rem; border: 1px solid #cbd5e0; border-radius: 8px; font-family: inherit; font-size: 1rem; resize: vertical; min-height: 120px; transition: border-color 0.2s, box-shadow 0.2s; } .analysis-input:focus { outline: none; border-color: #4299e1; box-shadow: 0 0 0 3px rgba(66, 153, 225, 0.1); } .analysis-input:disabled { background: #f7fafc; cursor: not-allowed; } .input-actions { display: flex; gap: 1rem; margin-top: 1rem; justify-content: flex-end; } .start-analysis-button { padding: 0.75rem 1.5rem; background: #48bb78; color: white; border: none; border-radius: 8px; font-weight: 600; font-size: 1rem; cursor: pointer; transition: all 0.2s; } .start-analysis-button:hover:not(:disabled) { background: #38a169; transform: translateY(-1px); } .start-analysis-button:disabled { background: #a0aec0; cursor: not-allowed; transform: none; } .error-display { background: #fed7d7; border: 1px solid #feb2b2; border-radius: 8px; padding: 1rem; display: flex; align-items: center; gap: 0.5rem; } .error-icon { font-size: 1.2rem; color: #e53e3e; } .error-message { color: #c53030; font-weight: 500; } .analysis-summary { display: flex; flex-direction: column; gap: 1rem; } .summary-item { display: flex; gap: 0.5rem; padding: 0.75rem; background: #f7fafc; border-radius: 6px; border-left: 4px solid #4299e1; } .summary-item strong { color: #2d3748; min-width: 80px; font-weight: 600; } .summary-item span { color: #4a5568; flex: 1; } .chat-hint { font-size: 0.8rem; color: #718096; font-style: italic; } .analysis-chat { margin-top: 1rem; height: 500px; } .instructions { background: #f0fff4; border: 1px solid #9ae6b4; border-radius: 12px; padding: 1.5rem; } .instructions h3 { color: #276749; margin-bottom: 1rem; font-size: 1.1rem; } .instructions ul { list-style: none; padding: 0; } .instructions li { color: #2f855a; margin-bottom: 0.5rem; padding-left: 1.5rem; position: relative; } .instructions li:before { content: "✓"; position: absolute; left: 0; color: #38a169; font-weight: bold; } /* 增强版流式聊天界面样式 */ .streaming-chat-interface { display: flex; flex-direction: column; height: 100%; background: linear-gradient(145deg, #ffffff, #f8fafc); border-radius: 16px; box-shadow: 0 4px 20px rgba(0,0,0,0.08), 0 1px 3px rgba(0,0,0,0.1), inset 0 1px 0 rgba(255,255,255,0.6); overflow: hidden; position: relative; transition: all 0.4s cubic-bezier(0.175, 0.885, 0.32, 1.275); border: 1px solid rgba(255,255,255,0.2); backdrop-filter: blur(10px); } .streaming-chat-interface::before { content: ''; position: absolute; top: 0; left: 0; right: 0; height: 3px; background: linear-gradient(90deg, #667eea, #764ba2, #667eea); background-size: 200% 100%; animation: shimmer 3s ease-in-out infinite; } @keyframes shimmer { 0%, 100% { background-position: 200% 0; } 50% { background-position: -200% 0; } } .streaming-chat-interface:hover { transform: translateY(-2px); box-shadow: 0 8px 30px rgba(0,0,0,0.12), 0 4px 8px rgba(0,0,0,0.08), inset 0 1px 0 rgba(255,255,255,0.8); } /* 全屏模式样式 */ .streaming-chat-interface.fullscreen { position: fixed; top: 0; left: 0; right: 0; bottom: 0; z-index: 1000; border-radius: 0; border: none; transform: none; background: linear-gradient(145deg, #f8fafc, #ffffff); box-shadow: none; transition: all 0.5s cubic-bezier(0.25, 0.1, 0.25, 1); overflow: hidden; } .streaming-chat-interface.fullscreen::before { height: 4px; background: linear-gradient(90deg, #667eea, #764ba2, #f093fb, #f5576c, #667eea); background-size: 300% 100%; animation: shimmer 2s ease-in-out infinite; } /* 全屏切换动画 */ .streaming-chat-interface.expanding { animation: expandToFullscreen 0.5s cubic-bezier(0.25, 0.1, 0.25, 1) forwards; } .streaming-chat-interface.collapsing { animation: collapseFromFullscreen 0.5s cubic-bezier(0.25, 0.1, 0.25, 1) forwards; } @keyframes expandToFullscreen { 0% { border-radius: 16px; transform: scale(1) translate(0, 0); } 50% { border-radius: 8px; transform: scale(1.02) translate(-1%, -1%); } 100% { border-radius: 0; transform: scale(1) translate(0, 0); position: fixed; top: 0; left: 0; right: 0; bottom: 0; z-index: 1000; } } @keyframes collapseFromFullscreen { 0% { border-radius: 0; transform: scale(1) translate(0, 0); } 50% { border-radius: 8px; transform: scale(0.98) translate(1%, 1%); } 100% { border-radius: 16px; transform: scale(1) translate(0, 0); } } .streaming-chat-interface .chat-messages { flex: 1; overflow-y: auto; padding: 1.5rem; display: flex; flex-direction: column; gap: 1.2rem; max-height: 500px; background: linear-gradient(to bottom, transparent, rgba(248,250,252,0.3)); position: relative; scroll-behavior: smooth; } .streaming-chat-interface.fullscreen .chat-messages { max-height: none; padding: 2rem 3rem; background: linear-gradient(135deg, #fafbfc 0%, #f0f4f8 100%); gap: 1.5rem; } .streaming-chat-interface .chat-messages::-webkit-scrollbar { width: 8px; } .streaming-chat-interface .chat-messages::-webkit-scrollbar-track { background: rgba(0,0,0,0.05); border-radius: 4px; } .streaming-chat-interface .chat-messages::-webkit-scrollbar-thumb { background: linear-gradient(45deg, #667eea, #764ba2); border-radius: 4px; transition: all 0.3s ease; } .streaming-chat-interface .chat-messages::-webkit-scrollbar-thumb:hover { background: linear-gradient(45deg, #5a6fd8, #6b46a3); transform: scale(1.1); } .message-wrapper { display: flex; flex-direction: column; gap: 0.5rem; } .message-wrapper.user { align-items: flex-end; } .message-wrapper.assistant { align-items: flex-start; } .message-wrapper .message-header { display: flex; align-items: center; gap: 0.5rem; font-size: 0.8rem; color: #666; } .message-wrapper.user .message-header { flex-direction: row-reverse; } .user-message-content { max-width: 75%; padding: 1rem 1.5rem; border-radius: 20px 20px 6px 20px; background: #f0f9ff; color: #0369a1; border: 1px solid #e0f2fe; word-wrap: break-word; box-shadow: 0 2px 4px rgba(3, 105, 161, 0.1); position: relative; transform: translateX(0); transition: all 0.3s ease; font-weight: 500; } .user-message-content:hover { transform: translateX(-2px); box-shadow: 0 4px 8px rgba(3, 105, 161, 0.15); border-color: #0369a1; } .streaming-chat-interface.fullscreen .user-message-content { max-width: 65%; padding: 1.2rem 2rem; font-size: 1.05rem; border-radius: 24px 24px 8px 24px; } .streaming-indicator { display: flex; align-items: center; gap: 1rem; padding: 1.2rem 1.5rem; background: linear-gradient(135deg, #f0f8ff, #e6f3ff); border: 1px solid rgba(66, 153, 225, 0.2); border-radius: 16px; margin: 0.8rem 0; box-shadow: 0 4px 12px rgba(66, 153, 225, 0.1); backdrop-filter: blur(10px); position: relative; overflow: hidden; } .streaming-indicator::before { content: ''; position: absolute; top: 0; left: -100%; width: 100%; height: 100%; background: linear-gradient(90deg, transparent, rgba(255,255,255,0.3), transparent); animation: loading-shine 2s infinite; } @keyframes loading-shine { 0% { left: -100%; } 100% { left: 100%; } } .streaming-chat-interface.fullscreen .streaming-indicator { padding: 1.5rem 2rem; margin: 1rem 0; border-radius: 20px; } .streaming-indicator .typing-dots { display: flex; gap: 4px; } .streaming-indicator .typing-dots span { width: 8px; height: 8px; border-radius: 50%; background: #4299e1; animation: typing 1.4s infinite ease-in-out; } .streaming-indicator .typing-dots span:nth-child(1) { animation-delay: -0.32s; } .streaming-indicator .typing-dots span:nth-child(2) { animation-delay: -0.16s; } .streaming-text { color: #2b6cb0; font-style: italic; font-weight: 500; } .streaming-chat-interface .chat-input-form { border-top: 1px solid rgba(226, 232, 240, 0.5); padding: 1.5rem; background: linear-gradient(135deg, #f7fafc, #ffffff); backdrop-filter: blur(10px); position: relative; } .streaming-chat-interface .chat-input-form::before { content: ''; position: absolute; top: 0; left: 0; right: 0; height: 1px; background: linear-gradient(90deg, transparent, #667eea, transparent); } .streaming-chat-interface.fullscreen .chat-input-form { padding: 2rem 3rem; background: linear-gradient(135deg, #ffffff, #f8fafc); border-top: 1px solid rgba(226, 232, 240, 0.6); box-shadow: 0 -4px 20px rgba(0,0,0,0.05); } .streaming-chat-interface .input-container { display: flex; flex-direction: column; gap: 0.75rem; } .streaming-chat-interface .chat-input { width: 100%; padding: 1rem 1.5rem; border: 2px solid transparent; background: linear-gradient(white, white) padding-box, linear-gradient(135deg, #667eea, #764ba2) border-box; border-radius: 16px; font-family: inherit; font-size: 1rem; resize: vertical; min-height: 70px; transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1); box-shadow: 0 4px 12px rgba(0,0,0,0.05); backdrop-filter: blur(10px); } .streaming-chat-interface .chat-input:focus { outline: none; background: linear-gradient(white, white) padding-box, linear-gradient(135deg, #667eea, #764ba2) border-box; box-shadow: 0 8px 24px rgba(102, 126, 234, 0.2), 0 4px 8px rgba(102, 126, 234, 0.1); transform: translateY(-1px); } .streaming-chat-interface.fullscreen .chat-input { padding: 1.2rem 2rem; font-size: 1.1rem; min-height: 80px; border-radius: 20px; } .streaming-chat-interface .chat-input:disabled { background: #edf2f7; cursor: not-allowed; opacity: 0.7; } .streaming-chat-interface .input-actions { display: flex; justify-content: flex-end; } .streaming-chat-interface .send-button { padding: 0.8rem 2rem; background: #f0f9ff; color: #0369a1; border: 1px solid #e0f2fe; border-radius: 12px; font-weight: 600; cursor: pointer; transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1); font-size: 1rem; box-shadow: 0 2px 4px rgba(3, 105, 161, 0.1); position: relative; overflow: hidden; } .streaming-chat-interface .send-button::before { content: ''; position: absolute; top: 0; left: -100%; width: 100%; height: 100%; background: linear-gradient(90deg, transparent, rgba(255,255,255,0.2), transparent); transition: left 0.5s; } .streaming-chat-interface .send-button:hover::before { left: 100%; } .streaming-chat-interface .send-button:hover:not(:disabled) { background: #e0f2fe; border-color: #0369a1; transform: translateY(-2px); box-shadow: 0 4px 8px rgba(3, 105, 161, 0.15); } .streaming-chat-interface.fullscreen .send-button { padding: 1rem 2.5rem; font-size: 1.1rem; border-radius: 16px; } .streaming-chat-interface .send-button:disabled { background: #f1f5f9; color: #94a3b8; border-color: #e2e8f0; cursor: not-allowed; box-shadow: none; } .chat-info { display: flex; justify-content: space-between; align-items: center; padding: 1rem 1.5rem; background: linear-gradient(135deg, #edf2f7, #f7fafc); border-top: 1px solid rgba(226, 232, 240, 0.5); font-size: 0.85rem; backdrop-filter: blur(10px); position: relative; } .chat-info::before { content: ''; position: absolute; top: 0; left: 0; right: 0; height: 1px; background: linear-gradient(90deg, transparent, rgba(102, 126, 234, 0.3), transparent); } .streaming-chat-interface.fullscreen .chat-info { padding: 1.2rem 3rem; font-size: 0.9rem; } .chat-stats { display: flex; gap: 1.5rem; color: #718096; font-weight: 500; } .chat-stats span { display: flex; align-items: center; gap: 0.5rem; padding: 0.4rem 0.8rem; background: rgba(255,255,255,0.7); border-radius: 8px; backdrop-filter: blur(5px); transition: all 0.3s ease; } .chat-stats span:hover { background: rgba(255,255,255,0.9); transform: translateY(-1px); } .streaming-status { color: #667eea; font-weight: 600; background: linear-gradient(135deg, rgba(102, 126, 234, 0.1), rgba(118, 75, 162, 0.1)); padding: 0.4rem 0.8rem; border-radius: 8px; backdrop-filter: blur(5px); animation: pulse 2s infinite; } @keyframes pulse { 0%, 100% { opacity: 1; } 50% { opacity: 0.7; } } .thinking-status { color: #9f7aea; font-weight: 600; background: linear-gradient(135deg, rgba(159, 122, 234, 0.1), rgba(147, 51, 234, 0.1)); padding: 0.4rem 0.8rem; border-radius: 8px; backdrop-filter: blur(5px); position: relative; } .thinking-status::before { content: '🧠'; margin-right: 0.5rem; animation: thinking 1.5s ease-in-out infinite; } @keyframes thinking { 0%, 100% { transform: scale(1); } 50% { transform: scale(1.1); } } /* 聊天工具栏样式 */ .chat-toolbar { display: flex; justify-content: space-between; align-items: center; padding: 1rem 1.5rem; background: linear-gradient(135deg, #ffffff, #f8fafc); border-bottom: 1px solid rgba(226, 232, 240, 0.6); backdrop-filter: blur(10px); position: relative; z-index: 10; } .chat-toolbar::after { content: ''; position: absolute; bottom: 0; left: 0; right: 0; height: 1px; background: linear-gradient(90deg, transparent, #667eea, transparent); } .streaming-chat-interface.fullscreen .chat-toolbar { padding: 1.5rem 3rem; background: linear-gradient(135deg, #f8fafc, #ffffff); box-shadow: 0 2px 10px rgba(0,0,0,0.05); } .toolbar-left { display: flex; align-items: center; gap: 1rem; } .chat-title { font-size: 1.1rem; font-weight: 600; color: #2d3748; background: linear-gradient(135deg, #667eea, #764ba2); -webkit-background-clip: text; -webkit-text-fill-color: transparent; background-clip: text; } .streaming-chat-interface.fullscreen .chat-title { font-size: 1.3rem; } .toolbar-right { display: flex; align-items: center; gap: 0.5rem; } .fullscreen-toggle-btn { padding: 0.6rem; background: linear-gradient(135deg, rgba(102, 126, 234, 0.1), rgba(118, 75, 162, 0.1)); border: 1px solid rgba(102, 126, 234, 0.2); border-radius: 10px; cursor: pointer; font-size: 1.2rem; color: #667eea; transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1); backdrop-filter: blur(5px); display: flex; align-items: center; justify-content: center; width: 40px; height: 40px; } .fullscreen-toggle-btn:hover:not(:disabled) { background: linear-gradient(135deg, rgba(102, 126, 234, 0.2), rgba(118, 75, 162, 0.2)); border-color: rgba(102, 126, 234, 0.4); transform: translateY(-1px) scale(1.05); box-shadow: 0 4px 12px rgba(102, 126, 234, 0.2); } .fullscreen-toggle-btn:disabled { opacity: 0.5; cursor: not-allowed; transform: none; } .streaming-chat-interface.fullscreen .fullscreen-toggle-btn { width: 44px; height: 44px; font-size: 1.3rem; } /* 聊天界面测试页面样式 */ .chat-interface-test { display: flex; flex-direction: column; height: 100%; background: linear-gradient(135deg, #f8fafc 0%, #e2e8f0 100%); overflow: hidden; } .test-header { background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; padding: 2rem; box-shadow: 0 4px 20px rgba(102, 126, 234, 0.3); } .test-header-content { display: flex; justify-content: space-between; align-items: center; max-width: 1200px; margin: 0 auto; } .test-title h2 { margin: 0 0 0.5rem 0; font-size: 2rem; font-weight: 700; } .test-description { margin: 0; opacity: 0.9; font-size: 1.1rem; } .back-button { padding: 0.75rem 1.5rem; background: rgba(255, 255, 255, 0.2); border: 1px solid rgba(255, 255, 255, 0.3); border-radius: 8px; color: white; cursor: pointer; font-weight: 500; transition: all 0.3s ease; backdrop-filter: blur(10px); } .back-button:hover { background: rgba(255, 255, 255, 0.3); transform: translateY(-1px); box-shadow: 0 4px 12px rgba(0, 0, 0, 0.2); } .test-content { flex: 1; padding: 2rem; overflow-y: auto; display: flex; flex-direction: column; gap: 2rem; max-width: 1200px; margin: 0 auto; width: 100%; } .feature-highlights { display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 1rem; margin-bottom: 1rem; } .feature-item { display: flex; align-items: center; gap: 0.75rem; padding: 1rem 1.5rem; background: white; border-radius: 12px; box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1); transition: all 0.3s ease; border: 1px solid rgba(102, 126, 234, 0.1); } .feature-item:hover { transform: translateY(-2px); box-shadow: 0 4px 16px rgba(102, 126, 234, 0.2); border-color: rgba(102, 126, 234, 0.3); } .feature-icon { font-size: 1.5rem; } .feature-text { font-weight: 500; color: #2d3748; } .chat-demo-container { flex: 1; min-height: 500px; background: white; border-radius: 16px; box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1); overflow: hidden; border: 1px solid rgba(102, 126, 234, 0.1); } .demo-chat { height: 100%; } .test-instructions { background: white; border-radius: 12px; padding: 1.5rem; box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1); border: 1px solid rgba(102, 126, 234, 0.1); } .test-instructions h3 { margin: 0 0 1rem 0; color: #2d3748; font-size: 1.2rem; } .instruction-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(250px, 1fr)); gap: 1rem; } .instruction-item { padding: 1rem; background: linear-gradient(135deg, #f8fafc, #edf2f7); border-radius: 8px; border: 1px solid rgba(226, 232, 240, 0.6); } .instruction-item strong { display: block; margin-bottom: 0.5rem; color: #667eea; font-size: 0.95rem; } .instruction-item p { margin: 0; color: #4a5568; font-size: 0.9rem; line-height: 1.4; } body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', sans-serif; background-color: #f5f5f5; color: #333; } .app { min-height: 100vh; display: flex; flex-direction: column; } .app-header { background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; padding: 1rem; text-align: center; box-shadow: 0 2px 10px rgba(0,0,0,0.1); } .app-header h1 { font-size: 1.5rem; font-weight: 600; } .keyboard-shortcuts-hint { margin-top: 0.5rem; font-size: 0.8rem; opacity: 0.8; } /* 导航栏样式 */ .app-nav { display: flex; background: white; border-bottom: 1px solid #e1e5e9; box-shadow: 0 2px 4px rgba(0,0,0,0.05); } .app-nav button { flex: 1; padding: 1rem; border: none; background: transparent; cursor: pointer; font-size: 1rem; transition: all 0.3s ease; border-bottom: 3px solid transparent; } .app-nav button:hover { background: #f8f9fa; } .app-nav button.active { background: #f8f9fa; border-bottom-color: #667eea; color: #667eea; font-weight: 600; } .data-management-button { background: #e8f5e8 !important; color: #28a745 !important; font-weight: 600; } .data-management-button:hover { background: #d4edda !important; } .app-main { flex: 1; padding: 1rem; max-width: 1200px; margin: 0 auto; width: 100%; } /* 左右分栏布局样式 (This is now primarily controlled by DeepStudent.css) */ .analysis-layout { display: flex; /* Changed to flex to match DeepStudent.css */ gap: 1.5rem; height: 100%; flex: 1; } /* 左侧上传栏 */ .left-panel { background: transparent; border-radius: 0; box-shadow: none; overflow-y: auto; max-width: 100%; box-sizing: border-box; padding: 24px; display: flex; flex-direction: column; justify-content: flex-start; align-items: stretch; } .upload-section { padding: 1.5rem; } .upload-section h3 { margin-bottom: 1.5rem; color: #333; font-size: 1.2rem; font-weight: 600; border-bottom: 2px solid #f0f0f0; padding-bottom: 0.5rem; } .action-buttons { margin-top: 1.5rem; padding-top: 1.5rem; border-top: 1px solid #e1e5e9; display: flex; flex-direction: column; gap: 0.75rem; } /* 右侧结果栏 */ .right-panel { background: white; border-radius: 24px; box-shadow: 0 4px 20px rgba(0,0,0,0.1); overflow: hidden; display: flex; flex-direction: column; } /* 空状态 */ .empty-result { display: flex; flex-direction: column; align-items: center; justify-content: center; height: 100%; color: #666; text-align: center; padding: 2rem; } .empty-icon { font-size: 4rem; margin-bottom: 1rem; opacity: 0.5; } .empty-logo { width: 64px; height: 64px; object-fit: contain; opacity: 0.6; border-radius: 12px; } .empty-result h3 { margin-bottom: 0.5rem; color: #333; } .empty-result p { opacity: 0.7; max-width: 300px; } /* 分析结果样式重构 */ .analysis-result { background: #ffffff; border-radius: 12px; border: 1px solid #e2e8f0; height: 100%; display: flex; flex-direction: column; box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05); overflow: hidden; } .result-header { padding: 1.5rem; background: #f8f9fa; border-bottom: 1px solid #e1e5e9; flex-shrink: 0; } .result-header h3 { color: #333; font-size: 1.2rem; margin: 0; } .result-info { padding: 1.5rem; border-bottom: 1px solid #e1e5e9; flex-shrink: 0; } .info-item { margin-bottom: 1rem; display: flex; flex-direction: column; gap: 0.5rem; } .info-item:last-child { margin-bottom: 0; } .info-item strong { color: #555; font-size: 0.9rem; text-transform: uppercase; letter-spacing: 0.5px; } .info-value { color: #333; font-weight: 500; } .tags { display: flex; flex-wrap: wrap; gap: 0.5rem; } .tag { background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; padding: 0.25rem 0.75rem; border-radius: 20px; font-size: 0.8rem; font-weight: 500; } .ocr-text { background: #f8f9fa; padding: 1rem; border-radius: 8px; border-left: 4px solid #667eea; font-family: 'Courier New', monospace; font-size: 0.9rem; line-height: 1.5; white-space: pre-wrap; max-height: 150px; overflow-y: auto; } /* Markdown渲染样式 */ .markdown-content { line-height: 1.2; color: #333; } .markdown-content .code-block { background: #f8f9fa; border: 1px solid #e9ecef; border-radius: 6px; padding: 1rem; margin: 0.5rem 0; overflow-x: auto; font-family: 'Courier New', Consolas, Monaco, monospace; font-size: 0.9rem; } .markdown-content .inline-code { background: #f1f3f4; padding: 0.2rem 0.4rem; border-radius: 3px; font-family: 'Courier New', Consolas, Monaco, monospace; font-size: 0.9em; color: #d63384; } .markdown-content .table-wrapper { overflow-x: auto; margin: 1rem 0; } .markdown-content .markdown-table { width: 100%; border-collapse: collapse; border: 1px solid #dee2e6; } .markdown-content .markdown-table th, .markdown-content .markdown-table td { padding: 0.75rem; text-align: left; border-bottom: 1px solid #dee2e6; } .markdown-content .markdown-table th { background-color: #f8f9fa; font-weight: 600; border-bottom: 2px solid #dee2e6; } .markdown-content .markdown-table tr:hover { background-color: #f8f9fa; } .markdown-content .markdown-link { color: #007bff; text-decoration: none; } .markdown-content .markdown-link:hover { text-decoration: underline; } .markdown-content .markdown-list { margin: 0.5rem 0; padding-left: 1.5rem; } .markdown-content .markdown-list li { margin: 0.25rem 0; } .markdown-content .markdown-blockquote { margin: 1rem 0; padding: 0.5rem 1rem; border-left: 4px solid #007bff; background: #f8f9fa; font-style: italic; } .markdown-content .markdown-h1, .markdown-content .markdown-h2, .markdown-content .markdown-h3, .markdown-content .markdown-h4, .markdown-content .markdown-h5, .markdown-content .markdown-h6 { margin: 1rem 0 0.5rem 0; color: #2c3e50; } .markdown-content .markdown-h1 { font-size: 1.5rem; } .markdown-content .markdown-h2 { font-size: 1.3rem; } .markdown-content .markdown-h3 { font-size: 1.1rem; } .markdown-content .markdown-h4 { font-size: 1rem; } .markdown-content .markdown-h5 { font-size: 0.9rem; } .markdown-content .markdown-h6 { font-size: 0.8rem; } .markdown-content p { margin: 0.3rem 0; } .markdown-content strong { font-weight: 600; color: #2c3e50; } .markdown-content em { font-style: italic; color: #6c757d; } /* 数学公式样式 */ .markdown-content .katex { font-size: 1em; } .markdown-content .katex-display { margin: 1rem 0; text-align: center; } /* 流式渲染样式 */ .streaming-markdown { position: relative; } .streaming-cursor { color: #007bff; font-weight: bold; opacity: 1; animation: blink 1s infinite; margin-left: 2px; } .partial-math-indicator { color: #ffc107; margin-left: 0.25rem; animation: pulse 1s infinite; font-size: 0.9em; } @keyframes blink { 0%, 50% { opacity: 1; } 51%, 100% { opacity: 0; } } @keyframes pulse { 0% { opacity: 0.6; } 50% { opacity: 1; } 100% { opacity: 0.6; } } .streaming-cursor.visible { opacity: 1; } /* 流式消息特殊样式 */ .message.streaming .message-content { border-left: 3px solid #007bff; background: linear-gradient(90deg, #f8f9fa 0%, #e3f2fd 100%); animation: streamingPulse 2s ease-in-out infinite; } @keyframes streamingPulse { 0%, 100% { background: linear-gradient(90deg, #f8f9fa 0%, #e3f2fd 100%); } 50% { background: linear-gradient(90deg, #e3f2fd 0%, #f8f9fa 100%); } } /* 聊天容器样式重构 */ .chat-container { flex: 1; display: flex; flex-direction: column; min-height: 0; } .chat-header { padding: 1rem 1.5rem; background: #f8f9fa; border-bottom: 1px solid #e1e5e9; flex-shrink: 0; display: flex; justify-content: space-between; align-items: center; } .chat-header h3, .chat-header h4 { margin: 0; color: #333; font-size: 1rem; } /* 聊天选项样式 */ .chat-options { padding: 1rem 1.5rem; background: #f8f9fa; border-bottom: 1px solid #e1e5e9; display: flex; gap: 2rem; flex-wrap: wrap; } .chat-options .form-group { margin-bottom: 0; } .chat-options label { font-size: 0.9rem; color: #555; cursor: pointer; user-select: none; } .chat-history { flex: 1; padding: 1rem; overflow-y: auto; min-height: 200px; max-height: none; } .message { margin-bottom: 1rem; display: flex; flex-direction: column; } .message.user { align-items: flex-end; } .message.assistant { align-items: flex-start; } .message-content { max-width: 85%; padding: 0.75rem 1rem; border-radius: 12px; line-height: 1.5; word-wrap: break-word; } .message.user .message-content { background: #f0f9ff; color: #0369a1; border: 1px solid #e0f2fe; border-bottom-right-radius: 4px; } .message.assistant .message-content { background: #f8f9fa; color: #333; border: 1px solid #e1e5e9; border-bottom-left-radius: 4px; } .message-time { font-size: 0.75rem; color: #666; margin-top: 0.25rem; padding: 0 0.5rem; } /* 打字动画 */ .typing-indicator { display: inline-flex; gap: 0.25rem; margin-right: 0.5rem; } .typing-indicator span { width: 6px; height: 6px; border-radius: 50%; background: #667eea; animation: typing 1.4s infinite ease-in-out; } .typing-indicator span:nth-child(1) { animation-delay: -0.32s; } .typing-indicator span:nth-child(2) { animation-delay: -0.16s; } @keyframes typing { 0%, 80%, 100% { transform: scale(0.8); opacity: 0.5; } 40% { transform: scale(1); opacity: 1; } } .chat-input { padding: 1rem 1.5rem; border-top: 1px solid #e1e5e9; background: white; display: flex; gap: 0.75rem; flex-shrink: 0; } .chat-input input { flex: 1; padding: 0.75rem; border: 2px solid #e1e5e9; border-radius: 25px; font-size: 0.9rem; outline: none; transition: border-color 0.3s ease; } .chat-input input:focus { border-color: #0369a1; box-shadow: 0 0 0 3px rgba(3, 105, 161, 0.1); } .send-button { padding: 0.75rem 1.25rem; background: #f0f9ff; color: #0369a1; border: 1px solid #e0f2fe; border-radius: 25px; font-size: 1rem; cursor: pointer; transition: all 0.3s ease; min-width: 60px; box-shadow: 0 2px 4px rgba(3, 105, 161, 0.1); } .send-button:hover:not(:disabled) { background: #e0f2fe; border-color: #0369a1; transform: translateY(-1px); box-shadow: 0 4px 8px rgba(3, 105, 161, 0.15); } .send-button:disabled { background: #f1f5f9; color: #94a3b8; border-color: #e2e8f0; cursor: not-allowed; transform: none; box-shadow: none; } /* 分析表单样式(保持向后兼容) */ .analysis-form { background: white; border-radius: 12px; padding: 2rem; box-shadow: 0 4px 20px rgba(0,0,0,0.1); } .form-group { margin-bottom: 1.5rem; } .form-group label { display: block; margin-bottom: 0.5rem; font-weight: 500; color: #555; } .form-group select, .form-group input, .form-group textarea { width: 100%; padding: 0.75rem; border: 2px solid #e1e5e9; border-radius: 8px; font-size: 1rem; transition: border-color 0.3s ease; } .form-group select:focus, .form-group input:focus, .form-group textarea:focus { outline: none; border-color: #667eea; } .form-group textarea { resize: vertical; min-height: 80px; } /* 图片预览 */ .image-preview { display: flex; flex-wrap: wrap; gap: 0.5rem; margin-top: 0.5rem; } .preview-image { width: 100px; height: 100px; object-fit: cover; border-radius: 8px; border: 2px solid #e1e5e9; } /* 按钮样式 */ .analyze-button { width: 100%; padding: 1rem; background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; border: none; border-radius: 8px; font-size: 1.1rem; font-weight: 600; cursor: pointer; transition: transform 0.2s ease, box-shadow 0.2s ease; } .analyze-button:hover:not(:disabled) { transform: translateY(-2px); box-shadow: 0 6px 20px rgba(102, 126, 234, 0.4); } .analyze-button:disabled { opacity: 0.6; cursor: not-allowed; } /* 分析结果样式 */ .analysis-result { background: #ffffff; border-radius: 12px; border: 1px solid #e2e8f0; height: 100%; display: flex; flex-direction: column; box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05); overflow: hidden; } .result-header { display: flex; justify-content: space-between; align-items: center; padding: 1.5rem; background: #f8f9fa; border-bottom: 1px solid #e1e5e9; } .result-header h2 { color: #333; font-size: 1.3rem; } .result-actions { display: flex; gap: 0.5rem; } .save-button { padding: 0.5rem 1rem; background: #f0f9ff; color: #0369a1; border: 1px solid #e2e8f0; border-radius: 6px; cursor: pointer; font-weight: 500; transition: all 0.15s ease; box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05); } .save-button:hover { background: #e0f2fe; border-color: #0369a1; box-shadow: 0 2px 4px rgba(3, 105, 161, 0.1); } .reset-button { padding: 0.5rem 1rem; background: #6c757d; color: white; border: none; border-radius: 6px; cursor: pointer; transition: background-color 0.3s ease; } .reset-button:hover { background: #5a6268; } .result-info { padding: 1.5rem; border-bottom: 1px solid #e1e5e9; } .info-item { margin-bottom: 1rem; } .info-item:last-child { margin-bottom: 0; } .info-item strong { color: #495057; } .ocr-text { margin-top: 0.5rem; padding: 1rem; background: #f8f9fa; border-radius: 6px; border-left: 4px solid #667eea; font-family: 'Courier New', monospace; white-space: pre-wrap; } /* 聊天容器 */ .chat-container { display: flex; flex-direction: column; flex: 1; min-height: 400px; max-height: calc(100vh - 300px); } /* 聊天容器全屏时移除高度限制 */ .chat-container.chat-fullscreen { min-height: unset; max-height: unset; } .chat-history { flex: 1; overflow-y: auto; padding: 1rem; display: flex; flex-direction: column; gap: 1rem; } .message { max-width: 80%; padding: 1rem; border-radius: 12px; position: relative; } .message.user { align-self: flex-end; background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; } .message.assistant { align-self: flex-start; background: #f8f9fa; border: 1px solid #e1e5e9; } .message-content { margin-bottom: 0.5rem; line-height: 1.5; } .message-time { font-size: 0.8rem; opacity: 0.7; } .chat-input { display: flex; padding: 1rem; border-top: 1px solid #e1e5e9; background: #f8f9fa; gap: 0.5rem; } .chat-input input { flex: 1; padding: 0.75rem; border: 2px solid #e1e5e9; border-radius: 8px; font-size: 1rem; } .chat-input input:focus { outline: none; border-color: #0369a1; box-shadow: 0 0 0 3px rgba(3, 105, 161, 0.1); } .chat-input button { padding: 0.75rem 1.5rem; background: #f0f9ff; color: #0369a1; border: 1px solid #e0f2fe; border-radius: 8px; cursor: pointer; font-weight: 500; transition: all 0.3s ease; box-shadow: 0 2px 4px rgba(3, 105, 161, 0.1); } .chat-input button:hover:not(:disabled) { background: #e0f2fe; border-color: #0369a1; box-shadow: 0 4px 8px rgba(3, 105, 161, 0.15); } .chat-input button:disabled { background: #f1f5f9; color: #94a3b8; border-color: #e2e8f0; cursor: not-allowed; box-shadow: none; } /* 错题库样式 */ .mistake-library { background: white; border-radius: 12px; display: flex; flex-direction: column; box-shadow: 0 4px 20px rgba(0,0,0,0.1); } .library-header { display: flex; align-items: center; gap: 1rem; padding: 1.5rem; background: #f8f9fa; border-bottom: 1px solid #e1e5e9; } .back-button { padding: 0.5rem 1rem; background: #6c757d; color: white; border: none; border-radius: 6px; cursor: pointer; transition: background-color 0.3s ease; } .back-button:hover { background: #5a6268; } .library-filters { display: flex; gap: 1rem; padding: 1rem 1.5rem; background: #f8f9fa; border-bottom: 1px solid #e1e5e9; } .filter-group { display: flex; flex-direction: column; gap: 0.5rem; } .filter-group label { font-size: 0.9rem; font-weight: 500; color: #555; } .filter-group select, .filter-group input { padding: 0.5rem; border: 1px solid #e1e5e9; border-radius: 6px; font-size: 0.9rem; } .library-content { padding: 1.5rem; flex: 1; overflow-y: auto; } .loading { text-align: center; padding: 2rem; color: #6c757d; } .empty-state { text-align: center; padding: 3rem; color: #6c757d; } .empty-state p { margin-bottom: 0.5rem; } .mistakes-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(300px, 1fr)); gap: 1rem; } .mistake-card { border: 1px solid #e1e5e9; border-radius: 8px; padding: 1rem; cursor: pointer; transition: all 0.3s ease; } .mistake-card:hover { border-color: #667eea; box-shadow: 0 4px 12px rgba(102, 126, 234, 0.15); transform: translateY(-2px); } .mistake-header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 0.5rem; } .subject-badge { background: #667eea; color: white; padding: 0.25rem 0.5rem; border-radius: 4px; font-size: 0.8rem; font-weight: 500; } .type-badge { background: #28a745; color: white; padding: 0.25rem 0.5rem; border-radius: 4px; font-size: 0.8rem; font-weight: 500; } .date { font-size: 0.8rem; color: #6c757d; } .date-info { font-size: 0.8rem; color: #6c757d; } .mistake-content h4 { margin-bottom: 0.5rem; color: #333; font-size: 1rem; } .ocr-preview { font-size: 0.9rem; color: #6c757d; line-height: 1.4; margin-bottom: 1rem; } .mistake-tags { display: flex; flex-wrap: wrap; gap: 0.25rem; margin-bottom: 1rem; } .tag { background: #e9ecef; color: #495057; padding: 0.2rem 0.5rem; border-radius: 4px; font-size: 0.8rem; } .tag-more { background: #6c757d; color: white; padding: 0.2rem 0.5rem; border-radius: 4px; font-size: 0.8rem; } .mistake-footer { display: flex; justify-content: space-between; align-items: center; font-size: 0.8rem; color: #6c757d; } /* 设置页面样式 */ .settings { background: white; border-radius: 12px; overflow: hidden; box-shadow: 0 4px 20px rgba(0,0,0,0.1); } .settings-header { display: flex; align-items: center; gap: 1rem; padding: 1.5rem; background: #f8f9fa; border-bottom: 1px solid #e1e5e9; } .settings-content { padding: 1.5rem; } .settings-section { margin-bottom: 2rem; } .settings-section:last-child { margin-bottom: 0; } .settings-section h3 { margin-bottom: 1rem; color: #333; font-size: 1.1rem; } .form-row { display: grid; grid-template-columns: 1fr 1fr; gap: 1rem; } .api-key-input { display: flex; gap: 0.5rem; } .api-key-input input { flex: 1; } .test-button { padding: 0.75rem 1rem; border: none; border-radius: 6px; cursor: pointer; font-weight: 500; transition: all 0.3s ease; white-space: nowrap; } .test-button { background: #6c757d; color: white; } .test-button.success { background: #28a745; color: white; } .test-button.error { background: #dc3545; color: white; } .test-button:hover:not(:disabled) { opacity: 0.9; } .test-button:disabled { opacity: 0.6; cursor: not-allowed; } .checkbox-label { display: flex; align-items: center; gap: 0.5rem; cursor: pointer; } .checkbox-label input[type="checkbox"] { width: auto; } .data-actions { display: flex; gap: 1rem; flex-wrap: wrap; } .primary-button { padding: 0.75rem 1.5rem; background: #f8fafc; color: #1e293b; border: 1px solid #e2e8f0; border-radius: 8px; cursor: pointer; font-weight: 500; transition: all 0.15s ease; box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05); } .primary-button:hover:not(:disabled) { background: #f1f5f9; border-color: #cbd5e1; box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1); } .primary-button:disabled { opacity: 0.5; cursor: not-allowed; } .secondary-button { padding: 0.75rem 1.5rem; background: #f8fafc; color: #64748b; border: 1px solid #e2e8f0; border-radius: 8px; cursor: pointer; font-weight: 500; transition: all 0.15s ease; box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05); } .secondary-button:hover { background: #f1f5f9; border-color: #cbd5e1; color: #475569; box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1); } .danger-button { padding: 0.75rem 1.5rem; background: #fef2f2; color: #dc2626; border: 1px solid #fecaca; border-radius: 8px; cursor: pointer; font-weight: 500; transition: all 0.15s ease; box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05); } .danger-button:hover { background: #fee2e2; border-color: #fca5a5; box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1); } .about-info p { margin-bottom: 0.5rem; color: #6c757d; } .settings-footer { display: flex; justify-content: space-between; padding: 1.5rem; background: #f8f9fa; border-top: 1px solid #e1e5e9; } /* 错题详情样式 */ .mistake-detail { background: white; border-radius: 12px; overflow: hidden; box-shadow: 0 4px 20px rgba(0,0,0,0.1); } .detail-header { display: flex; align-items: center; justify-content: space-between; padding: 1.5rem; background: #f8f9fa; border-bottom: 1px solid #e1e5e9; } .header-title { flex: 1; margin: 0 1rem; } .header-title h2 { margin: 0 0 0.5rem 0; color: #333; font-size: 1.3rem; } .header-meta { display: flex; gap: 1rem; align-items: center; } .header-actions { display: flex; gap: 0.5rem; } .edit-button { padding: 0.5rem 1rem; background: #fffbeb; color: #d97706; border: 1px solid #fed7aa; border-radius: 8px; cursor: pointer; font-weight: 500; transition: all 0.15s ease; box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05); } .edit-button:hover { background: #fef3c7; border-color: #fbbf24; box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1); } .delete-button { padding: 0.5rem 1rem; background: #fef2f2; color: #dc2626; border: 1px solid #fecaca; border-radius: 8px; cursor: pointer; font-weight: 500; transition: all 0.15s ease; box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05); } .delete-button:hover { background: #fee2e2; border-color: #fca5a5; box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1); } .cancel-button { padding: 0.5rem 1rem; background: #f8fafc; color: #64748b; border: 1px solid #e2e8f0; border-radius: 8px; cursor: pointer; font-weight: 500; transition: all 0.15s ease; box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05); } .cancel-button:hover { background: #f1f5f9; border-color: #cbd5e1; color: #475569; box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1); } .detail-content { display: grid; grid-template-columns: 1fr 1fr; gap: 2rem; padding: 1.5rem; min-height: calc(100vh - 250px); } /* 响应式设计 */ @media (max-width: 1400px) { .detail-content { grid-template-columns: 1fr 0.8fr; } } @media (max-width: 1200px) { .detail-content { grid-template-columns: 1fr; grid-template-rows: auto 1fr; } } @media (max-width: 768px) { .detail-content { padding: 1rem; gap: 1rem; } } .detail-main { display: flex; flex-direction: column; gap: 2rem; } .info-section { background: #f8f9fa; border-radius: 8px; padding: 1.5rem; } .info-section h3 { margin: 0 0 1rem 0; color: #333; font-size: 1.1rem; } .info-display .info-row { display: flex; align-items: flex-start; margin-bottom: 1rem; gap: 1rem; } .info-display .info-row:last-child { margin-bottom: 0; } .info-display .label { font-weight: 500; color: #555; min-width: 100px; } .info-display .value { color: #333; flex: 1; } .info-display .tags { display: flex; flex-wrap: wrap; gap: 0.25rem; } .edit-form .form-group { margin-bottom: 1rem; } .edit-form .form-group:last-child { margin-bottom: 0; } .edit-form label { display: block; margin-bottom: 0.5rem; font-weight: 500; color: #555; } .edit-form input, .edit-form select, .edit-form textarea { width: 100%; padding: 0.5rem; border: 1px solid #e1e5e9; border-radius: 6px; font-size: 0.9rem; } .ocr-section { background: #f8f9fa; border-radius: 8px; padding: 1.5rem; } .ocr-section h3 { margin: 0 0 1rem 0; color: #333; font-size: 1.1rem; } .images-section { background: #f8f9fa; border-radius: 8px; padding: 1.5rem; } .images-section h3 { margin: 0 0 1rem 0; color: #333; font-size: 1.1rem; } .image-group { margin-bottom: 1.5rem; } .image-group:last-child { margin-bottom: 0; } .image-group h4 { margin: 0 0 0.75rem 0; color: #555; font-size: 1rem; } .image-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(120px, 1fr)); gap: 1rem; } .image-thumbnail { position: relative; aspect-ratio: 1; border-radius: 8px; overflow: hidden; cursor: pointer; transition: transform 0.2s ease; } .image-thumbnail:hover { transform: scale(1.05); } .image-thumbnail img { width: 100%; height: 100%; object-fit: cover; } .image-overlay { position: absolute; top: 0; left: 0; right: 0; bottom: 0; background: rgba(0, 0, 0, 0.7); color: white; display: flex; align-items: center; justify-content: center; opacity: 0; transition: opacity 0.2s ease; font-size: 0.8rem; font-weight: 500; } .image-error { display: flex; flex-direction: column; align-items: center; justify-content: center; width: 100%; height: 100%; background: #f8f9fa; color: #6c757d; border: 2px dashed #dee2e6; border-radius: 4px; font-size: 0.8rem; text-align: center; padding: 1rem; } .error-path { font-size: 0.7rem; color: #adb5bd; margin-top: 0.5rem; word-break: break-all; max-width: 100%; } .images-loading { display: flex; align-items: center; justify-content: center; padding: 2rem; color: #6c757d; font-style: italic; } .image-thumbnail:hover .image-overlay { opacity: 1; } .chat-section { background: #f8f9fa; border-radius: 8px; overflow: hidden; display: flex; flex-direction: column; min-height: 500px; max-height: calc(100vh - 400px); } .chat-section h3 { margin: 0; padding: 1rem 1.5rem; background: #e9ecef; color: #333; font-size: 1.1rem; border-bottom: 1px solid #dee2e6; } .empty-chat { text-align: center; padding: 2rem; color: #6c757d; } .empty-chat p { margin-bottom: 0.5rem; } /* 公式测试组件样式 */ .formula-test { background: white; border-radius: 12px; overflow: hidden; box-shadow: 0 4px 20px rgba(0,0,0,0.1); } .test-header { display: flex; align-items: center; gap: 1rem; padding: 1.5rem; background: #f8f9fa; border-bottom: 1px solid #e1e5e9; } .test-header h2 { margin: 0; color: #333; } .test-header p { margin: 0; color: #666; font-size: 0.9rem; } .test-content { padding: 1.5rem; } .test-controls { margin-bottom: 2rem; } .test-controls h3 { margin: 0 0 1rem 0; color: #333; } .formula-buttons { display: flex; flex-wrap: wrap; gap: 0.5rem; margin-bottom: 1.5rem; } .formula-button { padding: 0.5rem 1rem; border: 1px solid #667eea; border-radius: 6px; background: white; color: #667eea; cursor: pointer; font-size: 0.9rem; transition: all 0.3s ease; } .formula-button:hover { background: #667eea; color: white; } .streaming-controls h4 { margin: 0 0 0.5rem 0; color: #555; font-size: 1rem; } .streaming-buttons { display: flex; flex-wrap: wrap; gap: 0.5rem; } .streaming-button { padding: 0.5rem 1rem; border: 1px solid #28a745; border-radius: 6px; background: white; color: #28a745; cursor: pointer; font-size: 0.9rem; transition: all 0.3s ease; } .streaming-button:hover:not(:disabled) { background: #28a745; color: white; } .streaming-button:disabled { opacity: 0.5; cursor: not-allowed; } .custom-input { margin-bottom: 2rem; padding: 1.5rem; background: #f8f9fa; border-radius: 8px; } .custom-input h3 { margin: 0 0 1rem 0; color: #333; } .test-textarea { width: 100%; padding: 0.75rem; border: 1px solid #e1e5e9; border-radius: 6px; font-family: 'Courier New', monospace; font-size: 0.9rem; resize: vertical; margin-bottom: 1rem; } .input-buttons { display: flex; gap: 0.5rem; } .test-results { display: grid; grid-template-columns: 1fr 1fr; gap: 2rem; margin-bottom: 2rem; } .result-section h3 { margin: 0 0 1rem 0; color: #333; display: flex; align-items: center; gap: 0.5rem; } .streaming-indicator { font-size: 0.8rem; color: #28a745; } .render-preview { min-height: 200px; padding: 1.5rem; border: 1px solid #e1e5e9; border-radius: 8px; background: white; } .render-preview.static { border-left: 4px solid #667eea; } .render-preview.streaming { border-left: 4px solid #28a745; } .placeholder { color: #6c757d; font-style: italic; text-align: center; padding: 2rem; } .usage-guide { padding: 1.5rem; background: #f8f9fa; border-radius: 8px; } .usage-guide h3 { margin: 0 0 1rem 0; color: #333; } .syntax-examples { display: grid; gap: 1rem; } .syntax-item { padding: 1rem; background: white; border-radius: 6px; border-left: 4px solid #ffc107; } .syntax-item strong { color: #333; font-size: 0.95rem; } .syntax-item code { background: #f1f3f4; padding: 0.2rem 0.4rem; border-radius: 3px; font-family: 'Courier New', monospace; font-size: 0.85rem; } .syntax-item .example { margin-top: 0.5rem; color: #666; font-size: 0.9rem; } @media (max-width: 1200px) { .test-results { grid-template-columns: 1fr; } } @media (max-width: 768px) { .formula-buttons, .streaming-buttons { flex-direction: column; } .test-results { gap: 1rem; } .input-buttons { flex-direction: column; } } /* 图片查看器样式 */ .image-viewer-overlay { position: fixed; top: 0; left: 0; right: 0; bottom: 0; background: rgba(0, 0, 0, 0.9); z-index: 1000; display: flex; align-items: center; justify-content: center; } .image-viewer-container { position: relative; width: 100%; height: 100%; display: flex; flex-direction: column; } .image-viewer-toolbar { position: absolute; top: 20px; left: 50%; transform: translateX(-50%); background: rgba(0, 0, 0, 0.8); border-radius: 8px; padding: 0.5rem 1rem; display: flex; align-items: center; gap: 1rem; z-index: 1001; } .toolbar-left, .toolbar-center, .toolbar-right { display: flex; align-items: center; gap: 0.5rem; } .image-counter { color: white; font-size: 0.9rem; font-weight: 500; } .toolbar-button { background: rgba(255, 255, 255, 0.2); color: white; border: none; border-radius: 4px; padding: 0.25rem 0.5rem; cursor: pointer; font-size: 0.8rem; transition: background-color 0.2s ease; } .toolbar-button:hover { background: rgba(255, 255, 255, 0.3); } .scale-indicator { color: white; font-size: 0.8rem; min-width: 40px; text-align: center; } .close-button { background: #fee2e2; color: #dc2626; border: 1px solid #fca5a5; border-radius: 4px; padding: 0.25rem 0.5rem; cursor: pointer; font-size: 0.9rem; font-weight: 500; transition: all 0.15s ease; box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05); } .close-button:hover { background: #fecaca; border-color: #dc2626; box-shadow: 0 2px 4px rgba(220, 38, 38, 0.1); } .image-viewer-content { flex: 1; display: flex; align-items: center; justify-content: center; overflow: hidden; } .viewer-image { max-width: 90%; max-height: 90%; object-fit: contain; transition: transform 0.1s ease; user-select: none; } .nav-button { position: absolute; top: 50%; transform: translateY(-50%); background: rgba(0, 0, 0, 0.7); color: white; border: none; border-radius: 50%; width: 50px; height: 50px; font-size: 1.5rem; cursor: pointer; transition: background-color 0.2s ease; z-index: 1001; } .nav-button:hover:not(:disabled) { background: rgba(0, 0, 0, 0.9); } .nav-button:disabled { opacity: 0.3; cursor: not-allowed; } .nav-prev { left: 20px; } .nav-next { right: 20px; } .image-viewer-thumbnails { position: absolute; bottom: 20px; left: 50%; transform: translateX(-50%); display: flex; gap: 0.5rem; background: rgba(0, 0, 0, 0.8); border-radius: 8px; padding: 0.5rem; z-index: 1001; } .thumbnail { width: 60px; height: 60px; border-radius: 4px; overflow: hidden; cursor: pointer; opacity: 0.6; transition: opacity 0.2s ease; border: 2px solid transparent; } .thumbnail:hover, .thumbnail.active { opacity: 1; border-color: white; } .thumbnail img { width: 100%; height: 100%; object-fit: cover; } .keyboard-hints { position: absolute; bottom: 20px; right: 20px; background: rgba(0, 0, 0, 0.8); border-radius: 8px; padding: 0.5rem; z-index: 1001; } .hint { color: white; font-size: 0.7rem; margin-bottom: 0.25rem; } .hint:last-child { margin-bottom: 0; } /* 模态框样式 */ .modal-overlay { position: fixed; top: 0; left: 0; right: 0; bottom: 0; background: rgba(0, 0, 0, 0.5); z-index: 1000; display: flex; align-items: center; justify-content: center; padding: 2rem; } .modal-container { background: white; border-radius: 12px; max-width: 800px; width: 100%; max-height: 90vh; overflow-y: auto; box-shadow: 0 10px 40px rgba(0, 0, 0, 0.3); } /* 数据导入导出样式 */ .data-import-export { display: flex; flex-direction: column; max-height: 90vh; } .modal-header { display: flex; justify-content: space-between; align-items: center; padding: 1.5rem; background: #f8f9fa; border-bottom: 1px solid #e1e5e9; } .modal-header h3 { margin: 0; color: #333; font-size: 1.3rem; } .modal-content { flex: 1; padding: 1.5rem; overflow-y: auto; } .section { margin-bottom: 2rem; padding: 1.5rem; background: #f8f9fa; border-radius: 8px; border: 1px solid #e1e5e9; } .section:last-child { margin-bottom: 0; } .section h4 { margin: 0 0 0.5rem 0; color: #333; font-size: 1.1rem; } .section p { margin: 0 0 1rem 0; color: #6c757d; font-size: 0.9rem; } .export-options, .import-options { margin-bottom: 1rem; } .format-selector { display: flex; align-items: center; gap: 0.5rem; margin-bottom: 0.5rem; } .format-selector label { font-weight: 500; color: #555; } .format-selector select { padding: 0.5rem; border: 1px solid #e1e5e9; border-radius: 6px; background: white; } .format-description { font-size: 0.8rem; color: #6c757d; font-style: italic; } .export-button, .import-button { padding: 0.75rem 1.5rem; background: #667eea; color: white; border: none; border-radius: 6px; cursor: pointer; font-weight: 500; transition: background-color 0.3s ease; } .export-button:hover:not(:disabled), .import-button:hover:not(:disabled) { background: #5a67d8; } .export-button:disabled, .import-button:disabled { opacity: 0.6; cursor: not-allowed; } .file-selector { margin-bottom: 1rem; } .file-selector input[type="file"] { display: none; } .file-label { display: inline-block; padding: 0.75rem 1rem; background: #e9ecef; color: #495057; border: 2px dashed #ced4da; border-radius: 6px; cursor: pointer; transition: all 0.3s ease; text-align: center; width: 100%; } .file-label:hover { background: #dee2e6; border-color: #adb5bd; } .file-info { background: #e8f5e8; border: 1px solid #c3e6cb; border-radius: 6px; padding: 0.75rem; margin-top: 0.5rem; } .file-info p { margin: 0.25rem 0; font-size: 0.8rem; color: #155724; } .data-stats { display: grid; grid-template-columns: repeat(auto-fit, minmax(150px, 1fr)); gap: 1rem; } .stat-item { display: flex; justify-content: space-between; align-items: center; padding: 0.75rem; background: white; border-radius: 6px; border: 1px solid #e1e5e9; } .stat-label { font-weight: 500; color: #555; } .stat-value { font-weight: 600; color: #333; font-size: 1.1rem; } .danger-section { background: #f8d7da !important; border-color: #f5c6cb !important; } .danger-section h4 { color: #721c24; } .danger-section p { color: #721c24; } .modal-footer { padding: 1.5rem; background: #f8f9fa; border-top: 1px solid #e1e5e9; } .tips h5 { margin: 0 0 0.5rem 0; color: #333; font-size: 1rem; } .tips ul { margin: 0; padding-left: 1.5rem; } .tips li { margin-bottom: 0.25rem; color: #6c757d; font-size: 0.9rem; } /* 批量分析样式 */ .batch-analysis { background: white; border-radius: 12px; overflow: hidden; box-shadow: 0 4px 20px rgba(0,0,0,0.1); height: 100%; display: flex; flex-direction: column; } .batch-header { display: flex; align-items: center; justify-content: space-between; padding: 1.5rem; background: #f8f9fa; border-bottom: 1px solid #e1e5e9; } .batch-actions { display: flex; gap: 0.5rem; } .add-button { padding: 0.5rem 1rem; background: #28a745; color: white; border: none; border-radius: 6px; cursor: pointer; font-weight: 500; transition: background-color 0.3s ease; } .add-button:hover { background: #218838; } .process-button { padding: 0.5rem 1rem; background: #667eea; color: white; border: none; border-radius: 6px; cursor: pointer; font-weight: 500; transition: background-color 0.3s ease; } .process-button:hover:not(:disabled) { background: #5a67d8; } .process-button:disabled { opacity: 0.6; cursor: not-allowed; } .progress-info { padding: 1rem 1.5rem; background: #e3f2fd; border-bottom: 1px solid #e1e5e9; } .progress-text { text-align: center; margin-bottom: 0.5rem; font-weight: 500; color: #1976d2; } .progress-bar { width: 100%; height: 8px; background: #e0e0e0; border-radius: 4px; overflow: hidden; } .progress-fill { height: 100%; background: linear-gradient(90deg, #667eea, #764ba2); transition: width 0.3s ease; } .batch-content { padding: 1.5rem; flex: 1; overflow-y: auto; min-height: 0; } .empty-batch { text-align: center; padding: 3rem; color: #6c757d; } .add-first-button { margin-top: 1rem; padding: 0.75rem 1.5rem; background: #667eea; color: white; border: none; border-radius: 8px; cursor: pointer; font-weight: 500; transition: background-color 0.3s ease; } .add-first-button:hover { background: #5a67d8; } .batch-summary { display: flex; gap: 2rem; margin-bottom: 2rem; padding: 1rem; background: #f8f9fa; border-radius: 8px; } .summary-item { display: flex; flex-direction: column; align-items: center; gap: 0.25rem; } .summary-item .label { font-size: 0.9rem; color: #6c757d; } .summary-item .value { font-size: 1.5rem; font-weight: 600; color: #333; } .tasks-list { display: flex; flex-direction: column; gap: 1rem; margin-bottom: 2rem; /* max-height: 60vh; Removed to allow tasks-list to grow within batch-content */ /* overflow-y: auto; Removed, batch-content will handle scrolling */ /* padding-right: 8px; Removed as tasks-list no longer has its own scrollbar */ } /* 自定义滚动条样式 */ .batch-content::-webkit-scrollbar { /* tasks-list scrollbar styles removed */ width: 8px; } .batch-content::-webkit-scrollbar-track { /* tasks-list scrollbar styles removed */ background: #f1f1f1; border-radius: 4px; } .batch-content::-webkit-scrollbar-thumb { /* tasks-list scrollbar styles removed */ background: #c1c1c1; border-radius: 4px; } .batch-content::-webkit-scrollbar-thumb:hover { /* tasks-list scrollbar styles removed */ background: #a8a8a8; } /* 批量任务详情模态框样式 */ .batch-task-detail { width: 90vw; max-width: 1000px; max-height: 90vh; display: flex; flex-direction: column; } .batch-task-detail .modal-body { flex: 1; overflow-y: auto; padding: 1.5rem; min-height: 0; } .batch-task-detail .modal-body::-webkit-scrollbar { width: 8px; } .batch-task-detail .modal-body::-webkit-scrollbar-track { background: #f1f1f1; border-radius: 4px; } .batch-task-detail .modal-body::-webkit-scrollbar-thumb { background: #c1c1c1; border-radius: 4px; } .batch-task-detail .modal-body::-webkit-scrollbar-thumb:hover { background: #a8a8a8; } /* 任务信息区块样式 */ .task-info-section { margin-bottom: 2rem; padding: 1rem; background: #f8f9fa; border-radius: 8px; } .info-row { display: flex; margin-bottom: 0.75rem; align-items: flex-start; } .info-row:last-child { margin-bottom: 0; } .info-label { min-width: 100px; font-weight: 600; color: #495057; margin-right: 1rem; } .info-value { flex: 1; color: #212529; word-break: break-word; } .ocr-result-section, .error-section, .chat-section { margin-top: 1.5rem; padding: 1rem; border: 1px solid #dee2e6; border-radius: 8px; } .ocr-result-section h4, .error-section h4, .chat-section h4 { margin: 0 0 1rem 0; color: #495057; } .error-section { background: #f8d7da; border-color: #f5c6cb; } .error-text { color: #721c24; font-weight: 500; } .chat-history { max-height: 400px; overflow-y: auto; margin-bottom: 1rem; padding-right: 8px; } .chat-history::-webkit-scrollbar { width: 6px; } .chat-history::-webkit-scrollbar-track { background: #f1f1f1; border-radius: 3px; } .chat-history::-webkit-scrollbar-thumb { background: #c1c1c1; border-radius: 3px; } .chat-history::-webkit-scrollbar-thumb:hover { background: #a8a8a8; } /* 批量分析详情页面模式样式 */ .batch-detail-page { height: 100%; display: flex; flex-direction: column; background: white; border-radius: 12px; overflow: hidden; box-shadow: 0 4px 20px rgba(0,0,0,0.1); } .detail-header { display: flex; align-items: center; justify-content: space-between; padding: 1.5rem; background: #f8f9fa; border-bottom: 1px solid #e1e5e9; } .detail-header h2 { margin: 0; color: #333; font-size: 1.25rem; } .detail-content { flex: 1; overflow: hidden; display: flex; flex-direction: column; } .batch-task-detail-page { height: 100%; display: flex; flex-direction: column; } .page-container { flex: 1; display: flex; flex-direction: column; overflow-y: auto; overflow-x: hidden; } .page-body { flex: 1; display: flex; flex-direction: column; overflow-y: auto; padding: 1.5rem; min-height: 0; } .page-body::-webkit-scrollbar { width: 8px; } .page-body::-webkit-scrollbar-track { background: #f1f1f1; border-radius: 4px; } .page-body::-webkit-scrollbar-thumb { background: #c1c1c1; border-radius: 4px; } .page-body::-webkit-scrollbar-thumb:hover { background: #a8a8a8; } .page-footer { padding: 1.5rem; border-top: 1px solid #e1e5e9; background: #f8f9fa; display: flex; justify-content: flex-end; } /* 简化的任务状态样式 */ .task-error-simple, .task-streaming-simple, .task-completed-simple { margin-top: 1rem; padding: 0.75rem; border-radius: 6px; font-size: 0.9rem; } .task-error-simple { background: #f8d7da; border: 1px solid #f5c6cb; color: #721c24; } .task-streaming-simple { background: #e3f2fd; border: 1px solid #bbdefb; color: #1976d2; } .task-completed-simple { background: #d4edda; border: 1px solid #c3e6cb; color: #155724; } .task-streaming-simple .streaming-indicator { display: flex; align-items: center; gap: 0.5rem; } .task-streaming-simple .spinner { animation: spin 1s linear infinite; } @keyframes spin { from { transform: rotate(0deg); } to { transform: rotate(360deg); } } /* 批量分析详情页面聊天样式 - 与App.tsx完全一致 */ .batch-detail-page .chat-container { background: white; border-radius: 12px; overflow: hidden; margin-top: 1.5rem; border: 1px solid #e1e5e9; } .batch-detail-page .chat-header { display: flex; align-items: center; justify-content: space-between; padding: 1rem 1.5rem; background: #f8f9fa; border-bottom: 1px solid #e1e5e9; } .batch-detail-page .chat-header h4 { margin: 0; font-size: 1.1rem; color: #333; } .batch-detail-page .chat-header-actions { display: flex; align-items: center; gap: 1rem; } .batch-detail-page .chain-indicator { font-size: 0.9rem; color: #667eea; font-weight: 500; } .batch-detail-page .chat-history { max-height: 500px; overflow-y: auto; padding: 1rem; min-height: 200px; } .batch-detail-page .chat-history::-webkit-scrollbar { width: 6px; } .batch-detail-page .chat-history::-webkit-scrollbar-track { background: #f1f1f1; border-radius: 3px; } .batch-detail-page .chat-history::-webkit-scrollbar-thumb { background: #c1c1c1; border-radius: 3px; } .batch-detail-page .chat-history::-webkit-scrollbar-thumb:hover { background: #a8a8a8; } .batch-detail-page .chat-input { padding: 1rem 1.5rem; background: #f8f9fa; border-top: 1px solid #e1e5e9; display: flex; gap: 0.5rem; align-items: center; } .batch-detail-page .chat-input input { flex: 1; padding: 0.75rem; border: 1px solid #ddd; border-radius: 8px; font-size: 0.9rem; outline: none; transition: border-color 0.2s; } .batch-detail-page .chat-input input:focus { border-color: #0369a1; box-shadow: 0 0 0 2px rgba(3, 105, 161, 0.1); } .batch-detail-page .send-button { padding: 0.75rem 1rem; background: #667eea; color: white; border: none; border-radius: 8px; cursor: pointer; font-weight: 500; transition: background-color 0.2s; min-width: 60px; } .batch-detail-page .send-button:hover:not(:disabled) { background: #5a67d8; } .batch-detail-page .send-button:disabled { opacity: 0.6; cursor: not-allowed; } .batch-detail-page .save-button-inline { padding: 0.75rem 1rem; background: #f0f9ff; color: #0369a1; border: 1px solid #e2e8f0; border-radius: 8px; cursor: pointer; font-weight: 500; transition: all 0.15s ease; margin-left: 0.5rem; white-space: nowrap; box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05); } .batch-detail-page .save-button-inline:hover:not(:disabled) { background: #e0f2fe; border-color: #0369a1; box-shadow: 0 2px 4px rgba(3, 105, 161, 0.1); } .batch-detail-page .save-button-inline:disabled { background: #f1f5f9; color: #94a3b8; border-color: #e2e8f0; cursor: not-allowed; box-shadow: none; } /* 消息气泡样式 */ .batch-detail-page .message { margin-bottom: 1rem; } .batch-detail-page .message.assistant { display: flex; justify-content: flex-start; } .batch-detail-page .message.user { display: flex; justify-content: flex-end; } .batch-detail-page .message-content { max-width: 80%; padding: 0.75rem 1rem; border-radius: 12px; word-wrap: break-word; } .batch-detail-page .message.assistant .message-content { background: #f1f3f4; color: #333; } .batch-detail-page .message.user .message-content { background: #667eea; color: white; } .batch-detail-page .message-content.typing { background: #f1f3f4; color: #666; font-style: italic; } .batch-detail-page .typing-indicator { display: inline-flex; align-items: center; gap: 2px; margin-right: 0.5rem; } .batch-detail-page .typing-indicator span { width: 4px; height: 4px; background: #666; border-radius: 50%; animation: typing 1.4s infinite ease-in-out; } .batch-detail-page .typing-indicator span:nth-child(1) { animation-delay: -0.32s; } .batch-detail-page .typing-indicator span:nth-child(2) { animation-delay: -0.16s; } @keyframes typing { 0%, 80%, 100% { transform: scale(0.8); opacity: 0.5; } 40% { transform: scale(1); opacity: 1; } } .task-card { border: 1px solid #e1e5e9; border-radius: 8px; overflow: hidden; transition: all 0.3s ease; } .task-card:hover { border-color: #667eea; box-shadow: 0 2px 8px rgba(102, 126, 234, 0.1); } .task-header { display: flex; align-items: center; justify-content: space-between; padding: 1rem; background: #f8f9fa; border-bottom: 1px solid #e1e5e9; } .task-number { font-weight: 600; color: #333; } .task-status { font-weight: 500; padding: 0.25rem 0.5rem; border-radius: 4px; font-size: 0.9rem; } .remove-button { padding: 0.25rem 0.5rem; background: #dc3545; color: white; border: none; border-radius: 4px; cursor: pointer; font-size: 0.9rem; transition: background-color 0.3s ease; } .remove-button:hover:not(:disabled) { background: #c82333; } .remove-button:disabled { opacity: 0.6; cursor: not-allowed; } .task-form { padding: 1rem; } .task-form .form-group { margin-bottom: 1rem; } .task-form .form-group:last-child { margin-bottom: 0; } .image-count { margin-top: 0.5rem; font-size: 0.9rem; color: #6c757d; font-style: italic; } .task-result { margin-top: 1rem; padding: 1rem; background: #e8f5e8; border-radius: 6px; border-left: 4px solid #28a745; } .task-result h4 { margin-bottom: 0.5rem; color: #155724; } .result-preview p { margin-bottom: 0.25rem; font-size: 0.9rem; color: #155724; } .task-error { margin-top: 1rem; padding: 1rem; background: #f8d7da; border-radius: 6px; border-left: 4px solid #dc3545; } .task-error p { margin: 0; color: #721c24; font-size: 0.9rem; } .batch-footer { display: flex; justify-content: space-between; padding: 1.5rem; background: #f8f9fa; border-top: 1px solid #e1e5e9; } .clear-button { padding: 0.75rem 1.5rem; background: #6c757d; color: white; border: none; border-radius: 6px; cursor: pointer; font-weight: 500; transition: background-color 0.3s ease; } .clear-button:hover { background: #5a6268; } .save-all-button { padding: 0.75rem 1.5rem; background: #28a745; color: white; border: none; border-radius: 6px; cursor: pointer; font-weight: 500; transition: background-color 0.3s ease; } .save-all-button:hover:not(:disabled) { background: #218838; } .save-all-button:disabled { opacity: 0.6; cursor: not-allowed; } /* 回顾分析样式 */ .review-analysis { padding: 20px; max-width: 1200px; margin: 0 auto; height: 100%; overflow-y: auto; display: flex; flex-direction: column; } .review-header { display: flex; align-items: center; justify-content: space-between; margin-bottom: 30px; padding-bottom: 15px; border-bottom: 2px solid #e9ecef; } .review-header h2 { margin: 0; color: #2c3e50; font-size: 1.8rem; } .reset-button { background: #6c757d; color: white; border: none; padding: 8px 16px; border-radius: 6px; cursor: pointer; font-size: 0.9rem; transition: background-color 0.2s; } .reset-button:hover { background: #5a6268; } /* 错题选择界面 */ .mistake-selection { display: flex; flex-direction: column; gap: 20px; flex: 1; overflow-y: auto; } .selection-controls { display: flex; justify-content: space-between; align-items: center; padding: 15px; background: #f8f9fa; border-radius: 8px; border: 1px solid #dee2e6; } .subject-selector { display: flex; align-items: center; gap: 10px; } .subject-selector label { font-weight: 600; color: #495057; } .subject-selector select { padding: 8px 12px; border: 1px solid #ced4da; border-radius: 4px; background: white; font-size: 1rem; } .selection-info { display: flex; align-items: center; gap: 15px; font-weight: 500; color: #6c757d; } .select-all-button { background: #007bff; color: white; border: none; padding: 6px 12px; border-radius: 4px; cursor: pointer; font-size: 0.9rem; transition: background-color 0.2s; } .select-all-button:hover { background: #0056b3; } /* 错题网格 */ .mistakes-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(350px, 1fr)); gap: 20px; margin: 20px 0; } .mistake-card { border: 2px solid #e9ecef; border-radius: 12px; padding: 16px; background: white; cursor: pointer; transition: all 0.3s ease; box-shadow: 0 2px 4px rgba(0,0,0,0.1); } .mistake-card:hover { border-color: #007bff; box-shadow: 0 4px 12px rgba(0,123,255,0.15); transform: translateY(-2px); } .mistake-card.selected { border-color: #28a745; background: #f8fff9; box-shadow: 0 4px 12px rgba(40,167,69,0.15); } .mistake-header { display: flex; align-items: center; justify-content: space-between; margin-bottom: 12px; } .mistake-header input[type="checkbox"] { width: 18px; height: 18px; cursor: pointer; } .mistake-type { background: #e9ecef; color: #495057; padding: 4px 8px; border-radius: 4px; font-size: 0.8rem; font-weight: 500; } .mistake-date { color: #6c757d; font-size: 0.85rem; } .mistake-content h4 { margin: 0 0 8px 0; color: #2c3e50; font-size: 1.1rem; line-height: 1.4; } .ocr-preview { color: #6c757d; font-size: 0.9rem; line-height: 1.4; margin: 8px 0; display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; overflow: hidden; } .tags { display: flex; flex-wrap: wrap; gap: 6px; margin-top: 10px; } .tag { background: #007bff; color: white; padding: 3px 8px; border-radius: 12px; font-size: 0.75rem; font-weight: 500; } /* 空状态 */ .empty-mistakes { text-align: center; padding: 60px 20px; color: #6c757d; } .empty-mistakes p { margin: 10px 0; font-size: 1.1rem; } /* 图片上传拖拽区域样式 */ .file-upload-area { border: 2px dashed #e1e5e9; border-radius: 8px; padding: 2rem; text-align: center; background: #fafafa; transition: all 0.3s ease; position: relative; cursor: pointer; /* 🎯 修复:确保上传区域不超出容器 */ max-width: 100%; box-sizing: border-box; } .file-upload-area:hover, .file-upload-area.drag-over { border-color: #667eea; background: #f8f9ff; } .upload-content { display: flex; flex-direction: column; align-items: center; gap: 0.5rem; } .upload-icon { font-size: 2rem; opacity: 0.7; } .upload-text { color: #666; font-size: 1rem; } .file-input { position: absolute; top: 0; left: 0; width: 100%; height: 100%; opacity: 0; cursor: pointer; } /* 图片网格容器 */ .image-grid-container { margin-top: 1rem; padding: 1rem; border: 2px dashed #e1e5e9; border-radius: 8px; background: #fafafa; transition: all 0.3s ease; } .image-grid-container.drag-over { border-color: #667eea; background: #f8f9ff; } .image-grid-scroll { display: grid; grid-template-columns: repeat(auto-fill, minmax(120px, 1fr)); gap: 1rem; max-height: 300px; overflow-y: auto; } /* 图片缩略图容器 */ .image-thumbnail-container { position: relative; aspect-ratio: 1; border-radius: 8px; overflow: hidden; cursor: pointer; transition: transform 0.2s ease; } .image-thumbnail-container:hover { transform: scale(1.05); } .image-thumbnail-container .image-thumbnail { width: 100%; height: 100%; object-fit: cover; border-radius: 8px; } .remove-image-btn { position: absolute; top: 4px; right: 4px; width: 24px; height: 24px; background: rgba(220, 53, 69, 0.8); color: white; border: none; border-radius: 50%; cursor: pointer; display: flex; align-items: center; justify-content: center; font-size: 12px; transition: all 0.2s ease; } .remove-image-btn:hover { background: rgba(220, 53, 69, 1); transform: scale(1.1); } /* 添加图片占位符 */ .add-image-placeholder { display: flex; flex-direction: column; align-items: center; justify-content: center; aspect-ratio: 1; border: 2px dashed #dee2e6; border-radius: 8px; background: #f8f9fa; cursor: pointer; transition: all 0.3s ease; position: relative; } .add-image-placeholder:hover { border-color: #667eea; background: #f0f4ff; } .add-image-input { position: absolute; top: 0; left: 0; width: 100%; height: 100%; opacity: 0; cursor: pointer; } .add-image-label { display: flex; flex-direction: column; align-items: center; gap: 0.5rem; pointer-events: none; color: #666; } .add-image-icon { font-size: 1.5rem; opacity: 0.7; } .add-image-text { font-size: 0.9rem; font-weight: 500; } /* 分析控制 */ .analysis-controls { display: flex; justify-content: center; padding: 30px 0; } .start-analysis-button { background: linear-gradient(135deg, #28a745, #20c997); color: white; border: none; padding: 15px 30px; border-radius: 8px; font-size: 1.1rem; font-weight: 600; cursor: pointer; transition: all 0.3s ease; box-shadow: 0 4px 12px rgba(40,167,69,0.3); } .start-analysis-button:hover:not(:disabled) { transform: translateY(-2px); box-shadow: 0 6px 20px rgba(40,167,69,0.4); } .start-analysis-button:disabled { background: #6c757d; cursor: not-allowed; transform: none; box-shadow: none; } /* 分析结果界面 */ .analysis-result { display: flex; flex-direction: column; height: calc(100vh - 200px); } .result-header { padding: 20px; background: #f8f9fa; border-radius: 8px; margin-bottom: 20px; border: 1px solid #dee2e6; } .result-header h3 { margin: 0 0 10px 0; color: #2c3e50; font-size: 1.5rem; } .result-info { display: flex; gap: 30px; color: #6c757d; font-size: 0.95rem; } .result-info span { display: flex; align-items: center; gap: 5px; } /* 聊天容器 */ .chat-container { flex: 1; display: flex; flex-direction: column; border: 1px solid #dee2e6; border-radius: 8px; overflow: hidden; background: white; transition: all 0.3s cubic-bezier(0.25, 0.1, 0.25, 1), transform 0.3s cubic-bezier(0.25, 0.1, 0.25, 1), position 0.3s cubic-bezier(0.25, 0.1, 0.25, 1), top 0.3s cubic-bezier(0.25, 0.1, 0.25, 1), left 0.3s cubic-bezier(0.25, 0.1, 0.25, 1), right 0.3s cubic-bezier(0.25, 0.1, 0.25, 1), bottom 0.3s cubic-bezier(0.25, 0.1, 0.25, 1), width 0.3s cubic-bezier(0.25, 0.1, 0.25, 1), height 0.3s cubic-bezier(0.25, 0.1, 0.25, 1); /* 设置变换原点为右下角,实现自然缩放 */ transform-origin: bottom right; } /* 错题库聊天容器全屏样式 */ .chat-container.chat-fullscreen { position: fixed !important; top: 0 !important; left: 0 !important; right: 0 !important; bottom: 0 !important; z-index: 999 !important; border-radius: 0 !important; border: none !important; box-shadow: 0 0 20px rgba(0, 0, 0, 0.1) !important; background: #ffffff !important; /* 保持变换原点为右下角 */ transform-origin: bottom right !important; display: flex !important; flex-direction: column !important; height: 100vh !important; width: 100vw !important; flex: none !important; } .chat-history { flex: 1; padding: 20px; overflow-y: auto; background: #fafafa; } .message { margin-bottom: 20px; max-width: 85%; } .message.user { margin-left: auto; } .message.assistant { margin-right: auto; } .message-content { padding: 15px 20px; border-radius: 18px; line-height: 1.2; } .message.user .message-content { background: #f0f9ff; color: #0369a1; border: 1px solid #e0f2fe; border-bottom-right-radius: 6px; } .message.assistant .message-content { background: white; color: #2c3e50; border: 1px solid #e9ecef; border-bottom-left-radius: 6px; } .message-time { font-size: 0.75rem; color: #6c757d; margin-top: 5px; text-align: right; } .message.assistant .message-time { text-align: left; } .chat-input { display: flex; padding: 20px; background: white; border-top: 1px solid #dee2e6; gap: 10px; } .chat-input input { flex: 1; padding: 12px 16px; border: 1px solid #ced4da; border-radius: 25px; font-size: 1rem; outline: none; transition: border-color 0.2s; } .chat-input input:focus { border-color: #0369a1; box-shadow: 0 0 0 3px rgba(3, 105, 161, 0.1); } .chat-input button { background: #f0f9ff; color: #0369a1; border: 1px solid #e0f2fe; padding: 12px 24px; border-radius: 25px; cursor: pointer; font-weight: 600; transition: all 0.2s; box-shadow: 0 2px 4px rgba(3, 105, 161, 0.1); } .chat-input button:hover:not(:disabled) { background: #e0f2fe; border-color: #0369a1; box-shadow: 0 4px 8px rgba(3, 105, 161, 0.15); } .chat-input button:disabled { background: #6c757d; cursor: not-allowed; } /* 仪表板样式 */ .dashboard { background: white; border-radius: 12px; overflow-y: auto; height: 100%; display: flex; flex-direction: column; box-shadow: 0 4px 20px rgba(0,0,0,0.1); } .dashboard-header { display: flex; align-items: center; gap: 1rem; padding: 1.5rem; background: #f8f9fa; border-bottom: 1px solid #e1e5e9; } .dashboard-content { padding: 1.5rem; flex: 1; overflow-y: auto; } .stats-overview { display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 1rem; margin-bottom: 2rem; } .stat-card { display: flex; align-items: center; gap: 1rem; padding: 1.5rem; background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; border-radius: 12px; box-shadow: 0 4px 12px rgba(102, 126, 234, 0.3); } .stat-icon { font-size: 2rem; } .stat-info { flex: 1; } .stat-number { font-size: 2rem; font-weight: 700; margin-bottom: 0.25rem; } .stat-label { font-size: 0.9rem; opacity: 0.9; } .stats-details { display: grid; grid-template-columns: repeat(auto-fit, minmax(300px, 1fr)); gap: 2rem; margin-bottom: 2rem; } .stats-section { background: #f8f9fa; border-radius: 12px; padding: 1.5rem; border: 1px solid #e1e5e9; } .stats-section h3 { margin: 0 0 1rem 0; color: #333; font-size: 1.1rem; } .stats-chart { display: flex; flex-direction: column; gap: 0.75rem; } .chart-item { display: flex; align-items: center; gap: 1rem; } .chart-label { min-width: 60px; font-size: 0.9rem; color: #555; font-weight: 500; } .chart-bar { flex: 1; height: 20px; background: #e9ecef; border-radius: 10px; overflow: hidden; } .chart-fill { height: 100%; border-radius: 10px; transition: width 0.3s ease; } .chart-value { min-width: 30px; text-align: right; font-weight: 600; color: #333; } .tags-cloud { display: flex; flex-wrap: wrap; gap: 0.75rem; } .tag-item { display: flex; align-items: center; gap: 0.25rem; padding: 0.5rem 1rem; background: #667eea; color: white; border-radius: 20px; font-weight: 500; transition: transform 0.2s ease; } .tag-item:hover { transform: scale(1.05); } .tag-name { font-weight: 600; } .tag-count { opacity: 0.8; font-size: 0.9em; } .recent-mistakes { display: flex; flex-direction: column; gap: 1rem; } .recent-item { padding: 1rem; background: white; border-radius: 8px; border: 1px solid #e1e5e9; transition: all 0.2s ease; } .recent-item:hover { border-color: #667eea; box-shadow: 0 2px 8px rgba(102, 126, 234, 0.1); } .recent-header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 0.5rem; } .recent-subject { background: #667eea; color: white; padding: 0.25rem 0.5rem; border-radius: 4px; font-size: 0.8rem; font-weight: 500; } .recent-date { color: #6c757d; font-size: 0.8rem; } .recent-question { font-weight: 500; color: #333; margin-bottom: 0.5rem; } .recent-tags { display: flex; flex-wrap: wrap; gap: 0.25rem; } .recent-tag { background: #e9ecef; color: #495057; padding: 0.2rem 0.5rem; border-radius: 4px; font-size: 0.75rem; } .empty-recent { text-align: center; padding: 2rem; color: #6c757d; font-style: italic; } .learning-suggestions { background: #f8f9fa; border-radius: 12px; padding: 1.5rem; border: 1px solid #e1e5e9; } .learning-suggestions h3 { margin: 0 0 1rem 0; color: #333; font-size: 1.1rem; } .suggestions-content { display: flex; flex-direction: column; gap: 1rem; } .tip-item { display: flex; align-items: flex-start; gap: 1rem; padding: 1rem; background: white; border-radius: 8px; border-left: 4px solid #667eea; box-shadow: 0 2px 4px rgba(0,0,0,0.05); } .tip-icon { font-size: 1.5rem; margin-top: 0.25rem; } .tip-text { flex: 1; color: #555; line-height: 1.5; } /* 响应式设计 */ @media (max-width: 768px) { .app-main { padding: 0.5rem; } .analysis-form { padding: 1rem; } .result-header { flex-direction: column; gap: 1rem; text-align: center; } .result-actions { justify-content: center; } .message { max-width: 90%; } .chat-input { flex-direction: column; } .chat-input button { width: 100%; } .library-filters { flex-direction: column; } .mistakes-grid { grid-template-columns: 1fr; } .form-row { grid-template-columns: 1fr; } .data-actions { flex-direction: column; } .settings-footer { flex-direction: column; gap: 1rem; } .api-key-input { flex-direction: column; } .stats-overview { grid-template-columns: 1fr; } .stats-details { grid-template-columns: 1fr; } .stat-card { padding: 1rem; } .stat-number { font-size: 1.5rem; } .chart-item { flex-direction: column; align-items: stretch; gap: 0.5rem; } .chart-label { min-width: auto; } .recent-header { flex-direction: column; align-items: flex-start; gap: 0.5rem; } .detail-content { grid-template-columns: 1fr; } .header-title { margin: 1rem 0; } .header-actions { flex-direction: column; gap: 0.5rem; } .image-grid { grid-template-columns: repeat(auto-fill, minmax(80px, 1fr)); } .modal-overlay { padding: 1rem; } .data-stats { grid-template-columns: 1fr; } } /* 滚动条样式 */ .chat-history::-webkit-scrollbar, .modal-content::-webkit-scrollbar { width: 6px; } .chat-history::-webkit-scrollbar-track, .modal-content::-webkit-scrollbar-track { background: #f1f1f1; border-radius: 3px; } .chat-history::-webkit-scrollbar-thumb, .modal-content::-webkit-scrollbar-thumb { background: #c1c1c1; border-radius: 3px; } .chat-history::-webkit-scrollbar-thumb:hover, .modal-content::-webkit-scrollbar-thumb:hover { background: #a8a8a8; } /* 后端测试组件样式 */ .backend-test { max-width: 1000px; margin: 0 auto; padding: 2rem; } .test-header { text-align: center; margin-bottom: 2rem; padding: 2rem; background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; border-radius: 12px; } .test-header h2 { margin: 0 0 0.5rem 0; font-size: 1.8rem; font-weight: 600; } .test-header p { margin: 0 0 1.5rem 0; opacity: 0.9; font-size: 1rem; } .run-tests-button { background: rgba(255, 255, 255, 0.2); color: white; border: 2px solid rgba(255, 255, 255, 0.3); padding: 0.75rem 2rem; border-radius: 8px; font-size: 1rem; font-weight: 500; cursor: pointer; transition: all 0.3s ease; backdrop-filter: blur(10px); } .run-tests-button:hover:not(:disabled) { background: rgba(255, 255, 255, 0.3); border-color: rgba(255, 255, 255, 0.5); transform: translateY(-2px); } .run-tests-button:disabled { opacity: 0.6; cursor: not-allowed; transform: none; } .test-results { display: flex; flex-direction: column; gap: 1rem; } .test-item { background: white; border: 1px solid #e1e5e9; border-radius: 12px; padding: 1.5rem; box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05); transition: all 0.3s ease; } .test-item:hover { box-shadow: 0 4px 16px rgba(0, 0, 0, 0.1); transform: translateY(-2px); } .test-header-row { display: flex; align-items: center; gap: 1rem; margin-bottom: 1rem; } .test-icon { font-size: 1.5rem; min-width: 2rem; text-align: center; } .test-name { flex: 1; font-weight: 600; font-size: 1.1rem; color: #333; } .test-status { font-weight: 500; font-size: 0.9rem; padding: 0.25rem 0.75rem; border-radius: 20px; background: #f8f9fa; } .test-duration { font-size: 0.8rem; color: #6c757d; background: #f8f9fa; padding: 0.25rem 0.5rem; border-radius: 4px; font-family: 'Courier New', monospace; } .test-error { background: #fff5f5; border: 1px solid #fed7d7; border-radius: 8px; padding: 1rem; margin-top: 1rem; } .test-error strong { color: #c53030; display: block; margin-bottom: 0.5rem; } .test-result { background: #f0fff4; border: 1px solid #c6f6d5; border-radius: 8px; padding: 1rem; margin-top: 1rem; } .test-result strong { color: #2f855a; display: block; margin-bottom: 0.5rem; } .test-result pre { background: #1a202c; color: #e2e8f0; padding: 1rem; border-radius: 6px; overflow-x: auto; font-size: 0.85rem; line-height: 1.4; margin: 0.5rem 0 0 0; max-height: 300px; overflow-y: auto; } .no-tests { text-align: center; padding: 4rem 2rem; color: #6c757d; background: #f8f9fa; border-radius: 12px; border: 2px dashed #dee2e6; } .no-tests p { margin: 0; font-size: 1.1rem; font-style: italic; } /* 响应式设计 */ @media (max-width: 768px) { .backend-test { padding: 1rem; } .test-header { padding: 1.5rem; } .test-header h2 { font-size: 1.5rem; } .test-header-row { flex-wrap: wrap; gap: 0.5rem; } .test-name { font-size: 1rem; } .test-item { padding: 1rem; } .test-result pre { font-size: 0.75rem; padding: 0.75rem; } .run-tests-button { padding: 0.6rem 1.5rem; font-size: 0.9rem; } } /* 思维链容器样式 */ .thinking-container { border: 2px solid #e3f2fd; border-radius: 12px; background: linear-gradient(135deg, #f8f9ff 0%, #e8f4fd 100%); margin-bottom: 1rem; overflow: hidden; box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1); } .thinking-header { display: flex; align-items: center; gap: 0.5rem; padding: 0.75rem 1rem; background: rgba(33, 150, 243, 0.1); border-bottom: 2px solid #2196f3; cursor: pointer; user-select: none; transition: background 0.2s ease; } .thinking-header:hover { background: rgba(33, 150, 243, 0.15); } .thinking-icon { font-size: 1.2rem; } .thinking-title { font-weight: bold; color: #1976d2; font-size: 1rem; flex: 1; } .thinking-toggle { color: #1976d2; font-size: 0.8rem; transition: transform 0.2s ease; } .thinking-content-box { padding: 1rem; background: rgba(255, 255, 255, 0.8); max-height: 400px; overflow-y: auto; font-size: 0.95rem; color: #555; line-height: 1.2; border-left: 3px solid #2196f3; margin: 0; word-wrap: break-word; overflow-wrap: break-word; white-space: pre-wrap; } .thinking-content-box::-webkit-scrollbar { width: 6px; } .thinking-content-box::-webkit-scrollbar-track { background: #f1f1f1; border-radius: 3px; } .thinking-content-box::-webkit-scrollbar-thumb { background: #90caf9; border-radius: 3px; } /* 旧的思维链样式(保留以兼容) */ .chain-of-thought { border: 2px solid #e3f2fd; border-radius: 12px; background: linear-gradient(135deg, #f8f9ff 0%, #e8f4fd 100%); padding: 1rem; margin-bottom: 1.5rem; box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1); } .chain-header { display: flex; align-items: center; gap: 0.5rem; margin-bottom: 1rem; padding-bottom: 0.5rem; border-bottom: 2px solid #2196f3; } .chain-icon { font-size: 1.2rem; } .chain-title { font-weight: bold; color: #1976d2; font-size: 1.1rem; } .chain-sections { display: flex; flex-direction: column; gap: 1rem; } .chain-section { background: white; border-radius: 8px; padding: 1rem; border-left: 4px solid #2196f3; box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05); transition: transform 0.2s ease, box-shadow 0.2s ease; } .chain-section:hover { transform: translateY(-2px); box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1); } .chain-section-title { display: flex; align-items: center; gap: 0.5rem; margin-bottom: 0.5rem; } .section-number { background: #2196f3; color: white; border-radius: 50%; width: 24px; height: 24px; display: flex; align-items: center; justify-content: center; font-size: 0.8rem; font-weight: bold; } .section-name { font-weight: 600; color: #1976d2; font-size: 0.95rem; } .chain-section-content { margin-left: 2rem; color: #333; } .chain-section-content p { margin: 0.5rem 0; line-height: 1.6; } .chain-section-content ul, .chain-section-content ol { margin: 0.5rem 0; padding-left: 1.5rem; } .chain-section-content li { margin: 0.25rem 0; line-height: 1.5; } /* 思维链内容样式 */ .thinking-content { background: rgba(255, 255, 255, 0.8); border-radius: 8px; padding: 1rem; font-size: 0.95rem; color: #555; line-height: 1.2; max-height: 400px; overflow-y: auto; border-left: 3px solid #2196f3; word-wrap: break-word; overflow-wrap: break-word; white-space: pre-wrap; } .thinking-content::-webkit-scrollbar { width: 6px; } .thinking-content::-webkit-scrollbar-track { background: #f1f1f1; border-radius: 3px; } .thinking-content::-webkit-scrollbar-thumb { background: #90caf9; border-radius: 3px; } /* 主要内容样式 */ .main-content { animation: fadeIn 0.3s ease-out; } /* 普通内容样式 */ .normal-content { position: relative; } /* 分析指示器样式 */ .analyzing-indicator { display: flex; align-items: center; gap: 0.5rem; color: #ff9800; font-size: 0.9rem; font-weight: 500; } .spinner { animation: spin 1s linear infinite; } @keyframes spin { from { transform: rotate(0deg); } to { transform: rotate(360deg); } } /* 思维链指示器样式 */ .chain-indicator { background: linear-gradient(135deg, #e3f2fd 0%, #bbdefb 100%); color: #1976d2; padding: 0.25rem 0.5rem; border-radius: 12px; font-size: 0.8rem; font-weight: 500; border: 1px solid #2196f3; } /* 结果头部样式 */ .result-header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 1rem; padding-bottom: 0.5rem; border-bottom: 2px solid #e0e0e0; } .result-header h3 { margin: 0; color: #333; } /* 聊天头部样式 */ .chat-header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 1rem; padding-bottom: 0.5rem; border-bottom: 1px solid #e0e0e0; } .chat-header h3, .chat-header h4 { margin: 0; color: #333; } .chat-header-actions { display: flex; align-items: center; gap: 1rem; } .chain-indicator { font-size: 0.875rem; color: #667eea; background: #ebf8ff; padding: 0.25rem 0.75rem; border-radius: 20px; font-weight: 500; } .chat-fullscreen-toggle { padding: 0.5rem; border: 1px solid #e2e8f0; background: #ffffff; border-radius: 8px; cursor: pointer; font-size: 1rem; color: #4a5568; transition: all 0.2s ease; display: flex; align-items: center; justify-content: center; width: 36px; height: 36px; } .chat-fullscreen-toggle:hover { background: #f7fafc; border-color: #cbd5e0; color: #2d3748; transform: scale(1.05); } /* 全屏状态下的聊天区域增强 */ .chat-container.chat-fullscreen .chat-header { border-radius: 0; padding: 1.5rem 2rem 1rem; background: #ffffff; border-bottom: 1px solid #e2e8f0; box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05); margin-bottom: 0; } .chat-container.chat-fullscreen .chat-history { padding: 2rem !important; flex: 1 !important; overflow-y: auto !important; max-height: none !important; min-height: 0 !important; height: auto !important; background: #fafafa !important; } .chat-container.chat-fullscreen .chat-input { border-radius: 0 !important; padding: 1.5rem 2rem !important; background: #ffffff !important; border-top: 1px solid #dee2e6 !important; box-shadow: 0 -2px 4px rgba(0, 0, 0, 0.05) !important; flex-shrink: 0 !important; } /* 聊天选项样式 */ .chat-options { padding: 1rem 1.5rem; border-bottom: 1px solid #e2e8f0; background: #f8f9fa; } .chat-container.chat-fullscreen .chat-options { padding: 1rem 2rem; background: #f8f9fa; } /* OCR结果立即显示的动画 */ .result-info { animation: slideInFromTop 0.5s ease-out; } @keyframes slideInFromTop { from { opacity: 0; transform: translateY(-20px); } to { opacity: 1; transform: translateY(0); } } /* AI解答区域动画 */ .chat-container { animation: fadeInUp 0.3s ease-out; } @keyframes fadeInUp { from { opacity: 0; transform: translateY(10px); } to { opacity: 1; transform: translateY(0); } } /* 数学公式错误样式 */ .math-error { color: #dc3545; background: #f8d7da; padding: 0.2rem 0.4rem; border-radius: 3px; font-family: monospace; border: 1px solid #f5c6cb; display: inline-block; } /* 增强KaTeX样式 */ .katex { font-size: 1.1em; } .katex-display { margin: 0.5em 0; text-align: center; } .katex-error { color: #cc0000 !important; border: 1px solid #cc0000; background: #ffebee; padding: 0.1em 0.3em; border-radius: 0.2em; font-family: monospace; } /* 修复CSS兼容性警告 */ .text-overflow-ellipsis { -webkit-line-clamp: 3; line-clamp: 3; overflow: hidden; display: -webkit-box; -webkit-box-orient: vertical; } /* 批量分析组件样式 */ .batch-analysis { display: flex; flex-direction: column; height: 100%; gap: 1rem; } .batch-header { display: flex; align-items: center; justify-content: space-between; padding: 1rem; background: #ffffff; border-radius: 8px; box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1); } .batch-header h2 { margin: 0; color: #2d3748; font-size: 1.5rem; font-weight: 600; } .back-button { padding: 0.5rem 1rem; background: #f7fafc; border: 1px solid #e2e8f0; border-radius: 6px; cursor: pointer; color: #4a5568; font-size: 0.9rem; transition: all 0.2s ease; } .back-button:hover { background: #edf2f7; color: #2d3748; } .batch-actions { display: flex; gap: 0.75rem; } .add-button, .process-button { padding: 0.75rem 1rem; border: 1px solid transparent; border-radius: 8px; cursor: pointer; font-size: 0.9rem; font-weight: 500; transition: all 0.15s ease; box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05); } .add-button { background: #f0fdf4; color: #166534; border-color: #bbf7d0; } .add-button:hover { background: #dcfce7; border-color: #86efac; box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1); } .process-button { background: #eff6ff; color: #2563eb; border-color: #dbeafe; } .process-button:hover:not(:disabled) { background: #dbeafe; border-color: #93c5fd; box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1); } .process-button:disabled { background: #f8fafc; color: #94a3b8; border-color: #e2e8f0; cursor: not-allowed; opacity: 0.5; } .progress-info { background: #ffffff; border-radius: 8px; padding: 1rem; box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1); } .progress-text { text-align: center; margin-bottom: 0.5rem; color: #4a5568; font-weight: 500; } .progress-bar { width: 100%; height: 8px; background: #e2e8f0; border-radius: 4px; overflow: hidden; } .tasks-list { display: flex; flex-direction: column; gap: 1rem; } .task-card { background: #ffffff; border-radius: 8px; border: 1px solid #e2e8f0; box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05); overflow: hidden; } .task-header { display: flex; align-items: center; justify-content: space-between; padding: 1rem; background: #f7fafc; border-bottom: 1px solid #e2e8f0; } .task-number { font-weight: 600; color: #4a5568; } .task-status { font-weight: 500; font-size: 0.9rem; } .remove-button { width: 24px; height: 24px; border: none; background: #fed7d7; color: #e53e3e; border-radius: 50%; cursor: pointer; font-size: 0.8rem; display: flex; align-items: center; justify-content: center; transition: all 0.2s ease; } .remove-button:hover:not(:disabled) { background: #feb2b2; } .remove-button:disabled { opacity: 0.5; cursor: not-allowed; } .task-form { padding: 1rem; } .form-row { display: flex; gap: 1rem; margin-bottom: 1rem; } .task-form .form-group { margin-bottom: 1rem; } .task-form label { display: block; margin-bottom: 0.5rem; font-weight: 500; color: #4a5568; font-size: 0.9rem; } .task-form select, .task-form input, .task-form textarea { width: 100%; padding: 0.5rem; border: 1px solid #e2e8f0; border-radius: 4px; font-size: 0.9rem; transition: border-color 0.2s ease; } .task-form select:focus, .task-form input:focus, .task-form textarea:focus { outline: none; border-color: #3182ce; box-shadow: 0 0 0 2px rgba(49, 130, 206, 0.1); } .image-count { margin-top: 0.5rem; font-size: 0.8rem; color: #718096; } .task-result { margin-top: 1rem; padding: 1rem; background: #f0fff4; border: 1px solid #9ae6b4; border-radius: 6px; } .task-result h4 { margin: 0 0 0.5rem 0; color: #22543d; font-size: 1rem; } .result-preview p { margin: 0.25rem 0; font-size: 0.9rem; color: #2f855a; } .task-error { margin-top: 1rem; padding: 1rem; background: #fed7d7; border: 1px solid #feb2b2; border-radius: 6px; color: #c53030; font-size: 0.9rem; } .batch-footer { display: flex; justify-content: space-between; gap: 1rem; padding: 1rem; background: #ffffff; border-radius: 8px; box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1); } .clear-button, .save-all-button { padding: 0.75rem 1rem; border: none; border-radius: 6px; cursor: pointer; font-size: 0.9rem; font-weight: 500; transition: all 0.2s ease; } .clear-button { background: #e2e8f0; color: #4a5568; } .clear-button:hover { background: #cbd5e0; } .save-all-button { background: #38a169; color: white; } .save-all-button:hover:not(:disabled) { background: #2f855a; } .save-all-button:disabled { background: #a0aec0; cursor: not-allowed; } /* 科目配置样式 */ .subject-config { display: flex; flex-direction: column; } .subject-config .settings-section { display: flex; flex-direction: column; gap: 1rem; } .subject-config .settings-section h3 { margin: 0 0 1rem 0; color: #333; font-size: 1.25rem; } .subject-config .toolbar { display: flex; gap: 0.5rem; align-items: center; margin-bottom: 1rem; } .subject-config .create-button, .subject-config .refresh-button { padding: 0.5rem 1rem; border: 1px solid #e2e8f0; border-radius: 6px; background: #f0f9ff; color: #0369a1; cursor: pointer; font-weight: 500; transition: all 0.15s ease; box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05); } .subject-config .refresh-button { background: #f8fafc; color: #64748b; border-color: #e2e8f0; } .subject-config .create-button:hover { background: #e0f2fe; border-color: #0369a1; box-shadow: 0 2px 4px rgba(3, 105, 161, 0.1); } .subject-config .refresh-button:hover:not(:disabled) { background: #f1f5f9; border-color: #64748b; box-shadow: 0 2px 4px rgba(100, 116, 139, 0.1); } .subject-config .refresh-button:disabled { background: #f1f5f9; color: #94a3b8; border-color: #e2e8f0; cursor: not-allowed; box-shadow: none; } .subject-config .config-list { flex: 1; display: flex; flex-direction: column; gap: 1rem; } .subject-config .config-item { border: 1px solid #ddd; border-radius: 8px; padding: 1rem; background: white; transition: all 0.2s ease; } .subject-config .config-item:hover { border-color: #007bff; box-shadow: 0 2px 8px rgba(0, 123, 255, 0.1); } .subject-config .config-item.disabled { background: #f8f9fa; opacity: 0.7; } .subject-config .config-header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 0.75rem; } .subject-config .config-header h4 { margin: 0; color: #333; font-size: 1.1rem; } .subject-config .config-actions { display: flex; gap: 0.5rem; } .subject-config .edit-button, .subject-config .delete-button { padding: 0.25rem 0.75rem; border: 1px solid #e2e8f0; border-radius: 4px; cursor: pointer; font-size: 0.875rem; transition: all 0.15s ease; box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05); } .subject-config .edit-button { background: #fef3c7; color: #d97706; border-color: #fbbf24; } .subject-config .edit-button:hover { background: #fde68a; border-color: #d97706; box-shadow: 0 2px 4px rgba(217, 119, 6, 0.1); } .subject-config .delete-button { background: #fee2e2; color: #dc2626; border-color: #fca5a5; } .subject-config .delete-button:hover { background: #fecaca; border-color: #dc2626; box-shadow: 0 2px 4px rgba(220, 38, 38, 0.1); } .subject-config .config-info { display: grid; grid-template-columns: 1fr 1fr; gap: 0.5rem; font-size: 0.875rem; } .subject-config .config-info p { margin: 0; color: #666; } .subject-config .config-info strong { color: #333; } .subject-config .empty-state { text-align: center; padding: 3rem 1rem; color: #666; } .subject-config .empty-state p { margin: 0 0 1rem 0; font-size: 1.1rem; } .subject-config .empty-state button { padding: 0.75rem 1.5rem; background: #f0f9ff; color: #0369a1; border: 1px solid #e2e8f0; border-radius: 6px; cursor: pointer; font-weight: 500; transition: all 0.15s ease; box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05); } .subject-config .empty-state button:hover { background: #e0f2fe; border-color: #0369a1; box-shadow: 0 2px 4px rgba(3, 105, 161, 0.1); } .subject-config .loading { text-align: center; padding: 2rem; color: #666; font-size: 1.1rem; } .subject-config .tips { margin-top: 1.5rem; padding: 1rem; background: #f8f9fa; border-radius: 6px; border-left: 4px solid #007bff; } .subject-config .tips h5 { margin: 0 0 0.75rem 0; color: #333; font-size: 1rem; } .subject-config .tips ul { margin: 0; padding-left: 1.25rem; } .subject-config .tips li { margin-bottom: 0.25rem; color: #666; font-size: 0.875rem; } /* 添加API配置按钮特殊样式 */ .add-api-button { background: #f0f9ff !important; color: #0369a1 !important; border: 1px solid #e2e8f0 !important; box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05) !important; font-weight: 500 !important; transition: all 0.15s ease !important; } .add-api-button:hover { background: #e0f2fe !important; border-color: #0369a1 !important; box-shadow: 0 2px 4px rgba(3, 105, 161, 0.1) !important; } /* 保存所有设置按钮特殊样式 */ .save-all-settings-button { background: #f0f9ff !important; color: #0369a1 !important; border: 1px solid #e2e8f0 !important; box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05) !important; font-weight: 500 !important; transition: all 0.15s ease !important; } .save-all-settings-button:hover:not(:disabled) { background: #e0f2fe !important; border-color: #0369a1 !important; box-shadow: 0 2px 4px rgba(3, 105, 161, 0.1) !important; } .save-all-settings-button:disabled { background: #f1f5f9 !important; color: #94a3b8 !important; border-color: #e2e8f0 !important; box-shadow: none !important; cursor: not-allowed !important; } /* API配置卡片中的按钮样式 */ .api-card .btn { font-weight: 500 !important; transition: all 0.15s ease !important; box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05) !important; border-width: 1px !important; border-style: solid !important; } /* 测试连接按钮 */ .api-card .btn-primary { background: #f0f9ff !important; color: #0369a1 !important; border-color: #e2e8f0 !important; } .api-card .btn-primary:hover:not(:disabled) { background: #e0f2fe !important; border-color: #0369a1 !important; box-shadow: 0 2px 4px rgba(3, 105, 161, 0.1) !important; } .api-card .btn-primary:disabled { background: #f1f5f9 !important; color: #94a3b8 !important; border-color: #e2e8f0 !important; box-shadow: none !important; cursor: not-allowed !important; } /* 编辑按钮 */ .api-card .btn-secondary { background: #fef3c7 !important; color: #d97706 !important; border-color: #fbbf24 !important; } .api-card .btn-secondary:hover { background: #fde68a !important; border-color: #d97706 !important; box-shadow: 0 2px 4px rgba(217, 119, 6, 0.1) !important; } /* 删除按钮 */ .api-card .btn-danger { background: #fee2e2 !important; color: #dc2626 !important; border-color: #fca5a5 !important; } .api-card .btn-danger:hover { background: #fecaca !important; border-color: #dc2626 !important; box-shadow: 0 2px 4px rgba(220, 38, 38, 0.1) !important; } /* 勾选框样式优化 */ .checkbox-group .checkbox-container { display: flex; justify-content: space-between; align-items: center; padding: 0.75rem; border: 1px solid #ddd; border-radius: 6px; background: #f8f9fa; transition: all 0.2s ease; } .checkbox-group .checkbox-container:hover { border-color: #007bff; background: #e7f3ff; } .checkbox-group .checkbox-container span { font-weight: 500; color: #333; user-select: none; } .checkbox-group .checkbox-container input[type="checkbox"] { width: 18px; height: 18px; cursor: pointer; accent-color: #007bff; } .app-content { flex: 1; display: flex; flex-direction: column; height: 100vh; position: relative; background-color: #f8fafc; } .content-header { display: flex; justify-content: space-between; align-items: center; padding: 1rem; background: #f8f9fa; border-bottom: 1px solid #e1e5e9; z-index: 10; } .content-body { flex: 1; overflow-y: auto; padding: 1rem; } /* ============================================================================ */ /* Cherry Studio Pro 风格美化样式 - 左侧面板专用 */ /* ============================================================================ */ :root { --cherry-bg-primary: #ffffff; --cherry-bg-secondary: #f8f9fa; --cherry-bg-tertiary: #e9ecef; --cherry-glass: rgba(255, 255, 255, 0.9); --cherry-border: rgba(0, 0, 0, 0.08); --cherry-border-active: rgba(0, 0, 0, 0.2); --cherry-text-primary: #1f2937; --cherry-text-secondary: #6b7280; --cherry-accent: #f472b6; --cherry-accent-hover: #f9a8d4; --cherry-radius-xl: 24px; --cherry-radius-lg: 16px; --cherry-radius-md: 12px; --cherry-radius-sm: 8px; --cherry-shadow: 0 8px 32px rgba(0, 0, 0, 0.1); --cherry-backdrop: blur(16px); } .cherry-app { width: 100%; height: auto; background: var(--cherry-glass); backdrop-filter: var(--cherry-backdrop); border: 1px solid var(--cherry-border); border-radius: var(--cherry-radius-xl); box-shadow: var(--cherry-shadow); overflow: visible; padding: 32px; box-sizing: border-box; color: var(--cherry-text-primary); font-family: 'Geist', -apple-system, BlinkMacSystemFont, sans-serif; } .app-header { margin-bottom: 6px; text-align: center; background: transparent; border: none; box-shadow: none; } .app-title { font-size: 20px; font-weight: 600; margin-bottom: 28px; letter-spacing: -0.2px; color: var(--cherry-text-primary); display: flex; justify-content: center; align-items: center; } .app-logo { height: 52px; width: auto; object-fit: contain; } .app-subtitle { font-size: 13px; color: var(--cherry-text-secondary); font-weight: 400; } .upload-card { position: relative; margin-bottom: 12px; border: 1px dashed var(--cherry-border); border-radius: var(--cherry-radius-lg); padding: 32px 24px; text-align: center; cursor: pointer; transition: all 0.3s cubic-bezier(0.16, 1, 0.3, 1); background: var(--cherry-bg-secondary); /* 确保拖拽事件可以正常传递 */ pointer-events: auto; } .upload-card:hover { border-color: var(--cherry-border-active); background: var(--cherry-bg-tertiary); } .upload-card.active { border-color: var(--cherry-accent); background: linear-gradient(rgba(244, 114, 182, 0.05), rgba(244, 114, 182, 0.05)); } .upload-card.has-files { border-style: solid; border-color: var(--cherry-accent); background: rgba(244, 114, 182, 0.05); } .upload-card:last-child { margin-bottom: 0; } .upload-icon { width: 48px; height: 48px; margin: 0 auto 16px; display: flex; align-items: center; justify-content: center; background: rgba(244, 114, 182, 0.1); border-radius: 50%; color: var(--cherry-accent); /* 允许拖拽事件穿透 */ pointer-events: none; } .upload-icon svg { animation: none; } @keyframes float { 0%, 100% { transform: translateY(0); } 50% { transform: translateY(-4px); } } .upload-text { font-size: 15px; margin-bottom: 6px; font-weight: 500; color: var(--cherry-text-primary); /* 允许拖拽事件穿透 */ pointer-events: none; } .upload-hint { font-size: 12px; color: var(--cherry-text-secondary); letter-spacing: 0.2px; /* 允许拖拽事件穿透 */ pointer-events: none; } .preview-list { display: flex; gap: 12px; overflow-x: auto; padding-bottom: 8px; margin-bottom: 20px; scrollbar-width: thin; scrollbar-color: var(--cherry-accent) var(--cherry-bg-secondary); } .preview-list::-webkit-scrollbar { height: 4px; } .preview-list::-webkit-scrollbar-track { background: var(--cherry-bg-secondary); border-radius: 2px; } .preview-list::-webkit-scrollbar-thumb { background-color: var(--cherry-accent); border-radius: 2px; } .preview-item { position: relative; flex: 0 0 80px; height: 80px; border-radius: var(--cherry-radius-sm); overflow: hidden; background: var(--cherry-bg-tertiary); } .preview-image { width: 100%; height: 100%; object-fit: cover; cursor: pointer; } .preview-remove { position: absolute; top: 4px; right: 4px; width: 18px; height: 18px; background: rgba(0, 0, 0, 0.7); border-radius: 50%; display: flex; align-items: center; justify-content: center; cursor: pointer; opacity: 0; transition: opacity 0.2s ease; } .preview-item:hover .preview-remove { opacity: 1; } .preview-remove svg { width: 10px; height: 10px; } .input-container { margin-bottom: 20px; } .input-label { display: block; font-size: 13px; font-weight: 500; margin-bottom: 10px; color: var(--cherry-text-primary); letter-spacing: 0.3px; } .cherry-textarea { width: 100%; padding: 16px; background: var(--cherry-bg-secondary); border: 1px solid var(--cherry-border); border-radius: var(--cherry-radius-lg); font-family: 'Geist', sans-serif; font-size: 14px; color: var(--cherry-text-primary); transition: all 0.3s cubic-bezier(0.16, 1, 0.3, 1); resize: none; min-height: 120px; line-height: 1.5; } .cherry-textarea:focus { outline: none; border-color: var(--cherry-accent); box-shadow: 0 0 0 2px rgba(244, 114, 182, 0.2); background: var(--cherry-bg-tertiary); } .cherry-textarea::placeholder { color: var(--cherry-text-secondary); opacity: 0.6; } .cherry-field { padding: 16px; background: var(--cherry-bg-secondary); border: 1px solid var(--cherry-border); border-radius: var(--cherry-radius-lg); font-size: 14px; color: var(--cherry-text-primary); line-height: 1.5; } .rag-toggle { display: flex; align-items: center; margin-bottom: 24px; padding: 12px 16px; background: var(--cherry-bg-secondary); border-radius: var(--cherry-radius-lg); cursor: pointer; transition: all 0.2s ease; } .rag-toggle:hover { background: var(--cherry-bg-tertiary); } .rag-toggle input { position: absolute; opacity: 0; width: 0; height: 0; pointer-events: none; } .rag-switch { position: relative; display: inline-block; width: 40px; height: 22px; background: var(--cherry-border); border-radius: 11px; margin-right: 12px; transition: all 0.3s ease; cursor: pointer; } .rag-slider { position: absolute; width: 18px; height: 18px; background: var(--cherry-text-secondary); border-radius: 50%; top: 2px; left: 2px; transition: all 0.3s ease; } .rag-toggle input:checked + .rag-switch { background: rgba(244, 114, 182, 0.3); } .rag-toggle input:checked + .rag-switch .rag-slider { background: var(--cherry-accent); transform: translateX(18px); } .rag-label { font-size: 14px; font-weight: 500; color: var(--cherry-text-primary); } .rag-hint { font-size: 12px; color: var(--cherry-text-secondary); margin-top: 4px; margin-left: 52px; } /* RAG控制容器 */ .rag-controls-container { display: flex; flex-direction: column; gap: 12px; margin-bottom: 24px; } /* 分库选择器样式 */ .rag-library-selector { position: relative; margin-left: 52px; } .library-selector-trigger { display: flex; align-items: center; justify-content: space-between; padding: 8px 12px; background: var(--cherry-bg-tertiary); border: 1px solid var(--cherry-border); border-radius: var(--cherry-radius-lg); cursor: pointer; transition: all 0.2s ease; font-size: 13px; color: var(--cherry-text-primary); } .library-selector-trigger:hover { background: var(--cherry-bg-secondary); border-color: var(--cherry-border-active); } .library-selector-label { font-weight: 500; color: var(--cherry-text-primary); } .library-selector-arrow { color: var(--cherry-text-secondary); font-size: 12px; transition: transform 0.2s ease; } .library-selector-dropdown { position: absolute; top: 100%; left: 0; right: 0; background: white; border: 1px solid var(--cherry-border); border-radius: var(--cherry-radius-lg); box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15); z-index: 1000; margin-top: 4px; max-height: 240px; overflow: hidden; display: flex; flex-direction: column; } .library-selector-header { padding: 8px 12px; border-bottom: 1px solid var(--cherry-border); background: var(--cherry-bg-secondary); flex-shrink: 0; } .library-selector-action { background: none; border: none; color: var(--cherry-accent); font-size: 12px; font-weight: 500; cursor: pointer; padding: 4px 8px; border-radius: 4px; transition: all 0.2s ease; } .library-selector-action:hover { background: rgba(244, 114, 182, 0.1); } .library-selector-list { flex: 1; max-height: 180px; overflow-y: scroll !important; min-height: 0; scrollbar-width: thin; scrollbar-color: var(--cherry-accent) var(--cherry-bg-secondary); /* 强制显示滚动条 */ -webkit-overflow-scrolling: touch; } .library-selector-list::-webkit-scrollbar { width: 8px; } .library-selector-list::-webkit-scrollbar-track { background: #f1f1f1; border-radius: 4px; margin: 2px; } .library-selector-list::-webkit-scrollbar-thumb { background: #c1c1c1; border-radius: 4px; border: 1px solid #f1f1f1; } .library-selector-list::-webkit-scrollbar-thumb:hover { background: #a8a8a8; } .library-selector-list::-webkit-scrollbar-corner { background: #f1f1f1; } .library-selector-item { display: flex; align-items: center; gap: 12px; padding: 10px 12px; cursor: pointer; transition: all 0.2s ease; border-bottom: 1px solid var(--cherry-border); } .library-selector-item:last-child { border-bottom: none; } .library-selector-item:hover { background: var(--cherry-bg-secondary); } .library-selector-item.selected { background: rgba(244, 114, 182, 0.1); } .library-checkbox { flex-shrink: 0; } .library-checkbox input[type="checkbox"] { width: 16px; height: 16px; cursor: pointer; accent-color: var(--cherry-accent); } .library-info { flex: 1; min-width: 0; } .library-name { font-weight: 500; color: var(--cherry-text-primary); font-size: 13px; margin-bottom: 2px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; } .library-stats { font-size: 11px; color: var(--cherry-text-secondary); display: flex; align-items: center; gap: 8px; } .library-selector-empty { display: flex; align-items: center; justify-content: center; min-height: 60px; color: var(--cherry-text-secondary); font-size: 13px; font-style: italic; } .analyze-btn { width: 100%; padding: 14px; background: var(--cherry-accent); color: #111; border: none; border-radius: var(--cherry-radius-lg); font-size: 14px; font-weight: 600; cursor: pointer; transition: all 0.3s cubic-bezier(0.16, 1, 0.3, 1); display: flex; align-items: center; justify-content: center; gap: 8px; letter-spacing: 0.3px; margin-bottom: 16px; } .analyze-btn:hover { background: var(--cherry-accent-hover); transform: translateY(-2px); } .analyze-btn:active { transform: translateY(0); } .analyze-btn:disabled { opacity: 0.6; cursor: not-allowed; transform: none; } .btn-icon { width: 16px; height: 16px; } .counter-badge { position: absolute; top: 12px; right: 12px; background: var(--cherry-accent); color: #111; font-size: 11px; font-weight: 600; padding: 2px 6px; border-radius: 10px; /* 允许拖拽事件穿透 */ pointer-events: none; } .action-buttons-cherry { display: flex; gap: 12px; flex-wrap: wrap; } .save-btn-cherry, .reset-btn-cherry, .back-btn-cherry { flex: 1; min-width: 120px; padding: 12px 16px; border: none; border-radius: var(--cherry-radius-lg); font-size: 13px; font-weight: 500; cursor: pointer; transition: all 0.3s cubic-bezier(0.16, 1, 0.3, 1); display: flex; align-items: center; justify-content: center; gap: 6px; } .save-btn-cherry { background: var(--cherry-accent); color: #111; } .save-btn-cherry:hover { background: var(--cherry-accent-hover); transform: translateY(-1px); } .reset-btn-cherry { background: var(--cherry-bg-tertiary); color: var(--cherry-text-primary); border: 1px solid var(--cherry-border); } .reset-btn-cherry:hover { background: var(--cherry-bg-secondary); border-color: var(--cherry-border-active); transform: translateY(-1px); } .back-btn-cherry { background: var(--cherry-bg-tertiary); color: var(--cherry-text-primary); border: 1px solid var(--cherry-border); } .back-btn-cherry:hover { background: var(--cherry-bg-secondary); border-color: var(--cherry-border-active); transform: translateY(-1px); } .no-images { text-align: center; padding: 40px 20px; color: var(--cherry-text-secondary); font-size: 14px; background: var(--cherry-bg-secondary); border-radius: var(--cherry-radius-lg); border: 1px dashed var(--cherry-border); } /* 只读模式样式调整 */ .preview-list.readonly { margin-bottom: 16px; } .preview-item.readonly .preview-remove { display: none; } .file-input { display: none; pointer-events: none; position: absolute; z-index: -1; } /* 新增样式 - 科目显示 */ .readonly-subject-display { text-align: center; margin-bottom: 20px; } .subject-badge { display: inline-block; background: var(--cherry-bg-tertiary); color: var(--cherry-text-primary); padding: 8px 16px; border-radius: 20px; font-size: 14px; font-weight: 500; border: 1px solid var(--cherry-border); } /* 只读模式样式 */ .upload-card.readonly-mode { background: var(--cherry-bg-tertiary); border: 1px solid var(--cherry-border); cursor: default; } .upload-card.readonly-mode:hover { background: var(--cherry-bg-tertiary); border: 1px solid var(--cherry-border); } .cherry-textarea.readonly { background: var(--cherry-bg-tertiary); border: 1px solid var(--cherry-border); cursor: default; resize: none; } /* 返回按钮样式 */ .analyze-btn.back-mode { background: var(--cherry-bg-tertiary); color: var(--cherry-text-primary); border: 1px solid var(--cherry-border); } .analyze-btn.back-mode:hover { background: var(--cherry-bg-secondary); border-color: var(--cherry-border-active); } /* 次要按钮样式 */ .secondary-buttons { display: flex; gap: 12px; margin-top: 12px; } .save-btn-secondary, .reset-btn-secondary { flex: 1; padding: 10px 14px; border: none; border-radius: var(--cherry-radius-lg); font-size: 12px; font-weight: 500; cursor: pointer; transition: all 0.3s cubic-bezier(0.16, 1, 0.3, 1); display: flex; align-items: center; justify-content: center; gap: 4px; } .save-btn-secondary { background: rgba(244, 114, 182, 0.2); color: var(--cherry-accent); border: 1px solid rgba(244, 114, 182, 0.3); } .save-btn-secondary:hover { background: rgba(244, 114, 182, 0.3); transform: translateY(-1px); } .reset-btn-secondary { background: var(--cherry-bg-tertiary); color: var(--cherry-text-secondary); border: 1px solid var(--cherry-border); } .reset-btn-secondary:hover { background: var(--cherry-bg-secondary); color: var(--cherry-text-primary); border-color: var(--cherry-border-active); transform: translateY(-1px); } /* Cherry组件专用样式已定义在上方 */
128,793
App
css
en
css
data
{"qsc_code_num_words": 17433, "qsc_code_num_chars": 128793.0, "qsc_code_mean_word_length": 4.83927035, "qsc_code_frac_words_unique": 0.04904491, "qsc_code_frac_chars_top_2grams": 0.0077048, "qsc_code_frac_chars_top_3grams": 0.00682764, "qsc_code_frac_chars_top_4grams": 0.0072188, "qsc_code_frac_chars_dupe_5grams": 0.68310752, "qsc_code_frac_chars_dupe_6grams": 0.59505945, "qsc_code_frac_chars_dupe_7grams": 0.50874198, "qsc_code_frac_chars_dupe_8grams": 0.43702808, "qsc_code_frac_chars_dupe_9grams": 0.36306201, "qsc_code_frac_chars_dupe_10grams": 0.310942, "qsc_code_frac_chars_replacement_symbols": 0.0, "qsc_code_frac_chars_digital": 0.08559039, "qsc_code_frac_chars_whitespace": 0.18528181, "qsc_code_size_file_byte": 128793.0, "qsc_code_num_lines": 7324.0, "qsc_code_num_chars_line_max": 90.0, "qsc_code_num_chars_line_mean": 17.58506281, "qsc_code_frac_chars_alphabet": 0.71837415, "qsc_code_frac_chars_comments": 0.0, "qsc_code_cate_xml_start": 0.0, "qsc_code_frac_lines_dupe_lines": 0.61909308, "qsc_code_cate_autogen": 0.0, "qsc_code_frac_lines_long_string": 0.0, "qsc_code_frac_chars_string_length": 0.0012423, "qsc_code_frac_chars_long_word_length": 0.0, "qsc_code_frac_lines_string_concat": 0.0, "qsc_code_cate_encoded_data": 0.0, "qsc_code_frac_chars_hex_words": 0.0, "qsc_code_frac_lines_prompt_comments": 0.0, "qsc_code_frac_lines_assert": 0.0}
0
{"qsc_code_frac_chars_replacement_symbols": 0, "qsc_code_num_words": 0, "qsc_code_num_chars": 1, "qsc_code_mean_word_length": 0, "qsc_code_frac_words_unique": 1, "qsc_code_frac_chars_top_2grams": 0, "qsc_code_frac_chars_top_3grams": 0, "qsc_code_frac_chars_top_4grams": 0, "qsc_code_frac_chars_dupe_5grams": 0, "qsc_code_frac_chars_dupe_6grams": 0, "qsc_code_frac_chars_dupe_7grams": 0, "qsc_code_frac_chars_dupe_8grams": 0, "qsc_code_frac_chars_dupe_9grams": 0, "qsc_code_frac_chars_dupe_10grams": 0, "qsc_code_frac_lines_dupe_lines": 0, "qsc_code_size_file_byte": 0, "qsc_code_num_lines": 0, "qsc_code_num_chars_line_max": 0, "qsc_code_num_chars_line_mean": 0, "qsc_code_frac_chars_alphabet": 0, "qsc_code_frac_chars_digital": 0, "qsc_code_frac_chars_whitespace": 0, "qsc_code_frac_chars_comments": 0, "qsc_code_cate_xml_start": 0, "qsc_code_cate_autogen": 0, "qsc_code_frac_chars_long_word_length": 0, "qsc_code_cate_encoded_data": 0, "qsc_code_frac_chars_hex_words": 0}
000haoji/deep-student
src/App.tsx
import { useState, useEffect, useCallback, useMemo } from 'react'; import { getCurrentWebviewWindow } from '@tauri-apps/api/webviewWindow'; import { MistakeLibrary } from './components/MistakeLibrary'; import { Settings } from './components/Settings'; import { BatchAnalysis } from './components/BatchAnalysis'; import UniversalAppChatHost, { HostedChatApiProvider, UniversalAppChatHostProps } from './components/UniversalAppChatHost'; // DEPRECATED: 单次回顾模块已废弃 - 2024年6月5日,功能被统一回顾替代 // import { ReviewAnalysis } from './components/ReviewAnalysis'; import { Dashboard } from './components/Dashboard'; import ReviewAnalysisDashboard from './components/ReviewAnalysisDashboard'; import CreateReviewAnalysisView from './components/CreateReviewAnalysisView'; import ReviewAnalysisSessionView from './components/ReviewAnalysisSessionView'; // DEPRECATED: import { ReviewAnalysisLibrary } from './components/ReviewAnalysisLibrary'; import { DataImportExport } from './components/DataImportExport'; import { MessageWithThinking } from './chat-core'; import AnkiCardGeneration from './components/AnkiCardGeneration'; import { EnhancedKnowledgeBaseManagement } from './components/EnhancedKnowledgeBaseManagement'; import { EnhancedRagQueryView } from './components/EnhancedRagQueryView'; import ImageOcclusion from './components/ImageOcclusion'; import TemplateManagementPage from './components/TemplateManagementPage'; import KnowledgeGraphManagement from './components/KnowledgeGraphManagement'; import { WindowControls } from './components/WindowControls'; import { useWindowDrag } from './hooks/useWindowDrag'; import { ImageViewer } from './components/ImageViewer'; import { GeminiAdapterTest } from './components/GeminiAdapterTest'; import { ModernSidebar } from './components/ModernSidebar'; // 移除不再使用的streamHandler import import { TauriAPI, MistakeItem } from './utils/tauriApi'; import { SubjectProvider } from './contexts/SubjectContext'; import { UnifiedSubjectSelector } from './components/shared/UnifiedSubjectSelector'; import './App.css'; import './DeepStudent.css'; import './components/AnkiCardGeneration.css'; import './chat-core/styles/index.css'; import './styles/modern-sidebar.css'; interface ChatMessage { role: 'user' | 'assistant' | 'system'; content: string; timestamp: string; thinking_content?: string; rag_sources?: Array<{ document_id: string; file_name: string; chunk_text: string; score: number; chunk_index: number; }>; } interface AnalysisResponse { temp_id: string; initial_data: { ocr_text: string; tags: string[]; mistake_type: string; first_answer: string; }; } interface ContinueChatResponse { new_assistant_message: string; } type CurrentView = 'analysis' | 'library' | 'settings' | 'mistake-detail' | 'batch' | 'review' | 'dashboard' | 'data-management' | 'unified-review' | 'create-review' | 'review-session' | /* 'review-library' - DEPRECATED */ 'anki-generation' | 'knowledge-base' | 'rag-query' | 'image-occlusion' | 'template-management' | 'gemini-adapter-test' | 'cogni-graph'; // 真实API调用 const analyzeNewMistake = TauriAPI.analyzeNewMistake; const continueChat = async (request: any): Promise<ContinueChatResponse> => { return TauriAPI.continueChat(request); }; function App() { const [currentView, setCurrentView] = useState<CurrentView>('analysis'); const [selectedMistake, setSelectedMistake] = useState<MistakeItem | null>(null); const [showDataManagement, setShowDataManagement] = useState(false); const [sidebarCollapsed, setSidebarCollapsed] = useState(false); const [isChatFullscreen, setIsChatFullscreen] = useState(false); const [currentReviewSessionId, setCurrentReviewSessionId] = useState<string | null>(null); // 🎯 修复:使用固定的分析会话ID,避免重新渲染时组件重新初始化 const [analysisSessionId] = useState(() => `analysis_session_${Date.now()}`); // 🎯 修复:错题库刷新触发器,每次切换到错题库页面时递增 const [libraryRefreshTrigger, setLibraryRefreshTrigger] = useState<number>(0); // 🎯 修复:处理页面切换,在切换到错题库时触发刷新 const handleViewChange = (newView: CurrentView) => { console.log('🔄 页面切换:', currentView, '->', newView); // 如果切换到错题库页面,触发刷新 if (newView === 'library' && currentView !== 'library') { console.log('🔄 切换到错题库,触发数据刷新'); setLibraryRefreshTrigger(prev => prev + 1); } setCurrentView(newView); }; // 开发者工具快捷键支持 (仅在生产模式下使用,开发模式依赖Tauri原生支持) useEffect(() => { // 检查是否为生产模式 const isProduction = !window.location.hostname.includes('localhost') && !window.location.hostname.includes('127.0.0.1') && !window.location.hostname.includes('tauri.localhost'); if (!isProduction) { // 开发模式:不拦截F12,让Tauri原生处理 console.log('🔧 开发模式:使用Tauri原生F12支持'); return; } const handleKeyDown = async (event: KeyboardEvent) => { // 支持多种快捷键组合 (仅生产模式) const isDevtoolsShortcut = event.key === 'F12' || (event.ctrlKey && event.shiftKey && event.key === 'I') || (event.metaKey && event.altKey && event.key === 'I'); if (isDevtoolsShortcut) { event.preventDefault(); try { const webview = getCurrentWebviewWindow(); // 使用Tauri 2.x的API if (await webview.isDevtoolsOpen()) { await webview.closeDevtools(); console.log('🔧 开发者工具已关闭'); } else { await webview.openDevtools(); console.log('🔧 开发者工具已打开'); } } catch (error) { console.error('❌ 切换开发者工具失败:', error); // 降级到基本切换方法 try { const webview = getCurrentWebviewWindow(); await webview.toggleDevtools(); console.log('🔧 使用降级方法打开开发者工具'); } catch (fallbackError) { console.error('❌ 降级方法也失败:', fallbackError); } } } }; window.addEventListener('keydown', handleKeyDown); return () => window.removeEventListener('keydown', handleKeyDown); }, []); // 模板管理状态 const [isSelectingTemplate, setIsSelectingTemplate] = useState(false); const [templateSelectionCallback, setTemplateSelectionCallback] = useState<((template: any) => void) | null>(null); const [previousView, setPreviousView] = useState<CurrentView>('anki-generation'); // 开发功能设置状态 const [geminiAdapterTestEnabled, setGeminiAdapterTestEnabled] = useState(false); // 调试App组件状态变化 console.log('🔍 App组件渲染状态:', { currentView, currentReviewSessionId, timestamp: new Date().toISOString() }); const { startDragging } = useWindowDrag(); // 分析相关状态 const [subject, setSubject] = useState('数学'); const [availableSubjects, setAvailableSubjects] = useState<string[]>([]); const [isLoadingSubjects, setIsLoadingSubjects] = useState(true); const [subjectConfigs, setSubjectConfigs] = useState<any[]>([]); const [userQuestion, setUserQuestion] = useState(''); const [questionImages, setQuestionImages] = useState<File[]>([]); const [questionImageUrls, setQuestionImageUrls] = useState<string[]>([]); const [imageViewerOpen, setImageViewerOpen] = useState(false); const [currentImageIndex, setCurrentImageIndex] = useState(0); const [isAnalyzing, setIsAnalyzing] = useState(false); const [analysisResult, setAnalysisResult] = useState<AnalysisResponse | null>(null); const [chatHistory, setChatHistory] = useState<ChatMessage[]>([]); const [currentMessage, setCurrentMessage] = useState(''); const [isChatting, setIsChatting] = useState(false); const [streamingMessageIndex, setStreamingMessageIndex] = useState<number | null>(null); const [isInputAllowed, setIsInputAllowed] = useState(false); const [useStreamMode] = useState(true); // 固定启用流式模式 // 新增状态:用于立即显示OCR结果 const [ocrResult, setOcrResult] = useState<{ ocr_text: string; tags: string[]; mistake_type: string; } | null>(null); const [isOcrComplete, setIsOcrComplete] = useState(false); const [enableChainOfThought] = useState(true); // 固定启用思维链 const [thinkingContent, setThinkingContent] = useState<Map<number, string>>(new Map()); // 存储每条消息的思维链内容 // RAG相关状态 const [enableRag, setEnableRag] = useState(false); const [ragTopK, setRagTopK] = useState(5); const [selectedLibraries, setSelectedLibraries] = useState<string[]>([]); // 批量分析功能开关状态 const [batchAnalysisEnabled, setBatchAnalysisEnabled] = useState(false); // 图片遮罩卡功能开关状态 const [imageOcclusionEnabled, setImageOcclusionEnabled] = useState(false); // 加载支持的科目和科目配置 useEffect(() => { const loadSubjects = async () => { try { const subjects = await TauriAPI.getSupportedSubjects(); setAvailableSubjects(subjects); // 设置默认科目为第一个 if (subjects.length > 0) { setSubject(subjects[0]); } } catch (error) { console.error('加载科目失败:', error); // 如果API失败,使用备用科目列表 const fallbackSubjects = ['数学', '物理', '化学', '英语']; setAvailableSubjects(fallbackSubjects); setSubject(fallbackSubjects[0]); } finally { setIsLoadingSubjects(false); } }; const loadSubjectConfigs = async () => { try { const configs = await TauriAPI.getAllSubjectConfigs(true); // 只获取启用的科目配置 setSubjectConfigs(configs); } catch (error) { console.error('加载科目配置失败:', error); setSubjectConfigs([]); } finally { // Loading completed } }; loadSubjects(); loadSubjectConfigs(); }, []); // 加载RAG设置、批量分析设置和开发功能设置 const loadSettings = async () => { try { const [ragEnabled, ragTopKSetting, batchAnalysisEnabledSetting, geminiAdapterTestEnabledSetting, imageOcclusionEnabledSetting] = await Promise.all([ TauriAPI.getSetting('rag_enabled').catch(() => 'false'), TauriAPI.getSetting('rag_top_k').catch(() => '5'), TauriAPI.getSetting('batch_analysis_enabled').catch(() => 'false'), TauriAPI.getSetting('gemini_adapter_test_enabled').catch(() => 'false'), TauriAPI.getSetting('image_occlusion_enabled').catch(() => 'false'), ]); console.log('🔄 加载系统设置:', { ragEnabled, ragTopKSetting, batchAnalysisEnabledSetting, geminiAdapterTestEnabledSetting, imageOcclusionEnabledSetting }); setEnableRag(ragEnabled === 'true'); setRagTopK(parseInt(ragTopKSetting || '5') || 5); setBatchAnalysisEnabled(batchAnalysisEnabledSetting === 'true'); setGeminiAdapterTestEnabled(geminiAdapterTestEnabledSetting === 'true'); setImageOcclusionEnabled(imageOcclusionEnabledSetting === 'true'); } catch (error) { console.error('加载设置失败:', error); } }; useEffect(() => { loadSettings(); }, []); // 监听设置变化,如果禁用了功能且当前在对应页面,则跳转到分析页面 useEffect(() => { if (!geminiAdapterTestEnabled && currentView === 'gemini-adapter-test') { console.log('🔄 Gemini适配器测试已禁用,跳转到分析页面'); setCurrentView('analysis'); } if (!imageOcclusionEnabled && currentView === 'image-occlusion') { console.log('🔄 图片遮罩卡已禁用,跳转到分析页面'); setCurrentView('analysis'); } }, [geminiAdapterTestEnabled, imageOcclusionEnabled, currentView]); // 监听窗口焦点,当用户切换回页面时重新加载设置 useEffect(() => { const handleWindowFocus = () => { console.log('🔄 窗口获得焦点,重新加载系统设置'); loadSettings(); }; window.addEventListener('focus', handleWindowFocus); return () => { window.removeEventListener('focus', handleWindowFocus); }; }, []); // 处理聊天全屏切换 - 简化为直接状态切换 const handleChatFullscreenToggle = () => { setIsChatFullscreen(!isChatFullscreen); }; // 处理图片上传 const handleImageUpload = (e: React.ChangeEvent<HTMLInputElement>) => { const files = Array.from(e.target.files || []); const remainingSlots = 9 - questionImages.length; const filesToAdd = files.slice(0, remainingSlots); if (filesToAdd.length > 0) { setQuestionImages(prev => [...prev, ...filesToAdd]); // URL管理由useEffect自动处理,不需要在这里手动创建 } // 清空input e.target.value = ''; }; // 删除图片 const removeImage = (index: number) => { // 只需要更新questionImages状态,URL管理由useEffect自动处理 setQuestionImages(prev => prev.filter((_, i) => i !== index)); }; // 打开图片查看器 const openImageViewer = (index: number) => { setCurrentImageIndex(index); setImageViewerOpen(true); }; // 优化的文件上传点击处理器 const handleFileUploadClick = useCallback(() => { const fileInput = document.querySelector('.file-input') as HTMLInputElement; if (fileInput) { fileInput.click(); } }, []); // 处理模板选择请求 const handleTemplateSelectionRequest = useCallback((callback: (template: any) => void) => { setPreviousView(currentView); setTemplateSelectionCallback(() => callback); setIsSelectingTemplate(true); setCurrentView('template-management'); }, [currentView]); // 处理模板选择完成 const handleTemplateSelected = useCallback((template: any) => { if (templateSelectionCallback) { templateSelectionCallback(template); } setIsSelectingTemplate(false); setTemplateSelectionCallback(null); setCurrentView(previousView); }, [templateSelectionCallback, previousView]); // 取消模板选择 const handleTemplateSelectionCancel = useCallback(() => { setIsSelectingTemplate(false); setTemplateSelectionCallback(null); setCurrentView(previousView); }, [previousView]); // 键盘快捷键 useEffect(() => { const handleKeyDown = (e: KeyboardEvent) => { // 只在没有输入框聚焦时处理快捷键 if (e.target instanceof HTMLInputElement || e.target instanceof HTMLTextAreaElement) { return; } // Ctrl/Cmd + 数字键切换视图 (已移除开发工具相关快捷键) if ((e.ctrlKey || e.metaKey) && !e.shiftKey && !e.altKey) { switch (e.key) { case '1': e.preventDefault(); handleViewChange('analysis'); break; case '2': e.preventDefault(); if (batchAnalysisEnabled) { handleViewChange('batch'); } break; case '3': e.preventDefault(); handleViewChange('unified-review'); break; case '4': e.preventDefault(); handleViewChange('library'); break; case '5': e.preventDefault(); handleViewChange('dashboard'); break; case '6': e.preventDefault(); setCurrentView('settings'); break; case '7': e.preventDefault(); setCurrentView('image-occlusion'); break; case '8': e.preventDefault(); if (geminiAdapterTestEnabled) { setCurrentView('gemini-adapter-test'); } break; case 's': e.preventDefault(); setCurrentView('settings'); break; case 'e': e.preventDefault(); setCurrentView('data-management'); break; case 'r': e.preventDefault(); console.log('🔄 手动刷新系统设置 (Ctrl+R)'); loadSettings(); // 同时刷新其他相关设置 break; } } }; document.addEventListener('keydown', handleKeyDown); return () => document.removeEventListener('keydown', handleKeyDown); }, [currentView, showDataManagement, isChatFullscreen, batchAnalysisEnabled, geminiAdapterTestEnabled]); // 管理题目图片URL的生命周期 useEffect(() => { // 清理旧的URLs(避免在第一次渲染时清理不存在的URLs) if (questionImageUrls.length > 0) { questionImageUrls.forEach(url => { try { URL.revokeObjectURL(url); } catch (error) { console.warn('清理URL时出错:', error); } }); } // 创建新的URLs const newUrls = questionImages.map(file => { try { return URL.createObjectURL(file); } catch (error) { console.error('创建图片URL失败:', error); return ''; } }).filter(url => url !== ''); setQuestionImageUrls(newUrls); // 清理函数 return () => { newUrls.forEach(url => { try { URL.revokeObjectURL(url); } catch (error) { console.warn('清理URL时出错:', error); } }); }; }, [questionImages]); // 仅依赖questionImages,避免questionImageUrls导致循环 // 开始分析 const handleAnalyze = async () => { if (!userQuestion.trim() || questionImages.length === 0) { alert('请输入问题并上传至少一张题目图片'); return; } setIsAnalyzing(true); setStreamingMessageIndex(null); setOcrResult(null); setIsOcrComplete(false); setAnalysisResult(null); setChatHistory([]); try { const request = { subject, question_image_files: questionImages, analysis_image_files: [], // 不再使用解析图片 user_question: userQuestion, enable_chain_of_thought: enableChainOfThought, }; if (useStreamMode) { console.log('🚀 开始分步骤分析...'); // 第一步:OCR分析,立即显示结果 console.log('📝 第一步:OCR和分类分析...'); const stepResult = await TauriAPI.analyzeStepByStep(request); // 立即显示OCR结果 setOcrResult(stepResult.ocr_result); setIsOcrComplete(true); console.log('✅ OCR分析完成:', stepResult.ocr_result); // 创建临时的分析结果对象 const tempAnalysisResult: AnalysisResponse = { temp_id: stepResult.temp_id, initial_data: { ocr_text: stepResult.ocr_result.ocr_text, tags: stepResult.ocr_result.tags, mistake_type: stepResult.ocr_result.mistake_type, first_answer: '', // 暂时为空,等待流式填充 }, }; setAnalysisResult(tempAnalysisResult); // 第二步:开始流式AI解答 console.log('🤖 第二步:开始流式AI解答...'); // 创建初始的助手消息(空内容,等待流式填充) const initialMessage: ChatMessage = { role: 'assistant', content: '', timestamp: new Date().toISOString(), }; setChatHistory([initialMessage]); setStreamingMessageIndex(0); // 改进的流式处理逻辑 const streamEvent = `analysis_stream_${stepResult.temp_id}`; let fullContent = ''; let fullThinkingContent = ''; let contentListenerActive = true; let thinkingListenerActive = true; // 使用Tauri的listen API而不是streamHandler const { listen } = await import('@tauri-apps/api/event'); // 统一检查并处理流完成状态的函数 const checkAndFinalizeStreams = () => { console.log(`🔍 检查流完成状态: contentActive=${contentListenerActive}, thinkingActive=${thinkingListenerActive}`); // 核心改进:主内容流完成就是整个流程完成 if (!contentListenerActive) { console.log('✅ 主内容流已完成,标记整个流程为完成状态'); setStreamingMessageIndex(null); // 停止显示流式光标 setIsInputAllowed(true); // 允许用户输入 setIsAnalyzing(false); // 分析完成 } // 当所有流都完成时,清理监听器 if (!contentListenerActive && !thinkingListenerActive) { console.log('🎉 所有流式内容(分析或对话)均已完成,清理监听器'); } else { console.log(`⏳ 流状态: 主内容=${contentListenerActive ? '进行中' : '已完成'}, 思维链=${thinkingListenerActive ? '进行中' : '已完成'}`); } }; // 监听主内容流 const unlistenContent = await listen(streamEvent, (event: any) => { if (!contentListenerActive) return; console.log(`💬 收到主内容流:`, event.payload); if (event.payload) { if (event.payload.is_complete) { if (event.payload.content && event.payload.content.length >= fullContent.length) { fullContent = event.payload.content; } console.log('🎉 主内容流完成,总长度:', fullContent.length); setChatHistory(prev => { const newHistory = [...prev]; if (newHistory[0]) { newHistory[0] = { ...newHistory[0], content: fullContent }; } return newHistory; }); contentListenerActive = false; // 立即更新分析结果中的first_answer if (analysisResult) { setAnalysisResult(prev => prev ? { ...prev, initial_data: { ...prev.initial_data, first_answer: fullContent } } : null); } checkAndFinalizeStreams(); // 检查是否所有流都完成了 } else if (event.payload.content) { fullContent += event.payload.content; console.log(`📝 累积内容,当前长度: ${fullContent.length}`); setChatHistory(prev => { const newHistory = [...prev]; if (newHistory[0]) { newHistory[0] = { ...newHistory[0], content: fullContent }; } return newHistory; }); } } }); // 如果启用了思维链,监听思维链事件 if (enableChainOfThought) { const reasoningEvent = `${streamEvent}_reasoning`; console.log(`🧠 监听思维链事件: ${reasoningEvent}`); const unlistenThinking = await listen(reasoningEvent, (event: any) => { if (!thinkingListenerActive) return; console.log(`🧠 思维链流内容:`, event.payload); if (event.payload) { if (event.payload.is_complete) { if (event.payload.content && event.payload.content.length >= fullThinkingContent.length) { fullThinkingContent = event.payload.content; } console.log('🎉 思维链流完成,总长度:', fullThinkingContent.length); setThinkingContent(prev => new Map(prev).set(0, fullThinkingContent)); thinkingListenerActive = false; checkAndFinalizeStreams(); // 检查是否所有流都完成了 } else if (event.payload.content) { fullThinkingContent += event.payload.content; console.log(`🧠 累积思维链,当前长度: ${fullThinkingContent.length}`); setThinkingContent(prev => new Map(prev).set(0, fullThinkingContent)); } } }); // 添加超时机制:如果主内容完成后5秒思维链还没完成,自动标记为完成 setTimeout(() => { if (!contentListenerActive && thinkingListenerActive) { console.warn('⚠️ 思维链流超时,自动标记为完成'); thinkingListenerActive = false; checkAndFinalizeStreams(); } }, 5000); } else { console.log('ℹ️ 未启用思维链,直接标记为完成'); thinkingListenerActive = false; checkAndFinalizeStreams(); // 如果没有思维链,立即检查一次,因为此时主内容可能已经完成 } // 如果启用了RAG,监听RAG来源信息 if (enableRag) { const ragSourcesEvent = `${streamEvent}_rag_sources`; console.log(`📚 监听RAG来源事件: ${ragSourcesEvent}`); const unlistenRagSources = await listen(ragSourcesEvent, (event: any) => { console.log(`📚 收到RAG来源信息:`, event.payload); if (event.payload && event.payload.sources) { // 更新聊天历史中的RAG来源信息 setChatHistory(prev => { const newHistory = [...prev]; if (newHistory[0] && newHistory[0].role === 'assistant') { newHistory[0] = { ...newHistory[0], rag_sources: event.payload.sources }; } return newHistory; }); console.log('✅ RAG来源信息已更新'); } }); } // 启动流式解答 console.log(`🚀 启动流式解答,temp_id: ${stepResult.temp_id}, enable_chain_of_thought: ${enableChainOfThought}, enable_rag: ${enableRag}`); if (enableRag) { // 使用RAG增强的流式解答 await TauriAPI.startRagEnhancedStreamingAnswer({ temp_id: stepResult.temp_id, enable_chain_of_thought: enableChainOfThought, enable_rag: true, rag_options: { top_k: ragTopK, enable_reranking: true // 如果配置了重排序模型会自动使用 } }); } else { // 使用普通的流式解答 await TauriAPI.startStreamingAnswer(stepResult.temp_id, enableChainOfThought); } } else { // 使用传统非流式分析 console.log('📊 使用传统分析模式...'); const response = await analyzeNewMistake(request); setAnalysisResult(response); // 立即显示OCR结果 setOcrResult({ ocr_text: response.initial_data.ocr_text, tags: response.initial_data.tags, mistake_type: response.initial_data.mistake_type, }); setIsOcrComplete(true); setChatHistory([{ role: 'assistant', content: response.initial_data.first_answer, timestamp: new Date().toISOString(), }]); } } catch (error) { console.error('❌ 分析失败:', error); alert('分析失败: ' + error); setStreamingMessageIndex(null); setOcrResult(null); setIsOcrComplete(false); } finally { setIsAnalyzing(false); } }; // 发送聊天消息 - 完全重写,修复所有流式问题 const handleSendMessage = async () => { if (!currentMessage.trim() || !analysisResult) return; const userMessage: ChatMessage = { role: 'user', content: currentMessage, timestamp: new Date().toISOString(), }; const newChatHistory = [...chatHistory, userMessage]; setChatHistory(newChatHistory); setCurrentMessage(''); setIsChatting(true); try { if (useStreamMode) { // 流式对话 - 全新改进版本 console.log('💬 开始流式对话...'); // 创建空的助手消息等待流式填充 const assistantMessage: ChatMessage = { role: 'assistant', content: '', timestamp: new Date().toISOString(), }; const streamingHistory = [...newChatHistory, assistantMessage]; setChatHistory(streamingHistory); setStreamingMessageIndex(streamingHistory.length - 1); // 改进的流式处理逻辑 const streamEvent = `continue_chat_stream_${analysisResult.temp_id}`; let fullContent = ''; let fullThinkingContent = ''; let contentListenerActive = true; let thinkingListenerActive = true; // 使用Tauri的listen API const { listen } = await import('@tauri-apps/api/event'); // 统一检查并处理流完成状态的函数 (对话部分,可以考虑提取到外部) const checkAndFinalizeChatStreams = () => { console.log(`🔍 检查对话流完成状态: contentActive=${contentListenerActive}, thinkingActive=${thinkingListenerActive}`); // 核心改进:主内容流完成就是整个对话完成 if (!contentListenerActive) { console.log('✅ 对话主内容流已完成,标记整个对话为完成状态'); setStreamingMessageIndex(null); // 停止显示流式光标 setIsInputAllowed(true); // 允许用户继续输入 setIsChatting(false); // 对话完成 } // 当所有流都完成时,清理监听器 if (!contentListenerActive && !thinkingListenerActive) { console.log('🎉 所有对话流式内容均已完成,清理监听器'); } else { console.log(`⏳ 对话流状态: 主内容=${contentListenerActive ? '进行中' : '已完成'}, 思维链=${thinkingListenerActive ? '进行中' : '已完成'}`); } }; // 监听主内容流 const unlistenContent = await listen(streamEvent, (event: any) => { if (!contentListenerActive) return; console.log(`💬 收到对话主内容流:`, event.payload); if (event.payload) { if (event.payload.is_complete) { if (event.payload.content && event.payload.content.length >= fullContent.length) { fullContent = event.payload.content; } console.log('🎉 对话主内容流完成,总长度:', fullContent.length); setChatHistory(prev => { const newHistory = [...prev]; const lastIdx = newHistory.length - 1; if (newHistory[lastIdx] && newHistory[lastIdx].role === 'assistant') { newHistory[lastIdx] = { ...newHistory[lastIdx], content: fullContent }; } return newHistory; }); contentListenerActive = false; // 立即更新分析结果中的first_answer if (analysisResult) { setAnalysisResult(prev => prev ? { ...prev, initial_data: { ...prev.initial_data, first_answer: fullContent } } : null); } checkAndFinalizeChatStreams(); // 检查是否所有流都完成了 } else if (event.payload.content) { fullContent += event.payload.content; setChatHistory(prev => { const newHistory = [...prev]; const lastIdx = newHistory.length - 1; if (newHistory[lastIdx] && newHistory[lastIdx].role === 'assistant') { newHistory[lastIdx] = { ...newHistory[lastIdx], content: fullContent }; } return newHistory; }); } } }); // 如果启用了思维链,监听思维链事件 if (enableChainOfThought) { const reasoningEvent = `${streamEvent}_reasoning`; console.log(`🧠 监听对话思维链事件: ${reasoningEvent}`); const lastMessageIndex = streamingHistory.length - 1; const unlistenThinking = await listen(reasoningEvent, (event: any) => { if (!thinkingListenerActive) return; console.log(`🧠 对话思维链流内容:`, event.payload); if (event.payload) { if (event.payload.is_complete) { if (event.payload.content && event.payload.content.length >= fullThinkingContent.length) { fullThinkingContent = event.payload.content; } console.log('🎉 对话思维链流完成,总长度:', fullThinkingContent.length); setThinkingContent(prev => new Map(prev).set(lastMessageIndex, fullThinkingContent)); thinkingListenerActive = false; checkAndFinalizeChatStreams(); // 检查是否所有流都完成了 } else if (event.payload.content) { fullThinkingContent += event.payload.content; setThinkingContent(prev => new Map(prev).set(lastMessageIndex, fullThinkingContent)); } } }); } else { thinkingListenerActive = false; checkAndFinalizeChatStreams(); // 如果没有思维链,立即检查 } // 如果启用了RAG,监听对话的RAG来源信息 if (enableRag) { const ragSourcesEvent = `${streamEvent}_rag_sources`; console.log(`📚 监听对话RAG来源事件: ${ragSourcesEvent}`); const unlistenRagSources = await listen(ragSourcesEvent, (event: any) => { console.log(`📚 收到对话RAG来源信息:`, event.payload); if (event.payload && event.payload.sources) { // 更新聊天历史中最后一条助手消息的RAG来源信息 setChatHistory(prev => { const newHistory = [...prev]; const lastIdx = newHistory.length - 1; if (newHistory[lastIdx] && newHistory[lastIdx].role === 'assistant') { newHistory[lastIdx] = { ...newHistory[lastIdx], rag_sources: event.payload.sources }; } return newHistory; }); console.log('✅ 对话RAG来源信息已更新'); } }); } // 调用后端API if (enableRag) { // 使用RAG增强的对话 const ragRequest = { temp_id: analysisResult.temp_id, chat_history: newChatHistory, enable_chain_of_thought: enableChainOfThought, enable_rag: true, rag_options: { top_k: ragTopK, enable_reranking: true } }; await TauriAPI.continueRagEnhancedChatStream(ragRequest); } else { // 使用普通对话 const request = { temp_id: analysisResult.temp_id, chat_history: newChatHistory, enable_chain_of_thought: enableChainOfThought, }; await TauriAPI.continueChatStream(request); } } else { // 传统非流式对话 const request = { temp_id: analysisResult.temp_id, chat_history: newChatHistory, enable_chain_of_thought: enableChainOfThought, }; const response = await continueChat(request); const assistantMessage: ChatMessage = { role: 'assistant', content: response.new_assistant_message, timestamp: new Date().toISOString(), }; setChatHistory([...newChatHistory, assistantMessage]); } } catch (error) { console.error('❌ 对话失败:', error); alert('对话失败: ' + error); setStreamingMessageIndex(null); } finally { setIsChatting(false); } }; // 保存到错题库 const handleSaveToLibrary = async () => { if (!analysisResult) return; try { // 复制聊天历史,并将思维链内容保存到message中 const chatHistoryWithThinking = chatHistory.map((message, index) => { // 如果是assistant消息且有思维链,则添加thinking_content字段 if (message.role === 'assistant' && thinkingContent.has(index)) { return { ...message, thinking_content: thinkingContent.get(index) }; } return message; }); const result = await TauriAPI.saveMistakeFromAnalysis({ temp_id: analysisResult.temp_id, final_chat_history: chatHistoryWithThinking, }); if (result.success) { alert('题目已保存到错题库!'); // 重置分析状态 handleReset(); } else { alert('保存失败,请重试'); } } catch (error) { console.error('保存失败:', error); alert('保存失败: ' + error); } }; // 重置分析 const handleReset = () => { setAnalysisResult(null); setChatHistory([]); setCurrentMessage(''); setStreamingMessageIndex(null); setOcrResult(null); setIsOcrComplete(false); setUserQuestion(''); setQuestionImages([]); setThinkingContent(new Map()); setIsInputAllowed(false); }; // 选择错题 const handleSelectMistake = async (mistake: MistakeItem) => { try { // 🎯 修复:保留MistakeLibrary中转换的图片URLs,但补充聊天记录 console.log('🔍 正在获取错题完整数据:', mistake.id); console.log('🔍 MistakeLibrary传入的数据:', { id: mistake.id, hasQuestionImageUrls: !!mistake.question_image_urls, questionImageUrlsLength: mistake.question_image_urls?.length || 0, hasQuestionImages: mistake.question_images?.length || 0, chatHistoryLength: mistake.chat_history?.length || 0 }); const fullMistakeData = await TauriAPI.getMistakeDetails(mistake.id); if (fullMistakeData) { // 🎯 关键修复:合并数据,保留转换后的图片URLs,并正确处理思维链 const mergedMistake = { ...fullMistakeData, // 如果MistakeLibrary提供了转换后的图片URLs,使用它们 question_image_urls: mistake.question_image_urls || fullMistakeData.question_image_urls || [] }; // 🎯 修复:从聊天历史中恢复思维链数据 const recoveredThinkingContent = new Map<number, string>(); if (mergedMistake.chat_history) { mergedMistake.chat_history.forEach((message, index) => { if (message.role === 'assistant' && message.thinking_content) { console.log(`🧠 [错题加载] 恢复思维链,索引${index}:`, message.thinking_content.substring(0, 50) + '...'); recoveredThinkingContent.set(index, message.thinking_content); } }); } console.log('✅ 获取到完整错题数据并保留图片URLs:', { id: mergedMistake.id, chatHistoryLength: mergedMistake.chat_history?.length || 0, chatHistoryData: mergedMistake.chat_history, hasQuestionImages: mergedMistake.question_images?.length || 0, hasQuestionImageUrls: !!mergedMistake.question_image_urls, questionImageUrlsLength: mergedMistake.question_image_urls?.length || 0, thinkingContentSize: recoveredThinkingContent.size }); // 🎯 修复:将恢复的思维链数据添加到错题对象中 const finalMistake = { ...mergedMistake, thinkingContent: recoveredThinkingContent }; setSelectedMistake(finalMistake); } else { console.warn('⚠️ 未获取到完整数据,使用原始数据'); setSelectedMistake(mistake); } handleViewChange('mistake-detail'); } catch (error) { console.error('❌ 获取错题详情失败:', error); // 如果获取失败,使用原始数据作为fallback setSelectedMistake(mistake); handleViewChange('mistake-detail'); } }; // 更新错题 const handleUpdateMistake = (updatedMistake: MistakeItem) => { setSelectedMistake(updatedMistake); }; // 删除错题 const handleDeleteMistake = (mistakeId: string) => { console.log('删除错题:', mistakeId); setSelectedMistake(null); handleViewChange('library'); }; // 为NEW_MISTAKE_ANALYSIS模式创建API Provider - 使用useCallback缓存 const createAnalysisApiProvider = useCallback((): HostedChatApiProvider => ({ initiateAndGetStreamId: async (params) => { const request = { subject: params.subject!, question_image_files: params.questionImages!, analysis_image_files: [], // 不再使用解析图片 user_question: params.userQuestion!, enable_chain_of_thought: params.enableChainOfThought, }; const stepResult = await TauriAPI.analyzeStepByStep(request); return { streamIdForEvents: stepResult.temp_id, ocrResultData: stepResult.ocr_result, initialMessages: [] }; }, startMainStreaming: async (params) => { if (params.enableRag) { await TauriAPI.startRagEnhancedStreamingAnswer({ temp_id: params.streamIdForEvents, enable_chain_of_thought: params.enableChainOfThought, enable_rag: true, rag_options: { top_k: params.ragTopK, enable_reranking: true } }); } else { await TauriAPI.startStreamingAnswer(params.streamIdForEvents, params.enableChainOfThought); } }, continueUserChat: async (params) => { if (params.enableRag) { const ragRequest = { temp_id: params.streamIdForEvents, chat_history: params.fullChatHistory, enable_chain_of_thought: params.enableChainOfThought, enable_rag: true, rag_options: { top_k: params.ragTopK, enable_reranking: true } }; await TauriAPI.continueRagEnhancedChatStream(ragRequest); } else { const request = { temp_id: params.streamIdForEvents, chat_history: params.fullChatHistory, enable_chain_of_thought: params.enableChainOfThought, }; await TauriAPI.continueChatStream(request); } } }), []); // 空依赖数组,因为这个provider不依赖任何状态 // 渲染侧边栏导航 - 现代化风格 const renderSidebar = () => ( <ModernSidebar currentView={currentView} onViewChange={handleViewChange} sidebarCollapsed={sidebarCollapsed} onToggleSidebar={() => setSidebarCollapsed(!sidebarCollapsed)} batchAnalysisEnabled={batchAnalysisEnabled} geminiAdapterTestEnabled={geminiAdapterTestEnabled} imageOcclusionEnabled={imageOcclusionEnabled} startDragging={startDragging} /> ); // 使用useMemo缓存hostProps,避免每次渲染都创建新对象 const analysisHostProps = useMemo((): UniversalAppChatHostProps => ({ mode: 'NEW_MISTAKE_ANALYSIS', businessSessionId: analysisSessionId, preloadedData: { subject, userQuestion, questionImages, // 不需要预加载其他数据,因为是新分析 }, serviceConfig: { apiProvider: createAnalysisApiProvider(), streamEventNames: { initialStream: (id) => ({ data: `analysis_stream_${id}`, reasoning: `analysis_stream_${id}_reasoning`, ragSources: `analysis_stream_${id}_rag_sources` }), continuationStream: (id) => ({ data: `continue_chat_stream_${id}`, reasoning: `continue_chat_stream_${id}_reasoning`, ragSources: `continue_chat_stream_${id}_rag_sources` }), }, defaultEnableChainOfThought: true, defaultEnableRag: enableRag, defaultRagTopK: ragTopK, defaultSelectedLibraries: selectedLibraries, }, onSaveRequest: async (data) => { // 实现原App.tsx中的保存逻辑 try { console.log('🔍 App.tsx保存请求:', data); console.log('📊 analysisResult:', analysisResult); // 优先使用直接传递的temp_id let temp_id = null; if (data.temp_id) { temp_id = data.temp_id; console.log('✅ 从data.temp_id获取temp_id:', temp_id); } else if (analysisResult?.temp_id) { temp_id = analysisResult.temp_id; console.log('✅ 从analysisResult获取temp_id:', temp_id); } else if (data.ocrResult?.temp_id) { temp_id = data.ocrResult.temp_id; console.log('✅ 从data.ocrResult获取temp_id:', temp_id); } else { // 如果都没有,使用businessSessionId作为fallback temp_id = data.businessSessionId; console.log('⚠️ 使用businessSessionId作为fallback temp_id:', temp_id); } // 验证数据有效性 if (!temp_id) { throw new Error('无法获取有效的temp_id,无法保存'); } if (!data.chatHistory || data.chatHistory.length === 0) { throw new Error('聊天历史为空,无法保存'); } console.log('🆔 最终使用的temp_id:', temp_id); console.log('📜 保存的聊天历史数量:', data.chatHistory.length); console.log('📝 聊天历史详情:', data.chatHistory); const result = await TauriAPI.saveMistakeFromAnalysis({ temp_id: temp_id, final_chat_history: data.chatHistory, }); if (result.success) { alert('题目已保存到错题库!'); // 🎯 优先处理前端传递的总结内容 if (data.summaryContent && result.final_mistake_item) { try { console.log('📝 保存前端生成的总结内容到数据库...'); // 🎯 修复:改进解析逻辑,保持原始格式 const parseSummaryContent = (content: string) => { console.log('📄 [总结解析] 原始内容长度:', content.length); console.log('📄 [总结解析] 原始内容预览:', content.substring(0, 200) + '...'); // 🎯 策略1:如果内容较短或者没有明显的分段标识,保存到第一个字段 const lines = content.split('\n'); const hasNumberedSections = lines.some(line => /^\s*\d+\.\s*(核心知识点|错误分析|学习建议)/.test(line)); const hasMarkdownSections = lines.some(line => /^#+\s*(核心知识点|错误分析|学习建议)/.test(line)); if (!hasNumberedSections && !hasMarkdownSections) { console.log('📄 [总结解析] 无明确分段,保存到mistake_summary'); return { mistakeSummary: content.trim(), userErrorAnalysis: null, }; } // 🎯 策略2:尝试分段,但保持更完整的内容 let mistakeSummary = ''; let userErrorAnalysis = ''; let currentSection = ''; let includeCurrentLine = false; for (const line of lines) { const trimmedLine = line.trim(); // 检测章节标题 if (/^\s*\d+\.\s*核心知识点|^#+\s*核心知识点|题目解析|正确解法/.test(trimmedLine)) { currentSection = 'mistake_summary'; includeCurrentLine = true; } else if (/^\s*\d+\.\s*错误分析|^#+\s*错误分析|^\s*\d+\.\s*学习建议|^#+\s*学习建议|薄弱环节/.test(trimmedLine)) { currentSection = 'user_error_analysis'; includeCurrentLine = true; } else { includeCurrentLine = true; } if (includeCurrentLine) { if (currentSection === 'mistake_summary') { mistakeSummary += line + '\n'; } else if (currentSection === 'user_error_analysis') { userErrorAnalysis += line + '\n'; } else if (!currentSection) { // 如果还没有检测到分段,先放到第一个字段 mistakeSummary += line + '\n'; } } } // 🎯 策略3:如果分段后某个字段为空,将所有内容保存到第一个字段 if (!mistakeSummary.trim() && !userErrorAnalysis.trim()) { console.log('📄 [总结解析] 分段失败,保存完整内容到mistake_summary'); return { mistakeSummary: content.trim(), userErrorAnalysis: null, }; } console.log('📄 [总结解析] 分段结果:', { mistakeSummaryLength: mistakeSummary.trim().length, userErrorAnalysisLength: userErrorAnalysis.trim().length }); return { mistakeSummary: mistakeSummary.trim() || null, userErrorAnalysis: userErrorAnalysis.trim() || null, }; }; const { mistakeSummary, userErrorAnalysis } = parseSummaryContent(data.summaryContent); // 更新错题记录,添加总结字段 const updatedMistake = { ...result.final_mistake_item, mistake_summary: mistakeSummary, user_error_analysis: userErrorAnalysis, status: "completed", // 🎯 修复:设置状态为已完成 updated_at: new Date().toISOString(), }; await TauriAPI.updateMistake(updatedMistake); console.log('✅ 前端总结内容已成功保存到数据库'); } catch (error) { console.error('保存前端总结内容失败:', error); alert(`⚠️ 总结保存失败:${error}\n错题已保存,可稍后手动生成总结。`); } } } else { alert('保存失败,请重试'); } } catch (error) { console.error('保存失败:', error); alert('保存失败: ' + error); } }, }), [analysisSessionId, subject, userQuestion, questionImages, enableRag, ragTopK, selectedLibraries, analysisResult]); // 缓存回调函数 const handleCoreStateUpdate = useCallback((data: any) => { // 仅在开发环境打印状态更新信息,避免生产环境噪音 if (import.meta.env.DEV) { console.log('🔄 UniversalAppChatHost state update:', { sessionId: analysisSessionId, chatHistoryLength: data.chatHistory.length, thinkingContentSize: data.thinkingContent.size, hasOcrResult: !!data.ocrResult, isAnalyzing: data.isAnalyzing, isChatting: data.isChatting }); } }, [analysisSessionId]); const handleSaveRequest = useCallback(async (data: any) => { // 实现原App.tsx中的保存逻辑 try { console.log('🔍 App.tsx保存请求:', data); console.log('📊 analysisResult:', analysisResult); // 优先使用直接传递的temp_id let temp_id = null; if (data.temp_id) { temp_id = data.temp_id; console.log('✅ 从data.temp_id获取temp_id:', temp_id); } else if (analysisResult?.temp_id) { temp_id = analysisResult.temp_id; console.log('✅ 从analysisResult获取temp_id:', temp_id); } else if (data.ocrResult?.temp_id) { temp_id = data.ocrResult.temp_id; console.log('✅ 从data.ocrResult获取temp_id:', temp_id); } else { // 如果都没有,使用businessSessionId作为fallback temp_id = data.businessSessionId; console.log('⚠️ 使用businessSessionId作为fallback temp_id:', temp_id); } // 验证数据有效性 if (!temp_id) { throw new Error('无法获取有效的temp_id,无法保存'); } if (!data.chatHistory || data.chatHistory.length === 0) { throw new Error('聊天历史为空,无法保存'); } console.log('🆔 最终使用的temp_id:', temp_id); console.log('📜 保存的聊天历史数量:', data.chatHistory.length); console.log('📝 聊天历史详情:', data.chatHistory); const result = await TauriAPI.saveMistakeFromAnalysis({ temp_id: temp_id, final_chat_history: data.chatHistory, }); if (result.success) { alert('题目已保存到错题库!'); // 🎯 优先处理前端传递的总结内容 if (data.summaryContent && result.final_mistake_item) { try { console.log('📝 保存前端生成的总结内容到数据库...'); // 🎯 修复:改进解析逻辑,保持原始格式 const parseSummaryContent = (content: string) => { console.log('📄 [总结解析] 原始内容长度:', content.length); console.log('📄 [总结解析] 原始内容预览:', content.substring(0, 200) + '...'); // 🎯 策略1:如果内容较短或者没有明显的分段标识,保存到第一个字段 const lines = content.split('\n'); const hasNumberedSections = lines.some(line => /^\s*\d+\.\s*(核心知识点|错误分析|学习建议)/.test(line)); const hasMarkdownSections = lines.some(line => /^#+\s*(核心知识点|错误分析|学习建议)/.test(line)); if (!hasNumberedSections && !hasMarkdownSections) { console.log('📄 [总结解析] 无明确分段,保存到mistake_summary'); return { mistakeSummary: content.trim(), userErrorAnalysis: null, }; } // 🎯 策略2:尝试分段,但保持更完整的内容 let mistakeSummary = ''; let userErrorAnalysis = ''; let currentSection = ''; let includeCurrentLine = false; for (const line of lines) { const trimmedLine = line.trim(); // 检测章节标题 if (/^\s*\d+\.\s*核心知识点|^#+\s*核心知识点|题目解析|正确解法/.test(trimmedLine)) { currentSection = 'mistake_summary'; includeCurrentLine = true; } else if (/^\s*\d+\.\s*错误分析|^#+\s*错误分析|^\s*\d+\.\s*学习建议|^#+\s*学习建议|薄弱环节/.test(trimmedLine)) { currentSection = 'user_error_analysis'; includeCurrentLine = true; } else { includeCurrentLine = true; } if (includeCurrentLine) { if (currentSection === 'mistake_summary') { mistakeSummary += line + '\n'; } else if (currentSection === 'user_error_analysis') { userErrorAnalysis += line + '\n'; } else if (!currentSection) { // 如果还没有检测到分段,先放到第一个字段 mistakeSummary += line + '\n'; } } } // 🎯 策略3:如果分段后某个字段为空,将所有内容保存到第一个字段 if (!mistakeSummary.trim() && !userErrorAnalysis.trim()) { console.log('📄 [总结解析] 分段失败,保存完整内容到mistake_summary'); return { mistakeSummary: content.trim(), userErrorAnalysis: null, }; } console.log('📄 [总结解析] 分段结果:', { mistakeSummaryLength: mistakeSummary.trim().length, userErrorAnalysisLength: userErrorAnalysis.trim().length }); return { mistakeSummary: mistakeSummary.trim() || null, userErrorAnalysis: userErrorAnalysis.trim() || null, }; }; const { mistakeSummary, userErrorAnalysis } = parseSummaryContent(data.summaryContent); // 更新错题记录,添加总结字段 const updatedMistake = { ...result.final_mistake_item, mistake_summary: mistakeSummary, user_error_analysis: userErrorAnalysis, status: "completed", // 🎯 修复:设置状态为已完成 updated_at: new Date().toISOString(), }; await TauriAPI.updateMistake(updatedMistake); console.log('✅ 前端总结内容已成功保存到数据库'); } catch (error) { console.error('保存前端总结内容失败:', error); alert(`⚠️ 总结保存失败:${error}\n错题已保存,可稍后手动生成总结。`); } } } else { alert('保存失败,请重试'); } } catch (error) { console.error('保存失败:', error); alert('保存失败: ' + error); } }, [analysisResult]); // 渲染分析界面 - 左右分栏布局 const renderAnalysisView = () => { return <UniversalAppChatHost key="analysis-host" {...analysisHostProps} onCoreStateUpdate={handleCoreStateUpdate} onSaveRequest={handleSaveRequest} />; }; return ( <SubjectProvider> <div className="app" style={{ '--sidebar-width': sidebarCollapsed ? '60px' : '240px' } as React.CSSProperties} > <WindowControls /> <div className="app-body"> {renderSidebar()} <main className="app-content"> <div className="content-header" onMouseDown={startDragging}> <div className="content-header-left"> <button className="sidebar-toggle" onClick={() => setSidebarCollapsed(!sidebarCollapsed)} onMouseDown={(e) => e.stopPropagation()} title={sidebarCollapsed ? '展开侧边栏' : '收起侧边栏'} > <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"> {sidebarCollapsed ? ( // 展开图标 (chevron-right) <polyline points="9,18 15,12 9,6"></polyline> ) : ( // 收起图标 (chevron-left) <polyline points="15,18 9,12 15,6"></polyline> )} </svg> </button> {/* 全局科目选择器 */} <UnifiedSubjectSelector mode="enabled" className="header-subject-selector compact" /> </div> </div> <div className="content-body"> {/* 分析页面组件始终挂载,只是控制显示/隐藏 - 实现保活机制 */} <div className="page-container" style={{ display: currentView === 'analysis' ? 'block' : 'none' }}> {(() => { console.log('🔄 [保活检查] 分析页面容器渲染,当前视图:', currentView, '显示状态:', currentView === 'analysis' ? 'block' : 'none'); return renderAnalysisView(); })()} </div> {/* 批量分析组件始终挂载,只是控制显示/隐藏 */} <div className="page-container" style={{ display: currentView === 'batch' ? 'block' : 'none' }}> <BatchAnalysis onBack={() => setCurrentView('analysis')} /> </div> {/* 🎯 修复:错题库组件每次切换时重新加载数据,不再保活 */} <div className="page-container" style={{ display: currentView === 'library' ? 'block' : 'none' }}> <MistakeLibrary onSelectMistake={handleSelectMistake} onBack={() => handleViewChange('analysis')} refreshTrigger={libraryRefreshTrigger} /> </div> {/* DEPRECATED: 单次回顾视图已废弃 - 2024年6月5日 该功能已被统一回顾模块替代 */} {/* {currentView === 'review' && ( <ReviewAnalysis onBack={() => setCurrentView('analysis')} /> )} */} {/* 统一回顾分析组件始终挂载,只是控制显示/隐藏 - 实现保活机制 */} <div className="page-container" style={{ display: currentView === 'unified-review' ? 'block' : 'none' }}> <ReviewAnalysisDashboard onCreateNew={() => setCurrentView('create-review')} onViewSession={(sessionId: string) => { setCurrentReviewSessionId(sessionId); setCurrentView('review-session'); }} /> </div> {/* 创建回顾分析组件始终挂载,只是控制显示/隐藏 - 实现保活机制 */} <div className="page-container" style={{ display: currentView === 'create-review' ? 'block' : 'none' }}> <CreateReviewAnalysisView onCancel={() => setCurrentView('unified-review')} onCreateSuccess={(sessionId: string) => { console.log('📍 App.tsx收到创建成功回调, sessionId:', sessionId); console.log('📍 App.tsx当前状态: currentView=', currentView, ', currentReviewSessionId=', currentReviewSessionId); setCurrentReviewSessionId(sessionId); setCurrentView('review-session'); console.log('📍 App.tsx状态更新后: currentView=review-session, currentReviewSessionId=', sessionId); // 确保状态更新后的下一个渲染周期能看到正确的组件 setTimeout(() => { console.log('📍 验证状态更新: currentView=', currentView, ', currentReviewSessionId=', currentReviewSessionId); }, 100); }} /> </div> {/* 回顾分析会话组件始终挂载,只是控制显示/隐藏 - 实现保活机制 */} <div className="page-container" style={{ display: currentView === 'review-session' ? 'block' : 'none' }}> {currentReviewSessionId && (() => { console.log('📍 正在渲染ReviewAnalysisSessionView, sessionId:', currentReviewSessionId); return ( <ReviewAnalysisSessionView sessionId={currentReviewSessionId} onBack={() => { console.log('📍 回到统一回顾页面'); setCurrentView('unified-review'); }} /> ); })()} </div> {/* DEPRECATED: 分析库组件已废弃 - 2024年6月8日,功能被统一回顾分析替代 */} {/* {currentView === 'review-library' && ( <ReviewAnalysisLibrary onSelectAnalysis={(analysis) => { setCurrentReviewSessionId(analysis.id); setCurrentView('review-session'); }} onBack={() => setCurrentView('unified-review')} /> )} */} {/* 数据统计组件始终挂载,只是控制显示/隐藏 - 实现保活机制 */} <div className="page-container" style={{ display: currentView === 'dashboard' ? 'block' : 'none' }}> <Dashboard onBack={() => setCurrentView('analysis')} /> </div> {/* 设置组件始终挂载,只是控制显示/隐藏 - 实现保活机制 */} <div className="page-container" style={{ display: currentView === 'settings' ? 'block' : 'none' }}> <Settings onBack={() => setCurrentView('analysis')} /> </div> {/* 错题详情组件始终挂载,只是控制显示/隐藏 - 实现保活机制 */} <div className="page-container" style={{ display: currentView === 'mistake-detail' ? 'block' : 'none' }}> {selectedMistake && (() => { // 调试日志:检查传递给UniversalAppChatHost的数据 console.log('🔍 App.tsx 传递给 UniversalAppChatHost 的错题数据:', { mistakeId: selectedMistake.id, chatHistoryLength: selectedMistake.chat_history?.length || 0, chatHistoryExists: !!selectedMistake.chat_history, chatHistoryData: selectedMistake.chat_history, questionImageUrls: selectedMistake.question_image_urls || [], questionImageUrlsExists: !!selectedMistake.question_image_urls, questionImageUrlsLength: selectedMistake.question_image_urls?.length || 0, questionImagesOriginal: selectedMistake.question_images || [], questionImageUrlsPreview: selectedMistake.question_image_urls?.map((url, i) => `${i+1}: ${url.substring(0, 50)}...`) || [], ocrText: selectedMistake.ocr_text?.substring(0, 100) + '...', }); console.log('🔍 App.tsx selectedMistake 完整对象检查:', { hasQuestionImageUrls: 'question_image_urls' in selectedMistake, questionImageUrlsValue: selectedMistake.question_image_urls, questionImageUrlsType: typeof selectedMistake.question_image_urls, allKeys: Object.keys(selectedMistake), mistakeId: selectedMistake.id }); return ( <UniversalAppChatHost mode="EXISTING_MISTAKE_DETAIL" businessSessionId={selectedMistake.id} preloadedData={{ subject: selectedMistake.subject, userQuestion: selectedMistake.user_question, questionImageUrls: selectedMistake.question_image_urls || [], ocrText: selectedMistake.ocr_text, tags: selectedMistake.tags || [], chatHistory: selectedMistake.chat_history || [], thinkingContent: (selectedMistake as any).thinkingContent || new Map(), // 🎯 修复:传递恢复的思维链数据 mistake_summary: selectedMistake.mistake_summary, // 错题总结 user_error_analysis: selectedMistake.user_error_analysis, // 用户错误分析 originalMistake: selectedMistake // 完整的原始错题对象 }} serviceConfig={{ apiProvider: { initiateAndGetStreamId: async (params) => ({ streamIdForEvents: params.businessId!, ocrResultData: { ocr_text: selectedMistake.ocr_text, tags: selectedMistake.tags || [], mistake_type: selectedMistake.mistake_type || '错题分析' }, initialMessages: selectedMistake.chat_history || [] }), startMainStreaming: async () => {}, // 错题详情不需要启动新的主流 continueUserChat: async (params) => { await TauriAPI.continueMistakeChatStream({ mistakeId: params.businessId, chatHistory: params.fullChatHistory, enableChainOfThought: params.enableChainOfThought }); } }, streamEventNames: { initialStream: (id) => ({ data: `mistake_chat_stream_${id}`, reasoning: `mistake_chat_stream_${id}_reasoning`, ragSources: `mistake_chat_stream_${id}_rag_sources` }), continuationStream: (id) => ({ data: `mistake_chat_stream_${id}`, reasoning: `mistake_chat_stream_${id}_reasoning`, ragSources: `mistake_chat_stream_${id}_rag_sources` }), }, defaultEnableChainOfThought: true, defaultEnableRag: enableRag, defaultRagTopK: ragTopK, defaultSelectedLibraries: selectedLibraries, }} onCoreStateUpdate={(data) => { // 减少控制台噪音 if (import.meta.env.DEV) { console.log('🔄 错题详情状态更新:', { chatHistoryLength: data.chatHistory.length, thinkingContentSize: data.thinkingContent.size }); } }} onSaveRequest={async (data) => { try { // 🎯 如果有总结内容,解析并更新 let updatedMistake = { ...selectedMistake, chat_history: data.chatHistory }; if (data.summaryContent) { console.log('📝 [App] 处理总结内容更新...'); // 🎯 修复:改进解析逻辑,保持原始格式 const parseSummaryContent = (content: string) => { console.log('📄 [总结解析] 原始内容长度:', content.length); console.log('📄 [总结解析] 原始内容预览:', content.substring(0, 200) + '...'); // 🎯 策略1:如果内容较短或者没有明显的分段标识,保存到第一个字段 const lines = content.split('\n'); const hasNumberedSections = lines.some(line => /^\s*\d+\.\s*(核心知识点|错误分析|学习建议)/.test(line)); const hasMarkdownSections = lines.some(line => /^#+\s*(核心知识点|错误分析|学习建议)/.test(line)); if (!hasNumberedSections && !hasMarkdownSections) { console.log('📄 [总结解析] 无明确分段,保存到mistake_summary'); return { mistakeSummary: content.trim(), userErrorAnalysis: null, }; } // 🎯 策略2:尝试分段,但保持更完整的内容 let mistakeSummary = ''; let userErrorAnalysis = ''; let currentSection = ''; let includeCurrentLine = false; for (const line of lines) { const trimmedLine = line.trim(); // 检测章节标题 if (/^\s*\d+\.\s*核心知识点|^#+\s*核心知识点|题目解析|正确解法/.test(trimmedLine)) { currentSection = 'mistake_summary'; includeCurrentLine = true; } else if (/^\s*\d+\.\s*错误分析|^#+\s*错误分析|^\s*\d+\.\s*学习建议|^#+\s*学习建议|薄弱环节/.test(trimmedLine)) { currentSection = 'user_error_analysis'; includeCurrentLine = true; } else { includeCurrentLine = true; } if (includeCurrentLine) { if (currentSection === 'mistake_summary') { mistakeSummary += line + '\n'; } else if (currentSection === 'user_error_analysis') { userErrorAnalysis += line + '\n'; } else if (!currentSection) { // 如果还没有检测到分段,先放到第一个字段 mistakeSummary += line + '\n'; } } } // 🎯 策略3:如果分段后某个字段为空,将所有内容保存到第一个字段 if (!mistakeSummary.trim() && !userErrorAnalysis.trim()) { console.log('📄 [总结解析] 分段失败,保存完整内容到mistake_summary'); return { mistakeSummary: content.trim(), userErrorAnalysis: null, }; } console.log('📄 [总结解析] 分段结果:', { mistakeSummaryLength: mistakeSummary.trim().length, userErrorAnalysisLength: userErrorAnalysis.trim().length }); return { mistakeSummary: mistakeSummary.trim() || null, userErrorAnalysis: userErrorAnalysis.trim() || null, }; }; const { mistakeSummary, userErrorAnalysis } = parseSummaryContent(data.summaryContent); updatedMistake = { ...updatedMistake, mistake_summary: mistakeSummary, user_error_analysis: userErrorAnalysis, status: "completed", // 🎯 修复:设置状态为已完成 updated_at: new Date().toISOString() }; console.log('📝 [App] 总结内容已加入更新数据'); } await TauriAPI.updateMistake(updatedMistake); // 🎯 更新本地状态 - 确保 selectedMistake 包含最新的总结内容 handleUpdateMistake(updatedMistake); setSelectedMistake(updatedMistake); // 重要:直接更新 selectedMistake console.log('✅ [App] 错题状态已更新,包含总结内容'); alert('错题已更新!'); } catch (error) { console.error('更新失败:', error); alert('更新失败: ' + error); } }} onExitRequest={() => setCurrentView('library')} /> ); })()} </div> {/* ANKI制卡组件始终挂载,只是控制显示/隐藏 */} <div className="page-container" style={{ display: currentView === 'anki-generation' ? 'block' : 'none' }}> <AnkiCardGeneration onTemplateSelectionRequest={handleTemplateSelectionRequest} /> </div> {/* RAG知识库管理组件始终挂载,只是控制显示/隐藏 - 实现保活机制 */} <div className="page-container" style={{ display: currentView === 'knowledge-base' ? 'block' : 'none' }}> <EnhancedKnowledgeBaseManagement /> </div> {/* RAG智能查询组件始终挂载,只是控制显示/隐藏 - 实现保活机制 */} <div className="page-container" style={{ display: currentView === 'rag-query' ? 'block' : 'none' }}> <EnhancedRagQueryView /> </div> {/* 数据管理组件始终挂载,只是控制显示/隐藏 - 实现保活机制 */} <div className="page-container" style={{ display: currentView === 'data-management' ? 'block' : 'none' }}> <DataImportExport /> </div> {/* 图片遮罩卡组件始终挂载,只是控制显示/隐藏 - 实现保活机制 */} <div className="page-container" style={{ display: currentView === 'image-occlusion' ? 'block' : 'none' }}> <ImageOcclusion /> </div> {/* 模板管理页面 */} <div className="page-container" style={{ display: currentView === 'template-management' ? 'block' : 'none' }}> <TemplateManagementPage isSelectingMode={isSelectingTemplate} onTemplateSelected={handleTemplateSelected} onCancel={handleTemplateSelectionCancel} /> </div> {/* Gemini适配器测试页面 */} <div className="page-container" style={{ display: currentView === 'gemini-adapter-test' ? 'block' : 'none' }}> <GeminiAdapterTest /> </div> {/* CogniGraph知识图谱管理页面 */} <div className="page-container" style={{ display: currentView === 'cogni-graph' ? 'block' : 'none' }}> <KnowledgeGraphManagement /> </div> </div> </main> {/* 图片查看器 */} <ImageViewer images={questionImageUrls} currentIndex={currentImageIndex} isOpen={imageViewerOpen} onClose={() => setImageViewerOpen(false)} onNext={() => setCurrentImageIndex(prev => (prev + 1) % questionImageUrls.length)} onPrev={() => setCurrentImageIndex(prev => (prev - 1 + questionImageUrls.length) % questionImageUrls.length)} /> </div> </div> </SubjectProvider> ); } export default App;
70,864
App
tsx
en
tsx
code
{"qsc_code_num_words": 5043, "qsc_code_num_chars": 70864.0, "qsc_code_mean_word_length": 7.66607178, "qsc_code_frac_words_unique": 0.18857823, "qsc_code_frac_chars_top_2grams": 0.02638386, "qsc_code_frac_chars_top_3grams": 0.00982928, "qsc_code_frac_chars_top_4grams": 0.01099327, "qsc_code_frac_chars_dupe_5grams": 0.44097258, "qsc_code_frac_chars_dupe_6grams": 0.39229177, "qsc_code_frac_chars_dupe_7grams": 0.3691671, "qsc_code_frac_chars_dupe_8grams": 0.35600103, "qsc_code_frac_chars_dupe_9grams": 0.33608381, "qsc_code_frac_chars_dupe_10grams": 0.32578893, "qsc_code_frac_chars_replacement_symbols": 0.0, "qsc_code_frac_chars_digital": 0.00334251, "qsc_code_frac_chars_whitespace": 0.32872827, "qsc_code_size_file_byte": 70864.0, "qsc_code_num_lines": 1867.0, "qsc_code_num_chars_line_max": 359.0, "qsc_code_num_chars_line_mean": 37.95607927, "qsc_code_frac_chars_alphabet": 0.80634447, "qsc_code_frac_chars_comments": 0.06732615, "qsc_code_cate_xml_start": 0.0, "qsc_code_frac_lines_dupe_lines": 0.5212766, "qsc_code_cate_autogen": 0.0, "qsc_code_frac_lines_long_string": 0.0, "qsc_code_frac_chars_string_length": 0.0776179, "qsc_code_frac_chars_long_word_length": 0.02268016, "qsc_code_frac_lines_string_concat": 0.0, "qsc_code_cate_encoded_data": 0.0, "qsc_code_frac_chars_hex_words": 0.0, "qsc_code_frac_lines_prompt_comments": 0.0, "qsc_code_frac_lines_assert": 0.0}
1
{"qsc_code_frac_chars_replacement_symbols": 0, "qsc_code_num_words": 0, "qsc_code_num_chars": 0, "qsc_code_mean_word_length": 0, "qsc_code_frac_chars_top_2grams": 0, "qsc_code_frac_chars_top_3grams": 0, "qsc_code_frac_chars_top_4grams": 0, "qsc_code_frac_chars_dupe_5grams": 0, "qsc_code_frac_chars_dupe_6grams": 0, "qsc_code_frac_chars_dupe_7grams": 0, "qsc_code_frac_chars_dupe_8grams": 0, "qsc_code_frac_chars_dupe_9grams": 0, "qsc_code_frac_chars_dupe_10grams": 0, "qsc_code_frac_lines_dupe_lines": 0, "qsc_code_size_file_byte": 0, "qsc_code_num_lines": 0, "qsc_code_num_chars_line_max": 0, "qsc_code_num_chars_line_mean": 0, "qsc_code_frac_chars_alphabet": 0, "qsc_code_frac_chars_digital": 0, "qsc_code_frac_chars_whitespace": 0, "qsc_code_frac_chars_comments": 0, "qsc_code_cate_xml_start": 0, "qsc_code_cate_autogen": 0, "qsc_code_frac_lines_long_string": 0, "qsc_code_frac_chars_string_length": 0, "qsc_code_frac_chars_long_word_length": 0, "qsc_code_cate_encoded_data": 0, "qsc_code_frac_chars_hex_words": 0, "qsc_code_frac_lines_prompt_comments": 0, "qsc_code_frac_lines_assert": 0}
000haoji/deep-student
ds-graph/1.md
个性化知识网络系统:最终设计报告 (Neo4j版) 项目代号: Project CogniGraph 版本: 9.0 (Final - Neo4j Architecture) 日期: 2025年6月17日 核心: 一个以Neo4j为统一知识库,融合了多模态输入、AI推荐和高级检索的智能学习系统。 1. 绪论 (Introduction) 1.1 项目愿景与目标 构建一个智能的学习伴侣,将用户在解题过程中的思考(疑问、灵感、方法)结构化、网络化,并通过AI赋能,实现知识的智能检索、主动关联与深度洞察。 1.2 设计哲学与原则 极简核心,智慧涌现: 采用最简化的基础设施(单体Rust后端 + 单一Neo4j数据库),通过设计精良的数据模型和可配置的复杂算法,实现强大的涌现智能。 开发者体验优先: 选择Neo4j,因其拥有极其友好的本地开发工具(Neo4j Desktop)和无缝的云端迁移路径(AuraDB),最大化开发效率。 AI驱动的自动化: 系统的核心价值在于利用AI自动完成知识的组织、链接和推荐,将用户从繁琐的手动整理中解放出来。 开放与集成: 拥抱Obsidian等开放平台,通过插件和工作流集成,融入用户已有的学习习惯。 2. 系统总体架构 (Overall System Architecture) 2.1 架构图 Code snippet graph TD subgraph A [用户前端 (Obsidian + 自研插件)] A1[UI / Excalidraw手写] -- 1. 触发操作 --> A2[插件逻辑 (TypeScript)] end A2 -- 2. REST API 请求 --> B[云端Rust后端API (Axum)] subgraph C [云端服务] B -- 3. Cypher查询 --> D[Neo4j数据库 (AuraDB)] B -- 4. API调用 --> E[外部AI API (OpenAI, Mathpix)] end 2.2 技术选型与理由 组件 技术选型 理由 后端语言 Rust 高性能、高安全性,确保API服务稳定可靠。 Web框架 Axum 与Tokio生态无缝集成,现代且高效。 图数据库 Neo4j (云端部署于AuraDB) 最佳综合选择:强大的Cypher查询、成熟的向量索引、一流的开发工具和无缝的免费云端部署路径。 前端平台 Obsidian (通过插件) 成熟的笔记平台,本地优先,高度可扩展,完美承载我们的系统。 手写识别 Mathpix API 业界领先的数学OCR服务,能将手写公式精准转换为LaTeX。 Export to Sheets 3. Neo4j图数据模型设计 3.1 节点标签与属性 (Node Labels & Properties) (:ProblemCard) id: String (UUID,主键) content_problem: String (题干原文) content_insight: String (核心灵感/解法) status: String ('unsolved', 'solved') embedding: Vector<Float> (由题干和灵感拼接后生成的向量) created_at, last_accessed_at: Datetime access_count: Integer source_excalidraw_path: String (可选,链接回原始手写草稿文件) (:Tag) name: String (标签名,如“定积分”,主键) type: String (标签类型,如knowledge_point, method) 3.2 关系类型 (Relationship Types) (:ProblemCard) -[:HAS_TAG]-> (:Tag) (:ProblemCard) -[:IS_VARIATION_OF]-> (:ProblemCard) (:ProblemCard) -[:USES_GENERAL_METHOD]-> (:ProblemCard) (:ProblemCard) -[:CONTRASTS_WITH]-> (:ProblemCard) 3.3 索引策略 (Cypher) Cypher // 确保ID和标签名的唯一性,并提供快速查找 CREATE CONSTRAINT pc_id FOR (n:ProblemCard) REQUIRE n.id IS UNIQUE; CREATE CONSTRAINT tag_name FOR (n:Tag) REQUIRE n.name IS UNIQUE; // 创建全文索引,用于关键词召回 CREATE FULLTEXT INDEX problem_card_content FOR (n:ProblemCard) ON (n.content_problem, n.content_insight); // 创建向量索引,用于语义搜索 CREATE VECTOR INDEX problem_card_embedding FOR (n:ProblemCard) ON (n.embedding) OPTIONS { indexConfig: { `vector.dimensions`: 1536, `vector.similarity_function`: 'cosine' }}; 4. 核心工作流与Cypher实现 4.1 手写知识输入流程 [Obsidian] 用户在Excalidraw画布上完成手写推导,圈选灵感区域,点击“解析入库”。 [Plugin] 插件将选中区域导出为图片,调用Mathpix API进行OCR。 [Plugin] 插件将识别出的LaTeX和文本,连同题干等信息,打包发送到 POST /api/cards。 [Rust Backend] a. 调用Embedding API生成向量。 b. 执行一条原子性的Cypher查询来创建节点和关系: Cypher // $props是包含所有属性的参数,$tags_list是标签名列表 // 1. 创建ProblemCard节点 CREATE (pc:ProblemCard) SET pc = $props // 2. 对于每个标签,如果不存在则创建,然后建立关系 WITH pc UNWIND $tags_list AS tag_name MERGE (t:Tag {name: tag_name}) CREATE (pc)-[:HAS_TAG]->(t) RETURN pc.id; [Rust Backend] 异步触发AI关系推荐流程。 4.2 多路召回与融合排序流程 [Rust Backend] 接收到 GET /api/search 请求。 并行执行召回查询: 向量召回: Cypher CALL db.index.vector.queryNodes('problem_card_embedding', 100, $query_vector) YIELD node, score RETURN node.id, score; 全文检索召回: Cypher CALL db.index.fulltext.queryNodes('problem_card_content', $query_string, {limit: 100}) YIELD node, score RETURN node.id, score; [Rust Backend] 在Rust代码中: a. 融合:将两路召回的ID合并去重。 b. 获取完整数据:用融合后的ID列表向Neo4j查询完整的节点属性。 c. 重排序:应用config.toml中定义的权重公式,计算每个卡片的最终得分并排序。 [API] 返回最终排序后的结果列表。 4.3 AI关系推荐流程 [Rust Backend] 在新卡片C_new创建后触发。 [Rust Backend] 执行一次轻量级的多路召回,找到最相关的候选卡片C_candidate。 [Rust Backend] 执行一条Cypher查询,评估C_candidate的“价值”(例如,它的关系数量和访问次数)。 Cypher MATCH (c:ProblemCard {id: $candidate_id}) OPTIONAL MATCH (c)-[r]-() RETURN c.access_count, count(r) AS degree; [Rust Backend] 在代码中根据评分和价值,决定是否生成推荐。 [API] 如果生成推荐,则通过WebSocket或HTTP轮询通知前端。 5. 开发到部署的“无墙”路径 本地开发: 下载并安装 Neo4j Desktop。 一键创建本地数据库实例。 在config.toml中配置本地数据库地址 (bolt://localhost:7687)。 安心开发和调试您的Rust后端与Obsidian插件。 云端部署: 前往 Neo4j AuraDB 官网,注册并创建一个免费的云端数据库实例。 将您的Rust后端服务打包成Docker镜像,部署到任意云平台(如 Vultr, DigitalOcean, Fly.io, AWS等)。 唯一需要修改的,是config.toml中的数据库连接信息,将其指向您的AuraDB实例地址。 您的应用就此全球可访问,且具备了高可用、自动备份等企业级特性。 未来扩展: 当您的知识库规模超过AuraDB免费版限制时,只需在官网点击升级按钮,即可获得更强的性能和更大的容量。您的代码库无需任何改动。 这个基于Neo4j的最终方案,为您提供了一个从零开始、体验流畅、功能强大且没有后顾之忧的完整实现蓝图。
4,144
1
md
zh
markdown
text
{"qsc_doc_frac_chars_curly_bracket": 0.00241313, "qsc_doc_frac_words_redpajama_stop": null, "qsc_doc_num_sentences": 85.0, "qsc_doc_num_words": 1098, "qsc_doc_num_chars": 4144.0, "qsc_doc_num_lines": 138.0, "qsc_doc_mean_word_length": 2.88433515, "qsc_doc_frac_words_full_bracket": 0.0, "qsc_doc_frac_lines_end_with_readmore": 0.0, "qsc_doc_frac_lines_start_with_bullet": 0.0, "qsc_doc_frac_words_unique": 0.46174863, "qsc_doc_entropy_unigram": 5.79986662, "qsc_doc_frac_words_all_caps": 0.06043614, "qsc_doc_frac_lines_dupe_lines": 0.09243697, "qsc_doc_frac_chars_dupe_lines": 0.02876609, "qsc_doc_frac_chars_top_2grams": 0.02778655, "qsc_doc_frac_chars_top_3grams": 0.01420903, "qsc_doc_frac_chars_top_4grams": 0.01073571, "qsc_doc_frac_chars_dupe_5grams": 0.04294285, "qsc_doc_frac_chars_dupe_6grams": 0.01957689, "qsc_doc_frac_chars_dupe_7grams": 0.01957689, "qsc_doc_frac_chars_dupe_8grams": 0.0, "qsc_doc_frac_chars_dupe_9grams": 0.0, "qsc_doc_frac_chars_dupe_10grams": 0.0, "qsc_doc_frac_chars_replacement_symbols": 0.0, "qsc_doc_cate_code_related_file_name": 0.0, "qsc_doc_num_chars_sentence_length_mean": 21.28494624, "qsc_doc_frac_chars_hyperlink_html_tag": 0.00168919, "qsc_doc_frac_chars_alphabet": null, "qsc_doc_frac_chars_digital": 0.01889849, "qsc_doc_frac_chars_whitespace": 0.10617761, "qsc_doc_frac_chars_hex_words": 0.0}
1
{"qsc_doc_frac_chars_replacement_symbols": 0, "qsc_doc_entropy_unigram": 0, "qsc_doc_frac_chars_top_2grams": 0, "qsc_doc_frac_chars_top_3grams": 0, "qsc_doc_frac_chars_top_4grams": 0, "qsc_doc_frac_chars_dupe_5grams": 0, "qsc_doc_frac_chars_dupe_6grams": 0, "qsc_doc_frac_chars_dupe_7grams": 0, "qsc_doc_frac_chars_dupe_8grams": 0, "qsc_doc_frac_chars_dupe_9grams": 0, "qsc_doc_frac_chars_dupe_10grams": 0, "qsc_doc_frac_chars_dupe_lines": 0, "qsc_doc_frac_lines_dupe_lines": 0, "qsc_doc_frac_lines_end_with_readmore": 0, "qsc_doc_frac_lines_start_with_bullet": 0, "qsc_doc_frac_words_full_bracket": 0, "qsc_doc_mean_word_length": 0, "qsc_doc_num_chars": 0, "qsc_doc_num_lines": 0, "qsc_doc_num_sentences": 0, "qsc_doc_num_words": 0, "qsc_doc_frac_chars_hex_words": 0, "qsc_doc_frac_chars_hyperlink_html_tag": 0, "qsc_doc_frac_chars_alphabet": 0, "qsc_doc_frac_chars_digital": 0, "qsc_doc_frac_chars_whitespace": 0}
000haoji/deep-student
src-tauri/src/apkg_exporter_service.rs
use serde::{Deserialize, Serialize}; use std::path::PathBuf; use std::fs::{File, self}; use std::io::Write; use rusqlite::{Connection, Result as SqliteResult, params}; use zip::{ZipWriter, write::FileOptions}; use crate::models::AnkiCard; use chrono::Utc; /// 清理卡片内容中的无效模板占位符 fn clean_template_placeholders(content: &str) -> String { let mut cleaned = content.to_string(); // 移除各种可能的占位符 cleaned = cleaned.replace("{{.}}", ""); cleaned = cleaned.replace("{{/}}", ""); cleaned = cleaned.replace("{{#}}", ""); cleaned = cleaned.replace("{{}}", ""); // 移除空的Mustache标签 {{}} while cleaned.contains("{{}}") { cleaned = cleaned.replace("{{}}", ""); } // 移除可能的空白标签 cleaned = cleaned.replace("{{ }}", ""); cleaned = cleaned.replace("{{ }}", ""); // 清理多余的空白和换行 cleaned.trim().to_string() } /// Anki的基本配置 const ANKI_COLLECTION_CONFIG: &str = r#"{ "nextPos": 1, "estTimes": true, "activeDecks": [1], "sortType": "noteFld", "timeLim": 0, "sortBackwards": false, "addToCur": true, "curDeck": 1, "newBury": 0, "newSpread": 0, "dueCounts": true, "curModel": "1425279151691", "collapseTime": 1200 }"#; #[derive(Serialize, Deserialize)] struct AnkiModel { #[serde(rename = "vers")] version: Vec<i32>, name: String, #[serde(rename = "type")] model_type: i32, #[serde(rename = "mod")] modified: i64, #[serde(rename = "usn")] update_sequence_number: i32, #[serde(rename = "sortf")] sort_field: i32, #[serde(rename = "did")] deck_id: i64, #[serde(rename = "tmpls")] templates: Vec<AnkiTemplate>, #[serde(rename = "flds")] fields: Vec<AnkiField>, css: String, #[serde(rename = "latexPre")] latex_pre: String, #[serde(rename = "latexPost")] latex_post: String, tags: Vec<String>, id: String, req: Vec<Vec<serde_json::Value>>, } #[derive(Serialize, Deserialize)] struct AnkiTemplate { name: String, ord: i32, qfmt: String, afmt: String, #[serde(rename = "bqfmt")] browser_qfmt: String, #[serde(rename = "bafmt")] browser_afmt: String, #[serde(rename = "did")] deck_id: Option<i64>, #[serde(rename = "bfont")] browser_font: String, #[serde(rename = "bsize")] browser_size: i32, } #[derive(Serialize, Deserialize)] struct AnkiField { name: String, ord: i32, sticky: bool, rtl: bool, font: String, size: i32, #[serde(rename = "media")] media: Vec<String>, description: String, } /// 创建基本的Anki模型定义 fn create_basic_model() -> AnkiModel { AnkiModel { version: vec![], name: "Basic".to_string(), model_type: 0, modified: Utc::now().timestamp(), update_sequence_number: -1, sort_field: 0, deck_id: 1, templates: vec![AnkiTemplate { name: "Card 1".to_string(), ord: 0, qfmt: "{{Front}}".to_string(), afmt: "{{FrontSide}}\n\n<hr id=answer>\n\n{{Back}}".to_string(), browser_qfmt: "".to_string(), browser_afmt: "".to_string(), deck_id: None, browser_font: "Arial".to_string(), browser_size: 12, }], fields: vec![ AnkiField { name: "Front".to_string(), ord: 0, sticky: false, rtl: false, font: "Arial".to_string(), size: 20, media: vec![], description: "".to_string(), }, AnkiField { name: "Back".to_string(), ord: 1, sticky: false, rtl: false, font: "Arial".to_string(), size: 20, media: vec![], description: "".to_string(), }, ], css: ".card {\n font-family: arial;\n font-size: 20px;\n text-align: center;\n color: black;\n background-color: white;\n}".to_string(), latex_pre: "\\documentclass[12pt]{article}\n\\special{papersize=3in,5in}\n\\usepackage[utf8]{inputenc}\n\\usepackage{amssymb,amsmath}\n\\pagestyle{empty}\n\\setlength{\\parindent}{0in}\n\\begin{document}\n".to_string(), latex_post: "\\end{document}".to_string(), tags: vec![], id: "1425279151691".to_string(), req: vec![vec![serde_json::Value::from(0), serde_json::Value::from("any"), serde_json::Value::Array(vec![serde_json::Value::from(0)])]], } } /// 根据模板创建自定义Anki模型定义 fn create_template_model( template_id: Option<&str>, template_name: &str, fields: &[String], front_template: &str, back_template: &str, css_style: &str, model_type: i32, // 新增参数 ) -> AnkiModel { // 创建字段定义 let anki_fields: Vec<AnkiField> = fields .iter() .enumerate() .map(|(i, field_name)| AnkiField { name: field_name.clone(), ord: i as i32, sticky: false, rtl: false, font: "Arial".to_string(), size: 20, media: vec![], description: "".to_string(), }) .collect(); let req = if model_type == 1 { // Cloze model requirement vec![vec![serde_json::Value::from(0), serde_json::Value::from("all"), serde_json::Value::Array(vec![serde_json::Value::from(0)])]] } else { // Basic model requirement vec![vec![serde_json::Value::from(0), serde_json::Value::from("any"), serde_json::Value::Array(vec![serde_json::Value::from(0)])]] }; AnkiModel { version: vec![], name: template_name.to_string(), model_type, // 使用传入的model_type modified: Utc::now().timestamp(), update_sequence_number: -1, sort_field: 0, deck_id: 1, templates: vec![AnkiTemplate { name: "Card 1".to_string(), ord: 0, qfmt: front_template.to_string(), afmt: back_template.to_string(), browser_qfmt: "".to_string(), browser_afmt: "".to_string(), deck_id: None, browser_font: "Arial".to_string(), browser_size: 12, }], fields: anki_fields, css: css_style.to_string(), latex_pre: "\\documentclass[12pt]{article}\n\\special{papersize=3in,5in}\n\\usepackage[utf8]{inputenc}\n\\usepackage{amssymb,amsmath}\n\\pagestyle{empty}\n\\setlength{\\parindent}{0in}\n\\begin{document}\n".to_string(), latex_post: "\\end{document}".to_string(), tags: vec![], id: template_id.unwrap_or("1425279151691").to_string(), req, } } /// 创建Cloze模型定义 fn create_cloze_model() -> AnkiModel { AnkiModel { version: vec![], name: "Cloze".to_string(), model_type: 1, // Cloze类型 modified: Utc::now().timestamp(), update_sequence_number: -1, sort_field: 0, deck_id: 1, templates: vec![AnkiTemplate { name: "Cloze".to_string(), ord: 0, qfmt: "{{cloze:Text}}".to_string(), afmt: "{{cloze:Text}}<br>{{Extra}}".to_string(), browser_qfmt: "".to_string(), browser_afmt: "".to_string(), deck_id: None, browser_font: "Arial".to_string(), browser_size: 12, }], fields: vec![ AnkiField { name: "Text".to_string(), ord: 0, sticky: false, rtl: false, font: "Arial".to_string(), size: 20, media: vec![], description: "".to_string(), }, AnkiField { name: "Extra".to_string(), ord: 1, sticky: false, rtl: false, font: "Arial".to_string(), size: 20, media: vec![], description: "".to_string(), }, ], css: ".card {\n font-family: arial;\n font-size: 20px;\n text-align: center;\n color: black;\n background-color: white;\n}\n.cloze {\n font-weight: bold;\n color: blue;\n}".to_string(), latex_pre: "\\documentclass[12pt]{article}\n\\special{papersize=3in,5in}\n\\usepackage[utf8]{inputenc}\n\\usepackage{amssymb,amsmath}\n\\pagestyle{empty}\n\\setlength{\\parindent}{0in}\n\\begin{document}\n".to_string(), latex_post: "\\end{document}".to_string(), tags: vec![], id: "1425279151692".to_string(), req: vec![vec![serde_json::Value::from(0), serde_json::Value::from("all"), serde_json::Value::Array(vec![serde_json::Value::from(0)])]], } } /// 初始化Anki数据库结构 fn initialize_anki_database(conn: &Connection, deck_name: &str, model_name: &str) -> SqliteResult<(i64, i64)> { initialize_anki_database_with_template(conn, deck_name, model_name, None) } fn initialize_anki_database_with_template( conn: &Connection, deck_name: &str, model_name: &str, template_config: Option<(String, Vec<String>, String, String, String)> ) -> SqliteResult<(i64, i64)> { // 创建基本表结构 conn.execute_batch(r#" PRAGMA journal_mode = WAL; CREATE TABLE col ( id integer primary key, crt integer not null, mod integer not null, scm integer not null, ver integer not null, dty integer not null, usn integer not null, ls integer not null, conf text not null, models text not null, decks text not null, dconf text not null, tags text not null ); CREATE TABLE notes ( id integer primary key, guid text not null unique, mid integer not null, mod integer not null, usn integer not null, tags text not null, flds text not null, sfld text not null, csum integer not null, flags integer not null, data text not null ); CREATE TABLE cards ( id integer primary key, nid integer not null, did integer not null, ord integer not null, mod integer not null, usn integer not null, type integer not null, queue integer not null, due integer not null, ivl integer not null, factor integer not null, reps integer not null, lapses integer not null, left integer not null, odue integer not null, odid integer not null, flags integer not null, data text not null ); CREATE TABLE revlog ( id integer primary key, cid integer not null, usn integer not null, ease integer not null, ivl integer not null, lastIvl integer not null, factor integer not null, time integer not null, type integer not null ); CREATE TABLE graves ( usn integer not null, oid integer not null, type integer not null ); CREATE INDEX ix_cards_nid on cards (nid); CREATE INDEX ix_cards_sched on cards (did, queue, due); CREATE INDEX ix_cards_usn on cards (usn); CREATE INDEX ix_notes_usn on notes (usn); CREATE INDEX ix_notes_csum on notes (csum); CREATE INDEX ix_revlog_usn on revlog (usn); CREATE INDEX ix_revlog_cid on revlog (cid); "#)?; let now = Utc::now().timestamp(); let deck_id = 1i64; let model_id = if model_name == "Cloze" { 1425279151692i64 } else { 1425279151691i64 }; // 创建牌组配置 let decks = serde_json::json!({ "1": { "id": 1, "name": deck_name, "extendRev": 50, "usn": 0, "collapsed": false, "newToday": [0, 0], "revToday": [0, 0], "lrnToday": [0, 0], "timeToday": [0, 0], "dyn": 0, "extendNew": 10, "conf": 1, "desc": "", "browserCollapsed": true, "mod": now } }); // 创建模型配置 let model = if let Some((template_name, fields, front_template, back_template, css_style)) = template_config { // 判断是否为Cloze类型 let model_type = if model_name == "Cloze" { 1 } else { 0 }; // 🎯 关键修复:清理模板HTML中的占位符 let cleaned_front_template = clean_template_placeholders(&front_template); let cleaned_back_template = clean_template_placeholders(&back_template); let cleaned_css_style = clean_template_placeholders(&css_style); create_template_model( Some(&model_id.to_string()), &template_name, &fields, &cleaned_front_template, &cleaned_back_template, &cleaned_css_style, model_type, ) } else if model_name == "Cloze" { create_cloze_model() } else { create_basic_model() }; let model_id_clone = model.id.clone(); let models = serde_json::json!({ model_id_clone: model }); // 创建牌组配置 let dconf = serde_json::json!({ "1": { "id": 1, "name": "Default", "replayq": true, "lapse": { "leechFails": 8, "minInt": 1, "leechAction": 0, "delays": [10], "mult": 0.0 }, "rev": { "perDay": 200, "ivlFct": 1.0, "maxIvl": 36500, "ease4": 1.3, "bury": true, "minSpace": 1 }, "timer": 0, "maxTaken": 60, "usn": 0, "new": { "perDay": 20, "delays": [1, 10], "separate": true, "ints": [1, 4, 7], "initialFactor": 2500, "bury": true, "order": 1 }, "mod": now, "autoplay": true } }); // 插入集合配置 conn.execute( "INSERT INTO col (id, crt, mod, scm, ver, dty, usn, ls, conf, models, decks, dconf, tags) VALUES (1, ?, ?, ?, 11, 0, 0, 0, ?, ?, ?, ?, '{}')", params![ now, now, now, ANKI_COLLECTION_CONFIG, models.to_string(), decks.to_string(), dconf.to_string() ] )?; Ok((deck_id, model_id)) } /// 生成字段校验和 fn field_checksum(text: &str) -> i64 { if text.is_empty() { return 0; } let mut sum = 0i64; for (i, ch) in text.chars().enumerate() { sum += (ch as u32 as i64) * (i as i64 + 1); } sum } /// 将AnkiCard转换为Anki数据库记录 fn convert_cards_to_anki_records( cards: Vec<AnkiCard>, _deck_id: i64, _model_id: i64, model_name: &str, ) -> Result<Vec<(String, String, String, i64, String)>, String> { convert_cards_to_anki_records_with_fields(cards, _deck_id, _model_id, model_name, None) } fn convert_cards_to_anki_records_with_fields( cards: Vec<AnkiCard>, _deck_id: i64, _model_id: i64, model_name: &str, template_fields: Option<&[String]>, ) -> Result<Vec<(String, String, String, i64, String)>, String> { let mut records = Vec::new(); let now = Utc::now().timestamp(); for card in cards { let note_id = now * 1000 + records.len() as i64; // 生成唯一ID let guid = format!("{}", uuid::Uuid::new_v4().to_string().replace("-", "")); // 根据模板字段或模型类型处理字段 let (fields, sort_field) = if let Some(field_names) = template_fields { // 使用模板字段 let mut field_values = Vec::new(); // 🐛 调试日志:打印字段处理信息 if field_names.len() > 4 { // 学术模板有6个字段 println!("🎯 DEBUG: 处理学术模板,字段数量: {}", field_names.len()); println!("🎯 DEBUG: 模板字段: {:?}", field_names); println!("🎯 DEBUG: 卡片extra_fields: {:?}", card.extra_fields.keys().collect::<Vec<_>>()); println!("🎯 DEBUG: 卡片tags字段: {:?}", card.tags); } for field_name in field_names { let value = match field_name.to_lowercase().as_str() { "front" => clean_template_placeholders(&card.front), "back" => clean_template_placeholders(&card.back), "text" => clean_template_placeholders(&card.text.clone().unwrap_or_default()), "tags" => { // 处理标签字段:将Vec<String>转换为逗号分隔的字符串 if card.tags.is_empty() { String::new() } else { clean_template_placeholders(&card.tags.join(", ")) } } _ => { // 从扩展字段中获取 (大小写不敏感) let field_key = field_name.to_lowercase(); let raw_value = card.extra_fields.get(&field_key) .or_else(|| card.extra_fields.get(field_name)) .cloned() .unwrap_or_else(|| { // 🐛 调试:记录缺失的字段 println!("⚠️ DEBUG: 字段 '{}' 未找到,使用空值", field_name); String::new() }); clean_template_placeholders(&raw_value) } }; // 🐛 调试:打印每个字段的值 (UTF-8安全截断) if field_names.len() > 4 { println!("🎯 DEBUG: 字段 '{}' -> '{}'", field_name, if value.chars().count() > 50 { format!("{}...", value.chars().take(50).collect::<String>()) } else { value.clone() }); } field_values.push(value); } let fields_str = field_values.join("\x1f"); let sort_field = field_values.first().cloned().unwrap_or_default(); (fields_str, sort_field) } else { // 传统处理方式 match model_name { "Cloze" => { let clean_front = clean_template_placeholders(&card.front); let clean_back = clean_template_placeholders(&card.back); let cloze_text = if clean_back.is_empty() { clean_front } else { format!("{{{{c1::{}}}}}\n\n{}", clean_front, clean_back) }; let fields = format!("{}\x1f\x1f", cloze_text); (fields, cloze_text) } _ => { let clean_front = clean_template_placeholders(&card.front); let clean_back = clean_template_placeholders(&card.back); let fields = format!("{}\x1f{}", clean_front, clean_back); (fields, clean_front) } } }; // 清理tags中的模板占位符 let cleaned_tags: Vec<String> = card.tags.iter() .map(|tag| clean_template_placeholders(tag)) .filter(|tag| !tag.is_empty()) // 过滤掉空标签 .collect(); let tags = cleaned_tags.join(" "); let csum = field_checksum(&sort_field); records.push(( note_id.to_string(), guid, fields, csum, tags, )); } Ok(records) } /// 导出卡片为.apkg文件 pub async fn export_cards_to_apkg( cards: Vec<AnkiCard>, deck_name: String, note_type: String, output_path: PathBuf, ) -> Result<(), String> { export_cards_to_apkg_with_template(cards, deck_name, note_type, output_path, None).await } /// 导出卡片为.apkg文件(支持模板) pub async fn export_cards_to_apkg_with_template( cards: Vec<AnkiCard>, deck_name: String, note_type: String, output_path: PathBuf, template_config: Option<(String, Vec<String>, String, String, String)>, // (name, fields, front, back, css) ) -> Result<(), String> { if cards.is_empty() { return Err("没有卡片可以导出".to_string()); } // 创建临时目录 let temp_dir = std::env::temp_dir().join(format!("anki_export_{}", Utc::now().timestamp())); fs::create_dir_all(&temp_dir).map_err(|e| format!("创建临时目录失败: {}", e))?; let db_path = temp_dir.join("collection.anki2"); // 确保输出目录存在 if let Some(parent) = output_path.parent() { fs::create_dir_all(parent).map_err(|e| format!("创建输出目录失败: {}", e))?; } let result = async move { // 创建并初始化数据库 let conn = Connection::open(&db_path) .map_err(|e| format!("创建数据库失败: {}", e))?; let (deck_id, model_id) = initialize_anki_database_with_template(&conn, &deck_name, &note_type, template_config.clone()) .map_err(|e| format!("初始化数据库失败: {}", e))?; // 转换卡片数据 let template_fields_ref = template_config.as_ref().map(|(_, fields, _, _, _)| fields.as_slice()); let records = convert_cards_to_anki_records_with_fields(cards, deck_id, model_id, &note_type, template_fields_ref)?; let now = Utc::now().timestamp(); // 插入笔记和卡片 for (i, (note_id, guid, fields, csum, tags)) in records.iter().enumerate() { // 插入笔记 conn.execute( "INSERT INTO notes (id, guid, mid, mod, usn, tags, flds, sfld, csum, flags, data) VALUES (?, ?, ?, ?, -1, ?, ?, ?, ?, 0, '')", params![ note_id.parse::<i64>().unwrap(), guid, model_id, now, tags, fields, "", // sfld 会在后面更新 csum ] ).map_err(|e| format!("插入笔记失败: {}", e))?; // 为每个笔记创建卡片(Basic类型通常只有一张卡片) let card_id = note_id.parse::<i64>().unwrap() * 100 + i as i64; conn.execute( "INSERT INTO cards (id, nid, did, ord, mod, usn, type, queue, due, ivl, factor, reps, lapses, left, odue, odid, flags, data) VALUES (?, ?, ?, 0, ?, -1, 0, 0, ?, 0, 2500, 0, 0, 0, 0, 0, 0, '')", params![ card_id, note_id.parse::<i64>().unwrap(), deck_id, now, i as i64 + 1 // due date ] ).map_err(|e| format!("插入卡片失败: {}", e))?; } conn.close().map_err(|e| format!("关闭数据库失败: {:?}", e))?; // 创建.apkg文件(实际上是一个zip文件) let output_file = File::create(&output_path) .map_err(|e| format!("创建输出文件失败: {}", e))?; let mut zip = ZipWriter::new(output_file); // 添加数据库文件到zip let db_content = fs::read(&db_path) .map_err(|e| format!("读取数据库文件失败: {}", e))?; zip.start_file("collection.anki2", FileOptions::default()) .map_err(|e| format!("创建zip文件条目失败: {}", e))?; zip.write_all(&db_content) .map_err(|e| format!("写入数据库到zip失败: {}", e))?; // 创建媒体文件列表(空的) zip.start_file("media", FileOptions::default()) .map_err(|e| format!("创建媒体文件条目失败: {}", e))?; zip.write_all(b"{}") .map_err(|e| format!("写入媒体文件列表失败: {}", e))?; zip.finish() .map_err(|e| format!("完成zip文件失败: {}", e))?; Ok(()) }.await; // 清理临时文件 if temp_dir.exists() { if let Err(e) = fs::remove_dir_all(&temp_dir) { println!("警告:清理临时目录失败: {}", e); } } result }
24,720
apkg_exporter_service
rs
en
rust
code
{"qsc_code_num_words": 2525, "qsc_code_num_chars": 24720.0, "qsc_code_mean_word_length": 4.61544554, "qsc_code_frac_words_unique": 0.17742574, "qsc_code_frac_chars_top_2grams": 0.03844174, "qsc_code_frac_chars_top_3grams": 0.04685087, "qsc_code_frac_chars_top_4grams": 0.01561696, "qsc_code_frac_chars_dupe_5grams": 0.4044105, "qsc_code_frac_chars_dupe_6grams": 0.37609404, "qsc_code_frac_chars_dupe_7grams": 0.34245753, "qsc_code_frac_chars_dupe_8grams": 0.30384417, "qsc_code_frac_chars_dupe_9grams": 0.27286768, "qsc_code_frac_chars_dupe_10grams": 0.25656427, "qsc_code_frac_chars_replacement_symbols": 0.0, "qsc_code_frac_chars_digital": 0.02172102, "qsc_code_frac_chars_whitespace": 0.36864887, "qsc_code_size_file_byte": 24720.0, "qsc_code_num_lines": 731.0, "qsc_code_num_chars_line_max": 228.0, "qsc_code_num_chars_line_mean": 33.81668947, "qsc_code_frac_chars_alphabet": 0.72429038, "qsc_code_frac_chars_comments": 0.03535599, "qsc_code_cate_xml_start": 0.0, "qsc_code_frac_lines_dupe_lines": 0.33931485, "qsc_code_cate_autogen": 0.0, "qsc_code_frac_lines_long_string": 0.01305057, "qsc_code_frac_chars_string_length": 0.10894909, "qsc_code_frac_chars_long_word_length": 0.02633565, "qsc_code_frac_lines_string_concat": 0.0, "qsc_code_cate_encoded_data": 0.0, "qsc_code_frac_chars_hex_words": 0.0, "qsc_code_frac_lines_prompt_comments": 0.0, "qsc_code_frac_lines_assert": 0.0}
1
{"qsc_code_frac_chars_replacement_symbols": 0, "qsc_code_num_words": 0, "qsc_code_num_chars": 0, "qsc_code_mean_word_length": 0, "qsc_code_frac_chars_top_2grams": 0, "qsc_code_frac_chars_top_3grams": 0, "qsc_code_frac_chars_top_4grams": 0, "qsc_code_frac_chars_dupe_5grams": 0, "qsc_code_frac_chars_dupe_6grams": 0, "qsc_code_frac_chars_dupe_7grams": 0, "qsc_code_frac_chars_dupe_8grams": 0, "qsc_code_frac_chars_dupe_9grams": 0, "qsc_code_frac_chars_dupe_10grams": 0, "qsc_code_frac_lines_dupe_lines": 0, "qsc_code_size_file_byte": 0, "qsc_code_num_lines": 0, "qsc_code_num_chars_line_max": 0, "qsc_code_num_chars_line_mean": 0, "qsc_code_frac_chars_alphabet": 0, "qsc_code_frac_chars_digital": 0, "qsc_code_frac_chars_whitespace": 0, "qsc_code_frac_chars_comments": 0, "qsc_code_cate_xml_start": 0, "qsc_code_cate_autogen": 0, "qsc_code_frac_lines_long_string": 0, "qsc_code_frac_chars_string_length": 0, "qsc_code_frac_chars_long_word_length": 0, "qsc_code_cate_encoded_data": 0, "qsc_code_frac_chars_hex_words": 0, "qsc_code_frac_lines_prompt_comments": 0, "qsc_code_frac_lines_assert": 0}
000haoji/deep-student
src-tauri/src/crypto.rs
use aes_gcm::{ aead::{Aead, AeadCore, KeyInit, OsRng}, Aes256Gcm, Nonce, Key }; use base64::{Engine as _, engine::general_purpose}; use keyring::Entry; use rand::RngCore; use serde::{Deserialize, Serialize}; use std::path::PathBuf; #[derive(Debug, Serialize, Deserialize)] pub struct EncryptedData { pub ciphertext: String, pub nonce: String, } pub struct CryptoService { cipher: Aes256Gcm, keyring_service: String, keyring_user: String, } impl CryptoService { /// 创建新的加密服务实例 pub fn new(app_data_dir: &PathBuf) -> Result<Self, String> { let keyring_service = "ai-mistake-manager"; let keyring_user = "master-key"; // 获取或创建主密钥 let key = Self::get_or_create_master_key(&keyring_service, &keyring_user, app_data_dir)?; let cipher = Aes256Gcm::new(&key); Ok(CryptoService { cipher, keyring_service: keyring_service.to_string(), keyring_user: keyring_user.to_string(), }) } /// 加密API密钥 pub fn encrypt_api_key(&self, api_key: &str) -> Result<EncryptedData, String> { let nonce = Aes256Gcm::generate_nonce(&mut OsRng); let ciphertext = self.cipher .encrypt(&nonce, api_key.as_bytes()) .map_err(|e| format!("加密失败: {}", e))?; Ok(EncryptedData { ciphertext: general_purpose::STANDARD.encode(&ciphertext), nonce: general_purpose::STANDARD.encode(&nonce), }) } /// 解密API密钥 pub fn decrypt_api_key(&self, encrypted_data: &EncryptedData) -> Result<String, String> { let ciphertext = general_purpose::STANDARD .decode(&encrypted_data.ciphertext) .map_err(|e| format!("Base64解码失败: {}", e))?; let nonce_bytes = general_purpose::STANDARD .decode(&encrypted_data.nonce) .map_err(|e| format!("Nonce解码失败: {}", e))?; let nonce = Nonce::from_slice(&nonce_bytes); let plaintext = self.cipher .decrypt(nonce, ciphertext.as_ref()) .map_err(|e| format!("解密失败: {}", e))?; String::from_utf8(plaintext) .map_err(|e| format!("UTF-8转换失败: {}", e)) } /// 获取或创建主密钥(使用操作系统密钥存储) fn get_or_create_master_key(service: &str, user: &str, app_data_dir: &PathBuf) -> Result<Key<Aes256Gcm>, String> { // 尝试从操作系统密钥存储中获取密钥 match Entry::new(service, user) { Ok(entry) => { // 首先尝试从密钥存储中获取现有密钥 match entry.get_password() { Ok(stored_key) => { // 验证密钥格式和长度 if let Ok(key_bytes) = general_purpose::STANDARD.decode(&stored_key) { if key_bytes.len() == 32 { println!("✅ 从操作系统密钥存储中成功加载主密钥"); return Ok(*Key::<Aes256Gcm>::from_slice(&key_bytes)); } } println!("⚠️ 密钥存储中的密钥格式无效,重新生成新密钥"); } Err(_) => { println!("📝 密钥存储中未找到密钥,生成新的主密钥"); } } // 生成新的随机主密钥 let mut key_bytes = [0u8; 32]; OsRng.fill_bytes(&mut key_bytes); // 将密钥保存到操作系统密钥存储 let key_b64 = general_purpose::STANDARD.encode(&key_bytes); if let Err(e) = entry.set_password(&key_b64) { println!("⚠️ 无法保存密钥到操作系统密钥存储: {}", e); // 回退到文件存储 return Self::get_or_create_file_based_key(app_data_dir); } println!("✅ 新主密钥已生成并保存到操作系统密钥存储"); Ok(*Key::<Aes256Gcm>::from_slice(&key_bytes)) } Err(e) => { println!("⚠️ 无法访问操作系统密钥存储 ({}), 回退到文件存储", e); // 回退到基于文件的密钥存储 Self::get_or_create_file_based_key(app_data_dir) } } } /// 基于文件的密钥存储(回退方案) fn get_or_create_file_based_key(app_data_dir: &PathBuf) -> Result<Key<Aes256Gcm>, String> { let key_file_path = app_data_dir.join(".master_key"); // 尝试读取现有密钥文件 if key_file_path.exists() { match std::fs::read_to_string(&key_file_path) { Ok(key_content) => { if let Ok(key_bytes) = general_purpose::STANDARD.decode(&key_content) { if key_bytes.len() == 32 { println!("✅ 从文件加载主密钥: {:?}", key_file_path); return Ok(*Key::<Aes256Gcm>::from_slice(&key_bytes)); } } println!("⚠️ 密钥文件格式无效,重新生成"); } Err(e) => { println!("⚠️ 无法读取密钥文件: {}", e); } } } // 生成新的随机主密钥 let mut key_bytes = [0u8; 32]; OsRng.fill_bytes(&mut key_bytes); // 保存到文件(设置适当的权限) let key_b64 = general_purpose::STANDARD.encode(&key_bytes); std::fs::create_dir_all(app_data_dir) .map_err(|e| format!("无法创建应用数据目录: {}", e))?; std::fs::write(&key_file_path, &key_b64) .map_err(|e| format!("无法保存密钥文件: {}", e))?; // 在Unix系统上设置文件权限为仅所有者可读 #[cfg(unix)] { use std::os::unix::fs::PermissionsExt; let metadata = std::fs::metadata(&key_file_path) .map_err(|e| format!("无法获取密钥文件元数据: {}", e))?; let mut permissions = metadata.permissions(); permissions.set_mode(0o600); // 仅所有者读写 std::fs::set_permissions(&key_file_path, permissions) .map_err(|e| format!("无法设置密钥文件权限: {}", e))?; } println!("✅ 新主密钥已生成并保存到文件: {:?}", key_file_path); Ok(*Key::<Aes256Gcm>::from_slice(&key_bytes)) } /// 检查是否为加密数据格式 pub fn is_encrypted_format(data: &str) -> bool { // 简单检查是否为JSON格式且包含必要字段 if let Ok(parsed) = serde_json::from_str::<EncryptedData>(data) { !parsed.ciphertext.is_empty() && !parsed.nonce.is_empty() } else { false } } /// 迁移明文API密钥到加密格式 pub fn migrate_plaintext_key(&self, plaintext_key: &str) -> Result<String, String> { let encrypted_data = self.encrypt_api_key(plaintext_key)?; serde_json::to_string(&encrypted_data) .map_err(|e| format!("序列化失败: {}", e)) } /// 轮换主密钥(高级安全操作) pub fn rotate_master_key(&self, app_data_dir: &PathBuf) -> Result<CryptoService, String> { println!("🔄 开始轮换主密钥..."); // 删除现有密钥存储 if let Ok(entry) = Entry::new(&self.keyring_service, &self.keyring_user) { let _ = entry.delete_password(); // 忽略删除错误 } // 删除文件存储的密钥 let key_file_path = app_data_dir.join(".master_key"); if key_file_path.exists() { std::fs::remove_file(&key_file_path) .map_err(|e| format!("无法删除旧密钥文件: {}", e))?; } // 创建新的加密服务实例(会生成新的主密钥) let new_service = CryptoService::new(app_data_dir)?; println!("✅ 主密钥轮换完成"); Ok(new_service) } /// 验证密钥完整性 pub fn verify_key_integrity(&self) -> Result<bool, String> { // 通过加密解密测试来验证密钥完整性 let test_data = "integrity-test-data"; match self.encrypt_api_key(test_data) { Ok(encrypted) => { match self.decrypt_api_key(&encrypted) { Ok(decrypted) => Ok(decrypted == test_data), Err(e) => Err(format!("解密测试失败: {}", e)), } } Err(e) => Err(format!("加密测试失败: {}", e)), } } } #[cfg(test)] mod tests { use super::*; use std::env; #[test] fn test_encrypt_decrypt_cycle() { let temp_dir = env::temp_dir().join("crypto_test"); let crypto = CryptoService::new(&temp_dir).unwrap(); let original = "sk-test-api-key-12345"; let encrypted = crypto.encrypt_api_key(original).unwrap(); let decrypted = crypto.decrypt_api_key(&encrypted).unwrap(); assert_eq!(original, decrypted); // 清理测试文件 let _ = std::fs::remove_dir_all(&temp_dir); } #[test] fn test_is_encrypted_format() { assert!(!CryptoService::is_encrypted_format("plain-text-key")); let temp_dir = env::temp_dir().join("crypto_test_format"); let crypto = CryptoService::new(&temp_dir).unwrap(); let encrypted = crypto.encrypt_api_key("test-key").unwrap(); let encrypted_json = serde_json::to_string(&encrypted).unwrap(); assert!(CryptoService::is_encrypted_format(&encrypted_json)); // 清理测试文件 let _ = std::fs::remove_dir_all(&temp_dir); } #[test] fn test_key_integrity() { let temp_dir = env::temp_dir().join("crypto_test_integrity"); let crypto = CryptoService::new(&temp_dir).unwrap(); assert!(crypto.verify_key_integrity().unwrap()); // 清理测试文件 let _ = std::fs::remove_dir_all(&temp_dir); } }
9,386
crypto
rs
en
rust
code
{"qsc_code_num_words": 953, "qsc_code_num_chars": 9386.0, "qsc_code_mean_word_length": 4.9003148, "qsc_code_frac_words_unique": 0.20671563, "qsc_code_frac_chars_top_2grams": 0.0137045, "qsc_code_frac_chars_top_3grams": 0.0235546, "qsc_code_frac_chars_top_4grams": 0.03062099, "qsc_code_frac_chars_dupe_5grams": 0.33640257, "qsc_code_frac_chars_dupe_6grams": 0.27087794, "qsc_code_frac_chars_dupe_7grams": 0.24068522, "qsc_code_frac_chars_dupe_8grams": 0.19914347, "qsc_code_frac_chars_dupe_9grams": 0.16616702, "qsc_code_frac_chars_dupe_10grams": 0.09250535, "qsc_code_frac_chars_replacement_symbols": 0.0, "qsc_code_frac_chars_digital": 0.0105076, "qsc_code_frac_chars_whitespace": 0.3409333, "qsc_code_size_file_byte": 9386.0, "qsc_code_num_lines": 270.0, "qsc_code_num_chars_line_max": 119.0, "qsc_code_num_chars_line_mean": 34.76296296, "qsc_code_frac_chars_alphabet": 0.74167475, "qsc_code_frac_chars_comments": 0.0516727, "qsc_code_cate_xml_start": 0.0, "qsc_code_frac_lines_dupe_lines": 0.14871795, "qsc_code_cate_autogen": 0.0, "qsc_code_frac_lines_long_string": 0.0, "qsc_code_frac_chars_string_length": 0.06043586, "qsc_code_frac_chars_long_word_length": 0.00471804, "qsc_code_frac_lines_string_concat": 0.0, "qsc_code_cate_encoded_data": 0.0, "qsc_code_frac_chars_hex_words": 0.0, "qsc_code_frac_lines_prompt_comments": 0.0, "qsc_code_frac_lines_assert": 0.02051282}
1
{"qsc_code_frac_chars_replacement_symbols": 0, "qsc_code_num_words": 0, "qsc_code_num_chars": 0, "qsc_code_mean_word_length": 0, "qsc_code_frac_chars_top_2grams": 0, "qsc_code_frac_chars_top_3grams": 0, "qsc_code_frac_chars_top_4grams": 0, "qsc_code_frac_chars_dupe_5grams": 0, "qsc_code_frac_chars_dupe_6grams": 0, "qsc_code_frac_chars_dupe_7grams": 0, "qsc_code_frac_chars_dupe_8grams": 0, "qsc_code_frac_chars_dupe_9grams": 0, "qsc_code_frac_chars_dupe_10grams": 0, "qsc_code_frac_lines_dupe_lines": 0, "qsc_code_size_file_byte": 0, "qsc_code_num_lines": 0, "qsc_code_num_chars_line_max": 0, "qsc_code_num_chars_line_mean": 0, "qsc_code_frac_chars_alphabet": 0, "qsc_code_frac_chars_digital": 0, "qsc_code_frac_chars_whitespace": 0, "qsc_code_frac_chars_comments": 0, "qsc_code_cate_xml_start": 0, "qsc_code_cate_autogen": 0, "qsc_code_frac_lines_long_string": 0, "qsc_code_frac_chars_string_length": 0, "qsc_code_frac_chars_long_word_length": 0, "qsc_code_cate_encoded_data": 0, "qsc_code_frac_chars_hex_words": 0, "qsc_code_frac_lines_prompt_comments": 0, "qsc_code_frac_lines_assert": 0}
000haoji/deep-student
src-tauri/src/document_processing_service.rs
use crate::models::{DocumentTask, TaskStatus, AnkiGenerationOptions, AppError}; use crate::database::Database; use std::sync::Arc; use uuid::Uuid; use chrono::Utc; pub struct DocumentProcessingService { db: Arc<Database>, } impl DocumentProcessingService { pub fn new(db: Arc<Database>) -> Self { Self { db } } /// 处理文档并创建分段任务 pub async fn process_document_and_create_tasks( &self, document_content: String, original_document_name: String, subject_name: String, options: AnkiGenerationOptions, ) -> Result<(String, Vec<DocumentTask>), AppError> { let document_id = Uuid::new_v4().to_string(); // 分段文档 let segments = self.segment_document(&document_content, &options)?; let mut tasks = Vec::new(); let anki_options_json = serde_json::to_string(&options) .map_err(|e| AppError::validation(format!("序列化AnkiGenerationOptions失败: {}", e)))?; let now = Utc::now().to_rfc3339(); for (index, segment) in segments.into_iter().enumerate() { let task = DocumentTask { id: Uuid::new_v4().to_string(), document_id: document_id.clone(), original_document_name: original_document_name.clone(), segment_index: index as u32, content_segment: segment, status: TaskStatus::Pending, created_at: now.clone(), updated_at: now.clone(), error_message: None, subject_name: subject_name.clone(), anki_generation_options_json: anki_options_json.clone(), }; // 保存到数据库 self.db.insert_document_task(&task) .map_err(|e| AppError::database(format!("保存文档任务失败: {}", e)))?; tasks.push(task); } Ok((document_id, tasks)) } /// 文档分段逻辑 fn segment_document( &self, content: &str, options: &AnkiGenerationOptions, ) -> Result<Vec<String>, AppError> { // 配置分段参数 let max_tokens_per_segment = self.calculate_max_tokens_per_segment(options); let estimated_content_tokens = self.estimate_tokens(content); // 如果内容较短,不需要分段 if estimated_content_tokens <= max_tokens_per_segment { return Ok(vec![content.to_string()]); } let overlap_size = options.segment_overlap_size as usize; println!("[DOCUMENT_DEBUG] 文档分段: 估计{}tokens,每段最大{}tokens,重叠区域{}字符", estimated_content_tokens, max_tokens_per_segment, overlap_size); println!("[DOCUMENT_DEBUG] 用户设置: 每个主题最大卡片数={}, 总体令牌限制={:?}", options.max_cards_per_mistake, options.max_tokens); // 使用重叠分段策略 let segments = if overlap_size > 0 { self.segment_with_overlap(content, max_tokens_per_segment, overlap_size)? } else { self.segment_without_overlap(content, max_tokens_per_segment)? }; println!("[DOCUMENT_DEBUG] 文档分段完成: {}个分段", segments.len()); for (i, segment) in segments.iter().enumerate() { let segment_tokens = self.estimate_tokens(segment); println!("[DOCUMENT_DEBUG] 分段{}: {}字符, 估计{}tokens", i+1, segment.len(), segment_tokens); } Ok(segments) } /// 分割过长的段落 fn split_long_paragraph(&self, paragraph: &str, max_tokens: usize) -> Result<Vec<String>, AppError> { // 按句子分割 let sentences: Vec<&str> = paragraph.split_inclusive(&['.', '!', '?', '。', '!', '?']) .filter(|s| !s.trim().is_empty()) .collect(); let mut segments = Vec::new(); let mut current_segment = String::new(); let mut current_tokens = 0; for sentence in sentences { let sentence_tokens = self.estimate_tokens(sentence); // 如果单个句子就超过限制,按字符数强制分割 if sentence_tokens > max_tokens { // 先保存当前分段 if !current_segment.is_empty() { segments.push(current_segment.trim().to_string()); current_segment.clear(); current_tokens = 0; } // 按字符数分割长句子 let char_segments = self.split_by_characters(sentence, max_tokens); segments.extend(char_segments); continue; } if current_tokens + sentence_tokens > max_tokens && !current_segment.is_empty() { segments.push(current_segment.trim().to_string()); current_segment = sentence.to_string(); current_tokens = sentence_tokens; } else { current_segment.push_str(sentence); current_tokens += sentence_tokens; } } if !current_segment.is_empty() { segments.push(current_segment.trim().to_string()); } Ok(segments) } /// 按字符数强制分割 fn split_by_characters(&self, text: &str, max_tokens: usize) -> Vec<String> { // 粗略估计:1个token ≈ 1.5个中文字符 或 4个英文字符 let max_chars = max_tokens * 2; // 保守估计 let mut segments = Vec::new(); let chars: Vec<char> = text.chars().collect(); let mut start = 0; while start < chars.len() { let end = std::cmp::min(start + max_chars, chars.len()); let segment: String = chars[start..end].iter().collect(); segments.push(segment); start = end; } segments } /// 估算文本的token数量 fn estimate_tokens(&self, text: &str) -> usize { // 简单的token估算算法 // 更精确的实现可以使用tiktoken_rs库 let char_count = text.chars().count(); let word_count = text.split_whitespace().count(); // 中文字符 ≈ 1 token per character // 英文单词 ≈ 1.3 tokens per word // 标点符号和空格 ≈ 0.2 tokens each let chinese_chars = text.chars().filter(|c| { let code = *c as u32; (0x4E00..=0x9FFF).contains(&code) // 基本汉字范围 }).count(); let other_chars = char_count - chinese_chars; let estimated_tokens = chinese_chars + (word_count as f32 * 1.3) as usize + (other_chars as f32 * 0.2) as usize; std::cmp::max(estimated_tokens, char_count / 4) // 最少不低于字符数的1/4 } /// 计算每个分段的最大token数 fn calculate_max_tokens_per_segment(&self, options: &AnkiGenerationOptions) -> usize { // 根据API配置或选项确定分段大小 // 默认值:2000 tokens per segment let base_limit = 2000; // 如果用户设置了较小的max_tokens,相应调整分段大小 if let Some(max_tokens) = options.max_output_tokens_override.or(options.max_tokens.map(|t| t as u32)) { if max_tokens < 4000 { // 如果输出限制较小,输入也应该相应减少 return std::cmp::min(base_limit, (max_tokens / 2) as usize); } } base_limit } /// 获取文档的所有任务 pub fn get_document_tasks(&self, document_id: &str) -> Result<Vec<DocumentTask>, AppError> { self.db.get_tasks_for_document(document_id) .map_err(|e| AppError::database(format!("获取文档任务失败: {}", e))) } /// 更新任务状态 pub fn update_task_status( &self, task_id: &str, status: TaskStatus, error_message: Option<String>, ) -> Result<(), AppError> { self.db.update_document_task_status(task_id, status, error_message) .map_err(|e| AppError::database(format!("更新任务状态失败: {}", e))) } /// 获取单个任务 pub fn get_task(&self, task_id: &str) -> Result<DocumentTask, AppError> { self.db.get_document_task(task_id) .map_err(|e| AppError::database(format!("获取任务失败: {}", e))) } /// 删除文档及其所有任务 pub fn delete_document(&self, document_id: &str) -> Result<(), AppError> { self.db.delete_document_session(document_id) .map_err(|e| AppError::database(format!("删除文档失败: {}", e))) } /// 无重叠的文档分段(原始逻辑) fn segment_without_overlap( &self, content: &str, max_tokens_per_segment: usize, ) -> Result<Vec<String>, AppError> { // 按自然段落分割 let paragraphs: Vec<&str> = content.split("\n\n") .filter(|p| !p.trim().is_empty()) .collect(); let mut segments = Vec::new(); let mut current_segment = String::new(); let mut current_tokens = 0; for paragraph in paragraphs { let paragraph_tokens = self.estimate_tokens(paragraph); // 如果单个段落就超过限制,需要进一步分割 if paragraph_tokens > max_tokens_per_segment { // 先保存当前分段(如果有内容) if !current_segment.is_empty() { segments.push(current_segment.trim().to_string()); current_segment.clear(); current_tokens = 0; } // 分割长段落 let sub_segments = self.split_long_paragraph(paragraph, max_tokens_per_segment)?; segments.extend(sub_segments); continue; } // 检查添加这个段落是否会超出限制 if current_tokens + paragraph_tokens > max_tokens_per_segment && !current_segment.is_empty() { // 保存当前分段并开始新分段 segments.push(current_segment.trim().to_string()); current_segment = paragraph.to_string(); current_tokens = paragraph_tokens; } else { // 添加到当前分段 if !current_segment.is_empty() { current_segment.push_str("\n\n"); } current_segment.push_str(paragraph); current_tokens += paragraph_tokens; } } // 添加最后一个分段 if !current_segment.is_empty() { segments.push(current_segment.trim().to_string()); } // 确保至少有一个分段 if segments.is_empty() { segments.push(content.to_string()); } Ok(segments) } /// 带重叠的文档分段 fn segment_with_overlap( &self, content: &str, max_tokens_per_segment: usize, overlap_size: usize, ) -> Result<Vec<String>, AppError> { // 首先进行无重叠分段 let base_segments = self.segment_without_overlap(content, max_tokens_per_segment)?; // 如果只有一个分段,不需要重叠 if base_segments.len() <= 1 { return Ok(base_segments); } println!("[DOCUMENT_DEBUG] 应用重叠策略,基础分段数: {}", base_segments.len()); let mut overlapped_segments = Vec::new(); for (i, segment) in base_segments.iter().enumerate() { let mut final_segment = segment.clone(); // 为非第一个分段添加前重叠 if i > 0 { let prev_segment = &base_segments[i - 1]; if let Some(overlap_prefix) = self.get_overlap_suffix(prev_segment, overlap_size) { final_segment = format!("{}\n\n{}", overlap_prefix, final_segment); println!("[DOCUMENT_DEBUG] 分段{}添加前重叠: {}字符", i+1, overlap_prefix.len()); } } // 为非最后一个分段添加后重叠 if i < base_segments.len() - 1 { let next_segment = &base_segments[i + 1]; if let Some(overlap_suffix) = self.get_overlap_prefix(next_segment, overlap_size) { final_segment = format!("{}\n\n{}", final_segment, overlap_suffix); println!("[DOCUMENT_DEBUG] 分段{}添加后重叠: {}字符", i+1, overlap_suffix.len()); } } overlapped_segments.push(final_segment); } println!("[DOCUMENT_DEBUG] 重叠处理完成,最终分段数: {}", overlapped_segments.len()); Ok(overlapped_segments) } /// 将字节索引转换为字符索引 fn byte_index_to_char_index(&self, text: &str, byte_index: usize) -> usize { text.char_indices().take_while(|(i, _)| *i <= byte_index).count() - 1 } /// 获取文本的前缀(用于重叠) fn get_overlap_prefix(&self, text: &str, max_chars: usize) -> Option<String> { let char_count = text.chars().count(); if char_count <= max_chars { return Some(text.to_string()); } // 安全地获取前缀(按字符数而非字节数) let prefix: String = text.chars().take(max_chars).collect(); // 尝试在句子边界处截断 if let Some(last_sentence_end_bytes) = prefix.rfind(&['.', '!', '?', '。', '!', '?'][..]) { let last_sentence_end_chars = self.byte_index_to_char_index(&prefix, last_sentence_end_bytes); if last_sentence_end_chars > max_chars / 2 { // 确保不会截断太多 return Some(prefix.chars().take(last_sentence_end_chars + 1).collect()); } } // 尝试在段落边界处截断 if let Some(last_paragraph_end_bytes) = prefix.rfind("\n\n") { let last_paragraph_end_chars = self.byte_index_to_char_index(&prefix, last_paragraph_end_bytes); if last_paragraph_end_chars > max_chars / 2 { return Some(prefix.chars().take(last_paragraph_end_chars).collect()); } } // 尝试在词边界处截断 if let Some(last_space_bytes) = prefix.rfind(' ') { let last_space_chars = self.byte_index_to_char_index(&prefix, last_space_bytes); if last_space_chars > max_chars / 2 { return Some(prefix.chars().take(last_space_chars).collect()); } } // 最后选择:直接返回安全截断的前缀 Some(prefix) } /// 获取文本的后缀(用于重叠) fn get_overlap_suffix(&self, text: &str, max_chars: usize) -> Option<String> { let char_count = text.chars().count(); if char_count <= max_chars { return Some(text.to_string()); } // 安全地获取后缀(按字符数而非字节数) let suffix: String = text.chars().skip(char_count - max_chars).collect(); // 尝试在句子边界处开始 if let Some(first_sentence_start_bytes) = suffix.find(&['.', '!', '?', '。', '!', '?'][..]) { let first_sentence_start_chars = self.byte_index_to_char_index(&suffix, first_sentence_start_bytes); let remaining: String = suffix.chars().skip(first_sentence_start_chars + 1).collect(); if remaining.chars().count() > max_chars / 2 { // 确保不会截断太多 return Some(remaining.trim().to_string()); } } // 尝试在段落边界处开始 if let Some(first_paragraph_start_bytes) = suffix.find("\n\n") { let first_paragraph_start_chars = self.byte_index_to_char_index(&suffix, first_paragraph_start_bytes); let remaining: String = suffix.chars().skip(first_paragraph_start_chars + 2).collect(); if remaining.chars().count() > max_chars / 2 { return Some(remaining.to_string()); } } // 尝试在词边界处开始 if let Some(first_space_bytes) = suffix.find(' ') { let first_space_chars = self.byte_index_to_char_index(&suffix, first_space_bytes); let remaining: String = suffix.chars().skip(first_space_chars + 1).collect(); if remaining.chars().count() > max_chars / 2 { return Some(remaining.to_string()); } } // 最后选择:直接返回安全截断的后缀 Some(suffix) } }
15,555
document_processing_service
rs
en
rust
code
{"qsc_code_num_words": 1617, "qsc_code_num_chars": 15555.0, "qsc_code_mean_word_length": 5.05256648, "qsc_code_frac_words_unique": 0.17006803, "qsc_code_frac_chars_top_2grams": 0.02643819, "qsc_code_frac_chars_top_3grams": 0.02741738, "qsc_code_frac_chars_top_4grams": 0.03023256, "qsc_code_frac_chars_dupe_5grams": 0.3498164, "qsc_code_frac_chars_dupe_6grams": 0.2877601, "qsc_code_frac_chars_dupe_7grams": 0.24712362, "qsc_code_frac_chars_dupe_8grams": 0.23329253, "qsc_code_frac_chars_dupe_9grams": 0.20795594, "qsc_code_frac_chars_dupe_10grams": 0.14761322, "qsc_code_frac_chars_replacement_symbols": 0.0, "qsc_code_frac_chars_digital": 0.00733823, "qsc_code_frac_chars_whitespace": 0.32542591, "qsc_code_size_file_byte": 15555.0, "qsc_code_num_lines": 420.0, "qsc_code_num_chars_line_max": 121.0, "qsc_code_num_chars_line_mean": 37.03571429, "qsc_code_frac_chars_alphabet": 0.77089488, "qsc_code_frac_chars_comments": 0.06640951, "qsc_code_cate_xml_start": 0.0, "qsc_code_frac_lines_dupe_lines": 0.19723183, "qsc_code_cate_autogen": 0.0, "qsc_code_frac_lines_long_string": 0.0, "qsc_code_frac_chars_string_length": 0.03029677, "qsc_code_frac_chars_long_word_length": 0.00406252, "qsc_code_frac_lines_string_concat": 0.0, "qsc_code_cate_encoded_data": 0.0, "qsc_code_frac_chars_hex_words": 0.00082628, "qsc_code_frac_lines_prompt_comments": 0.0, "qsc_code_frac_lines_assert": 0.0}
1
{"qsc_code_frac_chars_replacement_symbols": 0, "qsc_code_num_words": 0, "qsc_code_num_chars": 0, "qsc_code_mean_word_length": 0, "qsc_code_frac_chars_top_2grams": 0, "qsc_code_frac_chars_top_3grams": 0, "qsc_code_frac_chars_top_4grams": 0, "qsc_code_frac_chars_dupe_5grams": 0, "qsc_code_frac_chars_dupe_6grams": 0, "qsc_code_frac_chars_dupe_7grams": 0, "qsc_code_frac_chars_dupe_8grams": 0, "qsc_code_frac_chars_dupe_9grams": 0, "qsc_code_frac_chars_dupe_10grams": 0, "qsc_code_frac_lines_dupe_lines": 0, "qsc_code_size_file_byte": 0, "qsc_code_num_lines": 0, "qsc_code_num_chars_line_max": 0, "qsc_code_num_chars_line_mean": 0, "qsc_code_frac_chars_alphabet": 0, "qsc_code_frac_chars_digital": 0, "qsc_code_frac_chars_whitespace": 0, "qsc_code_frac_chars_comments": 0, "qsc_code_cate_xml_start": 0, "qsc_code_cate_autogen": 0, "qsc_code_frac_lines_long_string": 0, "qsc_code_frac_chars_string_length": 0, "qsc_code_frac_chars_long_word_length": 0, "qsc_code_cate_encoded_data": 0, "qsc_code_frac_chars_hex_words": 0, "qsc_code_frac_lines_prompt_comments": 0, "qsc_code_frac_lines_assert": 0}
007LiZhen/FFmpeg-QT-rtsp
mainwindow.h
/** * 李震 * 我的码云:https://git.oschina.net/git-lizhen * 我的CSDN博客:http://blog.csdn.net/weixin_38215395 * 联系:QQ1039953685 */ #ifndef MAINWINDOW_H #define MAINWINDOW_H #include <QMainWindow> #include <QImage> #include <QPaintEvent> #include <QWidget> #include "videoplayer/videoplayer.h" namespace Ui { class MainWindow; } class MainWindow : public QMainWindow { Q_OBJECT public: explicit MainWindow(QWidget *parent = 0); ~MainWindow(); protected: void paintEvent(QPaintEvent *event); private: Ui::MainWindow *ui; VideoPlayer *mPlayer; //播放线程 QImage mImage; //记录当前的图像 QImage R_mImage; //2017.8.11---lizhen QString url; bool open_red=false; private slots: void slotGetOneFrame(QImage img); void slotGetRFrame(QImage img);///2017.8.11---lizhen bool slotOpenRed(); ///2017.8.12---lizhen bool slotCloseRed(); ///2017.8.12 }; #endif // MAINWINDOW_H
929
mainwindow
h
zh
c
code
{"qsc_code_num_words": 118, "qsc_code_num_chars": 929.0, "qsc_code_mean_word_length": 5.28813559, "qsc_code_frac_words_unique": 0.56779661, "qsc_code_frac_chars_top_2grams": 0.03205128, "qsc_code_frac_chars_top_3grams": 0.0224359, "qsc_code_frac_chars_top_4grams": 0.04166667, "qsc_code_frac_chars_dupe_5grams": 0.0, "qsc_code_frac_chars_dupe_6grams": 0.0, "qsc_code_frac_chars_dupe_7grams": 0.0, "qsc_code_frac_chars_dupe_8grams": 0.0, "qsc_code_frac_chars_dupe_9grams": 0.0, "qsc_code_frac_chars_dupe_10grams": 0.0, "qsc_code_frac_chars_replacement_symbols": 0.0, "qsc_code_frac_chars_digital": 0.06208719, "qsc_code_frac_chars_whitespace": 0.18514532, "qsc_code_size_file_byte": 929.0, "qsc_code_num_lines": 53.0, "qsc_code_num_chars_line_max": 57.0, "qsc_code_num_chars_line_mean": 17.52830189, "qsc_code_frac_chars_alphabet": 0.76089828, "qsc_code_frac_chars_comments": 0.25296017, "qsc_code_cate_xml_start": 0.0, "qsc_code_frac_lines_dupe_lines": 0.0, "qsc_code_cate_autogen": 0.0, "qsc_code_frac_lines_long_string": 0.0, "qsc_code_frac_chars_string_length": 0.03607504, "qsc_code_frac_chars_long_word_length": 0.03607504, "qsc_code_frac_lines_string_concat": 0.0, "qsc_code_cate_encoded_data": 0.0, "qsc_code_frac_chars_hex_words": 0.0, "qsc_code_frac_lines_prompt_comments": 0.0, "qsc_code_frac_lines_assert": 0.0, "qsc_codec_frac_lines_func_ratio": 0.20689655, "qsc_codec_cate_bitsstdc": 0.0, "qsc_codec_nums_lines_main": 0, "qsc_codec_frac_lines_goto": 0.0, "qsc_codec_cate_var_zero": 0.0, "qsc_codec_score_lines_no_logic": 0.4137931, "qsc_codec_frac_lines_print": 0.0, "qsc_codec_frac_lines_preprocessor_directives": null}
0
{"qsc_code_frac_chars_replacement_symbols": 0, "qsc_code_num_words": 0, "qsc_code_num_chars": 0, "qsc_code_mean_word_length": 0, "qsc_code_frac_chars_top_2grams": 0, "qsc_code_frac_chars_top_3grams": 0, "qsc_code_frac_chars_top_4grams": 0, "qsc_code_frac_chars_dupe_5grams": 0, "qsc_code_frac_chars_dupe_6grams": 0, "qsc_code_frac_chars_dupe_7grams": 0, "qsc_code_frac_chars_dupe_8grams": 0, "qsc_code_frac_chars_dupe_9grams": 0, "qsc_code_frac_chars_dupe_10grams": 0, "qsc_code_size_file_byte": 0, "qsc_code_num_lines": 0, "qsc_code_num_chars_line_max": 0, "qsc_code_num_chars_line_mean": 0, "qsc_code_frac_chars_alphabet": 0, "qsc_code_frac_chars_digital": 0, "qsc_code_frac_chars_whitespace": 0, "qsc_code_frac_chars_comments": 0, "qsc_code_cate_xml_start": 0, "qsc_code_frac_lines_dupe_lines": 0, "qsc_code_cate_autogen": 0, "qsc_code_frac_lines_long_string": 0, "qsc_code_frac_chars_string_length": 0, "qsc_code_frac_chars_long_word_length": 0, "qsc_code_cate_encoded_data": 0, "qsc_code_frac_chars_hex_words": 0, "qsc_code_frac_lines_prompt_comments": 0, "qsc_code_frac_lines_assert": 0, "qsc_codec_frac_lines_func_ratio": 1, "qsc_codec_nums_lines_main": 0, "qsc_codec_score_lines_no_logic": 0, "qsc_codec_frac_lines_preprocessor_directives": 0, "qsc_codec_frac_lines_print": 0}
007LiZhen/FFmpeg-QT-rtsp
mainwindow.cpp
/** * 李震 * 我的码云:https://git.oschina.net/git-lizhen * 我的CSDN博客:http://blog.csdn.net/weixin_38215395 * 联系:QQ1039953685 */ #include "mainwindow.h" #include "ui_mainwindow.h" #include <QPainter> #include <QInputDialog> #include <QtMath> #include<iostream> using namespace std; MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) { ui->setupUi(this); mPlayer = new VideoPlayer; connect(mPlayer,SIGNAL(sig_GetOneFrame(QImage)),this,SLOT(slotGetOneFrame(QImage))); ///2017.8.11---lizhen connect(mPlayer,SIGNAL(sig_GetRFrame(QImage)),this,SLOT(slotGetRFrame(QImage))); ///2017.8.12---lizhen connect(ui->Open_red,&QAction::triggered,this,&MainWindow::slotOpenRed); connect(ui->Close_Red,&QAction::triggered,this,&MainWindow::slotCloseRed); mPlayer->startPlay(); } MainWindow::~MainWindow() { delete ui; } void MainWindow::paintEvent(QPaintEvent *event) { QPainter painter(this); painter.setBrush(Qt::white); painter.drawRect(0, 0, this->width(), this->height()); //先画成白色 if (mImage.size().width() <= 0) return; ///将图像按比例缩放成和窗口一样大小 QImage img = mImage.scaled(this->size(),Qt::KeepAspectRatio); int x = this->width() - img.width(); int y = this->height() - img.height(); x /= 2; y /= 2; painter.drawImage(QPoint(x,y),img); //画出图像 if(open_red==true){ ///2017.8.12 QWidget *red_video=new QWidget(this); red_video->resize(this->width()/3,this->height()/3); ///2017.8.11---lizhen //提取出图像中的R数据 painter.setBrush(Qt::white); painter.drawRect(0, 0, red_video->width(),red_video->height()); //先画成白色 if (R_mImage.size().width() <= 0) return; ///将图像按比例缩放成和窗口一样大小 QImage R_img = R_mImage.scaled(red_video->size(),Qt::KeepAspectRatio); int R_x = red_video->width() - R_img.width(); int R_y = red_video->height() - R_img.height(); R_x /= 2; R_y /= 2; painter.drawImage(QPoint(R_x,R_y),R_img); //画出图像 } ///2017.8.10---lizhen //获取图像中心点 double x0=this->width()/2; double y0=this->height()/2; //载体偏移角度,可从设备处获得 double alpha=2; //横滚角alpha int length=60; //设备偏移后的“水平”参考坐标 //横滚角产生 double x_Horizental_right=length*qCos(alpha); double y_Horizental_right=-length*qSin(alpha); double x_Horizental_left=-length*qCos(alpha); double y_Horizental_left=length*qSin(alpha); double x_Vertical_up=length*qSin(alpha); double y_Vertical_up=length*qCos(alpha); double x_Vertical_down=-length*qSin(alpha); double y_Vertical_down=-length*qCos(alpha); ///水平参考坐标系,2017.8.7---lizhen painter.setPen(QPen(Qt::blue,1,Qt::DotLine)); painter.drawLine( x0-40,y0, x0+40,y0); painter.drawLine( x0,y0-40, x0,y0+40); ///横滚运动-偏移坐标系,2017.8.7---lizhen if(alpha!=0) { painter.setPen(QPen(Qt::blue,3)); painter.drawLine( x0+x_Horizental_left,y0+y_Horizental_left, x0+x_Horizental_right,y0+y_Horizental_right); painter.drawLine( x0+x_Vertical_up,y0+y_Vertical_up, x0+x_Vertical_down,y0+y_Vertical_down); } } void MainWindow::slotGetOneFrame(QImage img) { mImage = img; update(); //调用update将执行 paintEvent函数 } ///小窗口显示 void MainWindow::slotGetRFrame(QImage img) { R_mImage = img; update(); //调用update将执行 paintEvent函数 } ///显示图像红色通道,2017.8.12---lizhen bool MainWindow::slotOpenRed() { open_red=true; return open_red; } ///关闭图像红色通道,2017.8.12 bool MainWindow::slotCloseRed() { open_red=false; return open_red; }
3,538
mainwindow
cpp
en
cpp
code
{"qsc_code_num_words": 471, "qsc_code_num_chars": 3538.0, "qsc_code_mean_word_length": 4.84076433, "qsc_code_frac_words_unique": 0.28237792, "qsc_code_frac_chars_top_2grams": 0.01973684, "qsc_code_frac_chars_top_3grams": 0.0122807, "qsc_code_frac_chars_top_4grams": 0.03684211, "qsc_code_frac_chars_dupe_5grams": 0.25, "qsc_code_frac_chars_dupe_6grams": 0.12719298, "qsc_code_frac_chars_dupe_7grams": 0.07280702, "qsc_code_frac_chars_dupe_8grams": 0.03421053, "qsc_code_frac_chars_dupe_9grams": 0.0, "qsc_code_frac_chars_dupe_10grams": 0.0, "qsc_code_frac_chars_replacement_symbols": 0.0, "qsc_code_frac_chars_digital": 0.04238725, "qsc_code_frac_chars_whitespace": 0.16647824, "qsc_code_size_file_byte": 3538.0, "qsc_code_num_lines": 144.0, "qsc_code_num_chars_line_max": 115.0, "qsc_code_num_chars_line_mean": 24.56944444, "qsc_code_frac_chars_alphabet": 0.73041709, "qsc_code_frac_chars_comments": 0.15488977, "qsc_code_cate_xml_start": 0.0, "qsc_code_frac_lines_dupe_lines": 0.06976744, "qsc_code_cate_autogen": 0.0, "qsc_code_frac_lines_long_string": 0.0, "qsc_code_frac_chars_string_length": 0.00904826, "qsc_code_frac_chars_long_word_length": 0.0, "qsc_code_frac_lines_string_concat": 0.0, "qsc_code_cate_encoded_data": 0.0, "qsc_code_frac_chars_hex_words": 0.0, "qsc_code_frac_lines_prompt_comments": 0.0, "qsc_code_frac_lines_assert": 0.0, "qsc_codecpp_frac_lines_preprocessor_directives": 0.08139535, "qsc_codecpp_frac_lines_func_ratio": 0.02325581, "qsc_codecpp_cate_bitsstdc": 0.0, "qsc_codecpp_nums_lines_main": 0.0, "qsc_codecpp_frac_lines_goto": 0.0, "qsc_codecpp_cate_var_zero": 0.0, "qsc_codecpp_score_lines_no_logic": 0.10465116, "qsc_codecpp_frac_lines_print": 0.0}
1
{"qsc_code_frac_chars_replacement_symbols": 0, "qsc_code_num_words": 0, "qsc_code_num_chars": 0, "qsc_code_mean_word_length": 0, "qsc_code_frac_chars_top_2grams": 0, "qsc_code_frac_chars_top_3grams": 0, "qsc_code_frac_chars_top_4grams": 0, "qsc_code_frac_chars_dupe_5grams": 0, "qsc_code_frac_chars_dupe_6grams": 0, "qsc_code_frac_chars_dupe_7grams": 0, "qsc_code_frac_chars_dupe_8grams": 0, "qsc_code_frac_chars_dupe_9grams": 0, "qsc_code_frac_chars_dupe_10grams": 0, "qsc_code_frac_lines_dupe_lines": 0, "qsc_code_size_file_byte": 0, "qsc_code_num_lines": 0, "qsc_code_num_chars_line_max": 0, "qsc_code_num_chars_line_mean": 0, "qsc_code_frac_chars_alphabet": 0, "qsc_code_frac_chars_digital": 0, "qsc_code_frac_chars_whitespace": 0, "qsc_code_frac_chars_comments": 0, "qsc_code_cate_xml_start": 0, "qsc_code_cate_autogen": 0, "qsc_code_frac_lines_long_string": 0, "qsc_code_frac_chars_string_length": 0, "qsc_code_frac_chars_long_word_length": 0, "qsc_code_cate_encoded_data": 0, "qsc_code_frac_chars_hex_words": 0, "qsc_code_frac_lines_prompt_comments": 0, "qsc_code_frac_lines_assert": 0, "qsc_codecpp_frac_lines_func_ratio": 0, "qsc_codecpp_nums_lines_main": 0, "qsc_codecpp_score_lines_no_logic": 0, "qsc_codecpp_frac_lines_preprocessor_directives": 0, "qsc_codecpp_frac_lines_print": 0}
007revad/Linux_Plex_Backup
Linux_Plex_Backup.sh
#!/usr/bin/env bash # shellcheck disable=SC2317,SC2181,SC2009,SC2129,SC2163 #-------------------------------------------------------------------------- # Backup Linux Plex Database to tgz file in Backup folder. # v1.3.10 3-Sep-2025 007revad # # MUST be run by a user in sudo, sudoers or wheel group, or as root # # To run the script: # sudo -i /share/scripts/backup_linux_plex_to_tar.sh # Change /share/scripts/ to the path where this script is located # # To do a test run on just Plex's profiles folder run: # sudo -i /share/scripts/backup_linux_plex_to_tar.sh test # Change /share/scripts/ to the path where this script is located # # Github: https://github.com/007revad/Linux_Plex_Backup # Script verified at https://www.shellcheck.net/ # # Scheduling the script: # https://www.freecodecamp.org/news/cron-jobs-in-linux/ # https://crontab.guru/ # # https://arnaudr.io/2020/08/24/send-emails-from-your-terminal-with-msmtp/ #-------------------------------------------------------------------------- scriptver="v1.3.10" script=Linux_Plex_Backup # Read variables from backup_linux_plex.config Backup_Directory="" Name="" snap="" LogAll="" KeepQty="" to_email_address="" from_email_address="" if [[ -f $(dirname -- "$0";)/backup_linux_plex.config ]];then # shellcheck disable=SC1090,SC1091 while read -r var; do if [[ $var =~ ^[a-zA-Z0-9_]+=.* ]]; then export "$var"; fi done < "$(dirname -- "$0";)"/backup_linux_plex.config else echo "backup_linux_plex.config file missing!" exit 1 fi # Check if backup directory exists if [[ ! -d $Backup_Directory ]]; then echo "Backup directory not found:" echo "$Backup_Directory" echo "Check your setting in backup_linux_plex.config" exit 1 fi #-------------------------------------------------------------------------- # Set date and time variables # Timer variable to log time taken to backup PMS start="${SECONDS}" # Get Start Time and Date Started=$( date ) # Get Today's date for filename Now=$( date '+%Y%m%d') # Get Today's date and time for filename in case filename exists NowLong=$( date '+%Y%m%d-%H%M') #-------------------------------------------------------------------------- # Set NAS name (used in backup and log filenames) case "${Name,,}" in distro) # Get Linux Distro Nas="$(uname -a | awk '{print $2}')" ;; hostname|"") # Get Hostname Nas=$( hostname ) ;; *) # Set Nas to nickname Nas="$Name" ;; esac #-------------------------------------------------------------------------- # Set temporary log filenames (we get the Plex version later) # Set backup filename Backup_Name="${Nas}"_"${Now}"_Plex_"${Version}"_Backup # If file exists already include time in name BackupPN="$Backup_Directory/$Backup_Name" if [[ -f $BackupPN.tgz ]] || [[ -f $BackupPN.log ]] || [[ -f "$BackupPN"_ERROR.log ]]; then Backup_Name="${Nas}"_"${NowLong}"_Plex_"${Version}"_Backup fi # Set log filename Log_File="${Backup_Directory}"/"${Backup_Name}".log # Set error log filename Err_Log_File="${Backup_Directory}"/"${Backup_Name}"_ERROR.log #-------------------------------------------------------------------------- # Create temp error log # Create temp directory for temp error log Tmp_Dir=$(mktemp -d -t plex_to_tar-XXXXXX) # Create temp error log Tmp_Err_Log_File=$(mktemp "${Tmp_Dir}"/errorlog-XXXXXX) #-------------------------------------------------------------------------- # Create trap and clean up function # Tmp logs clean up function # shellcheck disable=SC2329 cleanup(){ arg1=$? # Move tmp_error_log to error log if tmp_error_log is not empty if [[ -s $Tmp_Err_Log_File ]] && [[ -d $Backup_Directory ]]; then mv "${Tmp_Err_Log_File}" "${Err_Log_File}" if [[ $? -gt "0" ]]; then echo "WARNING Failed moving ${Tmp_Err_Log_File} to ${Err_Log_File}"\ |& tee -a "${Err_Log_File}" fi fi # Delete our tmp directory if [[ -d $Tmp_Dir ]]; then rm -rf "${Tmp_Dir}" if [[ $? -gt "0" ]]; then echo "WARNING Failed deleting ${Tmp_Dir}" |& tee -a "${Err_Log_File}" fi fi if [[ $Version ]]; then Version="${Version} "; fi # Log and notify of success or errors if [[ -f $Err_Log_File ]]; then # Log and notify backup had errors if [[ ! -f $Log_File ]]; then # Add script name to top of log file basename -- "$0" |& tee -a "${Log_File}" fi echo -e "\n\e[41mWARNING\e[0m Plex backup had errors! See error log:" echo -e "\nWARNING Plex backup had errors! See error log:" >> "${Log_File}" echo -e "$(basename -- "${Err_Log_File}")\n" |& tee -a "${Log_File}" else # Log and notify of backup success echo -e "\nPlex backup completed successfully" |& tee -a "${Log_File}" fi # Send log via email if both logging and emails are enabled if [[ $to_email_address && $from_email_address ]]; then echo -e "\nSending email..." email_contents="email_contents.txt" send_email "$to_email_address" "$from_email_address" "$Backup_Directory"\ "$email_contents" "$Nas - $script log" fi exit "${arg1}" } trap cleanup EXIT # Send email function # shellcheck disable=SC2329 # Invoked indirectly send_email(){ # $1 is $to_email_address # $2 is $from_email_address # $3 is $Backup_Directory # $4 is $email_contents" # $5 is $subject # $6 is $mail_body if [[ ! -f "$Log_File" ]]; then echo -e "\nWARNING Cannot send email as directory $Log_File does not exist"\ |& tee -a "${Err_Log_File}" elif [[ "${3}" == "" || "${4}" == "" ]]; then echo -e "\nWARNING Send email failed. Incorrect data was passed to \"send_email\" function"\ |& tee -a "${Err_Log_File}" else if [[ -d "${3}" ]]; then # Make sure directory exists if [[ -w "${3}" ]]; then # Make sure directory is writable if [[ -r "${3}" ]]; then # Make sure directory is readable echo "To: ${1} " > "${3}/${4}" echo "From: ${2} " >> "${3}/${4}" echo "Subject: ${5}" >> "${3}/${4}" echo "" >> "${3}/${4}" cat "$Log_File" >> "${3}/${4}" #if [[ "${1}" == "" || "${2}" == "" || "${5}" == "" || "${6}" == "" ]]; then if [[ "${1}" == "" || "${2}" == "" || "${5}" == "" ]]; then echo -e "\nWARNING One or more email address parameters [to, from, subject,"\ "mail_body] was not supplied, Cannot send an email" |& tee -a "${Log_File}" else if ! command -v msmtp &> /dev/null # Verify the msmtp command is available then echo -e "\nWARNING Cannot Send Email as command \"msmtp\" was not found"\ |& tee -a "${Log_File}" else local email_response email_response=$(msmtp "${1}" < "${3}/${4}" 2>&1) if [[ "$email_response" == "" ]]; then domain=$(echo "$to_email_address" | awk -F '@' '{print $NF}') echo -e "Email sent successfully to $domain" |& tee -a "${Log_File}" else echo -e "\nWARNING An error occurred while sending email."\ "The error was: $email_response\n\n" |& tee -a "${Log_File}" fi fi fi else echo -e "Cannot send email as directory \"${3}\" does not have READ permissions"\ |& tee -a "${Log_File}" fi else echo -e "Cannot send email as directory \"${3}\" does not have WRITE permissions"\ |& tee -a "${Log_File}" fi else echo -e "Cannot send email as directory \"${3}\" does not exist" |& tee -a "${Log_File}" fi fi } #-------------------------------------------------------------------------- # Check that script is running as root if [[ $( whoami ) != "root" ]]; then if [[ -d $Backup_Directory ]]; then echo "ERROR: This script must be run as root!" |& tee -a "${Tmp_Err_Log_File}" echo "ERROR: $( whoami ) is not root. Aborting." |& tee -a "${Tmp_Err_Log_File}" else # Can't log error to log file because $Backup_Directory does not exist echo -e "\nERROR: This script must be run as root!" echo -e "ERROR: $( whoami ) is not root. Aborting.\n" fi # Abort script because it isn't being run by root exit 255 fi #-------------------------------------------------------------------------- # "Plex Media Server" folder location # ADM /volume1/Plex/Library/Plex Media Server # DSM6 /volume1/Plex/Library/Application Support/Plex Media Server # DSM7 /volume1/PlexMediaServer/AppData/Plex Media Server # Linux /var/lib/plexmediaserver/Library/Application Support/Plex Media Server # snap /var/snap/plexmediaserver/common/Library/Application Support # Set the Plex Media Server data location if [[ ${snap,,} == "yes" ]]; then Plex_Data_Path="/var/snap/plexmediaserver/common/Library/Application Support" else Plex_Data_Path="/var/lib/plexmediaserver/Library/Application Support" fi #-------------------------------------------------------------------------- # Check Plex Media Server data path exists if [[ ! -d $Plex_Data_Path ]]; then echo "Plex Media Server data path invalid! Aborting." |& tee -a "${Tmp_Err_Log_File}" echo "${Plex_Data_Path}" |& tee -a "${Tmp_Err_Log_File}" # Abort script because Plex data path invalid exit 255 fi #-------------------------------------------------------------------------- # Get Plex Media Server version if [[ ${snap,,} == "yes" ]]; then #Version="$(/usr/snap/plexmediaserver/Plex\ Media\ Server --version)" Version="$(snap list plexmediaserver | head -n 2 | tail -n 1 | awk '{print $2}')" # Returns 1.29.2.6364-6d72b0cf6 # Plex version without hex string Version=$(printf %s "$Version"| cut -d "-" -f1) # Returns 1.29.2.6364 else Version="$(/usr/lib/plexmediaserver/Plex\ Media\ Server --version)" # Returns v1.29.2.6364-6d72b0cf6 # Plex version without v or hex string Version=$(printf %s "${Version:1}"| cut -d "-" -f1) # Returns 1.29.2.6364 fi #-------------------------------------------------------------------------- # Re-assign log names to include Plex version # Backup filename Backup_Name="${Nas}"_"${Now}"_Plex_"${Version}"_Backup # If file exists already include time in name BackupPN="$Backup_Directory/$Backup_Name" if [[ -f $BackupPN.tgz ]] || [[ -f $BackupPN.log ]] || [[ -f "$BackupPN"_ERROR.log ]]; then Backup_Name="${Nas}"_"${NowLong}"_Plex_"${Version}"_Backup fi # Log file filename Log_File="${Backup_Directory}"/"${Backup_Name}".log # Error log filename Err_Log_File="${Backup_Directory}"/"${Backup_Name}"_ERROR.log #-------------------------------------------------------------------------- # Start logging echo -e "$script $scriptver\n" |& tee -a "${Log_File}" # Log Linux distro, version and hostname Distro="$(uname -a | awk '{print $2}')" DistroVersion="$(uname -a | awk '{print $3}' | cut -d"-" -f1)" echo "${Distro}" "${DistroVersion}" |& tee -a "${Log_File}" echo "Hostname: $( hostname )" |& tee -a "${Log_File}" # Log Plex version echo Plex version: "${Version}" |& tee -a "${Log_File}" #-------------------------------------------------------------------------- # Check if backup directory exists if [[ ! -d $Backup_Directory ]]; then echo "ERROR: Backup directory not found! Aborting backup." |& tee -a "${Log_File}" "${Tmp_Err_Log_File}" # Abort script because backup directory not found exit 255 fi #-------------------------------------------------------------------------- # Stop Plex Media Server echo "Stopping Plex..." |& tee -a "${Log_File}" if [[ ${snap,,} == "yes" ]]; then Result=$(snap stop plexmediaserver) else Result=$(systemctl stop plexmediaserver) fi code="$?" # Give sockets a moment to close sleep 5 if [[ $code == "0" ]]; then echo "Plex Media Server has stopped." |& tee -a "$Log_File" else echo "$Result" |& tee -a "$Log_File" exit $code fi # Nicely terminate any residual Plex processes (plug-ins, tuner service and EAE etc) ###pgrep [Pp]lex | xargs kill -15 &>/dev/null # Give sockets a moment to close ###sleep 5 # Kill any residual processes which DSM did not clean up (plug-ins and EAE) Pids="$(ps -ef | grep -i 'plex plug-in' | grep -v grep | awk '{print $2}')" [ "$Pids" != "" ] && kill -9 "$Pids" Pids="$(ps -ef | grep -i 'plex eae service' | grep -v grep | awk '{print $2}')" [ "$Pids" != "" ] && kill -9 "$Pids" Pids="$(ps -ef | grep -i 'plex tuner service' | grep -v grep | awk '{print $2}')" [ "$Pids" != "" ] && kill -9 "$Pids" # Give sockets a moment to close sleep 2 #-------------------------------------------------------------------------- # Check if all Plex processes have stopped echo Checking status of Plex processes... |& tee -a "${Log_File}" Response=$(pgrep -l plex) # Check if plexmediaserver was found in $Response if [[ -n $Response ]]; then # Forcefully kill any residual Plex processes (plug-ins, tuner service and EAE etc) pgrep [Pp]lex | xargs kill -9 &>/dev/null sleep 5 # Check if plexmediaserver still found in $Response Response=$(pgrep -l plex) if [[ -n $Response ]]; then echo "ERROR: Some Plex processes still running! Aborting backup."\ |& tee -a "${Log_File}" "${Tmp_Err_Log_File}" echo "${Response}" |& tee -a "${Log_File}" "${Tmp_Err_Log_File}" # Start Plex to make sure it's not left partially running if [[ ${snap,,} == "yes" ]]; then snap start plexmediaserver else #/usr/lib/plexmediaserver/Resources/start.sh systemctl start plexmediaserver fi # Abort script because Plex didn't shut down fully exit 255 else echo "All Plex processes have stopped." |& tee -a "${Log_File}" fi else echo "All Plex processes have stopped." |& tee -a "${Log_File}" fi #-------------------------------------------------------------------------- # Backup Plex Media Server echo "=================================================" |& tee -a "${Log_File}" echo "Backing up Plex Media Server data files..." |& tee -a "${Log_File}" Exclude_File="$( dirname -- "$0"; )/plex_backup_exclude.txt" # Check for test or error arguments if [[ -n $1 ]] && [[ ${1,,} == "error" ]]; then # Trigger an error to test error logging Test="Plex Media Server/Logs/ERROR/" echo "Running small error test backup of Logs folder" |& tee -a "${Log_File}" elif [[ -n $1 ]] && [[ ${1,,} == "test" ]]; then # Test on small Logs folder only Test="Plex Media Server/Logs/" echo "Running small test backup of Logs folder" |& tee -a "${Log_File}" fi # Check if exclude file exists # Must come after "Check for test or error arguments" if [[ -f $Exclude_File ]]; then # Unset arguments while [[ $1 ]]; do shift; done # Set -X excludefile arguments for tar set -- "$@" "-X" set -- "$@" "${Exclude_File}" else echo "INFO: No exclude file found." |& tee -a "${Log_File}" fi # Use short variable names so tar command is not too long BD="${Backup_Directory}" BN="${Backup_Name}" PDP="${Plex_Data_Path}" LF="${Log_File}" TELF="${Tmp_Err_Log_File}" PMS="Plex Media Server" # Run tar backup command if [[ -n $Test ]]; then # Running backup test or error test if [[ ${LogAll,,} == "yes" ]]; then echo "Logging all archived files" |& tee -a "${Log_File}" tar -cvpzf "${BD}"/"${BN}".tgz -C "${PDP}" "${Test}" > >(tee -a "${LF}") 2> >(tee -a "${LF}" "${TELF}" >&2) else # Don't log all backed up files. echo "Only logging errors" |& tee -a "${Log_File}" tar -cvpzf "${BD}"/"${BN}".tgz -C "${PDP}" "${Test}" 2> >(tee -a "${LF}" "${TELF}" >&2) fi else # Backup to tgz with PMS version and date in file name, send all output to shell and log, plus errors to error.log # Using -C to change directory to "/share/Plex/Library/Application Support" to not backup absolute path # and avoid "tar: Removing leading /" error if [[ ${LogAll,,} == "yes" ]]; then echo "Logging all archived files" |& tee -a "${Log_File}" tar -cvpzf "${BD}"/"${BN}".tgz "$@" -C "${PDP}" "$PMS/" > >(tee -a "${LF}") 2> >(tee -a "${LF}" "${TELF}" >&2) else # Don't log all backed up files. echo "Only logging errors" |& tee -a "${Log_File}" tar -cvpzf "${BD}"/"${BN}".tgz "$@" -C "${PDP}" "$PMS/" 2> >(tee -a "${LF}" "${TELF}" >&2) fi fi echo "Finished backing up Plex Media Server data files." |& tee -a "${Log_File}" echo "=================================================" |& tee -a "${Log_File}" #-------------------------------------------------------------------------- # Start Plex Media Server echo "Starting Plex..." |& tee -a "${Log_File}" if [[ ${snap,,} == "yes" ]]; then snap start plexmediaserver else #/usr/lib/plexmediaserver/Resources/start.sh systemctl start plexmediaserver fi #-------------------------------------------------------------------------- # Delete old backups if [[ $KeepQty -gt "0" ]]; then readarray -t array < <(ls "$Backup_Directory" |\ grep -E "${Nas}"'_[0-9]{8,}(-[0-9]{4,})?_Plex_.*\.tgz' | head -n -"$KeepQty") if [[ "${#array[@]}" -gt "0" ]]; then echo -e "\nDeleting old backups" |& tee -a "${Log_File}" for file in "${array[@]}"; do if [[ -f "$Backup_Directory/$file" ]]; then echo "Deleting $file" |& tee -a "${Log_File}" rm "$Backup_Directory/$file" fi if [[ -f "$Backup_Directory/${file%.tgz}.log" ]]; then echo "Deleting ${file%.tgz}.log" |& tee -a "${Log_File}" rm "$Backup_Directory/${file%.tgz}.log" fi if [[ -f "$Backup_Directory/${file%.tgz}_ERROR.log" ]]; then echo "Deleting ${file%.tgz}_ERROR.log" |& tee -a "${Log_File}" rm "$Backup_Directory/${file%.tgz}_ERROR.log" fi done fi fi #-------------------------------------------------------------------------- # Append the time taken to stdout and log file # End Time and Date Finished=$( date ) # bash timer variable to log time taken to backup Plex end="${SECONDS}" # Elapsed time in seconds Runtime=$(( end - start )) # Append start and end date/time and runtime echo -e "\nBackup Started: " "${Started}" |& tee -a "${Log_File}" echo "Backup Finished:" "${Finished}" |& tee -a "${Log_File}" # Append days, hours, minutes and seconds from $Runtime printf "Backup Duration: " |& tee -a "${Log_File}" printf '%dd:%02dh:%02dm:%02ds\n' \ $((Runtime/86400)) $((Runtime%86400/3600)) $((Runtime%3600/60))\ $((Runtime%60)) |& tee -a "${Log_File}" #-------------------------------------------------------------------------- # Trigger cleanup function exit 0
19,456
Linux_Plex_Backup
sh
en
shell
code
{"qsc_code_num_words": 2428, "qsc_code_num_chars": 19456.0, "qsc_code_mean_word_length": 4.17586491, "qsc_code_frac_words_unique": 0.17339374, "qsc_code_frac_chars_top_2grams": 0.05316106, "qsc_code_frac_chars_top_3grams": 0.02968735, "qsc_code_frac_chars_top_4grams": 0.04665154, "qsc_code_frac_chars_dupe_5grams": 0.45122793, "qsc_code_frac_chars_dupe_6grams": 0.39313542, "qsc_code_frac_chars_dupe_7grams": 0.33346484, "qsc_code_frac_chars_dupe_8grams": 0.26402998, "qsc_code_frac_chars_dupe_9grams": 0.22615643, "qsc_code_frac_chars_dupe_10grams": 0.21540586, "qsc_code_frac_chars_replacement_symbols": 0.0, "qsc_code_frac_chars_digital": 0.01676952, "qsc_code_frac_chars_whitespace": 0.23375822, "qsc_code_size_file_byte": 19456.0, "qsc_code_num_lines": 554.0, "qsc_code_num_chars_line_max": 119.0, "qsc_code_num_chars_line_mean": 35.11913357, "qsc_code_frac_chars_alphabet": 0.66333512, "qsc_code_frac_chars_comments": 0.36132812, "qsc_code_cate_xml_start": 0.0, "qsc_code_frac_lines_dupe_lines": 0.41296928, "qsc_code_cate_autogen": 0.0, "qsc_code_frac_lines_long_string": 0.01365188, "qsc_code_frac_chars_string_length": 0.39018109, "qsc_code_frac_chars_long_word_length": 0.05102616, "qsc_code_frac_lines_string_concat": 0.0, "qsc_code_cate_encoded_data": 0.0, "qsc_code_frac_chars_hex_words": 0.0, "qsc_code_frac_lines_prompt_comments": 0.0, "qsc_code_frac_lines_assert": 0.0}
1
{"qsc_code_frac_chars_replacement_symbols": 0, "qsc_code_num_words": 0, "qsc_code_num_chars": 0, "qsc_code_mean_word_length": 0, "qsc_code_frac_chars_top_2grams": 0, "qsc_code_frac_chars_top_3grams": 0, "qsc_code_frac_chars_top_4grams": 0, "qsc_code_frac_chars_dupe_5grams": 0, "qsc_code_frac_chars_dupe_6grams": 0, "qsc_code_frac_chars_dupe_7grams": 0, "qsc_code_frac_chars_dupe_8grams": 0, "qsc_code_frac_chars_dupe_9grams": 0, "qsc_code_frac_chars_dupe_10grams": 0, "qsc_code_frac_lines_dupe_lines": 0, "qsc_code_size_file_byte": 0, "qsc_code_num_lines": 0, "qsc_code_num_chars_line_max": 0, "qsc_code_num_chars_line_mean": 0, "qsc_code_frac_chars_alphabet": 0, "qsc_code_frac_chars_digital": 0, "qsc_code_frac_chars_whitespace": 0, "qsc_code_frac_chars_comments": 0, "qsc_code_cate_xml_start": 0, "qsc_code_cate_autogen": 0, "qsc_code_frac_chars_long_word_length": 0, "qsc_code_cate_encoded_data": 0, "qsc_code_frac_chars_hex_words": 0, "qsc_code_frac_lines_prompt_comments": 0}
007gzs/meeting
README.md
# 开源会议室 开源会议室预约小程序+Django服务端后台 ## 扫码体验 ![开源会议室](https://raw.githubusercontent.com/007gzs/meeting/master/resource/room_demo.jpg "开源会议室") ## 安装方式 本项目在以下代码托管网站同步更新: * 码云:https://gitee.com/007gzs/meeting * GitHub:https://github.com/007gzs/meeting ### 获取代码 git clone https://github.com/007gzs/meeting.git ### 服务端配置 服务端使用[Django](https://github.com/django/django) + [django-rest-framework](https://github.com/encode/django-rest-framework) + [django-cool](https://github.com/007gzs/django-cool) 框架开发 #### 创建数据库 CREATE SCHEMA `meeting` DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci ; #### 初始化数据 将 `server/meeting/local_settings.py.default` 重命名为 `server/meeting/local_settings.py` 并修改其中相关信息 在`server`目录中执行(推荐使用虚拟python虚拟环境) # 安装依赖 pip install -r requirements.txt # 初始化数据库 python manage.py makemigrations python manage.py migrate # 创建管理员用户 python manage.py createsuperuser # 启动服务 python manage.py runserver 0.0.0.0:8000 #### 后台管理地址 http://127.0.0.1:8000/sysadmin 可以用上面创建的管理员账号登录查看 ### 小程序配置 + 将`miniprogram/utils/api.js`文件中`const server = 'http://10.100.0.7:8000'` 修改为本机内网IP + 将`miniprogram/project.config.json`中`appid`修改为自己的appid + 用微信web开发者工具打开`miniprogram`并编译 ## 软件截图 ![会议室列表](https://raw.githubusercontent.com/007gzs/meeting/master/resource/1.jpg "会议室列表") ![会议预约](https://raw.githubusercontent.com/007gzs/meeting/master/resource/2.png "会议预约") ![会议列表](https://raw.githubusercontent.com/007gzs/meeting/master/resource/3.jpg "会议列表") ![会议明细](https://raw.githubusercontent.com/007gzs/meeting/master/resource/4.jpg "会议明细") ![会议室二维码](https://raw.githubusercontent.com/007gzs/meeting/master/resource/5.jpg "会议室二维码") ![我的会议](https://raw.githubusercontent.com/007gzs/meeting/master/resource/6.png "我的会议")
1,769
README
md
zh
markdown
text
{"qsc_doc_frac_chars_curly_bracket": 0.0, "qsc_doc_frac_words_redpajama_stop": null, "qsc_doc_num_sentences": 56.0, "qsc_doc_num_words": 320, "qsc_doc_num_chars": 1769.0, "qsc_doc_num_lines": 61.0, "qsc_doc_mean_word_length": 4.084375, "qsc_doc_frac_words_full_bracket": 0.0, "qsc_doc_frac_lines_end_with_readmore": 0.0, "qsc_doc_frac_lines_start_with_bullet": 0.0, "qsc_doc_frac_words_unique": 0.45, "qsc_doc_entropy_unigram": 4.58637262, "qsc_doc_frac_words_all_caps": 0.01204819, "qsc_doc_frac_lines_dupe_lines": 0.0, "qsc_doc_frac_chars_dupe_lines": 0.0, "qsc_doc_frac_chars_top_2grams": 0.07574598, "qsc_doc_frac_chars_top_3grams": 0.12241775, "qsc_doc_frac_chars_top_4grams": 0.14996174, "qsc_doc_frac_chars_dupe_5grams": 0.38179036, "qsc_doc_frac_chars_dupe_6grams": 0.29762816, "qsc_doc_frac_chars_dupe_7grams": 0.29762816, "qsc_doc_frac_chars_dupe_8grams": 0.29762816, "qsc_doc_frac_chars_dupe_9grams": 0.08722265, "qsc_doc_frac_chars_dupe_10grams": 0.0, "qsc_doc_frac_chars_replacement_symbols": 0.0, "qsc_doc_cate_code_related_file_name": 1.0, "qsc_doc_num_chars_sentence_length_mean": 14.12820513, "qsc_doc_frac_chars_hyperlink_html_tag": 0.06896552, "qsc_doc_frac_chars_alphabet": null, "qsc_doc_frac_chars_digital": 0.04505632, "qsc_doc_frac_chars_whitespace": 0.09666478, "qsc_doc_frac_chars_hex_words": 0.0}
1
{"qsc_doc_frac_chars_replacement_symbols": 0, "qsc_doc_entropy_unigram": 0, "qsc_doc_frac_chars_top_2grams": 0, "qsc_doc_frac_chars_top_3grams": 0, "qsc_doc_frac_chars_top_4grams": 0, "qsc_doc_frac_chars_dupe_5grams": 0, "qsc_doc_frac_chars_dupe_6grams": 0, "qsc_doc_frac_chars_dupe_7grams": 0, "qsc_doc_frac_chars_dupe_8grams": 0, "qsc_doc_frac_chars_dupe_9grams": 0, "qsc_doc_frac_chars_dupe_10grams": 0, "qsc_doc_frac_chars_dupe_lines": 0, "qsc_doc_frac_lines_dupe_lines": 0, "qsc_doc_frac_lines_end_with_readmore": 0, "qsc_doc_frac_lines_start_with_bullet": 0, "qsc_doc_frac_words_full_bracket": 0, "qsc_doc_mean_word_length": 0, "qsc_doc_num_chars": 0, "qsc_doc_num_lines": 0, "qsc_doc_num_sentences": 0, "qsc_doc_num_words": 0, "qsc_doc_frac_chars_hex_words": 0, "qsc_doc_frac_chars_hyperlink_html_tag": 0, "qsc_doc_frac_chars_alphabet": 0, "qsc_doc_frac_chars_digital": 0, "qsc_doc_frac_chars_whitespace": 0}
007revad/Linux_Plex_Backup
my-other-scripts.md
## All my scripts, tools and guides <img src="https://hitscounter.dev/api/hit?url=https%3A%2F%2F007revad.github.io%2F&label=Visitors&icon=github&color=%23198754&message=&style=flat&tz=UTC"> #### Contents - [Plex](#plex) - [Synology docker](#synology-docker) - [Synology recovery](#synology-recovery) - [Other Synology scripts](#other-synology-scripts) - [Synology hardware restrictions](#synology-hardware-restrictions) - [2025 plus models](#2025-plus-models) - [How To Guides](#how-to-guides) - [Synology dev](#synology-dev) *** ### Plex - **<a href="https://github.com/007revad/Synology_Plex_Backup">Synology_Plex_Backup</a>** - A script to backup Plex to a tgz file foror DSM 7 and DSM 6. - Works for Plex Synology package and Plex in docker. - **<a href="https://github.com/007revad/Asustor_Plex_Backup">Asustor_Plex_Backup</a>** - Backup your Asustor's Plex Media Server settings and database. - **<a href="https://github.com/007revad/Linux_Plex_Backup">Linux_Plex_Backup</a>** - Backup your Linux Plex Media Server's settings and database. - **<a href="https://github.com/007revad/Plex_Server_Sync">Plex_Server_Sync</a>** - Sync your main Plex server database & metadata to a backup Plex server. - Works for Synology, Asustor, Linux and supports Plex package or Plex in docker. &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; [Back to Contents](#contents) ### Synology docker - **<a href="https://github.com/007revad/Synology_Docker_Export">Synology_Docker_export</a>** - Export all Synology Container Manager or Docker containers' settings as json files to your docker shared folder. - **<a href="https://github.com/007revad/Synology_ContainerManager_IPv6">Synology_ContainerManager_IPv6</a>** - Enable IPv6 for Container Manager's bridge network. - **<a href="https://github.com/007revad/ContainerManager_for_all_armv8">ContainerManager_for_all_armv8</a>** - Script to install Container Manager on a RS819, DS119j, DS418, DS418j, DS218, DS218play or DS118. - **<a href="https://github.com/007revad/Docker_Autocompose">Docker_Autocompose</a>** - Create .yml files from your docker existing containers. - **<a href="https://github.com/007revad/Synology_docker_cleanup">Synology_docker_cleanup</a>** - Remove orphan docker btrfs subvolumes and images in Synology DSM 7 and DSM 6. &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; [Back to Contents](#contents) ### Synology recovery - **<a href="https://github.com/007revad/Synology_DSM_reinstall">Synology_DSM_reinstall</a>** - Easily re-install the same DSM version without losing any data or settings. - **<a href="https://github.com/007revad/Synology_Recover_Data">Synology_Recover_Data</a>** - A script to make it easy to recover your data from your Synology's drives using a computer. - **<a href="https://github.com/007revad/Synology_clear_drive_error">Synology clear drive error</a>** - Clear drive critical errors so DSM will let you use the drive. - **<a href="https://github.com/007revad/Synology_DSM_Telnet_Password">Synology_DSM_Telnet_Password</a>** - Synology DSM Recovery Telnet Password of the Day generator. - **<a href="https://github.com/007revad/Syno_DSM_Extractor_GUI">Syno_DSM_Extractor_GUI</a>** - Windows GUI for extracting Synology DSM 7 pat files and spk package files. - **<a href="https://github.com/007revad/Synoboot_backup">Synoboot_backup</a>** - Back up synoboot after each DSM update so you can recover from a corrupt USBDOM. &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; [Back to Contents](#contents) ### Other Synology scripts - **<a href="https://github.com/007revad/Synology_app_mover">Synology_app_mover</a>** - Easily move Synology packages from one volume to another volume. - **<a href="https://github.com/007revad/Video_Station_for_DSM_722">Video_Station_for_DSM_722</a>** - Script to install Video Station in DSM 7.2.2 - **<a href="https://github.com/007revad/SS_Motion_Detection">SS_Motion_Detection</a>** - Installs previous Surveillance Station and Advanced Media Extensions versions so motion detection and HEVC are supported. - **<a href="https://github.com/007revad/Synology_Config_Backup">Synology_Config_Backup</a>** - Backup and export your Synology DSM configuration. - **<a href="https://github.com/007revad/Synology_CPU_temperature">Synology_CPU_temperature</a>** - Get and log Synology NAS CPU temperature via SSH. - **<a href="https://github.com/007revad/Synology_SMART_info">Synology_SMART_info</a>** - Show Synology smart test progress or smart health and attributes. - **<a href="https://github.com/007revad/Synology_Cleanup_Coredumps">Synology_Cleanup_Coredumps</a>** - Cleanup memory core dumps from crashed processes. - **<a href="https://github.com/007revad/Synology_toggle_reset_button">Synology_toggle_reset_button</a>** - Script to disable or enable the reset button and show current setting. - **<a href="https://github.com/007revad/Synology_Download_Station_Chrome_Extension">Synology_Download_Station_Chrome_Extension</a>** - Download Station Chrome Extension. - **<a href="https://github.com/007revad/Seagate_lowCurrentSpinup">Seagate_lowCurrentSpinup</a>** - This script avoids the need to buy and install a higher wattage power supply when using multiple large Seagate SATA HDDs. &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; [Back to Contents](#contents) ### Synology hardware restrictions - **<a href="https://github.com/007revad/Synology_HDD_db">Synology_HDD_db</a>** - Add your SATA or SAS HDDs and SSDs plus SATA and NVMe M.2 drives to your Synology's compatible drive databases, including your Synology M.2 PCIe card and Expansion Unit databases. - **<a href="https://github.com/007revad/Synology_enable_M2_volume">Synology_enable_M2_volume</a>** - Enable creating volumes with non-Synology M.2 drives. - Enable Health Info for non-Synology NVMe drives (not in DSM 7.2.1 or later). - **<a href="https://github.com/007revad/Synology_M2_volume">Synology_M2_volume</a>** - Easily create an M.2 volume on Synology NAS. - **<a href="https://github.com/007revad/Synology_enable_M2_card">Synology_enable_M2_card</a>** - Enable Synology M.2 PCIe cards in Synology NAS that don't officially support them. - **<a href="https://github.com/007revad/Synology_enable_eunit">Synology_enable_eunit</a>** - Enable an unsupported Synology eSATA Expansion Unit models. - **<a href="https://github.com/007revad/Synology_enable_Deduplication">Synology_enable_Deduplication</a>** - Enable deduplication with non-Synology SSDs and unsupported NAS models. - **<a href="https://github.com/007revad/Synology_SHR_switch">Synology_SHR_switch</a>** - Easily switch between SHR and RAID Groups, or enable RAID F1. - **<a href="https://github.com/007revad/Synology_enable_sequential_IO">Synology_enable_sequential_IO</a>** - Enables sequential I/O for your SSD caches, like DSM 6 had. - **<a href="https://github.com/007revad/Synology_Information_Wiki">Synology_Information_Wiki</a>** - Information about Synology hardware. &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; [Back to Contents](#contents) ### 2025 plus models - **<a href="https://github.com/007revad/Transcode_for_x25">Transcode_for_x25</a>** - Installs the modules needed for Plex or Jellyfin hardware transcoding in DS425+ and DS225+. - **<a href="https://github.com/007revad/Synology_HDD_db/blob/main/2025_plus_models.md">2025 series or later Plus models</a>** - Unverified 3rd party drive limitations and unofficial solutions. - **<a href="https://github.com/007revad/Synology_HDD_db/blob/main/2025_plus_models.md#setting-up-a-new-2025-or-later-plus-model-with-only-unverified-hdds">Setup with only 3rd party drives</a>** - Setting up a new 2025 or later plus model with only unverified HDDs. - **<a href="https://github.com/007revad/Synology_HDD_db/blob/main/2025_plus_models.md#deleting-and-recreating-your-storage-pool-on-unverified-hdds">Recreating storage pool on migrated drives</a>** - Deleting and recreating your storage pool on unverified HDDs. &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; [Back to Contents](#contents) ### How To Guides - **<a href="https://github.com/007revad/Synology_SSH_key_setup">Synology_SSH_key_setup</a>** - How to setup SSH key authentication for your Synology. &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; [Back to Contents](#contents) ### Synology dev - **<a href="https://github.com/007revad/Download_Synology_Archive">Download_Synology_Archive</a>** - Download all or part of the Synology archive. - **<a href="https://github.com/007revad/Syno_DSM_Extractor_GUI">Syno_DSM_Extractor_GUI</a>** - Windows GUI for extracting Synology DSM 7 pat files and spk package files. - **<a href="https://github.com/007revad/ScriptNotify">ScriptNotify</a>** - DSM 7 package to allow your scripts to send DSM notifications. - **<a href="https://github.com/007revad/DTC_GUI_for_Windows">DTC_GUI_for_Windows</a>** - GUI for DTC.exe for Windows. &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; [Back to Contents](#contents)
9,099
my-other-scripts
md
en
markdown
text
{"qsc_doc_frac_chars_curly_bracket": 0.0, "qsc_doc_frac_words_redpajama_stop": 0.16632653, "qsc_doc_num_sentences": 107.0, "qsc_doc_num_words": 1341, "qsc_doc_num_chars": 9099.0, "qsc_doc_num_lines": 180.0, "qsc_doc_mean_word_length": 4.94630872, "qsc_doc_frac_words_full_bracket": 0.0, "qsc_doc_frac_lines_end_with_readmore": 0.0, "qsc_doc_frac_lines_start_with_bullet": 0.0, "qsc_doc_frac_words_unique": 0.23191648, "qsc_doc_entropy_unigram": 4.76529845, "qsc_doc_frac_words_all_caps": 0.02908163, "qsc_doc_frac_lines_dupe_lines": 0.1025641, "qsc_doc_frac_chars_dupe_lines": 0.10911978, "qsc_doc_frac_chars_top_2grams": 0.05789236, "qsc_doc_frac_chars_top_3grams": 0.06482738, "qsc_doc_frac_chars_top_4grams": 0.10372381, "qsc_doc_frac_chars_dupe_5grams": 0.39981909, "qsc_doc_frac_chars_dupe_6grams": 0.36891301, "qsc_doc_frac_chars_dupe_7grams": 0.34041912, "qsc_doc_frac_chars_dupe_8grams": 0.25569124, "qsc_doc_frac_chars_dupe_9grams": 0.20624152, "qsc_doc_frac_chars_dupe_10grams": 0.15829941, "qsc_doc_frac_chars_replacement_symbols": 0.0, "qsc_doc_cate_code_related_file_name": 0.0, "qsc_doc_num_chars_sentence_length_mean": 30.70731707, "qsc_doc_frac_chars_hyperlink_html_tag": 0.34762062, "qsc_doc_frac_chars_alphabet": 0.79007303, "qsc_doc_frac_chars_digital": 0.03094442, "qsc_doc_frac_chars_whitespace": 0.11210023, "qsc_doc_frac_chars_hex_words": 0.0}
1
{"qsc_doc_frac_chars_replacement_symbols": 0, "qsc_doc_entropy_unigram": 0, "qsc_doc_frac_chars_top_2grams": 0, "qsc_doc_frac_chars_top_3grams": 0, "qsc_doc_frac_chars_top_4grams": 0, "qsc_doc_frac_chars_dupe_5grams": 0, "qsc_doc_frac_chars_dupe_6grams": 0, "qsc_doc_frac_chars_dupe_7grams": 0, "qsc_doc_frac_chars_dupe_8grams": 0, "qsc_doc_frac_chars_dupe_9grams": 0, "qsc_doc_frac_chars_dupe_10grams": 0, "qsc_doc_frac_chars_dupe_lines": 0, "qsc_doc_frac_lines_dupe_lines": 0, "qsc_doc_frac_lines_end_with_readmore": 0, "qsc_doc_frac_lines_start_with_bullet": 0, "qsc_doc_frac_words_all_caps": 0, "qsc_doc_mean_word_length": 0, "qsc_doc_num_chars": 0, "qsc_doc_num_lines": 0, "qsc_doc_num_sentences": 0, "qsc_doc_num_words": 0, "qsc_doc_frac_chars_hex_words": 0, "qsc_doc_frac_chars_hyperlink_html_tag": 0, "qsc_doc_frac_chars_alphabet": 0, "qsc_doc_frac_chars_digital": 0, "qsc_doc_frac_chars_whitespace": 0}
007revad/Linux_Plex_Backup
Restore_Linux_Plex_Backup.sh
#!/usr/bin/env bash # shellcheck disable=SC2317,SC2181 #-------------------------------------------------------------------------- # Companion script for Linux Plex Backup script. # v1.1.7 3-Sep-2025 007revad # # MUST be run by a user in sudo, sudoers or wheel group, or as root # # To run the script: # sudo i /share/scripts/Restore_Linux_Plex_Backup.sh # Change /share/scripts/ to the path where this script is located # # Github: https://github.com/007revad/Linux_Plex_Backup # Script verified at https://www.shellcheck.net/ #-------------------------------------------------------------------------- scriptver="v1.1.7" script=Restore_Linux_Plex_Backup # Read variables from backup_linux_plex.config Backup_Directory="" Name="" snap="" LogAll="" if [[ -f $(dirname -- "$0";)/backup_linux_plex.config ]];then # shellcheck disable=SC1090,SC1091 while read -r var; do if [[ $var =~ ^[a-zA-Z0-9_]+=.* ]]; then export "$var"; fi done < "$(dirname -- "$0";)"/backup_linux_plex.config else echo "backup_linux_plex.config file missing!" exit 1 fi # Check if backup directory exists # shellcheck disable=SC2154 if [[ ! -d $Backup_Directory ]]; then echo "Backup directory not found:" echo "$Backup_Directory" echo "Check your setting in backup_linux_plex.config" exit 1 fi #-------------------------------------------------------------------------- # Set date and time variables # Timer variable to log time taken to backup PMS start="${SECONDS}" # Get Start Time and Date Started=$( date ) #-------------------------------------------------------------------------- # Set NAS name (used in backup and log filenames) # shellcheck disable=SC2154 case "${Name,,}" in distro) # Get Linux Distro Nas="$(uname -a | awk '{print $2}')" ;; hostname|"") # Get Hostname Nas=$( hostname ) ;; *) # Set Nas to nickname Nas="$Name" ;; esac #-------------------------------------------------------------------------- # Get list of backups from backup path # filelist=() # readarray -d '' filelist < <(find "${Backup_Directory}/" -size +100\ # \( -iname "${Nas}*.tgz" -o -iname "${Nas}*.tar.gz" \) -print0) # set +m only needed for interactive command line. In a script job control is off by default. #set +m shopt -s lastpipe u_filelist=() BD="${Backup_Directory}" if [[ ${1,,} == "test" ]]; then echo "Listing only small test backups to restore" find "${BD}/" -maxdepth 1 -size -1000k \( -iname "${Nas}*.tgz" -o -iname "${Nas}*.tar.gz" \) -print0 |\ while IFS= read -r -d $'\0'; do u_filelist+=("$REPLY"); done; declare -p u_filelist >/dev/null else find "${BD}/" -maxdepth 1 -size +999k \( -iname "${Nas}*.tgz" -o -iname "${Nas}*.tar.gz" \) -print0 |\ while IFS= read -r -d $'\0'; do u_filelist+=("$REPLY"); done; declare -p u_filelist >/dev/null fi # Sort array into new array IFS=$'\n' filelist=($(sort <<<"${u_filelist[*]}")) unset IFS # Menu to select file to restore echo "Please select a file to restore:" num="0" while [[ $num -lt "${#filelist[@]}" ]]; do echo "$((num +1))) $(basename "${filelist[$num]}")" num=$((num +1)) done echo "$((num +1))) Quit" read -r choice # Validate choice if [[ ! $choice -eq "0" ]] && [[ $choice =~ ^[0-9]+$ ]] && [[ ! $choice -gt "${#filelist[@]}" ]]; then index=$((choice -1)) echo "You selected: $(basename "${filelist[$index]}")" tgz_file="${filelist[$index]}" else exit fi #-------------------------------------------------------------------------- # Set log names Backup_Name="Restore_Plex_Backup" # Set log filename Log_File="${Backup_Directory}"/"${Backup_Name}".log # Set error log filename Err_Log_File="${Backup_Directory}"/"${Backup_Name}"_ERROR.log #-------------------------------------------------------------------------- # Create temp error log # Create temp directory for temp error log Tmp_Dir=$(mktemp -d -t plex_to_tar-XXXXXX) # Create temp error log Tmp_Err_Log_File=$(mktemp "${Tmp_Dir}"/errorlog-XXXXXX) #-------------------------------------------------------------------------- # Create trap and clean up function # Tmp logs clean up function # shellcheck disable=SC2329 cleanup(){ arg1=$? # Move tmp_error_log to error log if tmp_error_log is not empty if [[ -s $Tmp_Err_Log_File ]] && [[ -d $Backup_Directory ]]; then mv "${Tmp_Err_Log_File}" "${Err_Log_File}" if [[ $? -gt "0" ]]; then echo "WARNING Failed moving ${Tmp_Err_Log_File} to ${Err_Log_File}"\ |& tee -a "${Err_Log_File}" fi fi # Delete our tmp directory if [[ -d $Tmp_Dir ]]; then rm -rf "${Tmp_Dir}" if [[ $? -gt "0" ]]; then echo "WARNING Failed deleting ${Tmp_Dir}" |& tee -a "${Err_Log_File}" fi fi if [[ $Version ]]; then Version="${Version} "; fi # Log and notify of success or errors if [[ -f $Err_Log_File ]]; then # Log and notify backup had errors if [[ ! -f $Log_File ]]; then # Add script name to top of log file basename -- "$0" |& tee -a "${Log_File}" fi echo -e "\n\e[41mWARNING\e[0m Plex restoration had errors! See error log:" echo -e "\nWARNING Plex restoration had errors! See error log:" >> "${Log_File}" echo -e "$(basename -- "${Err_Log_File}")\n" |& tee -a "${Log_File}" else # Log and notify of backup success echo -e "\nPlex restoration completed successfully" |& tee -a "${Log_File}" fi exit "${arg1}" } trap cleanup EXIT #-------------------------------------------------------------------------- # Check that script is running as root if [[ $( whoami ) != "root" ]]; then if [[ -d $Backup_Directory ]]; then echo "ERROR: This script must be run as root!" |& tee -a "${Tmp_Err_Log_File}" echo "ERROR: $( whoami ) is not root. Aborting." |& tee -a "${Tmp_Err_Log_File}" else # Can't log error to log file because $Backup_Directory does not exist echo -e "\nERROR: This script must be run as root!" echo -e "ERROR: $( whoami ) is not root. Aborting.\n" fi # Abort script because it isn't being run by root exit 255 fi #-------------------------------------------------------------------------- # Find Plex Media Server location # Set the Plex Media Server data location if [[ ${snap,,} == "yes" ]]; then Plex_Data_Path="/var/snap/plexmediaserver/common/Library/Application Support" else Plex_Data_Path="/var/lib/plexmediaserver/Library/Application Support" fi #-------------------------------------------------------------------------- # Check Plex Media Server data path exists if [[ ! -d $Plex_Data_Path ]]; then echo "Plex Media Server data path invalid! Aborting." |& tee -a "${Tmp_Err_Log_File}" echo "${Plex_Data_Path}" |& tee -a "${Tmp_Err_Log_File}" # Abort script because Plex data path invalid exit 255 fi #-------------------------------------------------------------------------- # Get Plex Media Server version if [[ ${snap,,} == "yes" ]]; then #Version="$(/usr/snap/plexmediaserver/Plex\ Media\ Server --version)" Version="$(snap list plexmediaserver | head -n 2 | tail -n 1 | awk '{print $2}')" # Returns 1.29.2.6364-6d72b0cf6 # Plex version without hex string Version=$(printf %s "$Version"| cut -d "-" -f1) # Returns 1.29.2.6364 else Version="$(/usr/lib/plexmediaserver/Plex\ Media\ Server --version)" # Returns v1.29.2.6364-6d72b0cf6 # Plex version without v or hex string Version=$(printf %s "${Version:1}"| cut -d "-" -f1) # Returns 1.29.2.6364 fi #-------------------------------------------------------------------------- # Start logging echo -e "$script $scriptver\n" |& tee -a "${Log_File}" # Log Linux distro, version and hostname Distro="$(uname -a | awk '{print $2}')" DistroVersion="$(uname -a | awk '{print $3}' | cut -d"-" -f1)" echo "${Distro}" "${DistroVersion}" |& tee -a "${Log_File}" echo "Hostname: $( hostname )" |& tee -a "${Log_File}" # Log Plex version echo Plex version: "${Version}" |& tee -a "${Log_File}" #-------------------------------------------------------------------------- # Stop Plex Media Server echo "Stopping Plex..." |& tee -a "${Log_File}" if [[ ${snap,,} == "yes" ]]; then Result=$(snap stop plexmediaserver) else Result=$(systemctl stop plexmediaserver) fi code="$?" # Give sockets a moment to close sleep 5 if [[ $code == "0" ]]; then echo "Plex Media Server has stopped." |& tee -a "$Log_File" else echo "$Result" |& tee -a "$Log_File" exit $code fi # Nicely terminate any residual Plex processes (plug-ins, tuner service and EAE etc) ###pgrep [Pp]lex | xargs kill -15 &>/dev/null # Give sockets a moment to close ###sleep 5 # Kill any residual processes which DSM did not clean up (plug-ins and EAE) Pids="$(ps -ef | grep -i 'plex plug-in' | grep -v grep | awk '{print $2}')" [ "$Pids" != "" ] && kill -9 "$Pids" Pids="$(ps -ef | grep -i 'plex eae service' | grep -v grep | awk '{print $2}')" [ "$Pids" != "" ] && kill -9 "$Pids" Pids="$(ps -ef | grep -i 'plex tuner service' | grep -v grep | awk '{print $2}')" [ "$Pids" != "" ] && kill -9 "$Pids" # Give sockets a moment to close sleep 2 #-------------------------------------------------------------------------- # Check if all Plex processes have stopped echo Checking status of Plex processes... |& tee -a "${Log_File}" Response=$(pgrep -l plex) # Check if plexmediaserver was found in $Response if [[ -n $Response ]]; then # Forcefully kill any residual Plex processes (plug-ins, tuner service and EAE etc) pgrep [Pp]lex | xargs kill -9 &>/dev/null sleep 5 # Check if plexmediaserver still found in $Response Response=$(pgrep -l plex) if [[ -n $Response ]]; then echo "ERROR: Some Plex processes still running! Aborting restore."\ |& tee -a "${Log_File}" "${Tmp_Err_Log_File}" echo "${Response}" |& tee -a "${Log_File}" "${Tmp_Err_Log_File}" # Start Plex to make sure it's not left partially running if [[ ${snap,,} == "yes" ]]; then snap start plexmediaserver else #/usr/lib/plexmediaserver/Resources/start.sh systemctl start plexmediaserver fi # Abort script because Plex didn't shut down fully exit 255 else echo "All Plex processes have stopped." |& tee -a "${Log_File}" fi else echo "All Plex processes have stopped." |& tee -a "${Log_File}" fi #-------------------------------------------------------------------------- # Restore Plex Media Server from backup echo "=================================================" |& tee -a "${Log_File}" echo "Restoring Plex Media Server data files from:" |& tee -a "${Log_File}" basename "$tgz_file" |& tee -a "${Log_File}" # Use short variable names so tar command is not too long BD="${Backup_Directory}" #BN="${Backup_Name}" PDP="${Plex_Data_Path}" LF="${Log_File}" TELF="${Tmp_Err_Log_File}" #PMS="Plex Media Server" # Restore tgz backup to PMS, send all output to shell and log, plus errors to error.log # Using -C to change directory to "/share/Plex/Library/Application Support" # shellcheck disable=SC2154 if [[ ${LogAll,,} == "yes" ]]; then echo "Logging all restored files" |& tee -a "${Log_File}" tar -zxvpf "$tgz_file" -C "${PDP}" > >(tee -a "${LF}") 2> >(tee -a "${LF}" "${TELF}" >&2) else # Don't log all backed up files. echo "Only logging errors" |& tee -a "${Log_File}" tar -zxvpf "$tgz_file" -C "${PDP}" 2> >(tee -a "${LF}" "${TELF}" >&2) fi echo "Finished restoring Plex Media Server data files." |& tee -a "${Log_File}" echo "=================================================" |& tee -a "${Log_File}" #-------------------------------------------------------------------------- # Start Plex Media Server echo "Starting Plex..." |& tee -a "${Log_File}" if [[ ${snap,,} == "yes" ]]; then snap start plexmediaserver else #/usr/lib/plexmediaserver/Resources/start.sh systemctl start plexmediaserver fi #-------------------------------------------------------------------------- # Append the time taken to stdout and log file # End Time and Date Finished=$( date ) # bash timer variable to log time taken to backup Plex end="${SECONDS}" # Elapsed time in seconds Runtime=$(( end - start )) # Append start and end date/time and runtime echo -e "\nRestore Started: " "${Started}" |& tee -a "${Log_File}" echo "Restore Finished:" "${Finished}" |& tee -a "${Log_File}" # Append days, hours, minutes and seconds from $Runtime printf "Restore Duration: " |& tee -a "${Log_File}" printf '%dd:%02dh:%02dm:%02ds\n' \ $((Runtime/86400)) $((Runtime%86400/3600)) $((Runtime%3600/60))\ $((Runtime%60)) |& tee -a "${Log_File}" #-------------------------------------------------------------------------- # Trigger cleanup function exit 0
12,981
Restore_Linux_Plex_Backup
sh
en
shell
code
{"qsc_code_num_words": 1656, "qsc_code_num_chars": 12981.0, "qsc_code_mean_word_length": 4.21618357, "qsc_code_frac_words_unique": 0.22101449, "qsc_code_frac_chars_top_2grams": 0.05213406, "qsc_code_frac_chars_top_3grams": 0.02706961, "qsc_code_frac_chars_top_4grams": 0.04253795, "qsc_code_frac_chars_dupe_5grams": 0.336723, "qsc_code_frac_chars_dupe_6grams": 0.27499284, "qsc_code_frac_chars_dupe_7grams": 0.21684331, "qsc_code_frac_chars_dupe_8grams": 0.16227442, "qsc_code_frac_chars_dupe_9grams": 0.13047837, "qsc_code_frac_chars_dupe_10grams": 0.11987969, "qsc_code_frac_chars_replacement_symbols": 0.0, "qsc_code_frac_chars_digital": 0.01874941, "qsc_code_frac_chars_whitespace": 0.19058624, "qsc_code_size_file_byte": 12981.0, "qsc_code_num_lines": 408.0, "qsc_code_num_chars_line_max": 108.0, "qsc_code_num_chars_line_mean": 31.81617647, "qsc_code_frac_chars_alphabet": 0.64575997, "qsc_code_frac_chars_comments": 0.40559279, "qsc_code_cate_xml_start": 0.0, "qsc_code_frac_lines_dupe_lines": 0.35121951, "qsc_code_cate_autogen": 0.0, "qsc_code_frac_lines_long_string": 0.0195122, "qsc_code_frac_chars_string_length": 0.38729747, "qsc_code_frac_chars_long_word_length": 0.03849644, "qsc_code_frac_lines_string_concat": 0.0, "qsc_code_cate_encoded_data": 0.0, "qsc_code_frac_chars_hex_words": 0.0, "qsc_code_frac_lines_prompt_comments": 0.0, "qsc_code_frac_lines_assert": 0.0}
1
{"qsc_code_frac_chars_replacement_symbols": 0, "qsc_code_num_words": 0, "qsc_code_num_chars": 0, "qsc_code_mean_word_length": 0, "qsc_code_frac_chars_top_2grams": 0, "qsc_code_frac_chars_top_3grams": 0, "qsc_code_frac_chars_top_4grams": 0, "qsc_code_frac_chars_dupe_5grams": 0, "qsc_code_frac_chars_dupe_6grams": 0, "qsc_code_frac_chars_dupe_7grams": 0, "qsc_code_frac_chars_dupe_8grams": 0, "qsc_code_frac_chars_dupe_9grams": 0, "qsc_code_frac_chars_dupe_10grams": 0, "qsc_code_frac_lines_dupe_lines": 0, "qsc_code_size_file_byte": 0, "qsc_code_num_lines": 0, "qsc_code_num_chars_line_max": 0, "qsc_code_num_chars_line_mean": 0, "qsc_code_frac_chars_alphabet": 0, "qsc_code_frac_chars_digital": 0, "qsc_code_frac_chars_whitespace": 0, "qsc_code_frac_chars_comments": 0, "qsc_code_cate_xml_start": 0, "qsc_code_cate_autogen": 0, "qsc_code_frac_chars_long_word_length": 0, "qsc_code_cate_encoded_data": 0, "qsc_code_frac_chars_hex_words": 0, "qsc_code_frac_lines_prompt_comments": 0}
007revad/Linux_Plex_Backup
README.md
# Linux Plex Backup <a href="https://github.com/007revad/Linux_Plex_Backup/releases"><img src="https://img.shields.io/github/release/007revad/Linux_Plex_Backup.svg"></a> ![Badge](https://hitscounter.dev/api/hit?url=https%3A%2F%2Fgithub.com%2F007revad%2FLinux_Plex_Backup&label=Visitors&icon=github&color=%23198754&message=&style=flat&tz=Australia%2FSydney) [![Donate](https://img.shields.io/badge/Donate-PayPal-green.svg)](https://www.paypal.com/paypalme/007revad) [![](https://img.shields.io/static/v1?label=Sponsor&message=%E2%9D%A4&logo=GitHub&color=%23fe8e86)](https://github.com/sponsors/007revad) [![committers.top badge](https://user-badge.committers.top/australia/007revad.svg)](https://user-badge.committers.top/australia/007revad) ### Description This is a bash script to backup Linux Plex Media Server settings and database, and log the results. #### What the script does: - Gets your Linux computer's hostname and distro name (for use in the backup filename and log name). - Checks that the script is running with the required privileges. - Gets Plex Media Server's version (for the backup filename and log). - Checks the volume and share name where Plex Media Server's database is located. - Checks that your specified backup location exists. - Stops Plex Media Server, then checks Plex actually stopped. - Backs up Plex Media Server to a tgz file (**excluding the folders listed in plex_backup_exclude.txt**). - Starts Plex Media Server. - Emails the log to your email address (optional). Use when you have scheduled the script. #### It also saves a log in the same location as the backup file, including: - Logging the start and end time plus how long the backup took. - Logging every file that was backed up (can be disabled in config file). - Logging any errors to a separate error log file to make it easy for you to see if there were errors. The Linux computer's hostname, date, and Plex Media Server version are included in the backup's filename in case you need to roll Plex back to an older version or you save backups from more than one Plex Servers. **Example of the backup's auto-generated filenames:** - ubuntu_20221025_Plex_1.29.0.6244_Backup.tgz - ubuntu_20221025_Plex_1.29.0.6244_Backup.log - ubuntu_20221025_Plex_1.29.0.6244_Backup_ERROR.log (**only if there was an error**) If you run multiple backups on the same day the time will be included in the filename. **Example of the backup's auto-generated filenames:** - ubuntu_20221025_1920_Plex_1.29.0.6244_Backup.tgz - ubuntu_20221025_1920_Plex_1.29.0.6244_Backup.log ### Download the script 1. Download the latest version _Source code (zip)_ from https://github.com/007revad/Linux_Plex_Backup/releases 2. Save the download zip file to a folder on the Linux computer. 3. Unzip the zip file. ### Settings You need to set **backupDirectory=** near the top of the script (below the header). Set it to the location where you want the backup saved to. ```YAML Backup_Directory=/share/Backups/Plex_Backups ``` or ```YAML Backup_Directory=/share/folder with spaces/Plex_Backups ``` The script gets the disto and hostname from the NAS to use logs and backup name. Set Name= to distro, hostname or you can set a 'nickname'. If Name= is blank the Linux computer's hostname will be used. The LogAll setting enables, or disables, logging every file that gets backed up. Set LogAll= to yes or no. Blank is the same as no. If to_email_address and from_email_address are set an email containing the log will be sent after the script finishes. ```YAML to_email_address=email@email.com from_email_address=email@email.com ``` The KeepQty setting tells the script to keep only keep the latest N backups (and delete older backups). - If KeepQty is blank or set to 0 all backups are kept. ```YAML Name=distro LogAll=no KeepQty=5 ``` ### Requirements Make sure that backup_linux_plex.config and plex_backup_exclude.txt are in the same folder as Linux_Plex_Backup.sh **Note:** Due to some of the commands used **this script needs to be** run by a user in sudo, sudoers or wheel group, or as root If you want the script to send an email of the log after the script finishes you need to have msmtp installed (most Linux distros include msmtp). ### Configuring msmtp so the script can send emails Depending on your Linux distro the msmtprc or config file can be either: ``` /etc/msmtprc ~/.msmtprc $XDG_CONFIG_HOME/msmtp/config ``` The default msmtprc or config file usually contains: ``` # Set default values for all following accounts. defaults timeout 15 tls on tls_trust_file /usr/builtin/etc/msmtp/ca-certificates.crt #logfile ~/.msmtplog # The SMTP server of the provider. #account user@gmail.com #host smtp.gmail.com #port 587 #from user@gmail.com #auth on #user user@gmail.com #password passwd # Set a default account #account default: user@gmail.com ``` **Example email account settings for using a smtp server** ``` defaults timeout 15 tls on tls_trust_file /usr/builtin/etc/msmtp/ca-certificates.crt #logfile ~/.msmtplog # The SMTP server of the provider. account dave@myisp.com host mail.myisp.com port 587 from dave@myisp.com auth on user dave@myisp.com password mypassword # Set a default account account default: dave@myisp.com ``` If you don't want to include your email account's password in plain text in the msmtprc or config file see https://marlam.de/msmtp/msmtprc.txt **Example email account settings for using gmail** ``` # Set default values for all following accounts. defaults timeout 15 tls on tls_trust_file /usr/builtin/etc/msmtp/ca-certificates.crt #logfile ~/.msmtplog # The SMTP server of the provider. account dave@gmail.com host smtp.gmail.com port 587 from dave@gmail.com auth on user dave@gmail.com password gmailapppassword # Set a default account account default: dave@gmail.com ``` For gmail you will need to generate an "app password" and use that instead of your gmail password. 1. Go to https://myaccount.google.com/apppasswords and sign into google. 2. Enter a name in the form of `appname@computer-name` like `plexbackup@ubuntu` and click Create. 3. In the "Generated app password" popup copy the 16 character app password which will be like `abcd efgh ijkl mnop` 4. In your msmtprc or config file replace `password passwd` with the 16 character app password (without spaces) like: ``` password abcdefghijklmnop ``` ### Running the script Run the script by a user in sudo, sudoers or wheel group. ```YAML sudo -s "/share/scripts/Linux_Plex_Backup.sh" ``` ### Troubleshooting | Issue | Cause | Solution | |-------|-------|----------| | /usr/bin/env: ‘bash\r’: No such file or directory | File has Mac line endings! | [Download latest zip file](https://github.com/007revad/Linux_Plex_Backup/releases) | | Cursor sits there doing nothing | File has Windows line endings! | [Download latest zip file](https://github.com/007revad/Linux_Plex_Backup/releases) | | syntax error near unexpected token | You downloaded the webpage! | [Download latest zip file](https://github.com/007revad/Linux_Plex_Backup/releases) | If you get a "No such file or directory" error check the following: 1. Make sure you unpacked the zip or rar file that you downloaded and are trying to run the Linux_Plex_Backup.sh file. 2. If the path to the script contains any spaces you need to enclose the path/scriptname in double quotes: ```YAML sudo -s "/share/folder with spaces/Linux_Plex_Backup.sh" ``` 3. Set the script files as executable: ```YAML sudo chmod +x "/share/scripts/Linux_Plex_Backup.sh" sudo chmod +x "/share/scripts/Restore_Linux_Plex_Backup.sh" ``` ### Testing the script If you run the script with the **test** argument it will only backup Plex's Logs folder. ```YAML sudo -s "/share/scripts/Linux_Plex_Backup.sh" test ``` If you run the script with the **error** argument it will only backup Plex's Logs folder and cause an error so you can test the error logging. ```YAML sudo -s "/share/scripts/Linux_Plex_Backup.sh" error ``` ### Restoring from a backup To restore Plex from a backup run the included Restore_Linux_Plex_Backup.sh in a shell: ```YAML sudo -s "/share/scripts/Restore_Linux_Plex_Backup.sh" ``` **Note:** Replace "/share/scripts/" with the path to where Linux Plex Backup's files are located. The first thing you'll see is a menu listing all of your Plex backups that you created with Linux Plex Backup. Select the backup you want to restore and the sript will do the rest. <img src="images/restore.png"> **Note:** I would only restore a backup from the same Plex version as you currently have installed (which is why the Plex version is included in the backup file name and logs. ### Restoring a test backup If you previously ran Linux Plex Backup with the **test** argument you can run Restore_Linux_Plex_Backup.sh with the **test** argument so the menu will list any small backups (less than 1 MiB). ```YAML sudo -s "/share/scripts/Restore_Linux_Plex_Backup.sh" test ``` **Note:** Replace "/share/scripts/" with the path to where Linux Plex Backup's files are located.
9,110
README
md
en
markdown
text
{"qsc_doc_frac_chars_curly_bracket": 0.0, "qsc_doc_frac_words_redpajama_stop": 0.25625626, "qsc_doc_num_sentences": 158.0, "qsc_doc_num_words": 1514, "qsc_doc_num_chars": 9110.0, "qsc_doc_num_lines": 244.0, "qsc_doc_mean_word_length": 4.50462351, "qsc_doc_frac_words_full_bracket": 0.0, "qsc_doc_frac_lines_end_with_readmore": 0.0, "qsc_doc_frac_lines_start_with_bullet": 0.0, "qsc_doc_frac_words_unique": 0.25693527, "qsc_doc_entropy_unigram": 5.24191768, "qsc_doc_frac_words_all_caps": 0.01151151, "qsc_doc_frac_lines_dupe_lines": 0.3480663, "qsc_doc_frac_chars_dupe_lines": 0.11782032, "qsc_doc_frac_chars_top_2grams": 0.03812317, "qsc_doc_frac_chars_top_3grams": 0.05058651, "qsc_doc_frac_chars_top_4grams": 0.02991202, "qsc_doc_frac_chars_dupe_5grams": 0.35219941, "qsc_doc_frac_chars_dupe_6grams": 0.28504399, "qsc_doc_frac_chars_dupe_7grams": 0.26583578, "qsc_doc_frac_chars_dupe_8grams": 0.22917889, "qsc_doc_frac_chars_dupe_9grams": 0.20865103, "qsc_doc_frac_chars_dupe_10grams": 0.14677419, "qsc_doc_frac_chars_replacement_symbols": 0.0, "qsc_doc_cate_code_related_file_name": 1.0, "qsc_doc_num_chars_sentence_length_mean": 21.60794045, "qsc_doc_frac_chars_hyperlink_html_tag": 0.09527991, "qsc_doc_frac_chars_alphabet": 0.85773302, "qsc_doc_frac_chars_digital": 0.0227214, "qsc_doc_frac_chars_whitespace": 0.14972558, "qsc_doc_frac_chars_hex_words": 0.0}
1
{"qsc_doc_frac_chars_replacement_symbols": 0, "qsc_doc_entropy_unigram": 0, "qsc_doc_frac_chars_top_2grams": 0, "qsc_doc_frac_chars_top_3grams": 0, "qsc_doc_frac_chars_top_4grams": 0, "qsc_doc_frac_chars_dupe_5grams": 0, "qsc_doc_frac_chars_dupe_6grams": 0, "qsc_doc_frac_chars_dupe_7grams": 0, "qsc_doc_frac_chars_dupe_8grams": 0, "qsc_doc_frac_chars_dupe_9grams": 0, "qsc_doc_frac_chars_dupe_10grams": 0, "qsc_doc_frac_chars_dupe_lines": 0, "qsc_doc_frac_lines_dupe_lines": 0, "qsc_doc_frac_lines_end_with_readmore": 0, "qsc_doc_frac_lines_start_with_bullet": 0, "qsc_doc_frac_words_all_caps": 0, "qsc_doc_mean_word_length": 0, "qsc_doc_num_chars": 0, "qsc_doc_num_lines": 0, "qsc_doc_num_sentences": 0, "qsc_doc_num_words": 0, "qsc_doc_frac_chars_hex_words": 0, "qsc_doc_frac_chars_hyperlink_html_tag": 0, "qsc_doc_frac_chars_alphabet": 0, "qsc_doc_frac_chars_digital": 0, "qsc_doc_frac_chars_whitespace": 0}
007gzs/meeting
miniprogram/app.js
"use strict"; //app.js const api = require("./utils/api.js") const request = require("./utils/request.js") const time = require('./utils/time.js') const meetings = require('./utils/meetings.js') App({ api: api, time: time, meetings: meetings, onLaunch: function (options) { if (wx.getUpdateManager){ const updateManager = wx.getUpdateManager() updateManager.onUpdateReady(function (e) { updateManager.applyUpdate() }) } // 获取用户信息 this.userInfo() }, onShow: function(options){ request.reconnectApiViews(5) }, onHide: function (options) { }, globalData: { config: null, userInfo: null, getUserInfoing: false, getUserInfoPromise: [], logining: false, loginPromise: [], timeDifference: 0, }, nowDate: function(){ return new Date(new Date().getTime() + this.globalData.timeDifference) }, config: function(){ return new Promise((resolve, reject) => { if (this.globalData.config != null){ resolve(this.globalData.config) return } api.api_meeting_config().then(res => { this.globalData.config = res resolve(this.globalData.config) }).catch(res => { reject(res) }) }) }, userInfo: function () { return new Promise((resolve, reject) => { this.globalData.getUserInfoPromise.push([resolve, reject]) if (this.globalData.getUserInfoing) { return } this.globalData.getUserInfoing = true let callback = (index, info) => { this.globalData.getUserInfoing = false while (this.globalData.getUserInfoPromise.length > 0) { let pro = this.globalData.getUserInfoPromise.pop() pro[index](info); } if (index == 0 && info.need_refresh){ this.getUserInfo() } } if (this.globalData.userInfo != null) { callback(0, this.globalData.userInfo) return } api.api_wechat_user_info().then(data => { if (!data.avatarurl){ this.getUserInfo().then(res => { callback(0, res) }).catch(res => { callback(1, res) }) }else{ this.globalData.userInfo = data callback(0, this.globalData.userInfo) } }).catch(res => { callback(1, res) }) }) }, getUserInfo: function () { return new Promise((resolve, reject) => { this.login().then(res => { wx.getUserInfo({ withCredentials: true, lang: 'zh_CN', success: res => { this.updateUserInfo(res.encryptedData, res.iv).then(res => { resolve(res) }).catch(res => { reject(res) }) }, fail(res) { reject(res.errMsg); } }) }) }) }, updateUserInfo: function (encryptedData, iv){ return new Promise((resolve, reject) => { api.api_wechat_user_info({ encrypted_data: encryptedData, iv: iv }).then(data => { this.globalData.userInfo = data resolve(this.globalData.userInfo) }).catch(msg => { this.login().then(res => { reject(msg) }) }) }) }, onGetPhoneNumber: function (e) { if (e.detail.errMsg == 'getPhoneNumber:ok') { return this.updateUserInfo(e.detail.encryptedData, e.detail.iv) }else{ return new Promise((resolve, reject) => { reject("获取失败") }); } }, onGetUserInfo: function (e) { if (e.detail.errMsg == 'getUserInfo:ok') { return this.updateUserInfo(e.detail.encryptedData, e.detail.iv) } else { return new Promise((resolve, reject) => { reject("获取失败") }); } }, gotoHome: function(){ wx.reLaunch({ url: '/pages/room/list', }) }, login: function() { return new Promise((resolve, reject) => { this.globalData.loginPromise.push([resolve, reject]) if (this.globalData.logining) { return } this.globalData.logining = true let callback = (index, data) => { this.globalData.logining = false while (this.globalData.loginPromise.length > 0) { let pro = this.globalData.loginPromise.pop() pro[index](data); } } wx.login({ success: res => { api.api_wechat_login({js_code: res.code}).then(data => { callback(0, data) }) // 发送 res.code 到后台换取 openId, sessionKey, unionId }, fail: res => { callback(1, res) } }) }) } })
4,580
app
js
en
javascript
code
{"qsc_code_num_words": 433, "qsc_code_num_chars": 4580.0, "qsc_code_mean_word_length": 5.80831409, "qsc_code_frac_words_unique": 0.23094688, "qsc_code_frac_chars_top_2grams": 0.12803181, "qsc_code_frac_chars_top_3grams": 0.0445328, "qsc_code_frac_chars_top_4grams": 0.0640159, "qsc_code_frac_chars_dupe_5grams": 0.29065606, "qsc_code_frac_chars_dupe_6grams": 0.21630219, "qsc_code_frac_chars_dupe_7grams": 0.13479125, "qsc_code_frac_chars_dupe_8grams": 0.11848907, "qsc_code_frac_chars_dupe_9grams": 0.07793241, "qsc_code_frac_chars_dupe_10grams": 0.07793241, "qsc_code_frac_chars_replacement_symbols": 0.0, "qsc_code_frac_chars_digital": 0.00375469, "qsc_code_frac_chars_whitespace": 0.30218341, "qsc_code_size_file_byte": 4580.0, "qsc_code_num_lines": 169.0, "qsc_code_num_chars_line_max": 89.0, "qsc_code_num_chars_line_mean": 27.10059172, "qsc_code_frac_chars_alphabet": 0.78316646, "qsc_code_frac_chars_comments": 0.01419214, "qsc_code_cate_xml_start": 0.0, "qsc_code_frac_lines_dupe_lines": 0.32317073, "qsc_code_cate_autogen": 0.0, "qsc_code_frac_lines_long_string": 0.0, "qsc_code_frac_chars_string_length": 0.03011515, "qsc_code_frac_chars_long_word_length": 0.0, "qsc_code_frac_lines_string_concat": 0.0, "qsc_code_cate_encoded_data": 0.0, "qsc_code_frac_chars_hex_words": 0.0, "qsc_code_frac_lines_prompt_comments": 0.0, "qsc_code_frac_lines_assert": 0.0, "qsc_codejavascript_cate_ast": 1.0, "qsc_codejavascript_cate_var_zero": 0.0, "qsc_codejavascript_frac_lines_func_ratio": 0.0, "qsc_codejavascript_num_statement_line": 0.03658537, "qsc_codejavascript_score_lines_no_logic": 0.02439024, "qsc_codejavascript_frac_words_legal_var_name": 1.0, "qsc_codejavascript_frac_words_legal_func_name": null, "qsc_codejavascript_frac_words_legal_class_name": null, "qsc_codejavascript_frac_lines_print": 0.0}
1
{"qsc_code_frac_chars_replacement_symbols": 0, "qsc_code_num_words": 0, "qsc_code_num_chars": 0, "qsc_code_mean_word_length": 0, "qsc_code_frac_chars_top_2grams": 0, "qsc_code_frac_chars_top_3grams": 0, "qsc_code_frac_chars_top_4grams": 0, "qsc_code_frac_chars_dupe_5grams": 0, "qsc_code_frac_chars_dupe_6grams": 0, "qsc_code_frac_chars_dupe_7grams": 0, "qsc_code_frac_chars_dupe_8grams": 0, "qsc_code_frac_chars_dupe_9grams": 0, "qsc_code_frac_chars_dupe_10grams": 0, "qsc_code_size_file_byte": 0, "qsc_code_num_lines": 0, "qsc_code_num_chars_line_max": 0, "qsc_code_num_chars_line_mean": 0, "qsc_code_frac_chars_alphabet": 0, "qsc_code_frac_chars_digital": 0, "qsc_code_frac_chars_whitespace": 0, "qsc_code_frac_chars_comments": 0, "qsc_code_cate_xml_start": 0, "qsc_code_frac_lines_dupe_lines": 0, "qsc_code_cate_autogen": 0, "qsc_code_frac_lines_long_string": 0, "qsc_code_frac_chars_string_length": 0, "qsc_code_frac_chars_long_word_length": 0, "qsc_code_cate_encoded_data": 0, "qsc_code_frac_chars_hex_words": 0, "qsc_code_frac_lines_prompt_comments": 0, "qsc_code_frac_lines_assert": 0, "qsc_codejavascript_cate_ast": 0, "qsc_codejavascript_cate_var_zero": 0, "qsc_codejavascript_frac_lines_func_ratio": 0, "qsc_codejavascript_score_lines_no_logic": 0, "qsc_codejavascript_frac_lines_print": 0}
007revad/Plex_Server_Sync
plex_server_sync.sh
#!/usr/bin/env bash #----------------------------------------------------------------------------- # Script to sync Plex server database & metadata to backup Plex server. # # It also syncs your settings, though you can disable this by adding the # following to the included plex_rsync_exclude.txt # Preferences.xml # # Requirements: # The script MUST be run on the device where the main Plex server is. # The following files must be in the same folder as Plex_Server_Sync.sh # 1. plex_server_sync.config # 2. plex_rsync_exclude.txt # 3. edit_preferences.sh # # If you want to schedule this script to run as a user: # 1. You need SSH keys setup so SCP and rsync can connect without passwords. # 2. You also need your user to be able to sudo without a password prompt. # # https://github.com/007revad/Plex_Server_Sync # Script verified at https://www.shellcheck.net/ #------------------------------------------------------------------------------ scriptver="v2.0.7" script=Plex_Server_Sync repo="007revad/Plex_Server_Sync" scriptname=plex_server_sync # Show script version echo -e "$script $scriptver\n" # Check if script is running in GNU bash and not BusyBox ash Shell=$(/proc/self/exe --version 2>/dev/null | grep "GNU bash" | cut -d "," -f1) if [ "$Shell" != "GNU bash" ]; then echo -e "You need to install bash to be able to run this script." echo -e "\nIf running this script on an ASUSTOR:" echo "1. Install Entware from App Central" echo "2. Run the following commands in a shell:" echo "opkg update && opkg upgrade" echo -e "opkg install bash\n" exit 1 fi # Read variables from plex_server_sync.config if [[ -f $(dirname -- "$0";)/plex_server_sync.config ]]; then # shellcheck disable=SC1090,SC1091 while read -r var; do if [[ $var =~ ^[a-zA-Z0-9_]+=.* ]]; then export "$var"; fi done < "$(dirname -- "$0";)"/plex_server_sync.config else echo "plex_server_sync.config file missing!" exit 1 fi #src_Directory="/volume1/plex_test/AppData/Plex Media Server" # test, delete later ########## #dst_Directory="/volume1/plex_test/Library/Plex Media Server" # test, delete later ########## #dst_Directory="/volume1/plex_test/From DSM7" # test, delete later ########## #----------------------------------------------------- # Set date and time variables # Timer variable to log time taken to sync PMS start="${SECONDS}" # Get Start Time and Date Started=$( date ) #----------------------------------------------------- # Set log file name if [[ ! -d $LogPath ]]; then LogPath=$( dirname -- "$0"; ) fi Log="$LogPath/$( date '+%Y%m%d')_Plex_Server_Sync.log" if [[ -f $Log ]]; then # Include hh-mm if log file already exists (already run today) Log="$LogPath/$( date '+%Y%m%d-%H%M')_Plex_Server_Sync.log" fi ErrLog="${Log%.*}_ERRORS.log" # Log header CYAN='\e[0;36m' WHITE='\e[0;37m' echo -e "${CYAN}--- Plex Server Sync ---${WHITE}" # shell only echo -e "--- Plex Server Sync ---\n" 1>> "$Log" # log only echo -e "Syncing $src_IP to $dst_IP\n" |& tee -a "$Log" #----------------------------------------------------- # Initial checks # Convert hostnames to lower case src_IP=${src_IP,,} dst_IP=${dst_IP,,} if [[ -z $dst_SshPort ]]; then dst_SshPort=22; fi if [[ ! $dst_SshPort =~ ^[0-9]+$ ]]; then echo "Aborting! Destination SSH Port is not numeric: $dst_SshPort" |& tee -a "$Log" exit 1 fi Exclude_File="$( dirname -- "$0"; )/plex_rsync_exclude.txt" if [[ ! -f $Exclude_File ]]; then echo -e "Aborting! Exclude_File not found: \n$Exclude_File" |& tee -a "$Log" exit 1 fi edit_preferences="$( dirname -- "$0"; )/edit_preferences.sh" if [[ ! -f $edit_preferences ]]; then echo -e "Aborting! edit_preferences.sh not found: \n$edit_preferences" |& tee -a "$Log" exit 1 fi # Check script is running on the source device host=$(hostname) # for comparability #ip=$(ip route get 1 | sed 's/^.*src \([^ ]*\).*$/\1/;q') # for comparability ip=$(ip -o route get $dst_IP | sed 's/^.*src \([^ ]*\).*$/\1/;q') # Issue #6 sed 's/^.*src \([^ ]*\).*$/\1/;q') if [[ $src_IP != "${host,,}" ]] && [[ $src_IP != "$ip" ]]; then echo "Aborting! Script is not running on source device: $src_IP" |& tee -a "$Log" exit 1 fi echo "Source: $src_Directory" |& tee -a "$Log" echo "Destination: $dst_Directory" |& tee -a "$Log" if [[ ${Delete,,} != "yes" ]] && [[ ${Delete,,} != "no" ]]; then echo -e "\nDelete extra files on destination? [y/n]:" |& tee -a "$Log" read -r -t 10 answer if [[ ${answer,,} == y ]]; then Delete=yes echo yes 1>> "$Log" else echo no 1>> "$Log" fi answer= fi if [[ ${DryRun,,} != "yes" ]] && [[ ${DryRun,,} != "no" ]]; then echo -e "\nDo a dry run test? [y/n]:" |& tee -a "$Log" read -r -t 10 answer if [[ ${answer,,} == y ]]; then DryRun=yes echo yes 1>> "$Log" else echo no 1>> "$Log" fi answer= fi #----------------------------------------------------- # Check host and destination are not the same # This function is also used by PlexVersion function Host2IP(){ if [[ $2 == "remote" ]]; then # Get remote IP from hostname ip=$(ssh "${dst_User}@${1,,}" -p "$dst_SshPort"\ "ip route get 1 | sed 's/^.*src \([^ ]*\).*$/\1/;q'") else # Get local IP from hostname ip=$(ip route get 1 | sed 's/^.*src \([^ ]*\).*$/\1/;q') fi echo "$ip" } # Check the source isn't also the target if [[ $src_IP == "$dst_IP" ]]; then echo -e "\nSource and Target are the same!" |& tee -a "$Log" echo "Source: $src_IP" |& tee -a "$Log" echo "Target: $dst_IP" |& tee -a "$Log" exit 1 elif [[ $(Host2IP "$src_IP") == $(Host2IP "$dst_IP" remote) ]]; then echo -e "\nSource and Target are the same!" echo "Source: $src_IP" echo "Target: $dst_IP" exit 1 fi #----------------------------------------------------- # Get Plex version BEFORE we stop both Plex servers # we can get the Plex version from Plex binary but location is OS dependant # so we'll use the independent method (but it requires Plex to be running) PlexVersion(){ if [[ $2 == "remote" ]]; then ip=$(Host2IP "$1" remote) else ip=$(Host2IP "$1") fi if [[ $ip ]]; then # Get Plex version from IP address Response=$(curl -s "http://${ip}:32400/identity") ver=$(printf %s "$Response" | grep '" version=' | awk -F= '$1=="version"\ {print $2}' RS=' ' | cut -d'"' -f2 | cut -d"-" -f1) echo "$ver" fi return } src_Version=$(PlexVersion "$src_IP") echo -e "\nSource Plex version: $src_Version" |& tee -a "$Log" dst_Version=$(PlexVersion "$dst_IP" remote) echo -e "Destination Plex version: $dst_Version\n" |& tee -a "$Log" if [[ ! $src_Version ]] || [[ ! $dst_Version ]]; then echo "WARN: Unable to get one or both Plex versions." |& tee -a "$Log" echo "One or both servers may be stopped already." |& tee -a "$Log" echo "Are both Plex versions the same? [y/n]" |& tee -a "$Log" read -r answer if [[ ${answer,,} != y ]]; then echo no 1>> "$Log" exit 1 else echo yes 1>> "$Log" fi fi # Check both versions are the same if [[ $src_Version != "$dst_Version" ]]; then if [[ $answer != "y" ]]; then echo "Plex versions are different. Aborting." |& tee -a "$Log" echo -e "Source: $src_Version \nDestination: $dst_Version" |& tee -a "$Log" exit 1 fi fi #----------------------------------------------------- # Plex Stop Start function PlexControl(){ if [[ $1 == "start" ]] || [[ $1 == "stop" ]]; then if [[ $2 == "local" ]]; then # stop or start local server if [[ $src_Docker == "yes" ]]; then if [[ ${src_OS,,} == "dsm7" ]] || [[ ${src_OS,,} == "dsm6" ]]; then # https://www.reddit.com/r/synology/comments/15h6dn3/how_to_stop_all_docker_containers_peacefully/ /usr/syno/bin/synowebapi --exec api=SYNO.Docker.Container method="$1" version=1 \ name="$src_Docker_plex_name" >/dev/null else # docker stop results in "Docker container stopped unexpectedly" alert and email. docker "$1" "$(docker ps -qf name=^"$src_Docker_plex_name"$)" >/dev/null fi else case ${src_OS,,} in dsm7) sudo /usr/syno/bin/synopkg "$1" PlexMediaServer >/dev/null ;; dsm6) sudo /usr/syno/bin/synopkg "$1" "Plex Media Server" ;; adm) sudo /usr/local/AppCentral/plexmediaserver/CONTROL/start-stop.sh "$1" ;; linux) # UNTESTED #sudo systemctl "$1" plexmediaserver sudo service plexmediaserver "$1" ;; *) echo "Unknown local OS type. Cannot $1 Plex." |& tee -a "$Log" exit 1 ;; esac fi elif [[ $2 == "remote" ]]; then # stop or start remote server if [[ $src_Docker == "yes" ]]; then if [[ ${src_OS,,} == "dsm7" ]] || [[ ${src_OS,,} == "dsm6" ]]; then # https://www.reddit.com/r/synology/comments/15h6dn3/how_to_stop_all_docker_containers_peacefully/ ssh "${dst_User}@${dst_IP}" -p "$dst_SshPort" \ "sudo /usr/syno/bin/synowebapi --exec api=SYNO.Docker.Container method=$1 version=1" \ "name=$dst_Docker_plex_name" >/dev/null else # docker stop results in "Docker container stopped unexpectedly" alert and email. ssh "${dst_User}@${dst_IP}" -p "$dst_SshPort" \ "sudo docker $1 $(docker ps -qf name=^"$dst_Docker_plex_name"$)" >/dev/null fi else case ${dst_OS,,} in dsm7) ssh "${dst_User}@${dst_IP}" -p "$dst_SshPort" \ "sudo /usr/syno/bin/synopkg $1 PlexMediaServer" >/dev/null ;; dsm6) ssh "${dst_User}@${dst_IP}" -p "$dst_SshPort" \ "sudo /usr/syno/bin/synopkg $1 Plex\ Media\ Server" ;; adm) ssh "${dst_User}@${dst_IP}" -p "$dst_SshPort" \ "sudo /usr/local/AppCentral/plexmediaserver/CONTROL/start-stop.sh $1" ;; linux) # UNTESTED #ssh "${dst_User}@${dst_IP}" -p "$dst_SshPort" "sudo systemctl $1 plexmediaserver" ssh "${dst_User}@${dst_IP}" -p "$dst_SshPort" "sudo service plexmediaserver $1" ;; *) echo "Unknown remote OS type. Cannot $1 Plex." |& tee -a "$Log" exit 1 ;; esac fi else echo "Invalid parameter #2: $2" |& tee -a "$Log" exit 1 fi if [[ $1 == "stop" ]]; then sleep 5 # Give sockets a moment to close fi else echo "Invalid parameter #1: $1" |& tee -a "$Log" exit 1 fi return } #----------------------------------------------------- # Stop both Plex servers echo "Stopping Plex on $src_IP" |& tee -a "$Log" PlexControl stop local |& tee -a "$Log" echo -e "\nStopping Plex on $dst_IP" |& tee -a "$Log" PlexControl stop remote |& tee -a "$Log" echo >> "$Log" #----------------------------------------------------- # Check both servers have stopped # not the best way to get Plex status but other ways are OS dependant abort= if [[ $(PlexVersion "$src_IP") ]]; then echo "Source Plex $src_IP is still running!" |& tee -a "$Log" abort=1 fi if [[ $(PlexVersion "$dst_IP" remote) ]]; then echo "Destination Plex $dst_IP is still running!" |& tee -a "$Log" abort=1 fi if [[ $abort ]]; then echo "Aborting!" |& tee -a "$Log" exit 1 fi #----------------------------------------------------- # Backup destination Preferences.xml # Backup Preferences.xml to Preferences.bak ssh "${dst_User}@${dst_IP}" -p "$dst_SshPort" \ "cp -u '${dst_Directory}/Preferences.xml' '${dst_Directory}/Preferences.bak'" |& tee -a "$Log" #----------------------------------------------------- # Sync source to destination with rsync cd / || { echo "cd / failed!" |& tee -a "$Log"; exit 1; } echo "" # ------ rsync flags used ------ # --rsh destination shell to use # -r recursive # -l copy symlinks as symlinks # -h human readable # -p preserver permissions <-- FAILED to set permissions. Operation not permitted. Need to test more. # -t preserve modification times # -O don't keep directory's mtime (with -t) # --progress show progress during transfer # --stats give some file-transfer stats # # ------ optional rsync flags ------ # --delete delete extraneous files from destination dirs # -n, --dry-run perform a trial run with no changes made # Unset any existing arguments while [[ $1 ]]; do shift; done if [[ ${DryRun,,} == yes ]]; then # Set --dry-run flag for rsync set -- "$@" "--dry-run" echo Running an rsync dry-run test |& tee -a "$Log" fi if [[ ${Delete,,} == yes ]]; then # Set --delete flag for rsync set -- "$@" "--delete" echo Running rsync with delete flag |& tee -a "$Log" fi # --delete doesn't delete if you have * wildcard after source directory path rsync --rsh="ssh -p$dst_SshPort" -rlhtO "$@" --progress --stats \ --exclude-from="$Exclude_File" "$src_Directory/" "$dst_IP":"$dst_Directory" |& tee -a "$Log" #----------------------------------------------------- # Restore unique IDs to destination's Preferences.xml echo -e "\nCopying edit_preferences.sh to destination" |& tee -a "$Log" if [[ $src_OS == DSM7 ]]; then # -O flag is required if DSM7 is the source or SCP defaults to SFTP sudo -u "$src_User" scp -O -P "$dst_SshPort" "$(dirname "$0")/edit_preferences.sh" \ "$dst_User"@"$dst_IP":"'${dst_Directory}/'" |& tee -a "$Log" else # Prepend spaces in destination path with \\ spath=$(dirname "$0") sudo -u "$src_User" scp -P "$dst_SshPort" "${spath}/edit_preferences.sh" \ "$dst_User"@"$dst_IP":"${dst_Directory// /\\ }/" |& tee -a "$Log" fi echo -e "\nRunning $dst_Directory/edit_preferences.sh" |& tee -a "$Log" ssh "${dst_User}@${dst_IP}" -p "$dst_SshPort" "'${dst_Directory}/edit_preferences.sh'" |& tee -a "$Log" #----------------------------------------------------- # Start both Plex servers echo -e "\nStarting Plex on $src_IP" |& tee -a "$Log" PlexControl start local |& tee -a "$Log" echo -e "\nStarting Plex on $dst_IP" |& tee -a "$Log" PlexControl start remote |& tee -a "$Log" #----------------------------------------------------- # Check if there errors from rsync, scp or cp if [[ -f $Log ]]; then tmp=$(awk '/^(rsync|cp|scp|\*\*\*|IO error).*/' "$Log") if [[ -n $tmp ]]; then echo "$tmp" >> "$ErrLog" fi fi if [[ -f $ErrLog ]]; then echo -e "\n${CYAN}Some errors occurred!${WHITE} See:" # shell only echo -e "\nSome errors occurred! See:" >> "$Log" # log only echo "$ErrLog" |& tee -a "$Log" fi #-------------------------------------------------------------------------- # Append the time taken to stdout # End Time and Date Finished=$( date ) # bash timer variable to log time taken end="${SECONDS}" # Elapsed time in seconds Runtime=$(( end - start )) # Append start and end date/time and runtime echo -e "\nPlex Sync Started: " "${Started}" |& tee -a "$Log" echo "Plex Sync Finished:" "${Finished}" |& tee -a "$Log" # Append days, hours, minutes and seconds from $Runtime printf "Plex Sync Duration: " |& tee -a "$Log" printf '%dd:%02dh:%02dm:%02ds\n' \ $((Runtime/86400)) $((Runtime%86400/3600)) $((Runtime%3600/60)) $((Runtime%60)) |& tee -a "$Log" echo "" |& tee -a "$Log" exit
16,437
plex_server_sync
sh
en
shell
code
{"qsc_code_num_words": 2094, "qsc_code_num_chars": 16437.0, "qsc_code_mean_word_length": 4.03581662, "qsc_code_frac_words_unique": 0.19484241, "qsc_code_frac_chars_top_2grams": 0.02366584, "qsc_code_frac_chars_top_3grams": 0.04141522, "qsc_code_frac_chars_top_4grams": 0.01692107, "qsc_code_frac_chars_dupe_5grams": 0.33747486, "qsc_code_frac_chars_dupe_6grams": 0.30150278, "qsc_code_frac_chars_dupe_7grams": 0.24446811, "qsc_code_frac_chars_dupe_8grams": 0.23760502, "qsc_code_frac_chars_dupe_9grams": 0.2018696, "qsc_code_frac_chars_dupe_10grams": 0.18057035, "qsc_code_frac_chars_replacement_symbols": 0.0, "qsc_code_frac_chars_digital": 0.01503197, "qsc_code_frac_chars_whitespace": 0.2674454, "qsc_code_size_file_byte": 16437.0, "qsc_code_num_lines": 481.0, "qsc_code_num_chars_line_max": 115.0, "qsc_code_num_chars_line_mean": 34.17255717, "qsc_code_frac_chars_alphabet": 0.68682003, "qsc_code_frac_chars_comments": 0.31848878, "qsc_code_cate_xml_start": 0.0, "qsc_code_frac_lines_dupe_lines": 0.40925267, "qsc_code_cate_autogen": 0.0, "qsc_code_frac_lines_long_string": 0.00355872, "qsc_code_frac_chars_string_length": 0.33791626, "qsc_code_frac_chars_long_word_length": 0.06802964, "qsc_code_frac_lines_string_concat": 0.0, "qsc_code_cate_encoded_data": 0.0, "qsc_code_frac_chars_hex_words": 0.0, "qsc_code_frac_lines_prompt_comments": 0.0, "qsc_code_frac_lines_assert": 0.0}
1
{"qsc_code_frac_chars_replacement_symbols": 0, "qsc_code_num_words": 0, "qsc_code_num_chars": 0, "qsc_code_mean_word_length": 0, "qsc_code_frac_chars_top_2grams": 0, "qsc_code_frac_chars_top_3grams": 0, "qsc_code_frac_chars_top_4grams": 0, "qsc_code_frac_chars_dupe_5grams": 0, "qsc_code_frac_chars_dupe_6grams": 0, "qsc_code_frac_chars_dupe_7grams": 0, "qsc_code_frac_chars_dupe_8grams": 0, "qsc_code_frac_chars_dupe_9grams": 0, "qsc_code_frac_chars_dupe_10grams": 0, "qsc_code_frac_lines_dupe_lines": 0, "qsc_code_size_file_byte": 0, "qsc_code_num_lines": 0, "qsc_code_num_chars_line_max": 0, "qsc_code_num_chars_line_mean": 0, "qsc_code_frac_chars_alphabet": 0, "qsc_code_frac_chars_digital": 0, "qsc_code_frac_chars_whitespace": 0, "qsc_code_frac_chars_comments": 0, "qsc_code_cate_xml_start": 0, "qsc_code_cate_autogen": 0, "qsc_code_frac_chars_long_word_length": 0, "qsc_code_cate_encoded_data": 0, "qsc_code_frac_chars_hex_words": 0, "qsc_code_frac_lines_prompt_comments": 0}
007revad/Plex_Server_Sync
README.md
# Plex Server Sync Sync main Plex server database &amp; metadata to a backup Plex server <a href="https://github.com/007revad/Plex_Server_Sync/releases"><img src="https://img.shields.io/github/release/007revad/Plex_Server_Sync.svg"></a> ![Badge](https://hitscounter.dev/api/hit?url=https%3A%2F%2Fgithub.com%2F007revad%2FPlex_Server_Sync&label=Visitors&icon=github&color=%23198754&message=&style=flat&tz=Australia%2FSydney) [![Donate](https://img.shields.io/badge/Donate-PayPal-green.svg)](https://www.paypal.com/paypalme/007revad) [![](https://img.shields.io/static/v1?label=Sponsor&message=%E2%9D%A4&logo=GitHub&color=%23fe8e86)](https://github.com/sponsors/007revad) [![committers.top badge](https://user-badge.committers.top/australia/007revad.svg)](https://user-badge.committers.top/australia/007revad) <p align="center"><img src="plex_server_sync_logo.png"></p> ### Description Plex Server Sync is a bash script to sync one Plex Media Server to another Plex Media Server, **including played status, play progress, posters, metadata, ratings and settings**. The only things not synced are settings specific to each Plex Media Server (like server ID, friendly name, public port etc), and files and folders listed in the plex_rsync_exclude.txt file. <br> ***NEW*** Version 2 and later also support Plex in docker. <br> This script was written for people who: * Have setup a clean installation of Plex Media Server on a different device and want to migrate their Plex settings, meta data, database, played status and played progress to the new device. * Have a main Plex server and a backup Plex server and want to keep the backup server in sync with the main server. * Have a Plex server at home and a Plex server at their holiday house and want to sync to their holiday house Plex server before leaving home, and then sync back to their home Plex server before leaving the holiday house to return home. The script needs to run on the source plex server machine. Tested on Synolgy DSM 7, DSM 6 and Asustor ADM. It should also work on Linux. #### What the script does * Gets the Plex version from both Plex servers. * Stops both the source and destination Plex servers. * Backs up the destination Plex server's Preferences.xml file. * Copies all newer data files from the source Plex server to the destination Plex server. * Files listed in the exclude file will not be copied. * Optionally deletes any extra files in the destination Plex server's data folder. * Files listed in the exclude file will not be deleted. * Restores the destination Plex server's machine specific settings in Preferences.xml. * Starts both Plex servers. Everything is saved to a log file, and any errors are also saved to an error log file. #### What the script does NOT do It does **not** do a 2-way sync. It only syncs one Plex server to another Plex server. ### Download the script 1. Download the latest version _Source code (zip)_ from https://github.com/007revad/Plex_Server_Sync/releases 2. Save the download zip file to a folder on the Synology. 3. Unzip the zip file. ### Requirements 1. **The script needs to run on the source Plex Media Server machine.** 2. **The following files must be in the same folder as plex_server_sync.sh** ```YAML plex_server_sync.config edit_preferences.sh plex_rsync_exclude.txt ``` 3. **Both Plex servers must be running the same Plex Media Server version** 4. **Both Plex servers must have the same library path** If the source Plex server accesses it's media libraries at "/volume1/videos" and "/volume1/music" then the destination server also needs to access it's media libraries at "/volume1/videos" and "/volume1/music" 5. **SSH Keys and sudoers** If you want to schedule the script to run unattended, as a scheduled cron job, the users need to have sudoers and SSH keys setup so that the SSH, SCP and rsync commands can access the remote server without you entering the user's password. See https://blog.golimb.com/2020/10/03/synology-ssh-key-authentication/ for steps on setting up SSH key authentication. **Asustor NAS requirements** Because the Asustor only has Busybox ash and this script requires bash you'll need to instal bash. To install bash on your Asustor: 1. First install Entware from App Central. 2. Then run the following commands via SSH. You can run the commands in "Shell In A Box" from App Central, or use PuTTY. ```YAML opkg update && opkg upgrade opkg install bash ``` ### Settings You need to set the source and destination settings in the **plex_server_sync.config** file. There are also a few optional settings in the plex_server_sync.config file. **Examples:** **Source and destination both Plex package:** ```YAML src_IP=192.168.0.70 src_OS=DSM7 src_Docker=no src_Docker_plex_name= src_Directory="/volume1/PlexMediaServer/AppData/Plex Media Server" src_User=Bob dst_IP=192.168.0.60 dst_OS=DSM6 dst_Docker=no dst_Docker_plex_name= dst_Directory="/volume1/Plex/Library/Application Support/Plex Media Server" dst_User=Bob dst_SshPort=22 Delete=yes DryRun=no LogPath=~/plex_server_sync_logs ``` **Source and destination both Plex in docker:** ```YAML src_IP=192.168.0.70 src_OS=DSM7 dst_Docker=yes dst_Docker_plex_name="plexinc-pms-docker-1" src_Directory="/volume1/docker/plex/Library/Application Support" src_User=Bob dst_IP=192.168.0.60 dst_OS=DSM6 dst_Docker=yes dst_Docker_plex_name="plexinc-pms-docker-1" dst_Directory="/volume1/docker/plex/Library/Application Support" dst_User=Bob dst_SshPort=22 Delete=yes DryRun=no LogPath=~/plex_server_sync_logs ``` ### Default contents of plex_rsync_exclude.txt Any files or folders listed in plex_rsync_exclude.txt will **not** be synced. The first 4 files listed must never be synced from one server to another. The folders listed are optional. **Contents of plex_rsync_exclude.txt** ```YAMLedit_preferences.sh Preferences.bak .LocalAdminToken plexmediaserver.pid Cache Codecs Crash Reports Diagnostics Drivers Logs Updates ```
6,016
README
md
en
markdown
text
{"qsc_doc_frac_chars_curly_bracket": 0.0, "qsc_doc_frac_words_redpajama_stop": 0.21141975, "qsc_doc_num_sentences": 104.0, "qsc_doc_num_words": 998, "qsc_doc_num_chars": 6016.0, "qsc_doc_num_lines": 162.0, "qsc_doc_mean_word_length": 4.59018036, "qsc_doc_frac_words_full_bracket": 0.0, "qsc_doc_frac_lines_end_with_readmore": 0.0, "qsc_doc_frac_lines_start_with_bullet": 0.0, "qsc_doc_frac_words_unique": 0.32164329, "qsc_doc_entropy_unigram": 5.13911962, "qsc_doc_frac_words_all_caps": 0.02083333, "qsc_doc_frac_lines_dupe_lines": 0.30434783, "qsc_doc_frac_chars_dupe_lines": 0.07937328, "qsc_doc_frac_chars_top_2grams": 0.06330496, "qsc_doc_frac_chars_top_3grams": 0.03667322, "qsc_doc_frac_chars_top_4grams": 0.02073783, "qsc_doc_frac_chars_dupe_5grams": 0.24536127, "qsc_doc_frac_chars_dupe_6grams": 0.2167649, "qsc_doc_frac_chars_dupe_7grams": 0.20410391, "qsc_doc_frac_chars_dupe_8grams": 0.16262825, "qsc_doc_frac_chars_dupe_9grams": 0.12726479, "qsc_doc_frac_chars_dupe_10grams": 0.09670378, "qsc_doc_frac_chars_replacement_symbols": 0.0, "qsc_doc_cate_code_related_file_name": 1.0, "qsc_doc_num_chars_sentence_length_mean": 21.62030075, "qsc_doc_frac_chars_hyperlink_html_tag": 0.12200798, "qsc_doc_frac_chars_alphabet": 0.86158902, "qsc_doc_frac_chars_digital": 0.02397062, "qsc_doc_frac_chars_whitespace": 0.14012633, "qsc_doc_frac_chars_hex_words": 0.0}
1
{"qsc_doc_frac_chars_replacement_symbols": 0, "qsc_doc_entropy_unigram": 0, "qsc_doc_frac_chars_top_2grams": 0, "qsc_doc_frac_chars_top_3grams": 0, "qsc_doc_frac_chars_top_4grams": 0, "qsc_doc_frac_chars_dupe_5grams": 0, "qsc_doc_frac_chars_dupe_6grams": 0, "qsc_doc_frac_chars_dupe_7grams": 0, "qsc_doc_frac_chars_dupe_8grams": 0, "qsc_doc_frac_chars_dupe_9grams": 0, "qsc_doc_frac_chars_dupe_10grams": 0, "qsc_doc_frac_chars_dupe_lines": 0, "qsc_doc_frac_lines_dupe_lines": 0, "qsc_doc_frac_lines_end_with_readmore": 0, "qsc_doc_frac_lines_start_with_bullet": 0, "qsc_doc_frac_words_all_caps": 0, "qsc_doc_mean_word_length": 0, "qsc_doc_num_chars": 0, "qsc_doc_num_lines": 0, "qsc_doc_num_sentences": 0, "qsc_doc_num_words": 0, "qsc_doc_frac_chars_hex_words": 0, "qsc_doc_frac_chars_hyperlink_html_tag": 0, "qsc_doc_frac_chars_alphabet": 0, "qsc_doc_frac_chars_digital": 0, "qsc_doc_frac_chars_whitespace": 0}
007revad/Plex_Server_Sync
edit_preferences.sh
#!/usr/bin/env bash #------------------------------------------------------------------------- # Companion script to Plex_Server_Sync.sh # # https://github.com/007revad/Plex_Server_Sync # Script verified at https://www.shellcheck.net/ #-------------------------------------------------------------------------- cd "$(dirname "$0")" || { echo "cd $(dirname "$0") failed!"; exit 1; } #echo $PWD # debug if [[ ! -f Preferences.bak ]]; then echo "Preferences.bak not found! Aborting." exit 1 elif [[ ! -f Preferences.xml ]]; then echo "Preferences.xml not found! Aborting." exit 1 fi # Assign Pref_keys string array Pref_keys=("AnonymousMachineIdentifier" "CertificateUUID" "FriendlyName" "LastAutomaticMappedPort") # Append more elements to the the array Pref_keys+=("MachineIdentifier" "ManualPortMappingPort" "PlexOnlineToken" "ProcessedMachineIdentifier") # Padding var for formatting padding=" " # Get length of Pref_keys Len=${#Pref_keys[@]} # Get backup Preferences.bak file's ID values echo -e "\nPreferences.bak" declare -A Pref_bak Num="0" while [[ $Num -lt "$Len" ]]; do Pref_bak[$Num]=$(grep -oP "(?<=\b${Pref_keys[$Num]}=\").*?(?=(\" |\"/>))" "Preferences.bak") #echo "${Pref_keys[$Num]} = ${Pref_bak[$Num]}" echo "${Pref_keys[$Num]}${padding:${#Pref_keys[$Num]}} = ${Pref_bak[$Num]}" Num=$((Num +1)) done # Get synced Preferences.xml file's ID values (so we can replace them) echo -e "\nPreferences.xml" declare -A Pref_new Num="0" while [[ $Num -lt "$Len" ]]; do Pref_new[$Num]=$(grep -oP "(?<=\b${Pref_keys[$Num]}=\").*?(?=(\" |\"/>))" "Preferences.xml") #echo "${Pref_keys[$Num]} = ${Pref_new[$Num]}" echo "${Pref_keys[$Num]}${padding:${#Pref_keys[$Num]}} = ${Pref_new[$Num]}" Num=$((Num +1)) done echo # Change synced Preferences.xml ID values to backed up ID values changed=0 Num="0" while [[ $Num -lt "$Len" ]]; do if [[ ${Pref_new[$Num]} ]] && [[ ${Pref_bak[$Num]} ]]; then if [[ ${Pref_new[$Num]} != "${Pref_bak[$Num]}" ]]; then echo "Updating ${Pref_keys[$Num]}" sed -i "s/ ${Pref_keys[$Num]}=\"${Pref_new[$Num]}/ ${Pref_keys[$Num]}=\"${Pref_bak[$Num]}/g" "Preferences.xml" changed=$((changed+1)) fi fi Num=$((Num +1)) done # VaapiDriver in Preferences.bak VaapiDriver=$(grep -oP '(?<=\bVaapiDriver=").*?(?=(" |"/>))' "Preferences.bak") echo -e "Back_VaapiDriver = $VaapiDriver\n" # VaapiDriver in Preferences.xml Main_VaapiDriver=$(grep -oP '(?<=\bVaapiDriver=").*?(?=(" |"/>))' "Preferences.xml") echo -e "Main_VaapiDriver = $Main_VaapiDriver\n" # VaapiDriver if [[ $Main_VaapiDriver ]] && [[ $VaapiDriver ]]; then if [[ $Main_VaapiDriver != "$VaapiDriver" ]]; then #echo -e "Updating VaapiDriver\n" echo "Updating VaapiDriver" sed -i "s/ VaapiDriver=\"${Main_VaapiDriver}/ VaapiDriver=\"${VaapiDriver}/g" "Preferences.xml" changed=$((changed+1)) else #echo -e "Same VaapiDriver already\n" echo "Same VaapiDriver already" fi elif [[ $VaapiDriver ]]; then # Insert VaapiDriver="i965" or VaapiDriver="iHD" at the end, before /> #echo -e "Adding VaapiDriver\n" echo "Adding VaapiDriver" sed -i "s/\/>/ VaapiDriver=\"${VaapiDriver}\"\/>/g" "Preferences.xml" changed=$((changed+1)) elif [[ $Main_VaapiDriver ]]; then # Delete VaapiDriver="i965" or VaapiDriver="iHD" #echo -e "Deleting VaapiDriver\n" echo "Deleting VaapiDriver" sed -i "s/ VaapiDriver=\"${Main_VaapiDriver}\"//g" "Preferences.xml" changed=$((changed+1)) fi if [[ $changed -eq "1" ]]; then echo -e "\n$changed change made in Preferences.xml" elif [[ $changed -gt "0" ]]; then echo -e "\n$changed changes made in Preferences.xml" else echo -e "\nNo changes needed in Preferences.xml" fi exit
3,869
edit_preferences
sh
en
shell
code
{"qsc_code_num_words": 469, "qsc_code_num_chars": 3869.0, "qsc_code_mean_word_length": 4.79104478, "qsc_code_frac_words_unique": 0.25799574, "qsc_code_frac_chars_top_2grams": 0.05696484, "qsc_code_frac_chars_top_3grams": 0.05384958, "qsc_code_frac_chars_top_4grams": 0.0400534, "qsc_code_frac_chars_dupe_5grams": 0.41433022, "qsc_code_frac_chars_dupe_6grams": 0.26835781, "qsc_code_frac_chars_dupe_7grams": 0.22830441, "qsc_code_frac_chars_dupe_8grams": 0.15398309, "qsc_code_frac_chars_dupe_9grams": 0.03560303, "qsc_code_frac_chars_dupe_10grams": 0.03560303, "qsc_code_frac_chars_replacement_symbols": 0.0, "qsc_code_frac_chars_digital": 0.00848256, "qsc_code_frac_chars_whitespace": 0.1773068, "qsc_code_size_file_byte": 3869.0, "qsc_code_num_lines": 113.0, "qsc_code_num_chars_line_max": 123.0, "qsc_code_num_chars_line_mean": 34.23893805, "qsc_code_frac_chars_alphabet": 0.69745523, "qsc_code_frac_chars_comments": 0.27707418, "qsc_code_cate_xml_start": 0.0, "qsc_code_frac_lines_dupe_lines": 0.37142857, "qsc_code_cate_autogen": 0.0, "qsc_code_frac_lines_long_string": 0.0, "qsc_code_frac_chars_string_length": 0.41881259, "qsc_code_frac_chars_long_word_length": 0.10729614, "qsc_code_frac_lines_string_concat": 0.0, "qsc_code_cate_encoded_data": 0.0, "qsc_code_frac_chars_hex_words": 0.0, "qsc_code_frac_lines_prompt_comments": 0.0, "qsc_code_frac_lines_assert": 0.0}
1
{"qsc_code_frac_chars_replacement_symbols": 0, "qsc_code_num_words": 0, "qsc_code_num_chars": 0, "qsc_code_mean_word_length": 0, "qsc_code_frac_chars_top_2grams": 0, "qsc_code_frac_chars_top_3grams": 0, "qsc_code_frac_chars_top_4grams": 0, "qsc_code_frac_chars_dupe_5grams": 0, "qsc_code_frac_chars_dupe_6grams": 0, "qsc_code_frac_chars_dupe_7grams": 0, "qsc_code_frac_chars_dupe_8grams": 0, "qsc_code_frac_chars_dupe_9grams": 0, "qsc_code_frac_chars_dupe_10grams": 0, "qsc_code_frac_lines_dupe_lines": 0, "qsc_code_size_file_byte": 0, "qsc_code_num_lines": 0, "qsc_code_num_chars_line_max": 0, "qsc_code_num_chars_line_mean": 0, "qsc_code_frac_chars_alphabet": 0, "qsc_code_frac_chars_digital": 0, "qsc_code_frac_chars_whitespace": 0, "qsc_code_frac_chars_comments": 0, "qsc_code_cate_xml_start": 0, "qsc_code_cate_autogen": 0, "qsc_code_frac_chars_long_word_length": 0, "qsc_code_cate_encoded_data": 0, "qsc_code_frac_chars_hex_words": 0, "qsc_code_frac_lines_prompt_comments": 0}
007gzs/dingtalk-sdk
README.rst
####################### DingTalk Sdk for Python ####################### .. image:: https://travis-ci.org/007gzs/dingtalk-sdk.svg?branch=master :target: https://travis-ci.org/007gzs/dingtalk-sdk .. image:: https://img.shields.io/pypi/v/dingtalk-sdk.svg :target: https://pypi.org/project/dingtalk-sdk 钉钉开放平台第三方 Python SDK。 `【阅读文档】 <http://dingtalk-sdk.readthedocs.io/zh_CN/latest/>`_。 ******** 功能特性 ******** + 企业内部开发接入api + 应用服务商(ISV)接入api ******** 安装 ******** 目前 dingtalk-sdk 支持的 Python 环境有 2.7, 3.4, 3.5, 3.6 和 pypy。 dingtalk-sdk 消息加解密同时兼容 cryptography 和 PyCrypto, 优先使用 cryptography 库。 可先自行安装 cryptography 或者 PyCrypto 库:: # 安装 cryptography pip install cryptography>=0.8.2 # 或者安装 PyCrypto pip install pycrypto>=2.6.1 为了简化安装过程,推荐使用 pip 进行安装 .. code-block:: bash pip install dingtalk-sdk # with cryptography pip install dingtalk-sdk[cryptography] # with pycrypto pip install dingtalk-sdk[pycrypto] 升级 dingtalk-sdk 到新版本:: pip install -U dingtalk-sdk **************** 使用示例 **************** django 示例 https://github.com/007gzs/dingtalk-django-example
1,112
README
rst
zh
restructuredtext
text
{"qsc_doc_frac_chars_curly_bracket": 0.0, "qsc_doc_frac_words_redpajama_stop": null, "qsc_doc_num_sentences": 27.0, "qsc_doc_num_words": 177, "qsc_doc_num_chars": 1112.0, "qsc_doc_num_lines": 50.0, "qsc_doc_mean_word_length": 4.01694915, "qsc_doc_frac_words_full_bracket": 0.00569801, "qsc_doc_frac_lines_end_with_readmore": 0.0, "qsc_doc_frac_lines_start_with_bullet": 0.0, "qsc_doc_frac_words_unique": 0.51412429, "qsc_doc_entropy_unigram": 4.13221057, "qsc_doc_frac_words_all_caps": 0.01139601, "qsc_doc_frac_lines_dupe_lines": 0.21621622, "qsc_doc_frac_chars_dupe_lines": 0.10912698, "qsc_doc_frac_chars_top_2grams": 0.20112518, "qsc_doc_frac_chars_top_3grams": 0.07594937, "qsc_doc_frac_chars_top_4grams": 0.08860759, "qsc_doc_frac_chars_dupe_5grams": 0.092827, "qsc_doc_frac_chars_dupe_6grams": 0.092827, "qsc_doc_frac_chars_dupe_7grams": 0.092827, "qsc_doc_frac_chars_dupe_8grams": 0.0, "qsc_doc_frac_chars_dupe_9grams": 0.0, "qsc_doc_frac_chars_dupe_10grams": 0.0, "qsc_doc_frac_chars_replacement_symbols": 0.0, "qsc_doc_cate_code_related_file_name": 1.0, "qsc_doc_num_chars_sentence_length_mean": 13.64473684, "qsc_doc_frac_chars_hyperlink_html_tag": 0.04496403, "qsc_doc_frac_chars_alphabet": null, "qsc_doc_frac_chars_digital": 0.02436441, "qsc_doc_frac_chars_whitespace": 0.15107914, "qsc_doc_frac_chars_hex_words": 0.0}
0
{"qsc_doc_frac_chars_replacement_symbols": 0, "qsc_doc_entropy_unigram": 0, "qsc_doc_frac_chars_top_2grams": 1, "qsc_doc_frac_chars_top_3grams": 0, "qsc_doc_frac_chars_top_4grams": 0, "qsc_doc_frac_chars_dupe_5grams": 0, "qsc_doc_frac_chars_dupe_6grams": 0, "qsc_doc_frac_chars_dupe_7grams": 0, "qsc_doc_frac_chars_dupe_8grams": 0, "qsc_doc_frac_chars_dupe_9grams": 0, "qsc_doc_frac_chars_dupe_10grams": 0, "qsc_doc_frac_chars_dupe_lines": 0, "qsc_doc_frac_lines_dupe_lines": 0, "qsc_doc_frac_lines_end_with_readmore": 0, "qsc_doc_frac_lines_start_with_bullet": 0, "qsc_doc_frac_words_full_bracket": 0, "qsc_doc_mean_word_length": 0, "qsc_doc_num_chars": 0, "qsc_doc_num_lines": 0, "qsc_doc_num_sentences": 0, "qsc_doc_num_words": 0, "qsc_doc_frac_chars_hex_words": 0, "qsc_doc_frac_chars_hyperlink_html_tag": 0, "qsc_doc_frac_chars_alphabet": 0, "qsc_doc_frac_chars_digital": 0, "qsc_doc_frac_chars_whitespace": 0}
007gzs/dingtalk-sdk
setup.py
#! /usr/bin/env python # encoding: utf-8 """A setuptools based setup module. See: https://packaging.python.org/en/latest/distributing.html https://github.com/pypa/sampleproject """ # Always prefer setuptools over distutils from setuptools import setup from setuptools.command.test import test as TestCommand # To use a consistent encoding from codecs import open from os import path import sys import ssl try: ssl._create_default_https_context = ssl._create_unverified_context except Exception: pass here = path.abspath(path.dirname(__file__)) class PyTest(TestCommand): user_options = [('pytest-args=', 'a', "Arguments to pass to py.test")] def initialize_options(self): TestCommand.initialize_options(self) self.pytest_args = [] def finalize_options(self): TestCommand.finalize_options(self) self.test_args = [] self.test_suite = True def run_tests(self): import pytest errno = pytest.main(self.pytest_args) sys.exit(errno) cmdclass = {} cmdclass['test'] = PyTest # Get the long description from the README file with open(path.join(here, 'README.rst'), encoding='utf-8') as f: long_description = f.read() with open('requirements.txt') as f: requirements = [line for line in f.read().splitlines() if line] setup( name='dingtalk-sdk', version='1.3.8', keywords='dingding, ding, dtalk, dingtalk, SDK', description='DingTalk SDK for Python', long_description=long_description, url='https://github.com/007gzs/dingtalk-sdk', author='007gzs', author_email='007gzs@sina.com', license='LGPL v3', classifiers=[ 'Development Status :: 3 - Alpha', 'Intended Audience :: Developers', 'Topic :: Software Development :: Build Tools', 'License :: OSI Approved :: ' 'GNU Lesser General Public License v3 (LGPLv3)', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6', ], packages=[ 'dingtalk', 'dingtalk.core', 'dingtalk.crypto', 'dingtalk.storage', 'dingtalk.model', 'dingtalk.client', 'dingtalk.client.api' ], install_requires=requirements, zip_safe=False, include_package_data=True, tests_require=[ 'pytest', 'redis', 'pymemcache', ], cmdclass=cmdclass, extras_require={ 'cryptography': ['cryptography'], 'pycrypto': ['pycrypto'], }, )
2,742
setup
py
en
python
code
{"qsc_code_num_words": 312, "qsc_code_num_chars": 2742.0, "qsc_code_mean_word_length": 5.5224359, "qsc_code_frac_words_unique": 0.49679487, "qsc_code_frac_chars_top_2grams": 0.07719095, "qsc_code_frac_chars_top_3grams": 0.10156703, "qsc_code_frac_chars_top_4grams": 0.0754498, "qsc_code_frac_chars_dupe_5grams": 0.03134068, "qsc_code_frac_chars_dupe_6grams": 0.0, "qsc_code_frac_chars_dupe_7grams": 0.0, "qsc_code_frac_chars_dupe_8grams": 0.0, "qsc_code_frac_chars_dupe_9grams": 0.0, "qsc_code_frac_chars_dupe_10grams": 0.0, "qsc_code_frac_chars_replacement_symbols": 0.0, "qsc_code_frac_chars_digital": 0.01423825, "qsc_code_frac_chars_whitespace": 0.23158279, "qsc_code_size_file_byte": 2742.0, "qsc_code_num_lines": 103.0, "qsc_code_num_chars_line_max": 75.0, "qsc_code_num_chars_line_mean": 26.62135922, "qsc_code_frac_chars_alphabet": 0.8035121, "qsc_code_frac_chars_comments": 0.10430343, "qsc_code_cate_xml_start": 0.0, "qsc_code_frac_lines_dupe_lines": 0.03896104, "qsc_code_cate_autogen": 0.0, "qsc_code_frac_lines_long_string": 0.0, "qsc_code_frac_chars_string_length": 0.33210634, "qsc_code_frac_chars_long_word_length": 0.0, "qsc_code_frac_lines_string_concat": 0.0, "qsc_code_cate_encoded_data": 0.0, "qsc_code_frac_chars_hex_words": 0.0, "qsc_code_frac_lines_prompt_comments": 0.0, "qsc_code_frac_lines_assert": 0.0, "qsc_codepython_cate_ast": 1.0, "qsc_codepython_frac_lines_func_ratio": 0.03896104, "qsc_codepython_cate_var_zero": false, "qsc_codepython_frac_lines_pass": 0.02597403, "qsc_codepython_frac_lines_import": 0.09090909, "qsc_codepython_frac_lines_simplefunc": 0.0, "qsc_codepython_score_lines_no_logic": 0.15584416, "qsc_codepython_frac_lines_print": 0.0}
1
{"qsc_code_frac_chars_replacement_symbols": 0, "qsc_code_num_words": 0, "qsc_code_num_chars": 0, "qsc_code_mean_word_length": 0, "qsc_code_frac_chars_top_2grams": 0, "qsc_code_frac_chars_top_3grams": 0, "qsc_code_frac_chars_top_4grams": 0, "qsc_code_frac_chars_dupe_5grams": 0, "qsc_code_frac_chars_dupe_6grams": 0, "qsc_code_frac_chars_dupe_7grams": 0, "qsc_code_frac_chars_dupe_8grams": 0, "qsc_code_frac_chars_dupe_9grams": 0, "qsc_code_frac_chars_dupe_10grams": 0, "qsc_code_frac_lines_dupe_lines": 0, "qsc_code_size_file_byte": 0, "qsc_code_num_lines": 0, "qsc_code_num_chars_line_max": 0, "qsc_code_num_chars_line_mean": 0, "qsc_code_frac_chars_alphabet": 0, "qsc_code_frac_chars_digital": 0, "qsc_code_frac_chars_whitespace": 0, "qsc_code_frac_chars_comments": 0, "qsc_code_cate_xml_start": 0, "qsc_code_cate_autogen": 0, "qsc_code_frac_lines_long_string": 0, "qsc_code_frac_chars_string_length": 0, "qsc_code_frac_chars_long_word_length": 0, "qsc_code_cate_encoded_data": 0, "qsc_code_frac_chars_hex_words": 0, "qsc_code_frac_lines_prompt_comments": 0, "qsc_code_frac_lines_assert": 0, "qsc_codepython_cate_ast": 0, "qsc_codepython_frac_lines_func_ratio": 0, "qsc_codepython_cate_var_zero": 0, "qsc_codepython_frac_lines_pass": 0, "qsc_codepython_frac_lines_import": 0, "qsc_codepython_frac_lines_simplefunc": 0, "qsc_codepython_score_lines_no_logic": 0, "qsc_codepython_frac_lines_print": 0}
007gzs/dingtalk-sdk
docs/index.rst
.. dingtalk-sdk documentation master file, created by sphinx-quickstart on Fri May 4 11:18:22 2018. You can adapt this file completely to your liking, but it should at least contain the root `toctree` directive. dingtalk-sdk 使用文档 ======================================== dingtalk-sdk 是一个钉钉开放平台的第三方 Python SDK, 实现了 企业内部开发 和 应用服务商(ISV)的 API。 快速入门 ------------- .. toctree:: :maxdepth: 2 install 企业内部开发 -------------------- 建议在使用前先阅读 `钉钉开放平台文档 <https://open-doc.dingtalk.com>`_ .. toctree:: :glob: :maxdepth: 2 model/message model/field client/index 应用服务商(ISV) ---------------------------- .. toctree:: :glob: :maxdepth: 2 client/isv 未实现接口 -------------------- 由于钉钉接口过多,文档较分散,有未实现的接口可以提交 Issues, sdk未更新时候可根据下面代码临时使用 post/get接口中的access_token,top接口中的session会在请求时自动设置,无需手动添加 .. module:: dingtalk.client.base .. autoclass:: BaseClient .. automethod:: get .. automethod:: post .. automethod:: top_request 调用示例:: client = SecretClient('CORP_ID', 'CORP_SECRET') # top 接口: 获取考勤组列表详情 ret = client._top_request( 'dingtalk.smartwork.attends.getsimplegroups', { "offset": 0, "size": 10 } ) has_more = ret.result.has_more groups = ret.result.groups # get 接口:获取子部门ID列表 ret = client.get( '/department/list_ids', {'id': 0} ) sub_dept_id_list = ret.sub_dept_id_list # post 接口:创建会话 return self._post( '/chat/create', { 'name': "群名称", 'owner': "zhangsan", 'useridlist': ["zhangsan", "lisi"] } ) chatid = ret.chatid 示例项目 --------------------- `django demo <https://github.com/007gzs/dingtalk-django-example/>`_ Changelogs --------------- .. toctree:: :maxdepth: 1 changelog
1,777
index
rst
zh
restructuredtext
text
{"qsc_doc_frac_chars_curly_bracket": 0.00337648, "qsc_doc_frac_words_redpajama_stop": null, "qsc_doc_num_sentences": 30.0, "qsc_doc_num_words": 264, "qsc_doc_num_chars": 1777.0, "qsc_doc_num_lines": 102.0, "qsc_doc_mean_word_length": 3.85606061, "qsc_doc_frac_words_full_bracket": 0.0, "qsc_doc_frac_lines_end_with_readmore": 0.00980392, "qsc_doc_frac_lines_start_with_bullet": 0.0, "qsc_doc_frac_words_unique": 0.62121212, "qsc_doc_entropy_unigram": 4.88632418, "qsc_doc_frac_words_all_caps": 0.01764706, "qsc_doc_frac_lines_dupe_lines": 0.25, "qsc_doc_frac_chars_dupe_lines": 0.09662162, "qsc_doc_frac_chars_top_2grams": 0.0324165, "qsc_doc_frac_chars_top_3grams": 0.01178782, "qsc_doc_frac_chars_top_4grams": 0.03929273, "qsc_doc_frac_chars_dupe_5grams": 0.0, "qsc_doc_frac_chars_dupe_6grams": 0.0, "qsc_doc_frac_chars_dupe_7grams": 0.0, "qsc_doc_frac_chars_dupe_8grams": 0.0, "qsc_doc_frac_chars_dupe_9grams": 0.0, "qsc_doc_frac_chars_dupe_10grams": 0.0, "qsc_doc_frac_chars_replacement_symbols": 0.0, "qsc_doc_cate_code_related_file_name": 0.0, "qsc_doc_num_chars_sentence_length_mean": 11.52112676, "qsc_doc_frac_chars_hyperlink_html_tag": 0.04670793, "qsc_doc_frac_chars_alphabet": null, "qsc_doc_frac_chars_digital": 0.01586157, "qsc_doc_frac_chars_whitespace": 0.21947102, "qsc_doc_frac_chars_hex_words": 0.0}
1
{"qsc_doc_frac_chars_replacement_symbols": 0, "qsc_doc_entropy_unigram": 0, "qsc_doc_frac_chars_top_2grams": 0, "qsc_doc_frac_chars_top_3grams": 0, "qsc_doc_frac_chars_top_4grams": 0, "qsc_doc_frac_chars_dupe_5grams": 0, "qsc_doc_frac_chars_dupe_6grams": 0, "qsc_doc_frac_chars_dupe_7grams": 0, "qsc_doc_frac_chars_dupe_8grams": 0, "qsc_doc_frac_chars_dupe_9grams": 0, "qsc_doc_frac_chars_dupe_10grams": 0, "qsc_doc_frac_chars_dupe_lines": 0, "qsc_doc_frac_lines_dupe_lines": 0, "qsc_doc_frac_lines_end_with_readmore": 0, "qsc_doc_frac_lines_start_with_bullet": 0, "qsc_doc_frac_words_full_bracket": 0, "qsc_doc_mean_word_length": 0, "qsc_doc_num_chars": 0, "qsc_doc_num_lines": 0, "qsc_doc_num_sentences": 0, "qsc_doc_num_words": 0, "qsc_doc_frac_chars_hex_words": 0, "qsc_doc_frac_chars_hyperlink_html_tag": 0, "qsc_doc_frac_chars_alphabet": 0, "qsc_doc_frac_chars_digital": 0, "qsc_doc_frac_chars_whitespace": 0}
007gzs/dingtalk-sdk
docs/changelog.rst
Changelog ================ Version 1.3.3 ------------------ + fix 创建审批bug Version 1.3.2 ------------------ + 增加审批待办接口 Version 1.3.1 ------------------ + 增加DING日程相关接口 + 增加钉钉运动相关接口 + 增加公告相关接口 + 增加待办事项相关接口 + 增加撤回工作通知消息接口 + fix 发送工作通知参数错误 Version 1.3.0 ------------------ + 增加企业外部联系人相关接口 + 增加日志相关接口 + 更新淘宝接口 Version 1.2.8 ------------------ + 发起审批实例支持会签/或签 Version 1.2.7 ------------------ + fix 会话 获取群会话请求方法错误 Version 1.2.6 ------------------ + 增加asyncsend_v2接口 Version 1.2.4 ------------------ + 增加新接口 Version 1.2.3 ------------------ + top接口成功状态判断增加 is_success, error_response 增加msg错误信息判断 Version 1.2.2 ------------------ + 增加淘宝接口 Version 1.1.9 ------------------ + fix callback接口的返回失败接口 使用错误 Version 1.1.8 ------------------ + ssl._create_unverified_context 增加异常判断 Version 1.1.7 ------------------ + 新增app_key app_secret 获取 access_token 的 AppKeyClient Version 1.1.5 ------------------ + [fix]the list_message_status api 's method is post Version 1.1.4 ------------------ + 解决接口返回 ObjectDict 时 json_loads 未return bug Version 1.1.3 ------------------ + 接口返回结果使用 ObjectDict Version 1.1.2 ------------------ + 增加 智能人事接口 Version 1.1.1 ------------------ + 修复 LinkBody 参数层级错误 + 修复 OaBodyContent form 参数处理错误 + 增加 testcase + 增加 文档 Version 1.1.0 ------------------ + 企业钉钉接口 + ISV服务商接口
1,316
changelog
rst
zh
restructuredtext
text
{"qsc_doc_frac_chars_curly_bracket": 0.0, "qsc_doc_frac_words_redpajama_stop": null, "qsc_doc_num_sentences": 40.0, "qsc_doc_num_words": 244, "qsc_doc_num_chars": 1316.0, "qsc_doc_num_lines": 110.0, "qsc_doc_mean_word_length": 2.77868852, "qsc_doc_frac_words_full_bracket": 0.0, "qsc_doc_frac_lines_end_with_readmore": 0.0, "qsc_doc_frac_lines_start_with_bullet": 0.0, "qsc_doc_frac_words_unique": 0.44262295, "qsc_doc_entropy_unigram": 3.99678142, "qsc_doc_frac_words_all_caps": 0.00613497, "qsc_doc_frac_lines_dupe_lines": 0.27142857, "qsc_doc_frac_chars_dupe_lines": 0.28358209, "qsc_doc_frac_chars_top_2grams": 0.22418879, "qsc_doc_frac_chars_top_3grams": 0.11946903, "qsc_doc_frac_chars_top_4grams": 0.04867257, "qsc_doc_frac_chars_dupe_5grams": 0.0, "qsc_doc_frac_chars_dupe_6grams": 0.0, "qsc_doc_frac_chars_dupe_7grams": 0.0, "qsc_doc_frac_chars_dupe_8grams": 0.0, "qsc_doc_frac_chars_dupe_9grams": 0.0, "qsc_doc_frac_chars_dupe_10grams": 0.0, "qsc_doc_frac_chars_replacement_symbols": 0.0, "qsc_doc_cate_code_related_file_name": 0.0, "qsc_doc_num_chars_sentence_length_mean": 7.78, "qsc_doc_frac_chars_hyperlink_html_tag": 0.0, "qsc_doc_frac_chars_alphabet": null, "qsc_doc_frac_chars_digital": 0.0516934, "qsc_doc_frac_chars_whitespace": 0.14741641, "qsc_doc_frac_chars_hex_words": 0.0}
0
{"qsc_doc_frac_chars_replacement_symbols": 0, "qsc_doc_entropy_unigram": 0, "qsc_doc_frac_chars_top_2grams": 1, "qsc_doc_frac_chars_top_3grams": 0, "qsc_doc_frac_chars_top_4grams": 0, "qsc_doc_frac_chars_dupe_5grams": 0, "qsc_doc_frac_chars_dupe_6grams": 0, "qsc_doc_frac_chars_dupe_7grams": 0, "qsc_doc_frac_chars_dupe_8grams": 0, "qsc_doc_frac_chars_dupe_9grams": 0, "qsc_doc_frac_chars_dupe_10grams": 0, "qsc_doc_frac_chars_dupe_lines": 0, "qsc_doc_frac_lines_dupe_lines": 0, "qsc_doc_frac_lines_end_with_readmore": 0, "qsc_doc_frac_lines_start_with_bullet": 0, "qsc_doc_frac_words_full_bracket": 0, "qsc_doc_mean_word_length": 0, "qsc_doc_num_chars": 0, "qsc_doc_num_lines": 0, "qsc_doc_num_sentences": 0, "qsc_doc_num_words": 0, "qsc_doc_frac_chars_hex_words": 0, "qsc_doc_frac_chars_hyperlink_html_tag": 0, "qsc_doc_frac_chars_alphabet": 0, "qsc_doc_frac_chars_digital": 0, "qsc_doc_frac_chars_whitespace": 0}
007gzs/dingtalk-sdk
docs/conf.py
# -*- coding: utf-8 -*- # # Configuration file for the Sphinx documentation builder. # # This file does only contain a selection of the most common options. For a # full list see the documentation: # http://www.sphinx-doc.org/en/master/config import sphinx_rtd_theme # -- Path setup -------------------------------------------------------------- # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. # import os import sys import dingtalk sys.path.insert(0, os.path.abspath('..')) # -- Project information ----------------------------------------------------- project = 'dingtalk-sdk' copyright = '2018, 007gzs' author = '007gzs' # The short X.Y version version = dingtalk.__version__ # The full version, including alpha/beta/rc tags release = dingtalk.__version__ # -- General configuration --------------------------------------------------- # If your documentation needs a minimal Sphinx version, state it here. # # needs_sphinx = '1.0' # Add any Sphinx extension module names here, as strings. They can be # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom # ones. extensions = [ 'sphinx.ext.autodoc', 'sphinx.ext.doctest', 'sphinx.ext.intersphinx', 'sphinx.ext.todo', 'sphinx.ext.coverage', 'sphinx.ext.mathjax', 'sphinx.ext.ifconfig', 'sphinx.ext.viewcode', 'sphinx.ext.githubpages', ] # Add any paths that contain templates here, relative to this directory. templates_path = ['_templates'] # The suffix(es) of source filenames. # You can specify multiple suffix as a list of string: # # source_suffix = ['.rst', '.md'] source_suffix = '.rst' # The master toctree document. master_doc = 'index' # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. # # This is also used if you do content translation via gettext catalogs. # Usually you set "language" from the command line for these cases. language = 'zh_cn' # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. # This pattern also affects html_static_path and html_extra_path . exclude_patterns = [] # The name of the Pygments (syntax highlighting) style to use. pygments_style = 'sphinx' # -- Options for HTML output ------------------------------------------------- # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. # # html_theme = 'alabaster' html_theme = "sphinx_rtd_theme" html_theme_path = [sphinx_rtd_theme.get_html_theme_path()] # Theme options are theme-specific and customize the look and feel of a theme # further. For a list of options available for each theme, see the # documentation. # # html_theme_options = {} # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". html_static_path = ['_static'] # Custom sidebar templates, must be a dictionary that maps document names # to template names. # # The default sidebars (for documents that don't match any pattern) are # defined by theme itself. Builtin themes are using these templates by # default: ``['localtoc.html', 'relations.html', 'sourcelink.html', # 'searchbox.html']``. # # html_sidebars = {} # -- Options for HTMLHelp output --------------------------------------------- # Output file base name for HTML help builder. htmlhelp_basename = 'dingtalk-sdkdoc' # -- Options for LaTeX output ------------------------------------------------ latex_elements = { # The paper size ('letterpaper' or 'a4paper'). # # 'papersize': 'letterpaper', # The font size ('10pt', '11pt' or '12pt'). # # 'pointsize': '10pt', # Additional stuff for the LaTeX preamble. # # 'preamble': '', # Latex figure (float) alignment # # 'figure_align': 'htbp', } # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, # author, documentclass [howto, manual, or own class]). latex_documents = [ (master_doc, 'dingtalk-sdk.tex', 'dingtalk-sdk Documentation', '007gzs', 'manual'), ] # -- Options for manual page output ------------------------------------------ # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). man_pages = [ (master_doc, 'dingtalk-sdk', 'dingtalk-sdk Documentation', [author], 1) ] # -- Options for Texinfo output ---------------------------------------------- # Grouping the document tree into Texinfo files. List of tuples # (source start file, target name, title, author, # dir menu entry, description, category) texinfo_documents = [ (master_doc, 'dingtalk-sdk', 'dingtalk-sdk Documentation', author, 'dingtalk-sdk', 'One line description of project.', 'Miscellaneous'), ] # -- Extension configuration ------------------------------------------------- # -- Options for intersphinx extension --------------------------------------- # Example configuration for intersphinx: refer to the Python standard library. intersphinx_mapping = {'https://docs.python.org/': None} # -- Options for todo extension ---------------------------------------------- # If true, `todo` and `todoList` produce output, else they produce nothing. todo_include_todos = True
5,606
conf
py
en
python
code
{"qsc_code_num_words": 689, "qsc_code_num_chars": 5606.0, "qsc_code_mean_word_length": 5.21480406, "qsc_code_frac_words_unique": 0.39187228, "qsc_code_frac_chars_top_2grams": 0.02504871, "qsc_code_frac_chars_top_3grams": 0.00779293, "qsc_code_frac_chars_top_4grams": 0.00834957, "qsc_code_frac_chars_dupe_5grams": 0.13053159, "qsc_code_frac_chars_dupe_6grams": 0.06484832, "qsc_code_frac_chars_dupe_7grams": 0.0573337, "qsc_code_frac_chars_dupe_8grams": 0.0573337, "qsc_code_frac_chars_dupe_9grams": 0.02950181, "qsc_code_frac_chars_dupe_10grams": 0.02950181, "qsc_code_frac_chars_replacement_symbols": 0.0, "qsc_code_frac_chars_digital": 0.00574468, "qsc_code_frac_chars_whitespace": 0.16161256, "qsc_code_size_file_byte": 5606.0, "qsc_code_num_lines": 184.0, "qsc_code_num_chars_line_max": 80.0, "qsc_code_num_chars_line_mean": 30.4673913, "qsc_code_frac_chars_alphabet": 0.7587234, "qsc_code_frac_chars_comments": 0.72136996, "qsc_code_cate_xml_start": 0.0, "qsc_code_frac_lines_dupe_lines": 0.04166667, "qsc_code_cate_autogen": 0.0, "qsc_code_frac_lines_long_string": 0.0, "qsc_code_frac_chars_string_length": 0.3267663, "qsc_code_frac_chars_long_word_length": 0.0298913, "qsc_code_frac_lines_string_concat": 0.0, "qsc_code_cate_encoded_data": 0.0, "qsc_code_frac_chars_hex_words": 0.0, "qsc_code_frac_lines_prompt_comments": 0.00543478, "qsc_code_frac_lines_assert": 0.0, "qsc_codepython_cate_ast": 1.0, "qsc_codepython_frac_lines_func_ratio": 0.0, "qsc_codepython_cate_var_zero": false, "qsc_codepython_frac_lines_pass": 0.0, "qsc_codepython_frac_lines_import": 0.08333333, "qsc_codepython_frac_lines_simplefunc": 0.0, "qsc_codepython_score_lines_no_logic": 0.08333333, "qsc_codepython_frac_lines_print": 0.0}
1
{"qsc_code_frac_chars_replacement_symbols": 0, "qsc_code_num_words": 0, "qsc_code_num_chars": 0, "qsc_code_mean_word_length": 0, "qsc_code_frac_chars_top_2grams": 0, "qsc_code_frac_chars_top_3grams": 0, "qsc_code_frac_chars_top_4grams": 0, "qsc_code_frac_chars_dupe_5grams": 0, "qsc_code_frac_chars_dupe_6grams": 0, "qsc_code_frac_chars_dupe_7grams": 0, "qsc_code_frac_chars_dupe_8grams": 0, "qsc_code_frac_chars_dupe_9grams": 0, "qsc_code_frac_chars_dupe_10grams": 0, "qsc_code_frac_lines_dupe_lines": 0, "qsc_code_size_file_byte": 0, "qsc_code_num_lines": 0, "qsc_code_num_chars_line_max": 0, "qsc_code_num_chars_line_mean": 0, "qsc_code_frac_chars_alphabet": 0, "qsc_code_frac_chars_digital": 0, "qsc_code_frac_chars_whitespace": 0, "qsc_code_frac_chars_comments": 0, "qsc_code_cate_xml_start": 0, "qsc_code_cate_autogen": 0, "qsc_code_frac_lines_long_string": 0, "qsc_code_frac_chars_string_length": 0, "qsc_code_frac_chars_long_word_length": 0, "qsc_code_cate_encoded_data": 0, "qsc_code_frac_chars_hex_words": 0, "qsc_code_frac_lines_prompt_comments": 0, "qsc_code_frac_lines_assert": 0, "qsc_codepython_cate_ast": 0, "qsc_codepython_frac_lines_func_ratio": 0, "qsc_codepython_cate_var_zero": 0, "qsc_codepython_frac_lines_pass": 0, "qsc_codepython_frac_lines_import": 0, "qsc_codepython_frac_lines_simplefunc": 0, "qsc_codepython_score_lines_no_logic": 0, "qsc_codepython_frac_lines_print": 0}
0015/ESP32-OpenCV-Projects
esp32/examples/color_code/main/main.cpp
///////////////////////////////////////////////////////////////// /* RGB Pixel Detector & Histogram (Running OpenCV on ESP32) For More Information: https://youtu.be/DNQuCkPtzYA Created by Eric N. (ThatProject) */ ///////////////////////////////////////////////////////////////// #undef EPS // specreg.h defines EPS which interfere with opencv #include "opencv2/core.hpp" #include "opencv2/imgproc.hpp" #include "opencv2/imgcodecs.hpp" #define EPS 192 #include <esp_log.h> #include <esp_err.h> #include <esp_timer.h> #include <freertos/FreeRTOS.h> #include <freertos/task.h> #include <esp_freertos_hooks.h> #include <iostream> #include <map> #include "system.h" #include "app_screen.h" #include "app_camera.h" #include "iot_lvgl.h" using namespace cv; extern "C" { void app_main(void); } #define TAG "main" extern CEspLcd *tft; static lv_obj_t *lvCameraImage; // Camera image object static lv_obj_t *lv_container_RGB; static lv_obj_t *lv_bar_red; static lv_obj_t *lv_label_red; static lv_obj_t *lv_bar_blue; static lv_obj_t *lv_label_blue; static lv_obj_t *lv_bar_green; static lv_obj_t *lv_label_green; const int histSize = 240; const int hist_w = 240; const int hist_h = 240; void gui_screen() { static lv_style_t style; lv_style_init(&style); lv_style_set_radius(&style, LV_STATE_DEFAULT, 2); lv_style_set_bg_opa(&style, LV_STATE_DEFAULT, LV_OPA_COVER); lv_style_set_bg_color(&style, LV_STATE_DEFAULT, LV_COLOR_MAKE(190, 190, 190)); lv_style_set_border_width(&style, LV_STATE_DEFAULT, 2); lv_style_set_border_color(&style, LV_STATE_DEFAULT, LV_COLOR_MAKE(142, 142, 142)); lv_style_set_pad_top(&style, LV_STATE_DEFAULT, 60); lv_style_set_pad_bottom(&style, LV_STATE_DEFAULT, 60); lv_style_set_pad_left(&style, LV_STATE_DEFAULT, 60); lv_style_set_pad_right(&style, LV_STATE_DEFAULT, 60); lv_style_set_text_color(&style, LV_STATE_DEFAULT, LV_COLOR_MAKE(102, 102, 102)); lv_style_set_text_letter_space(&style, LV_STATE_DEFAULT, 5); lv_style_set_text_line_space(&style, LV_STATE_DEFAULT, 20); /*Create an object with the new style*/ lv_obj_t *obj = lv_label_create(lv_scr_act(), NULL); lv_obj_add_style(obj, LV_LABEL_PART_MAIN, &style); lv_label_set_text(obj, "Color Code\n" "Histogram"); lv_obj_align(obj, NULL, LV_ALIGN_CENTER, 0, 0); wait_msec(2000); static lv_style_t style_container; lv_style_init(&style_container); lv_style_set_bg_color(&style_container, LV_STATE_DEFAULT, LV_COLOR_WHITE); lv_style_set_bg_opa(&style_container, LV_STATE_DEFAULT, LV_OPA_TRANSP); lv_style_set_border_width(&style_container, LV_STATE_DEFAULT, 0); lv_container_RGB = lv_cont_create(lv_scr_act(), NULL); lv_obj_add_style(lv_container_RGB, LV_CONT_PART_MAIN, &style_container); lv_obj_align(lv_container_RGB, NULL, LV_ALIGN_IN_TOP_LEFT, 0, 0); lv_obj_set_size(lv_container_RGB, 240, 46); static lv_style_t label_style; lv_style_init(&label_style); lv_style_set_text_opa(&label_style, LV_STATE_DEFAULT, LV_OPA_COVER); lv_label_red = lv_label_create(lv_container_RGB, NULL); lv_obj_add_style(lv_label_red, LV_LABEL_PART_MAIN, &label_style); lv_label_set_recolor(lv_label_red, true); lv_label_set_text(lv_label_red, "#ff0000 R: 128"); lv_obj_set_size(lv_label_red, 40, 10); lv_obj_align(lv_label_red, NULL, LV_ALIGN_IN_TOP_LEFT, 2, 2); lv_label_green = lv_label_create(lv_container_RGB, NULL); lv_obj_add_style(lv_label_green, LV_LABEL_PART_MAIN, &label_style); lv_label_set_recolor(lv_label_green, true); lv_label_set_text(lv_label_green, "#00ff00 G: 128"); lv_obj_set_size(lv_label_green, 40, 10); lv_obj_align(lv_label_green, NULL, LV_ALIGN_IN_TOP_LEFT, 2, 16); lv_label_blue = lv_label_create(lv_container_RGB, NULL); lv_obj_add_style(lv_label_blue, LV_LABEL_PART_MAIN, &label_style); lv_label_set_recolor(lv_label_blue, true); lv_label_set_text(lv_label_blue, "#0000ff B: 128"); lv_obj_set_size(lv_label_blue, 40, 10); lv_obj_align(lv_label_blue, NULL, LV_ALIGN_IN_TOP_LEFT, 2, 30); static lv_style_t style_bar; lv_style_init(&style_bar); lv_style_set_radius(&style_bar, LV_STATE_DEFAULT, 4); lv_style_set_bg_color(&style_bar, LV_STATE_DEFAULT, LV_COLOR_RED); lv_bar_red = lv_bar_create(lv_container_RGB, NULL); lv_obj_add_style(lv_bar_red, LV_BAR_PART_INDIC, &style_bar); lv_obj_set_size(lv_bar_red, 160, 8); lv_obj_align(lv_bar_red, NULL, LV_ALIGN_IN_TOP_LEFT, 60, 6); lv_bar_set_anim_time(lv_bar_red, 100); lv_bar_set_value(lv_bar_red, 100, LV_ANIM_ON); lv_bar_set_range(lv_bar_red, 0, 255); lv_obj_set_style_local_bg_opa(lv_bar_red, LV_BAR_PART_BG, LV_STATE_DEFAULT, LV_OPA_TRANSP); lv_bar_green = lv_bar_create(lv_container_RGB, NULL); lv_obj_add_style(lv_bar_green, LV_BAR_PART_INDIC, &style_bar); lv_obj_set_size(lv_bar_green, 160, 8); lv_obj_align(lv_bar_green, NULL, LV_ALIGN_IN_TOP_LEFT, 60, 20); lv_bar_set_anim_time(lv_bar_green, 100); lv_bar_set_value(lv_bar_green, 100, LV_ANIM_ON); lv_bar_set_range(lv_bar_green, 0, 255); lv_obj_set_style_local_bg_color(lv_bar_green, LV_BAR_PART_INDIC, LV_STATE_DEFAULT, LV_COLOR_GREEN); lv_obj_set_style_local_bg_opa(lv_bar_green, LV_BAR_PART_BG, LV_STATE_DEFAULT, LV_OPA_TRANSP); lv_bar_blue = lv_bar_create(lv_container_RGB, NULL); lv_obj_add_style(lv_bar_blue, LV_BAR_PART_INDIC, &style_bar); lv_obj_set_size(lv_bar_blue, 160, 8); lv_obj_align(lv_bar_blue, NULL, LV_ALIGN_IN_TOP_LEFT, 60, 34); lv_bar_set_anim_time(lv_bar_blue, 100); lv_bar_set_value(lv_bar_blue, 100, LV_ANIM_ON); lv_bar_set_range(lv_bar_blue, 0, 255); lv_obj_set_style_local_bg_color(lv_bar_blue, LV_BAR_PART_INDIC, LV_STATE_DEFAULT, LV_COLOR_BLUE); lv_obj_set_style_local_bg_opa(lv_bar_blue, LV_BAR_PART_BG, LV_STATE_DEFAULT, LV_OPA_TRANSP); } esp_err_t updateCameraImage(const Mat &img) { // static variables because they must still be available when lv_task_handler() is called static Mat imgCopy; static lv_img_dsc_t my_img_dsc; if (img.empty()) { ESP_LOGW(TAG, "Can't display empty image"); return ESP_ERR_INVALID_ARG; } // convert image to bgr565 if needed if (img.type() == CV_8UC1) { // grayscale image cvtColor(img, imgCopy, COLOR_GRAY2BGR565, 1); } else if (img.type() == CV_8UC3) { // BGR888 image cvtColor(img, imgCopy, COLOR_BGR2BGR565, 1); } else if (img.type() == CV_8UC2) { // BGR565 image img.copyTo(imgCopy); } my_img_dsc.header.always_zero = 0; my_img_dsc.header.w = imgCopy.cols; my_img_dsc.header.h = imgCopy.rows; my_img_dsc.header.cf = LV_IMG_CF_TRUE_COLOR; my_img_dsc.data_size = imgCopy.size().width * imgCopy.size().height; my_img_dsc.data = imgCopy.ptr<uchar>(0); lv_img_set_src(lvCameraImage, &my_img_dsc); /* Set the created file as image */ lv_obj_set_pos(lvCameraImage, 0, 0); return ESP_OK; } void updateColorCode(int red, int green, int blue) { lv_obj_move_foreground(lv_container_RGB); lv_bar_set_value(lv_bar_red, red, LV_ANIM_ON); lv_bar_set_value(lv_bar_green, green, LV_ANIM_ON); lv_bar_set_value(lv_bar_blue, blue, LV_ANIM_ON); std::string str = "#ff0000 R: " + std::to_string(red); lv_label_set_text(lv_label_red, str.c_str()); str = "#00ff00 G: " + std::to_string(green); lv_label_set_text(lv_label_green, str.c_str()); str = "#0000ff B: " + std::to_string(blue); lv_label_set_text(lv_label_blue, str.c_str()); ESP_LOGI("COLOR", "R: %d,G: %d, B: %d", red, green, blue); } void drawCenterMark(Mat &src) { Point pc1(120, 100), pc2(120, 140); line(src, pc1, pc2, Scalar(255, 255, 255), 2, LINE_8); Point pc3(100, 120), pc4(140, 120); line(src, pc3, pc4, Scalar(255, 255, 255), 2, LINE_8); } void drawHistogram(Mat &b_hist, Mat &g_hist, Mat &r_hist, Mat &src) { int bin_w = cvRound((double)hist_w / histSize); normalize(b_hist, b_hist, 0, src.rows, NORM_MINMAX, -1, Mat()); normalize(g_hist, g_hist, 0, src.rows, NORM_MINMAX, -1, Mat()); normalize(r_hist, r_hist, 0, src.rows, NORM_MINMAX, -1, Mat()); for (int i = 1; i < histSize; i++) { line( src, Point(bin_w * (i - 1), hist_h - cvRound(b_hist.at<float>(i - 1))), Point(bin_w * (i), hist_h - cvRound(b_hist.at<float>(i))), Scalar(255, 0, 0), 1, LINE_AA); line( src, Point(bin_w * (i - 1), hist_h - cvRound(g_hist.at<float>(i - 1))), Point(bin_w * (i), hist_h - cvRound(g_hist.at<float>(i))), Scalar(0, 255, 0), 1, LINE_AA); line( src, Point(bin_w * (i - 1), hist_h - cvRound(r_hist.at<float>(i - 1))), Point(bin_w * (i), hist_h - cvRound(r_hist.at<float>(i))), Scalar(0, 0, 255), 1, LINE_AA); } } void find_color(void *arg) { ESP_LOGI(TAG, "Starting find_color"); sensor_t *s = esp_camera_sensor_get(); lvCameraImage = lv_img_create(lv_disp_get_scr_act(nullptr), nullptr); lv_obj_move_foreground(lvCameraImage); while (true) { auto start = esp_timer_get_time(); camera_fb_t *fb = esp_camera_fb_get(); if (!fb) { ESP_LOGE(TAG, "Camera capture failed"); } else { if (s->pixformat == PIXFORMAT_JPEG) { TFT_jpg_image(CENTER, CENTER, 0, -1, NULL, fb->buf, fb->len); esp_camera_fb_return(fb); fb = NULL; } else { // RGB565 pixformat Mat inputImage(fb->height, fb->width, CV_8UC2, fb->buf); // rgb565 is 2 channels of 8-bit unsigned cvtColor(inputImage, inputImage, COLOR_BGR5652BGR); int pos_x = fb->width / 2; int pos_y = fb->height / 2; int blue = inputImage.at<Vec3b>(pos_x, pos_y)[0]; // getting the pixel values// int green = inputImage.at<Vec3b>(pos_x, pos_y)[1]; // getting the pixel values// int red = inputImage.at<Vec3b>(pos_x, pos_y)[2]; // getting the pixel values// updateColorCode(red, green, blue); std::vector<Mat> bgr_planes; split(inputImage, bgr_planes); float range[] = {0, 240}; const float *histRange = {range}; bool uniform = true; bool accumulate = false; Mat b_hist, g_hist, r_hist; calcHist(&bgr_planes[0], 1, 0, Mat(), b_hist, 1, &histSize, &histRange, uniform, accumulate); calcHist(&bgr_planes[1], 1, 0, Mat(), g_hist, 1, &histSize, &histRange, uniform, accumulate); calcHist(&bgr_planes[2], 1, 0, Mat(), r_hist, 1, &histSize, &histRange, uniform, accumulate); drawHistogram(b_hist, g_hist, r_hist, inputImage); drawCenterMark(inputImage); updateCameraImage(inputImage); } } ESP_LOGI(TAG, "Around %f fps", 1.0f / ((esp_timer_get_time() - start) / 1000000.0f)); } } void app_main() { ESP_LOGI(TAG, "Starting main"); app_camera_init(); lvgl_init(); gui_screen(); xTaskCreatePinnedToCore(find_color, "find_color", 1024 * 9, nullptr, 24, nullptr, 0); }
11,652
main
cpp
en
cpp
code
{"qsc_code_num_words": 1824, "qsc_code_num_chars": 11652.0, "qsc_code_mean_word_length": 3.77905702, "qsc_code_frac_words_unique": 0.15953947, "qsc_code_frac_chars_top_2grams": 0.03989555, "qsc_code_frac_chars_top_3grams": 0.04671406, "qsc_code_frac_chars_top_4grams": 0.03583345, "qsc_code_frac_chars_dupe_5grams": 0.53097345, "qsc_code_frac_chars_dupe_6grams": 0.46235311, "qsc_code_frac_chars_dupe_7grams": 0.39968084, "qsc_code_frac_chars_dupe_8grams": 0.27912375, "qsc_code_frac_chars_dupe_9grams": 0.23124909, "qsc_code_frac_chars_dupe_10grams": 0.15116785, "qsc_code_frac_chars_replacement_symbols": 0.0, "qsc_code_frac_chars_digital": 0.03830998, "qsc_code_frac_chars_whitespace": 0.2159286, "qsc_code_size_file_byte": 11652.0, "qsc_code_num_lines": 334.0, "qsc_code_num_chars_line_max": 115.0, "qsc_code_num_chars_line_mean": 34.88622754, "qsc_code_frac_chars_alphabet": 0.71617776, "qsc_code_frac_chars_comments": 0.06556814, "qsc_code_cate_xml_start": 0.0, "qsc_code_frac_lines_dupe_lines": 0.05577689, "qsc_code_cate_autogen": 0.0, "qsc_code_frac_lines_long_string": 0.0, "qsc_code_frac_chars_string_length": 0.02966296, "qsc_code_frac_chars_long_word_length": 0.00192855, "qsc_code_frac_lines_string_concat": 0.0, "qsc_code_cate_encoded_data": 0.0, "qsc_code_frac_chars_hex_words": 0.0, "qsc_code_frac_lines_prompt_comments": 0.0, "qsc_code_frac_lines_assert": 0.0, "qsc_codecpp_frac_lines_preprocessor_directives": 0.07171315, "qsc_codecpp_frac_lines_func_ratio": 0.0438247, "qsc_codecpp_cate_bitsstdc": 0.0, "qsc_codecpp_nums_lines_main": 0.0, "qsc_codecpp_frac_lines_goto": 0.0, "qsc_codecpp_cate_var_zero": 0.0, "qsc_codecpp_score_lines_no_logic": 0.10756972, "qsc_codecpp_frac_lines_print": 0.0}
1
{"qsc_code_frac_chars_replacement_symbols": 0, "qsc_code_num_words": 0, "qsc_code_num_chars": 0, "qsc_code_mean_word_length": 0, "qsc_code_frac_chars_top_2grams": 0, "qsc_code_frac_chars_top_3grams": 0, "qsc_code_frac_chars_top_4grams": 0, "qsc_code_frac_chars_dupe_5grams": 0, "qsc_code_frac_chars_dupe_6grams": 0, "qsc_code_frac_chars_dupe_7grams": 0, "qsc_code_frac_chars_dupe_8grams": 0, "qsc_code_frac_chars_dupe_9grams": 0, "qsc_code_frac_chars_dupe_10grams": 0, "qsc_code_frac_lines_dupe_lines": 0, "qsc_code_size_file_byte": 0, "qsc_code_num_lines": 0, "qsc_code_num_chars_line_max": 0, "qsc_code_num_chars_line_mean": 0, "qsc_code_frac_chars_alphabet": 0, "qsc_code_frac_chars_digital": 0, "qsc_code_frac_chars_whitespace": 0, "qsc_code_frac_chars_comments": 0, "qsc_code_cate_xml_start": 0, "qsc_code_cate_autogen": 0, "qsc_code_frac_lines_long_string": 0, "qsc_code_frac_chars_string_length": 0, "qsc_code_frac_chars_long_word_length": 0, "qsc_code_cate_encoded_data": 0, "qsc_code_frac_chars_hex_words": 0, "qsc_code_frac_lines_prompt_comments": 0, "qsc_code_frac_lines_assert": 0, "qsc_codecpp_frac_lines_func_ratio": 0, "qsc_codecpp_nums_lines_main": 0, "qsc_codecpp_score_lines_no_logic": 0, "qsc_codecpp_frac_lines_preprocessor_directives": 0, "qsc_codecpp_frac_lines_print": 0}
0015/ESP32-OpenCV-Projects
esp32/examples/color_code/main/app_camera.c
/* ESPRESSIF MIT License * * Copyright (c) 2018 <ESPRESSIF SYSTEMS (SHANGHAI) PTE LTD> * * Permission is hereby granted for use on all ESPRESSIF SYSTEMS products, in which case, * it is free of charge, to any person obtaining a copy of this software and associated * documentation files (the "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the Software is furnished * to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or * substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include "app_camera.h" static const char *TAG = "app_camera"; void app_camera_init() { /* IO13, IO14 is designed for JTAG by default, * to use it as generalized input, * firstly declair it as pullup input */ gpio_config_t conf; conf.mode = GPIO_MODE_INPUT; conf.pull_up_en = GPIO_PULLUP_ENABLE; conf.pull_down_en = GPIO_PULLDOWN_DISABLE; conf.intr_type = GPIO_INTR_DISABLE; conf.pin_bit_mask = 1LL << 13; gpio_config(&conf); // conf.pin_bit_mask = 1LL << 14; // gpio_config(&conf); camera_config_t config; config.ledc_channel = LEDC_CHANNEL_0; config.ledc_timer = LEDC_TIMER_0; config.pin_d0 = Y2_GPIO_NUM; config.pin_d1 = Y3_GPIO_NUM; config.pin_d2 = Y4_GPIO_NUM; config.pin_d3 = Y5_GPIO_NUM; config.pin_d4 = Y6_GPIO_NUM; config.pin_d5 = Y7_GPIO_NUM; config.pin_d6 = Y8_GPIO_NUM; config.pin_d7 = Y9_GPIO_NUM; config.pin_xclk = XCLK_GPIO_NUM; config.pin_pclk = PCLK_GPIO_NUM; config.pin_vsync = VSYNC_GPIO_NUM; config.pin_href = HREF_GPIO_NUM; config.pin_sscb_sda = SIOD_GPIO_NUM; config.pin_sscb_scl = SIOC_GPIO_NUM; config.pin_reset = RESET_GPIO_NUM; config.pin_pwdn = PWDN_GPIO_NUM; config.xclk_freq_hz = XCLK_FREQ; config.pixel_format = CAMERA_PIXEL_FORMAT; config.frame_size = CAMERA_FRAME_SIZE; config.jpeg_quality = 10; config.fb_count = 1; // camera init esp_err_t err = esp_camera_init(&config); if (err != ESP_OK) { ESP_LOGE(TAG, "Camera init failed with error 0x%x", err); return; } sensor_t *s = esp_camera_sensor_get(); s->set_framesize(s, CAMERA_FRAME_SIZE); s->set_vflip(s, 1); s->set_hmirror(s, 1); }
2,950
app_camera
c
en
c
code
{"qsc_code_num_words": 457, "qsc_code_num_chars": 2950.0, "qsc_code_mean_word_length": 4.39606127, "qsc_code_frac_words_unique": 0.45295405, "qsc_code_frac_chars_top_2grams": 0.07167745, "qsc_code_frac_chars_top_3grams": 0.1035341, "qsc_code_frac_chars_top_4grams": 0.11946242, "qsc_code_frac_chars_dupe_5grams": 0.03683425, "qsc_code_frac_chars_dupe_6grams": 0.0, "qsc_code_frac_chars_dupe_7grams": 0.0, "qsc_code_frac_chars_dupe_8grams": 0.0, "qsc_code_frac_chars_dupe_9grams": 0.0, "qsc_code_frac_chars_dupe_10grams": 0.0, "qsc_code_frac_chars_replacement_symbols": 0.0, "qsc_code_frac_chars_digital": 0.0161496, "qsc_code_frac_chars_whitespace": 0.20237288, "qsc_code_size_file_byte": 2950.0, "qsc_code_num_lines": 79.0, "qsc_code_num_chars_line_max": 96.0, "qsc_code_num_chars_line_mean": 37.34177215, "qsc_code_frac_chars_alphabet": 0.83765406, "qsc_code_frac_chars_comments": 0.48440678, "qsc_code_cate_xml_start": 0.0, "qsc_code_frac_lines_dupe_lines": 0.0, "qsc_code_cate_autogen": 0.0, "qsc_code_frac_lines_long_string": 0.0, "qsc_code_frac_chars_string_length": 0.03681788, "qsc_code_frac_chars_long_word_length": 0.0, "qsc_code_frac_lines_string_concat": 0.0, "qsc_code_cate_encoded_data": 0.0, "qsc_code_frac_chars_hex_words": 0.0, "qsc_code_frac_lines_prompt_comments": 0.0, "qsc_code_frac_lines_assert": 0.0, "qsc_codec_frac_lines_func_ratio": 0.02173913, "qsc_codec_cate_bitsstdc": 0.0, "qsc_codec_nums_lines_main": 0, "qsc_codec_frac_lines_goto": 0.0, "qsc_codec_cate_var_zero": 0.0, "qsc_codec_score_lines_no_logic": 0.06521739, "qsc_codec_frac_lines_print": 0.0, "qsc_codec_frac_lines_preprocessor_directives": 0.02173913}
1
{"qsc_code_frac_chars_replacement_symbols": 0, "qsc_code_num_words": 0, "qsc_code_num_chars": 0, "qsc_code_mean_word_length": 0, "qsc_code_frac_chars_top_2grams": 0, "qsc_code_frac_chars_top_3grams": 0, "qsc_code_frac_chars_top_4grams": 0, "qsc_code_frac_chars_dupe_5grams": 0, "qsc_code_frac_chars_dupe_6grams": 0, "qsc_code_frac_chars_dupe_7grams": 0, "qsc_code_frac_chars_dupe_8grams": 0, "qsc_code_frac_chars_dupe_9grams": 0, "qsc_code_frac_chars_dupe_10grams": 0, "qsc_code_size_file_byte": 0, "qsc_code_num_lines": 0, "qsc_code_num_chars_line_max": 0, "qsc_code_num_chars_line_mean": 0, "qsc_code_frac_chars_alphabet": 0, "qsc_code_frac_chars_digital": 0, "qsc_code_frac_chars_whitespace": 0, "qsc_code_frac_chars_comments": 0, "qsc_code_cate_xml_start": 0, "qsc_code_frac_lines_dupe_lines": 0, "qsc_code_cate_autogen": 0, "qsc_code_frac_lines_long_string": 0, "qsc_code_frac_chars_string_length": 0, "qsc_code_frac_chars_long_word_length": 0, "qsc_code_cate_encoded_data": 0, "qsc_code_frac_chars_hex_words": 0, "qsc_code_frac_lines_prompt_comments": 0, "qsc_code_frac_lines_assert": 0, "qsc_codec_frac_lines_func_ratio": 0, "qsc_codec_nums_lines_main": 0, "qsc_codec_score_lines_no_logic": 0, "qsc_codec_frac_lines_preprocessor_directives": 0, "qsc_codec_frac_lines_print": 0}
0015/ESP32-OpenCV-Projects
esp32/examples/color_code/components/lcd/iot_lcd.cpp
/* This is the subclass graphics library for all our displays, providing a common set of graphics primitives (points, lines, circles, etc.) Adafruit invests time and resources providing this open source code, please support Adafruit & open-source hardware by purchasing products from Adafruit! Based on ESP8266 library https://github.com/Sermus/ESP8266_Adafruit_lcd Copyright (c) 2015-2016 Andrey Filimonov. All rights reserved. Additions for ESP32 Copyright (c) 2016-2017 Espressif Systems (Shanghai) PTE LTD Copyright (c) 2013 Adafruit Industries. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "Adafruit_GFX.h" #include "iot_lcd.h" #include "spi_lcd.h" #include "font7s.h" #include "esp_partition.h" #include "esp_log.h" #include "driver/gpio.h" #include "freertos/semphr.h" #include "freertos/task.h" #include "sdkconfig.h" /*Rotation Defines*/ #define MADCTL_MY 0x80 // Y-mirror #define MADCTL_MX 0x40 // X-mirror #define MADCTL_MV 0x20 // X-Y exchange #define MADCTL_ML 0x10 #define MADCTL_RGB 0x00 #define MADCTL_BGR 0x08 #define MADCTL_MH 0x04 // Horizontal lcd refresh direction #define SWAPBYTES(i) ((i>>8) | (i<<8)) static const char *TAG = "LCD"; CEspLcd::CEspLcd(lcd_conf_t *lcd_conf, int height, int width, bool dma_en, int dma_word_size, int dma_chan) : Adafruit_GFX(width, height) { m_height = height; m_width = width; tabcolor = 0; dma_mode = dma_en; dma_buf_size = dma_word_size; spi_mux = xSemaphoreCreateRecursiveMutex(); m_dma_chan = dma_chan; setSpiBus(lcd_conf); } CEspLcd::~CEspLcd() { spi_bus_remove_device(spi_wr); vSemaphoreDelete(spi_mux); } void CEspLcd::acquireBus() { xSemaphoreTakeRecursive(spi_mux, portMAX_DELAY); } void CEspLcd::releaseBus() { xSemaphoreGiveRecursive(spi_mux); } void CEspLcd::setSpiBus(lcd_conf_t *lcd_conf) { cmd_io = (gpio_num_t) lcd_conf->pin_num_dc; dc.dc_io = cmd_io; id.id = lcd_init(lcd_conf, &spi_wr, &dc, m_dma_chan); id.mfg_id = (id.id >> (8 * 1)) & 0xff ; id.lcd_driver_id = (id.id >> (8 * 2)) & 0xff; id.lcd_id = (id.id >> (8 * 3)) & 0xff; } void CEspLcd::setAddrWindow(uint16_t x0, uint16_t y0, uint16_t x1, uint16_t y1) { /* * If screen is 240x240, an offset must be added when Y is mirrored because * st7789 controller is for 320x240 and therefore the starting address is 80 * pixels below the screen. * TODO: adding a start_x and start_y would be cleaner and safer */ if(m_width == 240 && m_height == 240) { if (rotation == 2) { // Y is mirrored y0 += 80; y1 += 80; } else if (rotation == 3) { // X-Y are exchanged x0 += 80; x1 += 80; } } xSemaphoreTakeRecursive(spi_mux, portMAX_DELAY); transmitCmdData(LCD_CASET, MAKEWORD(x0 >> 8, x0 & 0xFF, x1 >> 8, x1 & 0xFF)); transmitCmdData(LCD_PASET, MAKEWORD(y0 >> 8, y0 & 0xFF, y1 >> 8, y1 & 0xFF)); transmitCmd(LCD_RAMWR); // write to RAM xSemaphoreGiveRecursive(spi_mux); } void CEspLcd::transmitData(uint16_t data) { xSemaphoreTakeRecursive(spi_mux, portMAX_DELAY); lcd_data(spi_wr, (uint8_t *)&data, 2, &dc); xSemaphoreGiveRecursive(spi_mux); } void CEspLcd::transmitData(uint8_t data) { xSemaphoreTakeRecursive(spi_mux, portMAX_DELAY); lcd_data(spi_wr, (uint8_t *)&data, 1, &dc); xSemaphoreGiveRecursive(spi_mux); } void CEspLcd::transmitCmdData(uint8_t cmd, uint32_t data) { xSemaphoreTakeRecursive(spi_mux, portMAX_DELAY); lcd_cmd(spi_wr, cmd, &dc); lcd_data(spi_wr, (uint8_t *)&data, 4, &dc); xSemaphoreGiveRecursive(spi_mux); } void CEspLcd::transmitData(uint16_t data, int32_t repeats) { xSemaphoreTakeRecursive(spi_mux, portMAX_DELAY); lcd_send_uint16_r(spi_wr, data, repeats, &dc); xSemaphoreGiveRecursive(spi_mux); } void CEspLcd::transmitData(uint8_t *data, int length) { xSemaphoreTakeRecursive(spi_mux, portMAX_DELAY); lcd_data(spi_wr, (uint8_t *)data, length, &dc); xSemaphoreGiveRecursive(spi_mux); } void CEspLcd::transmitCmd(uint8_t cmd) { xSemaphoreTakeRecursive(spi_mux, portMAX_DELAY); lcd_cmd(spi_wr, cmd, &dc); xSemaphoreGiveRecursive(spi_mux); } void CEspLcd::transmitCmdData(uint8_t cmd, const uint8_t data, uint8_t numDataByte) { xSemaphoreTakeRecursive(spi_mux, portMAX_DELAY); lcd_cmd(spi_wr, (const uint8_t) cmd, &dc); lcd_data(spi_wr, &data, 1, &dc); xSemaphoreGiveRecursive(spi_mux); } uint32_t CEspLcd::getLcdId() { xSemaphoreTakeRecursive(spi_mux, portMAX_DELAY); uint32_t id = lcd_get_id(spi_wr, &dc); xSemaphoreGiveRecursive(spi_mux); return id; } void CEspLcd::drawPixel(int16_t x, int16_t y, uint16_t color) { if ((x < 0) || (x >= _width) || (y < 0) || (y >= _height)) { return; } xSemaphoreTakeRecursive(spi_mux, portMAX_DELAY); setAddrWindow(x, y, x + 1, y + 1); transmitData((uint16_t) SWAPBYTES(color)); xSemaphoreGiveRecursive(spi_mux); } void CEspLcd::_fastSendBuf(const uint16_t *buf, int point_num, bool swap) { if ((point_num * sizeof(uint16_t)) <= (16 * sizeof(uint32_t))) { transmitData((uint8_t *) buf, sizeof(uint16_t) * point_num); } else { int gap_point = dma_buf_size; uint16_t *data_buf = (uint16_t *) malloc(gap_point * sizeof(uint16_t)); int offset = 0; while (point_num > 0) { int trans_points = point_num > gap_point ? gap_point : point_num; if (swap) { for (int i = 0; i < trans_points; i++) { data_buf[i] = SWAPBYTES(buf[i + offset]); } } else { memcpy((uint8_t *) data_buf, (uint8_t *) (buf + offset), trans_points * sizeof(uint16_t)); } transmitData((uint8_t *) (data_buf), trans_points * sizeof(uint16_t)); offset += trans_points; point_num -= trans_points; } free(data_buf); data_buf = NULL; } } void CEspLcd::_fastSendRep(uint16_t val, int rep_num) { int point_num = rep_num; int gap_point = dma_buf_size; gap_point = (gap_point > point_num ? point_num : gap_point); uint16_t *data_buf = (uint16_t *) malloc(gap_point * sizeof(uint16_t)); int offset = 0; while (point_num > 0) { for (int i = 0; i < gap_point; i++) { data_buf[i] = val; } int trans_points = point_num > gap_point ? gap_point : point_num; transmitData((uint8_t *) (data_buf), sizeof(uint16_t) * trans_points); offset += trans_points; point_num -= trans_points; } free(data_buf); data_buf = NULL; } void CEspLcd::drawBitmap(int16_t x, int16_t y, const uint16_t *bitmap, int16_t w, int16_t h) { xSemaphoreTakeRecursive(spi_mux, portMAX_DELAY); setAddrWindow(x, y, x + w - 1, y + h - 1); if (dma_mode) { _fastSendBuf(bitmap, w * h); } else { for (int i = 0; i < w * h; i++) { transmitData(SWAPBYTES(bitmap[i]), 1); } } xSemaphoreGiveRecursive(spi_mux); } void CEspLcd::drawBitmapnotswap(int16_t x, int16_t y, const uint16_t *bitmap, int16_t w, int16_t h) { xSemaphoreTakeRecursive(spi_mux, portMAX_DELAY); setAddrWindow(x, y, x + w - 1, y + h - 1); if (dma_mode) { _fastSendBuf(bitmap, w * h, false); } else { for (int i = 0; i < w * h; i++) { transmitData(SWAPBYTES(bitmap[i]), 1); } } xSemaphoreGiveRecursive(spi_mux); } esp_err_t CEspLcd::drawBitmapFromFlashPartition(int16_t x, int16_t y, int16_t w, int16_t h, esp_partition_t *data_partition, int data_offset, int malloc_pixal_size, bool swap_bytes_en) { if (data_partition == NULL) { ESP_LOGE(TAG, "Partition error, null!"); return ESP_FAIL; } xSemaphoreTakeRecursive(spi_mux, portMAX_DELAY); uint16_t *recv_buf = (uint16_t *) calloc(malloc_pixal_size, sizeof(uint16_t)); setAddrWindow(x, y, x + w - 1, y + h - 1); int offset = 0; int point_num = w * h; while (point_num) { int len = malloc_pixal_size > point_num ? point_num : malloc_pixal_size; esp_partition_read(data_partition, data_offset + offset * sizeof(uint16_t), (uint8_t *) recv_buf, len * sizeof(uint16_t)); if (swap_bytes_en) { for (int i = 0; i < len; i++) { recv_buf[i] = SWAPBYTES(recv_buf[i]); } } transmitData((uint8_t *) recv_buf, len * sizeof(uint16_t)); offset += len; point_num -= len; } free(recv_buf); recv_buf = NULL; xSemaphoreGiveRecursive(spi_mux); return ESP_OK; } void CEspLcd::drawBitmapFont(int16_t x, int16_t y, uint8_t w, uint8_t h, const uint16_t *bitmap) { //Saves some memory and SWAPBYTES as compared to above API xSemaphoreTakeRecursive(spi_mux, portMAX_DELAY); setAddrWindow(x, y, x + w - 1, y + h - 1); if (dma_mode) { _fastSendBuf(bitmap, w * h, false); } else { transmitData((uint8_t *) bitmap, sizeof(uint16_t) * w * h); } xSemaphoreGiveRecursive(spi_mux); } void CEspLcd::drawFastVLine(int16_t x, int16_t y, int16_t h, uint16_t color) { // Rudimentary clipping if ((x >= _width) || (y >= _height)) { return; } if ((y + h - 1) >= _height) { h = _height - y; } xSemaphoreTakeRecursive(spi_mux, portMAX_DELAY); setAddrWindow(x, y, x, y + h - 1); if (dma_mode) { _fastSendRep(SWAPBYTES(color), h); } else { transmitData(SWAPBYTES(color), h); } xSemaphoreGiveRecursive(spi_mux); } void CEspLcd::drawFastHLine(int16_t x, int16_t y, int16_t w, uint16_t color) { // Rudimentary clipping if ((x >= _width) || (y >= _height)) { return; } if ((x + w - 1) >= _width) { w = _width - x; } xSemaphoreTakeRecursive(spi_mux, portMAX_DELAY); setAddrWindow(x, y, x + w - 1, y); if (dma_mode) { _fastSendRep(SWAPBYTES(color), w); } else { transmitData(SWAPBYTES(color), w); } xSemaphoreGiveRecursive(spi_mux); } void CEspLcd::fillScreen(uint16_t color) { fillRect(0, 0, _width, _height, color); } void CEspLcd::fillRect(int16_t x, int16_t y, int16_t w, int16_t h, uint16_t color) { // rudimentary clipping (drawChar w/big text requires this) if ((x >= _width) || (y >= _height)) { return; } if ((x + w - 1) >= _width) { w = _width - x; } if ((y + h - 1) >= _height) { h = _height - y; } xSemaphoreTakeRecursive(spi_mux, portMAX_DELAY); setAddrWindow(x, y, x + w - 1, y + h - 1); if (dma_mode) { _fastSendRep(SWAPBYTES(color), h * w); } else { transmitData(SWAPBYTES(color), h * w); } xSemaphoreGiveRecursive(spi_mux); } uint16_t CEspLcd::color565(uint8_t r, uint8_t g, uint8_t b) { return ((r & 0xF8) << 8) | ((g & 0xFC) << 3) | (b >> 3); } void CEspLcd::scrollTo(uint16_t y) { xSemaphoreTakeRecursive(spi_mux, portMAX_DELAY); transmitCmd(0x37); transmitData(y); xSemaphoreGiveRecursive(spi_mux); } #if CONFIG_M5STACK void CEspLcd::setRotation(uint8_t m) { uint8_t data = 0; rotation = m % 4; //Can't be more than 3 switch (rotation) { case 0: data = MADCTL_MY | MADCTL_MV | MADCTL_BGR; _width = m_width; _height = m_height; break; case 1: data = MADCTL_BGR; _width = m_height; _height = m_width; break; case 2: data = MADCTL_MV | MADCTL_MX | MADCTL_BGR; _width = m_width; _height = m_height; break; case 3: data = MADCTL_MX | MADCTL_MY | MADCTL_BGR; _width = m_height; _height = m_width; break; } transmitCmdData(LCD_MADCTL, data, 1); } #else void CEspLcd::setRotation(uint8_t m) { uint8_t data = 0; rotation = m % 4; //Can't be more than 3 switch (rotation) { case 0: // 0° data = MADCTL_MX | MADCTL_BGR; _width = m_width; _height = m_height; break; case 1: // 90° (counterclockwise) data = MADCTL_MV | MADCTL_BGR; _width = m_height; _height = m_width; break; case 2: // 180° (counterclockwise) data = MADCTL_MY | MADCTL_BGR; _width = m_width; _height = m_height; break; case 3: // 270° (counterclockwise) data = MADCTL_MX | MADCTL_MY | MADCTL_MV | MADCTL_BGR; _width = m_height; _height = m_width; break; } transmitCmdData(LCD_MADCTL, data, 1); } #endif void CEspLcd::invertDisplay(bool i) { transmitCmd(i ? LCD_INVON : LCD_INVOFF); } int CEspLcd::drawFloatSevSeg(float floatNumber, uint8_t decimal, uint16_t poX, uint16_t poY, uint8_t size) { unsigned int temp = 0; float decy = 0.0; float rounding = 0.5; float eep = 0.000001; int sumX = 0; uint16_t xPlus = 0; if (floatNumber - 0.0 < eep) { xPlus = drawUnicodeSevSeg('-', poX, poY, size); floatNumber = -floatNumber; poX += xPlus; sumX += xPlus; } for (unsigned char i = 0; i < decimal; ++i) { rounding /= 10.0; } floatNumber += rounding; temp = (long)floatNumber; xPlus = drawNumberSevSeg(temp, poX, poY, size); poX += xPlus; sumX += xPlus; if (decimal > 0) { xPlus = drawUnicodeSevSeg('.', poX, poY, size); poX += xPlus; /* Move cursor right */ sumX += xPlus; } else { return sumX; } decy = floatNumber - temp; for (unsigned char i = 0; i < decimal; i++) { decy *= 10; /* For the next decimal*/ temp = decy; /* Get the decimal */ xPlus = drawNumberSevSeg(temp, poX, poY, size); poX += xPlus; /* Move cursor right */ sumX += xPlus; decy -= temp; } return sumX; } int CEspLcd::drawUnicodeSevSeg(uint16_t uniCode, uint16_t x, uint16_t y, uint8_t size) { if (size) { uniCode -= 32; } uint16_t width = 0; uint16_t height = 0; const uint8_t *flash_address = 0; int8_t gap = 0; if (size == 7) { flash_address = chrtbl_f7s[uniCode]; width = *(widtbl_f7s + uniCode); height = CHR_HGT_F7S; gap = 2; } uint16_t w = (width + 7) / 8; uint8_t line = 0; xSemaphoreTakeRecursive(spi_mux, portMAX_DELAY); setAddrWindow(x, y, x + w * 8 - 1, y + height - 1); uint16_t *data_buf = (uint16_t *) malloc(dma_buf_size * sizeof(uint16_t)); int point_num = w * height * 8; int idx = 0; int trans_points = point_num > dma_buf_size ? dma_buf_size : point_num; for (int i = 0; i < height; i++) { for (int j = 0; j < w; j++) { line = *(flash_address + w * i + j); for (int m = 0; m < 8; m++) { if ((line >> (7 - m)) & 0x1) { data_buf[idx++] = SWAPBYTES(textcolor); } else { data_buf[idx++] = SWAPBYTES(textbgcolor); } if (idx >= trans_points) { transmitData((uint8_t *) (data_buf), trans_points * sizeof(uint16_t)); point_num -= trans_points; idx = 0; trans_points = point_num > dma_buf_size ? dma_buf_size : point_num; } } } } free(data_buf); data_buf = NULL; xSemaphoreGiveRecursive(spi_mux); return width + gap; } int CEspLcd::drawStringSevSeg(const char *string, uint16_t poX, uint16_t poY, uint8_t size) { uint16_t sumX = 0; while (*string) { uint16_t xPlus = drawUnicodeSevSeg(*string, poX, poY, size); sumX += xPlus; string++; poX += xPlus; /* Move cursor right*/ } return sumX; } int CEspLcd::drawNumberSevSeg(int long_num, uint16_t poX, uint16_t poY, uint8_t size) { char tmp[12]; if (long_num < 0) { snprintf(tmp, sizeof(tmp), "%d", long_num); } else { snprintf(tmp, sizeof(tmp), "%u", long_num); } return drawStringSevSeg(tmp, poX, poY, size); } int CEspLcd::write_char(uint8_t c) { if (!gfxFont) { // 'Classic' built-in font if (c == '\n') { // Newline? cursor_x = 0; // Reset x to zero, cursor_y += textsize * 8; // advance y one line } else if (c != '\r') { // Ignore carriage returns if (wrap && ((cursor_x + textsize * 6) > _width)) { // Off right? cursor_x = 0; // Reset x to zero, cursor_y += textsize * 8; // advance y one line } drawChar(cursor_x, cursor_y, c, textcolor, textbgcolor, textsize); cursor_x += textsize * 6; // Advance x one char } } else { if (c == '\n') { cursor_x = 0; cursor_y += (int16_t)textsize * (uint8_t)gfxFont->yAdvance; } else if (c != '\r') { uint8_t first = gfxFont->first; if ((c >= first) && (c <= (uint8_t)gfxFont->last)) { GFXglyph *glyph = &(((GFXglyph *)gfxFont->glyph))[c - first]; uint8_t w = glyph->width, h = glyph->height; if ((w > 0) && (h > 0)) { // Is there an associated bitmap? int16_t xo = (int8_t)glyph->xOffset; // sic if (wrap && ((cursor_x + textsize * (xo + w)) > _width)) { cursor_x = 0; cursor_y += (int16_t)textsize * (uint8_t)gfxFont->yAdvance; } drawChar(cursor_x, cursor_y, c, textcolor, textbgcolor, textsize); } cursor_x += (uint8_t)glyph->xAdvance * (int16_t)textsize; } } } return cursor_x; } int CEspLcd::drawString(const char *string, uint16_t x, uint16_t y) { uint16_t xPlus = x; setCursor(xPlus, y); while (*string) { xPlus = write_char(*string); // write_char string char-by-char setCursor(xPlus, y); // increment cursor string++; // Move cursor right } return xPlus; } int CEspLcd::drawNumber(int long_num, uint16_t poX, uint16_t poY) { char tmp[12]; if (long_num < 0) { snprintf(tmp, sizeof(tmp), "%d", long_num); } else { snprintf(tmp, sizeof(tmp), "%u", long_num); } return drawString(tmp, poX, poY); } int CEspLcd::drawFloat(float floatNumber, uint8_t decimal, uint16_t poX, uint16_t poY) { unsigned int temp = 0; float decy = 0.0; float rounding = 0.5; float eep = 0.000001; uint16_t xPlus = 0; if (floatNumber - 0.0 < eep) { xPlus = drawString("-", poX, poY); floatNumber = -floatNumber; poX = xPlus; } for (unsigned char i = 0; i < decimal; ++i) { rounding /= 10.0; } floatNumber += rounding; temp = (long)floatNumber; xPlus = drawNumber(temp, poX, poY); poX = xPlus; if (decimal > 0) { xPlus = drawString(".", poX, poY); poX = xPlus; /* Move cursor right */ } else { return poX; } decy = floatNumber - temp; for (unsigned char i = 0; i < decimal; i++) { decy *= 10; /* For the next decimal*/ temp = decy; /* Get the decimal */ xPlus = drawNumber(temp, poX, poY); poX = xPlus; /* Move cursor right */ decy -= temp; } return poX; }
21,232
iot_lcd
cpp
en
cpp
code
{"qsc_code_num_words": 2686, "qsc_code_num_chars": 21232.0, "qsc_code_mean_word_length": 4.44676098, "qsc_code_frac_words_unique": 0.16679077, "qsc_code_frac_chars_top_2grams": 0.03750837, "qsc_code_frac_chars_top_3grams": 0.04855995, "qsc_code_frac_chars_top_4grams": 0.06028131, "qsc_code_frac_chars_dupe_5grams": 0.52168453, "qsc_code_frac_chars_dupe_6grams": 0.45696584, "qsc_code_frac_chars_dupe_7grams": 0.40949431, "qsc_code_frac_chars_dupe_8grams": 0.39685198, "qsc_code_frac_chars_dupe_9grams": 0.38035834, "qsc_code_frac_chars_dupe_10grams": 0.34837575, "qsc_code_frac_chars_replacement_symbols": 0.0, "qsc_code_frac_chars_digital": 0.03592175, "qsc_code_frac_chars_whitespace": 0.29460249, "qsc_code_size_file_byte": 21232.0, "qsc_code_num_lines": 684.0, "qsc_code_num_chars_line_max": 185.0, "qsc_code_num_chars_line_mean": 31.04093567, "qsc_code_frac_chars_alphabet": 0.76130066, "qsc_code_frac_chars_comments": 0.14445177, "qsc_code_cate_xml_start": 0.0, "qsc_code_frac_lines_dupe_lines": 0.39305302, "qsc_code_cate_autogen": 0.0, "qsc_code_frac_lines_long_string": 0.0, "qsc_code_frac_chars_string_length": 0.0090834, "qsc_code_frac_chars_long_word_length": 0.0, "qsc_code_frac_lines_string_concat": 0.0, "qsc_code_cate_encoded_data": 0.0, "qsc_code_frac_chars_hex_words": 0.00390862, "qsc_code_frac_lines_prompt_comments": 0.00146199, "qsc_code_frac_lines_assert": 0.0, "qsc_codecpp_frac_lines_preprocessor_directives": 0.03290676, "qsc_codecpp_frac_lines_func_ratio": 0.023766, "qsc_codecpp_cate_bitsstdc": 0.0, "qsc_codecpp_nums_lines_main": 0.0, "qsc_codecpp_frac_lines_goto": 0.0, "qsc_codecpp_cate_var_zero": 0.0, "qsc_codecpp_score_lines_no_logic": 0.06764168, "qsc_codecpp_frac_lines_print": 0.00731261}
1
{"qsc_code_frac_chars_replacement_symbols": 0, "qsc_code_num_words": 0, "qsc_code_num_chars": 0, "qsc_code_mean_word_length": 0, "qsc_code_frac_chars_top_2grams": 0, "qsc_code_frac_chars_top_3grams": 0, "qsc_code_frac_chars_top_4grams": 0, "qsc_code_frac_chars_dupe_5grams": 0, "qsc_code_frac_chars_dupe_6grams": 0, "qsc_code_frac_chars_dupe_7grams": 0, "qsc_code_frac_chars_dupe_8grams": 0, "qsc_code_frac_chars_dupe_9grams": 0, "qsc_code_frac_chars_dupe_10grams": 0, "qsc_code_frac_lines_dupe_lines": 0, "qsc_code_size_file_byte": 0, "qsc_code_num_lines": 0, "qsc_code_num_chars_line_max": 0, "qsc_code_num_chars_line_mean": 0, "qsc_code_frac_chars_alphabet": 0, "qsc_code_frac_chars_digital": 0, "qsc_code_frac_chars_whitespace": 0, "qsc_code_frac_chars_comments": 0, "qsc_code_cate_xml_start": 0, "qsc_code_cate_autogen": 0, "qsc_code_frac_lines_long_string": 0, "qsc_code_frac_chars_string_length": 0, "qsc_code_frac_chars_long_word_length": 0, "qsc_code_cate_encoded_data": 0, "qsc_code_frac_chars_hex_words": 0, "qsc_code_frac_lines_prompt_comments": 0, "qsc_code_frac_lines_assert": 0, "qsc_codecpp_frac_lines_func_ratio": 0, "qsc_codecpp_nums_lines_main": 0, "qsc_codecpp_score_lines_no_logic": 0, "qsc_codecpp_frac_lines_preprocessor_directives": 0, "qsc_codecpp_frac_lines_print": 0}
0015/ESP32-OpenCV-Projects
esp32/examples/color_code/components/lcd/adaptation.cpp
/* This is the subclass graphics library for all our displays, providing a common set of graphics primitives (points, lines, circles, etc.) Adafruit invests time and resources providing this open source code, please support Adafruit & open-source hardware by purchasing products from Adafruit! Based on ESP8266 library https://github.com/Sermus/ESP8266_Adafruit_lcd Copyright (c) 2015-2016 Andrey Filimonov. All rights reserved. Additions for ESP32 Copyright (c) 2016-2017 Espressif Systems (Shanghai) PTE LTD Copyright (c) 2013 Adafruit Industries. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "WProgram.h" // Do nothing here void Print::print(char* s){ }
1,898
adaptation
cpp
en
cpp
code
{"qsc_code_num_words": 277, "qsc_code_num_chars": 1898.0, "qsc_code_mean_word_length": 5.48375451, "qsc_code_frac_words_unique": 0.57400722, "qsc_code_frac_chars_top_2grams": 0.01974984, "qsc_code_frac_chars_top_3grams": 0.02238315, "qsc_code_frac_chars_top_4grams": 0.03028308, "qsc_code_frac_chars_dupe_5grams": 0.12113232, "qsc_code_frac_chars_dupe_6grams": 0.08953259, "qsc_code_frac_chars_dupe_7grams": 0.08953259, "qsc_code_frac_chars_dupe_8grams": 0.08953259, "qsc_code_frac_chars_dupe_9grams": 0.08953259, "qsc_code_frac_chars_dupe_10grams": 0.08953259, "qsc_code_frac_chars_replacement_symbols": 0.0, "qsc_code_frac_chars_digital": 0.01869159, "qsc_code_frac_chars_whitespace": 0.15437302, "qsc_code_size_file_byte": 1898.0, "qsc_code_num_lines": 42.0, "qsc_code_num_chars_line_max": 81.0, "qsc_code_num_chars_line_mean": 45.19047619, "qsc_code_frac_chars_alphabet": 0.92772586, "qsc_code_frac_chars_comments": 0.96944152, "qsc_code_cate_xml_start": 0.0, "qsc_code_frac_lines_dupe_lines": 0.0, "qsc_code_cate_autogen": 0.0, "qsc_code_frac_lines_long_string": 0.0, "qsc_code_frac_chars_string_length": 0.16949153, "qsc_code_frac_chars_long_word_length": 0.0, "qsc_code_frac_lines_string_concat": 0.0, "qsc_code_cate_encoded_data": 0.0, "qsc_code_frac_chars_hex_words": 0.0, "qsc_code_frac_lines_prompt_comments": 0.0, "qsc_code_frac_lines_assert": 0.0, "qsc_codecpp_frac_lines_preprocessor_directives": 0.33333333, "qsc_codecpp_frac_lines_func_ratio": 0.0, "qsc_codecpp_cate_bitsstdc": 0.0, "qsc_codecpp_nums_lines_main": 0.0, "qsc_codecpp_frac_lines_goto": 0.0, "qsc_codecpp_cate_var_zero": 1.0, "qsc_codecpp_score_lines_no_logic": 0.33333333, "qsc_codecpp_frac_lines_print": 0.0}
0
{"qsc_code_frac_chars_replacement_symbols": 0, "qsc_code_num_words": 0, "qsc_code_num_chars": 0, "qsc_code_mean_word_length": 0, "qsc_code_frac_chars_top_2grams": 0, "qsc_code_frac_chars_top_3grams": 0, "qsc_code_frac_chars_top_4grams": 0, "qsc_code_frac_chars_dupe_5grams": 0, "qsc_code_frac_chars_dupe_6grams": 0, "qsc_code_frac_chars_dupe_7grams": 0, "qsc_code_frac_chars_dupe_8grams": 0, "qsc_code_frac_chars_dupe_9grams": 0, "qsc_code_frac_chars_dupe_10grams": 0, "qsc_code_frac_lines_dupe_lines": 0, "qsc_code_size_file_byte": 0, "qsc_code_num_lines": 0, "qsc_code_num_chars_line_max": 0, "qsc_code_num_chars_line_mean": 0, "qsc_code_frac_chars_alphabet": 0, "qsc_code_frac_chars_digital": 0, "qsc_code_frac_chars_whitespace": 0, "qsc_code_frac_chars_comments": 1, "qsc_code_cate_xml_start": 0, "qsc_code_cate_autogen": 0, "qsc_code_frac_lines_long_string": 0, "qsc_code_frac_chars_string_length": 0, "qsc_code_frac_chars_long_word_length": 0, "qsc_code_cate_encoded_data": 0, "qsc_code_frac_chars_hex_words": 0, "qsc_code_frac_lines_prompt_comments": 0, "qsc_code_frac_lines_assert": 0, "qsc_codecpp_frac_lines_func_ratio": 0, "qsc_codecpp_nums_lines_main": 0, "qsc_codecpp_score_lines_no_logic": 0, "qsc_codecpp_frac_lines_preprocessor_directives": 0, "qsc_codecpp_frac_lines_print": 0}
0015/ESP32-OpenCV-Projects
esp32/examples/color_code/components/lcd/spi_lcd.c
// Copyright 2015-2016 Espressif Systems (Shanghai) PTE LTD // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <sys/param.h> #include "spi_lcd.h" #include "driver/gpio.h" #include <string.h> #include "freertos/FreeRTOS.h" #include "freertos/task.h" #include "freertos/semphr.h" #include "freertos/xtensa_api.h" #include "freertos/task.h" #define SPIFIFOSIZE 16 /* This struct stores a bunch of command values to be initialized for ILI9341 */ typedef struct { uint8_t cmd; uint8_t data[16]; uint8_t databytes; //No of data in data; bit 7 = delay after set; 0xFF = end of cmds. } lcd_init_cmd_t; DRAM_ATTR static const lcd_init_cmd_t ili_init_cmds[]={ {0xCF, {0x00, 0x83, 0x30}, 3}, {0xED, {0x64, 0x03, 0x12, 0x81}, 4}, {0xE8, {0x85, 0x01, 0x79}, 3}, {0xCB, {0x39, 0x2C, 0x00, 0x34, 0x02}, 5}, {0xF7, {0x20}, 1}, {0xEA, {0x00, 0x00}, 2}, {0xC0, {0x26}, 1}, {0xC1, {0x11}, 1}, {0xC5, {0x35, 0x3E}, 2}, {0xC7, {0xBE}, 1}, {0x36, {0x28}, 1}, {0x3A, {0x55}, 1}, {0xB1, {0x00, 0x1B}, 2}, {0xF2, {0x08}, 1}, {0x26, {0x01}, 1}, {0xE0, {0x1F, 0x1A, 0x18, 0x0A, 0x0F, 0x06, 0x45, 0X87, 0x32, 0x0A, 0x07, 0x02, 0x07, 0x05, 0x00}, 15}, {0XE1, {0x00, 0x25, 0x27, 0x05, 0x10, 0x09, 0x3A, 0x78, 0x4D, 0x05, 0x18, 0x0D, 0x38, 0x3A, 0x1F}, 15}, {0x2A, {0x00, 0x00, 0x00, 0xEF}, 4}, {0x2B, {0x00, 0x00, 0x01, 0x3f}, 4}, {0x2C, {0}, 0}, {0xB7, {0x07}, 1}, {0xB6, {0x0A, 0x82, 0x27, 0x00}, 4}, {0x11, {0}, 0x80}, {0x29, {0}, 0x80}, {0, {0}, 0xff}, }; DRAM_ATTR static const lcd_init_cmd_t st7789_init_cmds[] = { {0xC0, {0x00}, 1}, //LCMCTRL: LCM Control [2C] //sumpremely related to 0x36, MADCTL {0xC2, {0x01, 0xFF}, 2}, //VDVVRHEN: VDV and VRH Command Enable [01 FF] {0xC3, {0x13}, 1}, //VRHS: VRH Set VAP=???, VAN=-??? [0B] {0xC4, {0x20}, 1}, //VDVS: VDV Set [20] {0xC6, {0x0F}, 1}, //FRCTRL2: Frame Rate control in normal mode [0F] {0xCA, {0x0F}, 1}, //REGSEL2 [0F] {0xC8, {0x08}, 1}, //REGSEL1 [08] {0x55, {0xB0}, 1}, //WRCACE [00] {0x36, {0x00}, 1}, {0x3A, {0x55}, 1}, //this says 0x05 {0xB1, {0x40, 0x02, 0x14}, 3}, //sync setting not reqd {0x26, {0x01}, 1}, {0x2A, {0x00, 0x00, 0x00, 0xEF}, 4}, {0x2B, {0x00, 0x00, 0x01, 0x3F}, 4}, {0x2C, {0x00}, 1}, {0xE0, {0xD0, 0x00, 0x05, 0x0E, 0x15, 0x0D, 0x37, 0x43, 0x47, 0x09, 0x15, 0x12, 0x16, 0x19}, 14}, //PVGAMCTRL: Positive Voltage Gamma control {0xE1, {0xD0, 0x00, 0x05, 0x0D, 0x0C, 0x06, 0x2D, 0x44, 0x40, 0x0E, 0x1C, 0x18, 0x16, 0x19}, 14}, //NVGAMCTRL: Negative Voltage Gamma control {0x11, {0}, 0x80}, {0x29, {0}, 0x80}, {0, {0}, 0xff}, }; #define LCD_CMD_LEV (0) #define LCD_DATA_LEV (1) /*This function is called (in irq context!) just before a transmission starts. It will set the D/C line to the value indicated in the user field */ void lcd_spi_pre_transfer_callback(spi_transaction_t *t) { lcd_dc_t *dc = (lcd_dc_t *) t->user; gpio_set_level((int)dc->dc_io, (int)dc->dc_level); } static SemaphoreHandle_t _spi_mux = NULL; static esp_err_t _lcd_spi_send(spi_device_handle_t spi, spi_transaction_t* t) { xSemaphoreTake(_spi_mux, portMAX_DELAY); esp_err_t res = spi_device_transmit(spi, t); //Transmit! xSemaphoreGive(_spi_mux); return res; } void lcd_cmd(spi_device_handle_t spi, const uint8_t cmd, lcd_dc_t *dc) { esp_err_t ret; dc->dc_level = LCD_CMD_LEV; spi_transaction_t t = { .length = 8, // Command is 8 bits .tx_buffer = &cmd, // The data is the cmd itself .user = (void *) dc, // D/C needs to be set to 0 }; ret = _lcd_spi_send(spi, &t); // Transmit! assert(ret == ESP_OK); // Should have had no issues. } void lcd_data(spi_device_handle_t spi, const uint8_t *data, int len, lcd_dc_t *dc) { esp_err_t ret; if (len == 0) { return; //no need to send anything } dc->dc_level = LCD_DATA_LEV; spi_transaction_t t = { .length = len * 8, // Len is in bytes, transaction length is in bits. .tx_buffer = data, // Data .user = (void *) dc, // D/C needs to be set to 1 }; ret = _lcd_spi_send(spi, &t); // Transmit! assert(ret == ESP_OK); // Should have had no issues. } uint32_t lcd_init(lcd_conf_t* lcd_conf, spi_device_handle_t *spi_wr_dev, lcd_dc_t *dc, int dma_chan) { if (_spi_mux == NULL) { _spi_mux = xSemaphoreCreateMutex(); } //Initialize non-SPI GPIOs gpio_pad_select_gpio(lcd_conf->pin_num_dc); gpio_set_direction(lcd_conf->pin_num_dc, GPIO_MODE_OUTPUT); //Reset the display if (lcd_conf->pin_num_rst < GPIO_NUM_MAX) { gpio_pad_select_gpio(lcd_conf->pin_num_rst); gpio_set_direction(lcd_conf->pin_num_rst, GPIO_MODE_OUTPUT); gpio_set_level(lcd_conf->pin_num_rst, (lcd_conf->rst_active_level) & 0x1); vTaskDelay(100 / portTICK_RATE_MS); gpio_set_level(lcd_conf->pin_num_rst, (~(lcd_conf->rst_active_level)) & 0x1); vTaskDelay(100 / portTICK_RATE_MS); } if (lcd_conf->init_spi_bus) { //Initialize SPI Bus for LCD spi_bus_config_t buscfg = { .miso_io_num = lcd_conf->pin_num_miso, .mosi_io_num = lcd_conf->pin_num_mosi, .sclk_io_num = lcd_conf->pin_num_clk, .quadwp_io_num = -1, .quadhd_io_num = -1, }; spi_bus_initialize(lcd_conf->spi_host, &buscfg, dma_chan); } spi_device_interface_config_t devcfg = { // Use low speed to read ID. .clock_speed_hz = 1 * 1000 * 1000, //Clock out frequency .mode = 0, //SPI mode 0 .spics_io_num = lcd_conf->pin_num_cs, //CS pin .queue_size = 7, //We want to be able to queue 7 transactions at a time .pre_cb = lcd_spi_pre_transfer_callback, //Specify pre-transfer callback to handle D/C line }; spi_device_handle_t rd_id_handle; spi_bus_add_device(lcd_conf->spi_host, &devcfg, &rd_id_handle); uint32_t lcd_id = lcd_get_id(rd_id_handle, dc); spi_bus_remove_device(rd_id_handle); // Use high speed to write LCD devcfg.clock_speed_hz = lcd_conf->clk_freq; spi_bus_add_device(lcd_conf->spi_host, &devcfg, spi_wr_dev); int cmd = 0; const lcd_init_cmd_t* lcd_init_cmds = NULL; if(lcd_conf->lcd_model == LCD_MOD_ST7789) { lcd_init_cmds = st7789_init_cmds; } else if(lcd_conf->lcd_model == LCD_MOD_ILI9341) { lcd_init_cmds = ili_init_cmds; } else if(lcd_conf->lcd_model == LCD_MOD_AUTO_DET) { if (((lcd_id >> 8) & 0xff) == 0x42) { lcd_init_cmds = st7789_init_cmds; } else { lcd_init_cmds = ili_init_cmds; } } assert(lcd_init_cmds != NULL); //Send all the commands while (lcd_init_cmds[cmd].databytes!=0xff) { lcd_cmd(*spi_wr_dev, lcd_init_cmds[cmd].cmd, dc); lcd_data(*spi_wr_dev, lcd_init_cmds[cmd].data, lcd_init_cmds[cmd].databytes&0x1F, dc); if (lcd_init_cmds[cmd].databytes&0x80) { vTaskDelay(100 / portTICK_RATE_MS); } cmd++; } //Enable backlight if (lcd_conf->pin_num_bckl < GPIO_NUM_MAX) { gpio_pad_select_gpio(lcd_conf->pin_num_bckl); gpio_set_direction(lcd_conf->pin_num_bckl, GPIO_MODE_OUTPUT); gpio_set_level(lcd_conf->pin_num_bckl, (lcd_conf->bckl_active_level) & 0x1); } return lcd_id; } void lcd_send_uint16_r(spi_device_handle_t spi, const uint16_t data, int32_t repeats, lcd_dc_t *dc) { uint32_t i; uint32_t word = data << 16 | data; uint32_t word_tmp[16]; spi_transaction_t t; dc->dc_level = LCD_DATA_LEV; while (repeats > 0) { uint16_t bytes_to_transfer = MIN(repeats * sizeof(uint16_t), SPIFIFOSIZE * sizeof(uint32_t)); for (i = 0; i < (bytes_to_transfer + 3) / 4; i++) { word_tmp[i] = word; } memset(&t, 0, sizeof(t)); //Zero out the transaction t.length = bytes_to_transfer * 8; //Len is in bytes, transaction length is in bits. t.tx_buffer = word_tmp; //Data t.user = (void *) dc; //D/C needs to be set to 1 _lcd_spi_send(spi, &t); //Transmit! repeats -= bytes_to_transfer / 2; } } uint32_t lcd_get_id(spi_device_handle_t spi, lcd_dc_t *dc) { //get_id cmd lcd_cmd( spi, 0x04, dc); spi_transaction_t t; dc->dc_level = LCD_DATA_LEV; memset(&t, 0, sizeof(t)); t.length = 8 * 4; t.flags = SPI_TRANS_USE_RXDATA; t.user = (void *) dc; esp_err_t ret = _lcd_spi_send(spi, &t); assert( ret == ESP_OK ); return *(uint32_t*) t.rx_data; }
9,459
spi_lcd
c
en
c
code
{"qsc_code_num_words": 1428, "qsc_code_num_chars": 9459.0, "qsc_code_mean_word_length": 3.77661064, "qsc_code_frac_words_unique": 0.28151261, "qsc_code_frac_chars_top_2grams": 0.03634341, "qsc_code_frac_chars_top_3grams": 0.02781383, "qsc_code_frac_chars_top_4grams": 0.03615798, "qsc_code_frac_chars_dupe_5grams": 0.35286482, "qsc_code_frac_chars_dupe_6grams": 0.29575375, "qsc_code_frac_chars_dupe_7grams": 0.24160949, "qsc_code_frac_chars_dupe_8grams": 0.20452438, "qsc_code_frac_chars_dupe_9grams": 0.17003523, "qsc_code_frac_chars_dupe_10grams": 0.14815502, "qsc_code_frac_chars_replacement_symbols": 0.0, "qsc_code_frac_chars_digital": 0.09277912, "qsc_code_frac_chars_whitespace": 0.2547838, "qsc_code_size_file_byte": 9459.0, "qsc_code_num_lines": 257.0, "qsc_code_num_chars_line_max": 157.0, "qsc_code_num_chars_line_mean": 36.80544747, "qsc_code_frac_chars_alphabet": 0.67229394, "qsc_code_frac_chars_comments": 0.2188392, "qsc_code_cate_xml_start": 0.0, "qsc_code_frac_lines_dupe_lines": 0.16959064, "qsc_code_cate_autogen": 0.0, "qsc_code_frac_lines_long_string": 0.0, "qsc_code_frac_chars_string_length": 0.01475365, "qsc_code_frac_chars_long_word_length": 0.00284245, "qsc_code_frac_lines_string_concat": 0.0, "qsc_code_cate_encoded_data": 0.0, "qsc_code_frac_chars_hex_words": 0.09813211, "qsc_code_frac_lines_prompt_comments": 0.0, "qsc_code_frac_lines_assert": 0.02339181, "qsc_codec_frac_lines_func_ratio": 0.06432749, "qsc_codec_cate_bitsstdc": 0.0, "qsc_codec_nums_lines_main": 0, "qsc_codec_frac_lines_goto": 0.0, "qsc_codec_cate_var_zero": 0.0, "qsc_codec_score_lines_no_logic": 0.12865497, "qsc_codec_frac_lines_print": 0.0, "qsc_codec_frac_lines_preprocessor_directives": 0.07602339}
1
{"qsc_code_frac_chars_replacement_symbols": 0, "qsc_code_num_words": 0, "qsc_code_num_chars": 0, "qsc_code_mean_word_length": 0, "qsc_code_frac_chars_top_2grams": 0, "qsc_code_frac_chars_top_3grams": 0, "qsc_code_frac_chars_top_4grams": 0, "qsc_code_frac_chars_dupe_5grams": 0, "qsc_code_frac_chars_dupe_6grams": 0, "qsc_code_frac_chars_dupe_7grams": 0, "qsc_code_frac_chars_dupe_8grams": 0, "qsc_code_frac_chars_dupe_9grams": 0, "qsc_code_frac_chars_dupe_10grams": 0, "qsc_code_size_file_byte": 0, "qsc_code_num_lines": 0, "qsc_code_num_chars_line_max": 0, "qsc_code_num_chars_line_mean": 0, "qsc_code_frac_chars_alphabet": 0, "qsc_code_frac_chars_digital": 0, "qsc_code_frac_chars_whitespace": 0, "qsc_code_frac_chars_comments": 0, "qsc_code_cate_xml_start": 0, "qsc_code_frac_lines_dupe_lines": 0, "qsc_code_cate_autogen": 0, "qsc_code_frac_lines_long_string": 0, "qsc_code_frac_chars_string_length": 0, "qsc_code_frac_chars_long_word_length": 0, "qsc_code_cate_encoded_data": 0, "qsc_code_frac_chars_hex_words": 0, "qsc_code_frac_lines_prompt_comments": 0, "qsc_code_frac_lines_assert": 0, "qsc_codec_frac_lines_func_ratio": 0, "qsc_codec_nums_lines_main": 0, "qsc_codec_score_lines_no_logic": 0, "qsc_codec_frac_lines_preprocessor_directives": 0, "qsc_codec_frac_lines_print": 0}
0015/ESP32-OpenCV-Projects
esp32/examples/color_code/components/lcd/README.md
##TFT LCD Example Code for ESP32## This example is based on [Adafruit’s Library](https://github.com/adafruit/Adafruit-GFX-Library.git) for ILI9341. This component can display<br /> 1. Text<br /> 2. Bitmap Images<br /> 3. Shapes<br /> on the 320*240 TFT LCD<br /> Users can refer `ui_example.jpg` in the root folder of this example to learn more about the APIs & what they do. LCD has Serial & Parallel Interfaces, esp-wrover-kit is designed for Serial SPI interfacing. However, LCD requires some additional pins except the normal SPI pins. > Tip: TFT LCDs work on a basic bitmap, where you should tell each pixel what to do. The library is able to display data by a concept of foreground and background.<br />For eg: If white text is required on a black background, screen is filled with black, the foreground color is set to white. Only the bitmap pixels which define the font are cleared, and the rest are kept as they are. This is how bitmaps, fonts and shapes are printed on the screen. **Additional files required for the GUI** `components\lcd` folder<br /> 1. `Adafruit-GFX-Library`: Adafruit-GFX-Library<br /> 2. `Adafruit_lcd_fast_as.cpp`: Used for drawing pixels and some lines on the screen, and this subclass overrides most of the superclass methods in `Adafruit_GFX.cpp`<br /> 3. `Adafruit-GFX-Library/Font files`: It is the bitmap for various sizes of fonts (Prefer to only #include your desired fonts to save space)<br /> 4. `spi_lcd.c` : It has some SPI structures & functions which use the spi_master driver for sending out the data as required by Adafruit Libraries. > Note: To reduce the number of pins between the LCD & ESP32<br /> > - It is okay to leave out the MISO pin<br /> > - Short the backlight pin to always ON<br /> > - Reset pin can be shorted with the ESP32’s reset pin, but it might lead to unexpected behavior depending on the code. There have been multiple additions to the [Adafruit repository](https://github.com/adafruit/Adafruit_ILI9341) for the LCD, users can replace these files by new library if needed. Adafruit has made a good [documentation](https://cdn-learn.adafruit.com/downloads/pdf/adafruit-2-8-tft-touch-shield-v2.pdf) on TFT LCDs. If you are willing to share your User Interface for ESP32, you can do so by posting on the forum [here](http://bbs.esp32.com/).
2,331
README
md
en
markdown
text
{"qsc_doc_frac_chars_curly_bracket": 0.0, "qsc_doc_frac_words_redpajama_stop": 0.29067642, "qsc_doc_num_sentences": 33.0, "qsc_doc_num_words": 407, "qsc_doc_num_chars": 2331.0, "qsc_doc_num_lines": 32.0, "qsc_doc_mean_word_length": 4.31203931, "qsc_doc_frac_words_full_bracket": 0.0, "qsc_doc_frac_lines_end_with_readmore": 0.0, "qsc_doc_frac_lines_start_with_bullet": 0.0, "qsc_doc_frac_words_unique": 0.46683047, "qsc_doc_entropy_unigram": 4.82131066, "qsc_doc_frac_words_all_caps": 0.04570384, "qsc_doc_frac_lines_dupe_lines": 0.0, "qsc_doc_frac_chars_dupe_lines": 0.0, "qsc_doc_frac_chars_top_2grams": 0.03133903, "qsc_doc_frac_chars_top_3grams": 0.04102564, "qsc_doc_frac_chars_top_4grams": 0.02507123, "qsc_doc_frac_chars_dupe_5grams": 0.03418803, "qsc_doc_frac_chars_dupe_6grams": 0.0, "qsc_doc_frac_chars_dupe_7grams": 0.0, "qsc_doc_frac_chars_dupe_8grams": 0.0, "qsc_doc_frac_chars_dupe_9grams": 0.0, "qsc_doc_frac_chars_dupe_10grams": 0.0, "qsc_doc_frac_chars_replacement_symbols": 0.0, "qsc_doc_cate_code_related_file_name": 1.0, "qsc_doc_num_chars_sentence_length_mean": 34.87692308, "qsc_doc_frac_chars_hyperlink_html_tag": 0.12183612, "qsc_doc_frac_chars_alphabet": 0.88347023, "qsc_doc_frac_chars_digital": 0.0174538, "qsc_doc_frac_chars_whitespace": 0.16430716, "qsc_doc_frac_chars_hex_words": 0.0}
1
{"qsc_doc_frac_chars_replacement_symbols": 0, "qsc_doc_entropy_unigram": 0, "qsc_doc_frac_chars_top_2grams": 0, "qsc_doc_frac_chars_top_3grams": 0, "qsc_doc_frac_chars_top_4grams": 0, "qsc_doc_frac_chars_dupe_5grams": 0, "qsc_doc_frac_chars_dupe_6grams": 0, "qsc_doc_frac_chars_dupe_7grams": 0, "qsc_doc_frac_chars_dupe_8grams": 0, "qsc_doc_frac_chars_dupe_9grams": 0, "qsc_doc_frac_chars_dupe_10grams": 0, "qsc_doc_frac_chars_dupe_lines": 0, "qsc_doc_frac_lines_dupe_lines": 0, "qsc_doc_frac_lines_end_with_readmore": 0, "qsc_doc_frac_lines_start_with_bullet": 0, "qsc_doc_frac_words_all_caps": 0, "qsc_doc_mean_word_length": 0, "qsc_doc_num_chars": 0, "qsc_doc_num_lines": 0, "qsc_doc_num_sentences": 0, "qsc_doc_num_words": 0, "qsc_doc_frac_chars_hex_words": 0, "qsc_doc_frac_chars_hyperlink_html_tag": 0, "qsc_doc_frac_chars_alphabet": 0, "qsc_doc_frac_chars_digital": 0, "qsc_doc_frac_chars_whitespace": 0}
0015/ESP32-OpenCV-Projects
esp32/examples/color_code/components/lcd/font7s.c
// Font size 7 is a 7 segment font intended to display numbers and time // This font only contains characters [space] 0 1 2 3 4 5 6 7 8 9 : . // All other characters print as a space #include "font7s.h" const unsigned char widtbl_f7s[96] = { // character width table 12, 12, 12, 12, 12, 12, 12, 12, // char 32 - 39 12, 12, 12, 12, 12, 12, 12, 12, // char 40 - 47 32, 32, 32, 32, 32, 32, 32, 32, // char 48 - 55 32, 32, 12, 12, 12, 12, 12, 12, // char 56 - 63 12, 12, 12, 12, 12, 12, 12, 12, // char 64 - 71 12, 12, 12, 12, 12, 12, 12, 12, // char 72 - 79 12, 12, 12, 12, 12, 12, 12, 12, // char 80 - 87 12, 12, 12, 12, 12, 12, 12, 12, // char 88 - 95 12, 12, 12, 12, 12, 12, 12, 12, // char 96 - 103 12, 12, 12, 12, 12, 12, 12, 12, // char 104 - 111 12, 12, 12, 12, 12, 12, 12, 12, // char 112 - 119 12, 12, 12, 12, 12, 12, 12, 12 // char 120 - 127 }; // Row format, MSB left const unsigned char chr_f7s_20[96] = { // 2 bytes per row 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // row 1 - 6 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // row 7 - 12 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // row 13 - 18 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // row 19 - 24 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // row 25 - 30 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // row 31 - 36 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // row 37 - 42 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 // row 43 - 48 }; const unsigned char chr_f7s_2E[96] = { // 2 bytes per row 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // row 1 - 6 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // row 7 - 12 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // row 13 - 18 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // row 19 - 24 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // row 25 - 30 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // row 31 - 36 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // row 37 - 42 0x0E, 0x00, 0x1F, 0x00, 0x1F, 0x00, 0x1F, 0x00, 0x0E, 0x00, 0x00, 0x00 // row 43 - 48 }; const unsigned char chr_f7s_30[192] = { // 4 bytes per row 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, 0xFE, 0x00, 0x01, 0xFF, 0xFF, 0x00, // row 1 - 3 0x03, 0xFF, 0xFF, 0x80, 0x01, 0xFF, 0xFF, 0x20, 0x0C, 0xFF, 0xFE, 0x70, // row 4 - 6 0x1E, 0x00, 0x00, 0xF8, 0x3F, 0x00, 0x01, 0xF8, 0x3F, 0x00, 0x01, 0xF8, // row 7 - 9 0x3F, 0x00, 0x01, 0xF8, 0x3F, 0x00, 0x01, 0xF8, 0x3F, 0x00, 0x01, 0xF8, // row 10 - 12 0x3F, 0x00, 0x01, 0xF8, 0x3F, 0x00, 0x01, 0xF8, 0x3F, 0x00, 0x01, 0xF8, // row 13 - 15 0x3F, 0x00, 0x01, 0xF8, 0x3F, 0x00, 0x01, 0xF8, 0x3F, 0x00, 0x01, 0xF8, // row 16 - 18 0x3F, 0x00, 0x01, 0xF8, 0x3F, 0x00, 0x01, 0xF8, 0x3E, 0x00, 0x00, 0xF8, // row 19 - 21 0x38, 0x00, 0x00, 0x38, 0x20, 0x00, 0x00, 0x08, 0x00, 0x00, 0x00, 0x00, // row 22 - 24 0x20, 0x00, 0x00, 0x00, 0x38, 0x00, 0x00, 0x18, 0x3E, 0x00, 0x00, 0x78, // row 25 - 27 0x3F, 0x00, 0x01, 0xF8, 0x3F, 0x00, 0x01, 0xF8, 0x3F, 0x00, 0x01, 0xF8, // row 28 - 30 0x3F, 0x00, 0x01, 0xF8, 0x3F, 0x00, 0x01, 0xF8, 0x3F, 0x00, 0x01, 0xF8, // row 31 - 33 0x3F, 0x00, 0x01, 0xF8, 0x3F, 0x00, 0x01, 0xF8, 0x3F, 0x00, 0x01, 0xF8, // row 34 - 36 0x3F, 0x00, 0x01, 0xF8, 0x3F, 0x00, 0x01, 0xF8, 0x3F, 0x00, 0x01, 0xF8, // row 37 - 39 0x3F, 0x00, 0x01, 0xF8, 0x3F, 0x00, 0x01, 0xF8, 0x1E, 0x00, 0x00, 0xF0, // row 40 - 42 0x0C, 0xFF, 0xFE, 0x60, 0x01, 0xFF, 0xFF, 0x00, 0x03, 0xFF, 0xFF, 0x80, // row 43 - 45 0x01, 0xFF, 0xFF, 0x00, 0x00, 0xFF, 0xFE, 0x00, 0x00, 0x00, 0x00, 0x00 // row 46 - 48 }; const unsigned char chr_f7s_31[192] = { // 4 bytes per row 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // row 1 - 3 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x20, 0x00, 0x00, 0x00, 0x70, // row 4 - 6 0x00, 0x00, 0x00, 0xF8, 0x00, 0x00, 0x01, 0xF8, 0x00, 0x00, 0x01, 0xF8, // row 7 - 9 0x00, 0x00, 0x01, 0xF8, 0x00, 0x00, 0x01, 0xF8, 0x00, 0x00, 0x01, 0xF8, // row 10 - 12 0x00, 0x00, 0x01, 0xF8, 0x00, 0x00, 0x01, 0xF8, 0x00, 0x00, 0x01, 0xF8, // row 13 - 15 0x00, 0x00, 0x01, 0xF8, 0x00, 0x00, 0x01, 0xF8, 0x00, 0x00, 0x01, 0xF8, // row 16 - 18 0x00, 0x00, 0x01, 0xF8, 0x00, 0x00, 0x01, 0xF8, 0x00, 0x00, 0x00, 0x78, // row 19 - 21 0x00, 0x00, 0x00, 0x18, 0x00, 0x00, 0x00, 0x08, 0x00, 0x00, 0x00, 0x00, // row 22 - 24 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x18, 0x00, 0x00, 0x00, 0x78, // row 25 - 27 0x00, 0x00, 0x01, 0xF8, 0x00, 0x00, 0x01, 0xF8, 0x00, 0x00, 0x01, 0xF8, // row 28 - 30 0x00, 0x00, 0x01, 0xF8, 0x00, 0x00, 0x01, 0xF8, 0x00, 0x00, 0x01, 0xF8, // row 31 - 33 0x00, 0x00, 0x01, 0xF8, 0x00, 0x00, 0x01, 0xF8, 0x00, 0x00, 0x01, 0xF8, // row 34 - 36 0x00, 0x00, 0x01, 0xF8, 0x00, 0x00, 0x01, 0xF8, 0x00, 0x00, 0x01, 0xF8, // row 37 - 39 0x00, 0x00, 0x01, 0xF8, 0x00, 0x00, 0x01, 0xF8, 0x00, 0x00, 0x00, 0xF0, // row 40 - 42 0x00, 0x00, 0x00, 0x60, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // row 43 - 45 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 // row 46 - 48 }; const unsigned char chr_f7s_32[192] = { // 4 bytes per row 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, 0xFE, 0x00, 0x01, 0xFF, 0xFF, 0x00, // row 1 - 3 0x03, 0xFF, 0xFF, 0x80, 0x01, 0xFF, 0xFF, 0x20, 0x00, 0xFF, 0xFE, 0x70, // row 4 - 6 0x00, 0x00, 0x00, 0xF8, 0x00, 0x00, 0x01, 0xF8, 0x00, 0x00, 0x01, 0xF8, // row 7 - 9 0x00, 0x00, 0x01, 0xF8, 0x00, 0x00, 0x01, 0xF8, 0x00, 0x00, 0x01, 0xF8, // row 10 - 12 0x00, 0x00, 0x01, 0xF8, 0x00, 0x00, 0x01, 0xF8, 0x00, 0x00, 0x01, 0xF8, // row 13 - 15 0x00, 0x00, 0x01, 0xF8, 0x00, 0x00, 0x01, 0xF8, 0x00, 0x00, 0x01, 0xF8, // row 16 - 18 0x00, 0x00, 0x01, 0xF8, 0x00, 0x00, 0x01, 0xF8, 0x00, 0x00, 0x00, 0xF8, // row 19 - 21 0x00, 0xFF, 0xFE, 0x38, 0x03, 0xFF, 0xFF, 0x88, 0x0F, 0xFF, 0xFF, 0xE0, // row 22 - 24 0x27, 0xFF, 0xFF, 0xC0, 0x39, 0xFF, 0xFF, 0x00, 0x3E, 0x00, 0x00, 0x00, // row 25 - 27 0x3F, 0x00, 0x00, 0x00, 0x3F, 0x00, 0x00, 0x00, 0x3F, 0x00, 0x00, 0x00, // row 28 - 30 0x3F, 0x00, 0x00, 0x00, 0x3F, 0x00, 0x00, 0x00, 0x3F, 0x00, 0x00, 0x00, // row 31 - 33 0x3F, 0x00, 0x00, 0x00, 0x3F, 0x00, 0x00, 0x00, 0x3F, 0x00, 0x00, 0x00, // row 34 - 36 0x3F, 0x00, 0x00, 0x00, 0x3F, 0x00, 0x00, 0x00, 0x3F, 0x00, 0x00, 0x00, // row 37 - 39 0x3F, 0x00, 0x00, 0x00, 0x3F, 0x00, 0x00, 0x00, 0x1E, 0x00, 0x00, 0x00, // row 40 - 42 0x0C, 0xFF, 0xFE, 0x00, 0x01, 0xFF, 0xFF, 0x00, 0x03, 0xFF, 0xFF, 0x80, // row 43 - 45 0x01, 0xFF, 0xFF, 0x00, 0x00, 0xFF, 0xFE, 0x00, 0x00, 0x00, 0x00, 0x00 // row 46 - 48 }; const unsigned char chr_f7s_33[192] = { // 4 bytes per row 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, 0xFE, 0x00, 0x01, 0xFF, 0xFF, 0x00, // row 1 - 3 0x03, 0xFF, 0xFF, 0x80, 0x01, 0xFF, 0xFF, 0x20, 0x00, 0xFF, 0xFE, 0x70, // row 4 - 6 0x00, 0x00, 0x00, 0xF8, 0x00, 0x00, 0x01, 0xF8, 0x00, 0x00, 0x01, 0xF8, // row 7 - 9 0x00, 0x00, 0x01, 0xF8, 0x00, 0x00, 0x01, 0xF8, 0x00, 0x00, 0x01, 0xF8, // row 10 - 12 0x00, 0x00, 0x01, 0xF8, 0x00, 0x00, 0x01, 0xF8, 0x00, 0x00, 0x01, 0xF8, // row 13 - 15 0x00, 0x00, 0x01, 0xF8, 0x00, 0x00, 0x01, 0xF8, 0x00, 0x00, 0x01, 0xF8, // row 16 - 18 0x00, 0x00, 0x01, 0xF8, 0x00, 0x00, 0x01, 0xF8, 0x00, 0x00, 0x00, 0xF8, // row 19 - 21 0x00, 0xFF, 0xFE, 0x38, 0x03, 0xFF, 0xFF, 0x88, 0x0F, 0xFF, 0xFF, 0xE0, // row 22 - 24 0x07, 0xFF, 0xFF, 0xC0, 0x01, 0xFF, 0xFF, 0x18, 0x00, 0x00, 0x00, 0x78, // row 25 - 27 0x00, 0x00, 0x01, 0xF8, 0x00, 0x00, 0x01, 0xF8, 0x00, 0x00, 0x01, 0xF8, // row 28 - 30 0x00, 0x00, 0x01, 0xF8, 0x00, 0x00, 0x01, 0xF8, 0x00, 0x00, 0x01, 0xF8, // row 31 - 33 0x00, 0x00, 0x01, 0xF8, 0x00, 0x00, 0x01, 0xF8, 0x00, 0x00, 0x01, 0xF8, // row 34 - 36 0x00, 0x00, 0x01, 0xF8, 0x00, 0x00, 0x01, 0xF8, 0x00, 0x00, 0x01, 0xF8, // row 37 - 39 0x00, 0x00, 0x01, 0xF8, 0x00, 0x00, 0x01, 0xF8, 0x00, 0x00, 0x00, 0xF0, // row 40 - 42 0x00, 0xFF, 0xFE, 0x60, 0x01, 0xFF, 0xFF, 0x00, 0x03, 0xFF, 0xFF, 0x80, // row 43 - 45 0x01, 0xFF, 0xFF, 0x00, 0x00, 0xFF, 0xFE, 0x00, 0x00, 0x00, 0x00, 0x00 // row 46 - 48 }; const unsigned char chr_f7s_34[192] = { // 4 bytes per row 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // row 1 - 3 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x20, 0x0C, 0x00, 0x00, 0x70, // row 4 - 6 0x1E, 0x00, 0x00, 0xF8, 0x3F, 0x00, 0x01, 0xF8, 0x3F, 0x00, 0x01, 0xF8, // row 7 - 9 0x3F, 0x00, 0x01, 0xF8, 0x3F, 0x00, 0x01, 0xF8, 0x3F, 0x00, 0x01, 0xF8, // row 10 - 12 0x3F, 0x00, 0x01, 0xF8, 0x3F, 0x00, 0x01, 0xF8, 0x3F, 0x00, 0x01, 0xF8, // row 13 - 15 0x3F, 0x00, 0x01, 0xF8, 0x3F, 0x00, 0x01, 0xF8, 0x3F, 0x00, 0x01, 0xF8, // row 16 - 18 0x3F, 0x00, 0x01, 0xF8, 0x3F, 0x00, 0x01, 0xF8, 0x3E, 0x00, 0x00, 0xF8, // row 19 - 21 0x38, 0xFF, 0xFE, 0x38, 0x23, 0xFF, 0xFF, 0x88, 0x0F, 0xFF, 0xFF, 0xE0, // row 22 - 24 0x07, 0xFF, 0xFF, 0xC0, 0x01, 0xFF, 0xFF, 0x18, 0x00, 0x00, 0x00, 0x78, // row 25 - 27 0x00, 0x00, 0x01, 0xF8, 0x00, 0x00, 0x01, 0xF8, 0x00, 0x00, 0x01, 0xF8, // row 28 - 30 0x00, 0x00, 0x01, 0xF8, 0x00, 0x00, 0x01, 0xF8, 0x00, 0x00, 0x01, 0xF8, // row 31 - 33 0x00, 0x00, 0x01, 0xF8, 0x00, 0x00, 0x01, 0xF8, 0x00, 0x00, 0x01, 0xF8, // row 34 - 36 0x00, 0x00, 0x01, 0xF8, 0x00, 0x00, 0x01, 0xF8, 0x00, 0x00, 0x01, 0xF8, // row 37 - 39 0x00, 0x00, 0x01, 0xF8, 0x00, 0x00, 0x01, 0xF8, 0x00, 0x00, 0x00, 0xF0, // row 40 - 42 0x00, 0x00, 0x00, 0x60, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // row 43 - 45 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 // row 46 - 48 }; const unsigned char chr_f7s_35[192] = { // 4 bytes per row 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, 0xFE, 0x00, 0x01, 0xFF, 0xFF, 0x00, // row 1 - 3 0x03, 0xFF, 0xFF, 0x80, 0x01, 0xFF, 0xFF, 0x00, 0x0C, 0xFF, 0xFE, 0x00, // row 4 - 6 0x1E, 0x00, 0x00, 0x00, 0x3F, 0x00, 0x00, 0x00, 0x3F, 0x00, 0x00, 0x00, // row 7 - 9 0x3F, 0x00, 0x00, 0x00, 0x3F, 0x00, 0x00, 0x00, 0x3F, 0x00, 0x00, 0x00, // row 10 - 12 0x3F, 0x00, 0x00, 0x00, 0x3F, 0x00, 0x00, 0x00, 0x3F, 0x00, 0x00, 0x00, // row 13 - 15 0x3F, 0x00, 0x00, 0x00, 0x3F, 0x00, 0x00, 0x00, 0x3F, 0x00, 0x00, 0x00, // row 16 - 18 0x3F, 0x00, 0x00, 0x00, 0x3F, 0x00, 0x00, 0x00, 0x3E, 0x00, 0x00, 0x00, // row 19 - 21 0x38, 0xFF, 0xFE, 0x00, 0x23, 0xFF, 0xFF, 0x80, 0x0F, 0xFF, 0xFF, 0xE0, // row 22 - 24 0x07, 0xFF, 0xFF, 0xC0, 0x01, 0xFF, 0xFF, 0x18, 0x00, 0x00, 0x00, 0x78, // row 25 - 27 0x00, 0x00, 0x01, 0xF8, 0x00, 0x00, 0x01, 0xF8, 0x00, 0x00, 0x01, 0xF8, // row 28 - 30 0x00, 0x00, 0x01, 0xF8, 0x00, 0x00, 0x01, 0xF8, 0x00, 0x00, 0x01, 0xF8, // row 31 - 33 0x00, 0x00, 0x01, 0xF8, 0x00, 0x00, 0x01, 0xF8, 0x00, 0x00, 0x01, 0xF8, // row 34 - 36 0x00, 0x00, 0x01, 0xF8, 0x00, 0x00, 0x01, 0xF8, 0x00, 0x00, 0x01, 0xF8, // row 37 - 39 0x00, 0x00, 0x01, 0xF8, 0x00, 0x00, 0x01, 0xF8, 0x00, 0x00, 0x00, 0xF0, // row 40 - 42 0x00, 0xFF, 0xFE, 0x60, 0x01, 0xFF, 0xFF, 0x00, 0x03, 0xFF, 0xFF, 0x80, // row 43 - 45 0x01, 0xFF, 0xFF, 0x00, 0x00, 0xFF, 0xFE, 0x00, 0x00, 0x00, 0x00, 0x00 // row 46 - 48 }; const unsigned char chr_f7s_36[192] = { // 4 bytes per row 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, 0xFE, 0x00, 0x01, 0xFF, 0xFF, 0x00, // row 1 - 3 0x03, 0xFF, 0xFF, 0x80, 0x01, 0xFF, 0xFF, 0x00, 0x0C, 0xFF, 0xFE, 0x00, // row 4 - 6 0x1E, 0x00, 0x00, 0x00, 0x3F, 0x00, 0x00, 0x00, 0x3F, 0x00, 0x00, 0x00, // row 7 - 9 0x3F, 0x00, 0x00, 0x00, 0x3F, 0x00, 0x00, 0x00, 0x3F, 0x00, 0x00, 0x00, // row 10 - 12 0x3F, 0x00, 0x00, 0x00, 0x3F, 0x00, 0x00, 0x00, 0x3F, 0x00, 0x00, 0x00, // row 13 - 15 0x3F, 0x00, 0x00, 0x00, 0x3F, 0x00, 0x00, 0x00, 0x3F, 0x00, 0x00, 0x00, // row 16 - 18 0x3F, 0x00, 0x00, 0x00, 0x3F, 0x00, 0x00, 0x00, 0x3E, 0x00, 0x00, 0x00, // row 19 - 21 0x38, 0xFF, 0xFE, 0x00, 0x23, 0xFF, 0xFF, 0x80, 0x0F, 0xFF, 0xFF, 0xE0, // row 22 - 24 0x27, 0xFF, 0xFF, 0xC0, 0x39, 0xFF, 0xFF, 0x18, 0x3E, 0x00, 0x00, 0x78, // row 25 - 27 0x3F, 0x00, 0x01, 0xF8, 0x3F, 0x00, 0x01, 0xF8, 0x3F, 0x00, 0x01, 0xF8, // row 28 - 30 0x3F, 0x00, 0x01, 0xF8, 0x3F, 0x00, 0x01, 0xF8, 0x3F, 0x00, 0x01, 0xF8, // row 31 - 33 0x3F, 0x00, 0x01, 0xF8, 0x3F, 0x00, 0x01, 0xF8, 0x3F, 0x00, 0x01, 0xF8, // row 34 - 36 0x3F, 0x00, 0x01, 0xF8, 0x3F, 0x00, 0x01, 0xF8, 0x3F, 0x00, 0x01, 0xF8, // row 37 - 39 0x3F, 0x00, 0x01, 0xF8, 0x3F, 0x00, 0x01, 0xF8, 0x1E, 0x00, 0x00, 0xF0, // row 40 - 42 0x0C, 0xFF, 0xFE, 0x60, 0x01, 0xFF, 0xFF, 0x00, 0x03, 0xFF, 0xFF, 0x80, // row 43 - 45 0x01, 0xFF, 0xFF, 0x00, 0x00, 0xFF, 0xFE, 0x00, 0x00, 0x00, 0x00, 0x00 // row 46 - 48 }; const unsigned char chr_f7s_37[192] = { // 4 bytes per row 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, 0xFE, 0x00, 0x01, 0xFF, 0xFF, 0x00, // row 1 - 3 0x03, 0xFF, 0xFF, 0x80, 0x01, 0xFF, 0xFF, 0x20, 0x00, 0xFF, 0xFE, 0x70, // row 4 - 6 0x00, 0x00, 0x00, 0xF8, 0x00, 0x00, 0x01, 0xF8, 0x00, 0x00, 0x01, 0xF8, // row 7 - 9 0x00, 0x00, 0x01, 0xF8, 0x00, 0x00, 0x01, 0xF8, 0x00, 0x00, 0x01, 0xF8, // row 10 - 12 0x00, 0x00, 0x01, 0xF8, 0x00, 0x00, 0x01, 0xF8, 0x00, 0x00, 0x01, 0xF8, // row 13 - 15 0x00, 0x00, 0x01, 0xF8, 0x00, 0x00, 0x01, 0xF8, 0x00, 0x00, 0x01, 0xF8, // row 16 - 18 0x00, 0x00, 0x01, 0xF8, 0x00, 0x00, 0x01, 0xF8, 0x00, 0x00, 0x00, 0xF8, // row 19 - 21 0x00, 0x00, 0x00, 0x38, 0x00, 0x00, 0x00, 0x08, 0x00, 0x00, 0x00, 0x00, // row 22 - 24 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x18, 0x00, 0x00, 0x00, 0x78, // row 25 - 27 0x00, 0x00, 0x01, 0xF8, 0x00, 0x00, 0x01, 0xF8, 0x00, 0x00, 0x01, 0xF8, // row 28 - 30 0x00, 0x00, 0x01, 0xF8, 0x00, 0x00, 0x01, 0xF8, 0x00, 0x00, 0x01, 0xF8, // row 31 - 33 0x00, 0x00, 0x01, 0xF8, 0x00, 0x00, 0x01, 0xF8, 0x00, 0x00, 0x01, 0xF8, // row 34 - 36 0x00, 0x00, 0x01, 0xF8, 0x00, 0x00, 0x01, 0xF8, 0x00, 0x00, 0x01, 0xF8, // row 37 - 39 0x00, 0x00, 0x01, 0xF8, 0x00, 0x00, 0x01, 0xF8, 0x00, 0x00, 0x00, 0xF0, // row 40 - 42 0x00, 0x00, 0x00, 0x60, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // row 43 - 45 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 // row 46 - 48 }; const unsigned char chr_f7s_38[192] = { // 4 bytes per row 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, 0xFE, 0x00, 0x01, 0xFF, 0xFF, 0x00, // row 1 - 3 0x03, 0xFF, 0xFF, 0x80, 0x01, 0xFF, 0xFF, 0x20, 0x0C, 0xFF, 0xFE, 0x70, // row 4 - 6 0x1E, 0x00, 0x00, 0xF8, 0x3F, 0x00, 0x01, 0xF8, 0x3F, 0x00, 0x01, 0xF8, // row 7 - 9 0x3F, 0x00, 0x01, 0xF8, 0x3F, 0x00, 0x01, 0xF8, 0x3F, 0x00, 0x01, 0xF8, // row 10 - 12 0x3F, 0x00, 0x01, 0xF8, 0x3F, 0x00, 0x01, 0xF8, 0x3F, 0x00, 0x01, 0xF8, // row 13 - 15 0x3F, 0x00, 0x01, 0xF8, 0x3F, 0x00, 0x01, 0xF8, 0x3F, 0x00, 0x01, 0xF8, // row 16 - 18 0x3F, 0x00, 0x01, 0xF8, 0x3F, 0x00, 0x01, 0xF8, 0x3E, 0x00, 0x00, 0xF8, // row 19 - 21 0x38, 0xFF, 0xFE, 0x38, 0x23, 0xFF, 0xFF, 0x88, 0x0F, 0xFF, 0xFF, 0xE0, // row 22 - 24 0x27, 0xFF, 0xFF, 0xC0, 0x39, 0xFF, 0xFF, 0x18, 0x3E, 0x00, 0x00, 0x78, // row 25 - 27 0x3F, 0x00, 0x01, 0xF8, 0x3F, 0x00, 0x01, 0xF8, 0x3F, 0x00, 0x01, 0xF8, // row 28 - 30 0x3F, 0x00, 0x01, 0xF8, 0x3F, 0x00, 0x01, 0xF8, 0x3F, 0x00, 0x01, 0xF8, // row 31 - 33 0x3F, 0x00, 0x01, 0xF8, 0x3F, 0x00, 0x01, 0xF8, 0x3F, 0x00, 0x01, 0xF8, // row 34 - 36 0x3F, 0x00, 0x01, 0xF8, 0x3F, 0x00, 0x01, 0xF8, 0x3F, 0x00, 0x01, 0xF8, // row 37 - 39 0x3F, 0x00, 0x01, 0xF8, 0x3F, 0x00, 0x01, 0xF8, 0x1E, 0x00, 0x00, 0xF0, // row 40 - 42 0x0C, 0xFF, 0xFE, 0x60, 0x01, 0xFF, 0xFF, 0x00, 0x03, 0xFF, 0xFF, 0x80, // row 43 - 45 0x01, 0xFF, 0xFF, 0x00, 0x00, 0xFF, 0xFE, 0x00, 0x00, 0x00, 0x00, 0x00 // row 46 - 48 }; const unsigned char chr_f7s_39[192] = { // 4 bytes per row 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, 0xFE, 0x00, 0x01, 0xFF, 0xFF, 0x00, // row 1 - 3 0x03, 0xFF, 0xFF, 0x80, 0x01, 0xFF, 0xFF, 0x20, 0x0C, 0xFF, 0xFE, 0x70, // row 4 - 6 0x1E, 0x00, 0x00, 0xF8, 0x3F, 0x00, 0x01, 0xF8, 0x3F, 0x00, 0x01, 0xF8, // row 7 - 9 0x3F, 0x00, 0x01, 0xF8, 0x3F, 0x00, 0x01, 0xF8, 0x3F, 0x00, 0x01, 0xF8, // row 10 - 12 0x3F, 0x00, 0x01, 0xF8, 0x3F, 0x00, 0x01, 0xF8, 0x3F, 0x00, 0x01, 0xF8, // row 13 - 15 0x3F, 0x00, 0x01, 0xF8, 0x3F, 0x00, 0x01, 0xF8, 0x3F, 0x00, 0x01, 0xF8, // row 16 - 18 0x3F, 0x00, 0x01, 0xF8, 0x3F, 0x00, 0x01, 0xF8, 0x3E, 0x00, 0x00, 0xF8, // row 19 - 21 0x38, 0xFF, 0xFE, 0x38, 0x23, 0xFF, 0xFF, 0x88, 0x0F, 0xFF, 0xFF, 0xE0, // row 22 - 24 0x07, 0xFF, 0xFF, 0xC0, 0x01, 0xFF, 0xFF, 0x18, 0x00, 0x00, 0x00, 0x78, // row 25 - 27 0x00, 0x00, 0x01, 0xF8, 0x00, 0x00, 0x01, 0xF8, 0x00, 0x00, 0x01, 0xF8, // row 28 - 30 0x00, 0x00, 0x01, 0xF8, 0x00, 0x00, 0x01, 0xF8, 0x00, 0x00, 0x01, 0xF8, // row 31 - 33 0x00, 0x00, 0x01, 0xF8, 0x00, 0x00, 0x01, 0xF8, 0x00, 0x00, 0x01, 0xF8, // row 34 - 36 0x00, 0x00, 0x01, 0xF8, 0x00, 0x00, 0x01, 0xF8, 0x00, 0x00, 0x01, 0xF8, // row 37 - 39 0x00, 0x00, 0x01, 0xF8, 0x00, 0x00, 0x01, 0xF8, 0x00, 0x00, 0x00, 0xF0, // row 40 - 42 0x00, 0xFF, 0xFE, 0x60, 0x01, 0xFF, 0xFF, 0x00, 0x03, 0xFF, 0xFF, 0x80, // row 43 - 45 0x01, 0xFF, 0xFF, 0x00, 0x00, 0xFF, 0xFE, 0x00, 0x00, 0x00, 0x00, 0x00 // row 46 - 48 }; const unsigned char chr_f7s_3A[96] = { // 2 bytes per row 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // row 1 - 6 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // row 7 - 12 0x00, 0x00, 0x0E, 0x00, 0x1F, 0x00, 0x1F, 0x00, 0x1F, 0x00, 0x0E, 0x00, // row 13 - 18 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // row 19 - 24 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // row 25 - 30 0x0E, 0x00, 0x1F, 0x00, 0x1F, 0x00, 0x1F, 0x00, 0x0E, 0x00, 0x00, 0x00, // row 31 - 36 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // row 37 - 42 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 // row 43 - 48 }; const unsigned char *chrtbl_f7s[96] = { // character pointer table chr_f7s_20, chr_f7s_20, chr_f7s_20, chr_f7s_20, chr_f7s_20, chr_f7s_20, chr_f7s_20, chr_f7s_20, chr_f7s_20, chr_f7s_20, chr_f7s_20, chr_f7s_20, chr_f7s_20, chr_f7s_20, chr_f7s_2E, chr_f7s_20, chr_f7s_30, chr_f7s_31, chr_f7s_32, chr_f7s_33, chr_f7s_34, chr_f7s_35, chr_f7s_36, chr_f7s_37, chr_f7s_38, chr_f7s_39, chr_f7s_3A, chr_f7s_20, chr_f7s_20, chr_f7s_20, chr_f7s_20, chr_f7s_20, chr_f7s_20, chr_f7s_20, chr_f7s_20, chr_f7s_20, chr_f7s_20, chr_f7s_20, chr_f7s_20, chr_f7s_20, chr_f7s_20, chr_f7s_20, chr_f7s_20, chr_f7s_20, chr_f7s_20, chr_f7s_20, chr_f7s_20, chr_f7s_20, chr_f7s_20, chr_f7s_20, chr_f7s_20, chr_f7s_20, chr_f7s_20, chr_f7s_20, chr_f7s_20, chr_f7s_20, chr_f7s_20, chr_f7s_20, chr_f7s_20, chr_f7s_20, chr_f7s_20, chr_f7s_20, chr_f7s_20, chr_f7s_20, chr_f7s_20, chr_f7s_20, chr_f7s_20, chr_f7s_20, chr_f7s_20, chr_f7s_20, chr_f7s_20, chr_f7s_20, chr_f7s_20, chr_f7s_20, chr_f7s_20, chr_f7s_20, chr_f7s_20, chr_f7s_20, chr_f7s_20, chr_f7s_20, chr_f7s_20, chr_f7s_20, chr_f7s_20, chr_f7s_20, chr_f7s_20, chr_f7s_20, chr_f7s_20, chr_f7s_20, chr_f7s_20, chr_f7s_20, chr_f7s_20, chr_f7s_20, chr_f7s_20, chr_f7s_20, chr_f7s_20, chr_f7s_20 };
20,372
font7s
c
en
c
code
{"qsc_code_num_words": 3385, "qsc_code_num_chars": 20372.0, "qsc_code_mean_word_length": 3.51196455, "qsc_code_frac_words_unique": 0.03899557, "qsc_code_frac_chars_top_2grams": 0.48183042, "qsc_code_frac_chars_top_3grams": 0.43001346, "qsc_code_frac_chars_top_4grams": 0.40107672, "qsc_code_frac_chars_dupe_5grams": 0.96155787, "qsc_code_frac_chars_dupe_6grams": 0.95642665, "qsc_code_frac_chars_dupe_7grams": 0.94860363, "qsc_code_frac_chars_dupe_8grams": 0.94355653, "qsc_code_frac_chars_dupe_9grams": 0.94086474, "qsc_code_frac_chars_dupe_10grams": 0.92404105, "qsc_code_frac_chars_replacement_symbols": 0.0, "qsc_code_frac_chars_digital": 0.46225113, "qsc_code_frac_chars_whitespace": 0.25294522, "qsc_code_size_file_byte": 20372.0, "qsc_code_num_lines": 249.0, "qsc_code_num_chars_line_max": 100.0, "qsc_code_num_chars_line_mean": 81.81526104, "qsc_code_frac_chars_alphabet": 0.31887772, "qsc_code_frac_chars_comments": 0.16669939, "qsc_code_cate_xml_start": 0.0, "qsc_code_frac_lines_dupe_lines": 0.25, "qsc_code_cate_autogen": 0.0, "qsc_code_frac_lines_long_string": 0.0, "qsc_code_frac_chars_string_length": 0.00047125, "qsc_code_frac_chars_long_word_length": 0.0, "qsc_code_frac_lines_string_concat": 0.0, "qsc_code_cate_encoded_data": 0.0, "qsc_code_frac_chars_hex_words": 0.5202639, "qsc_code_frac_lines_prompt_comments": 0.0, "qsc_code_frac_lines_assert": 0.0, "qsc_codec_frac_lines_func_ratio": 0.0, "qsc_codec_cate_bitsstdc": 0.0, "qsc_codec_nums_lines_main": 0, "qsc_codec_frac_lines_goto": 0.0, "qsc_codec_cate_var_zero": 0.0, "qsc_codec_score_lines_no_logic": 0.03571429, "qsc_codec_frac_lines_print": 0.0, "qsc_codec_frac_lines_preprocessor_directives": 0.03571429}
0
{"qsc_code_frac_chars_replacement_symbols": 0, "qsc_code_num_words": 0, "qsc_code_num_chars": 0, "qsc_code_mean_word_length": 0, "qsc_code_frac_chars_top_2grams": 1, "qsc_code_frac_chars_top_3grams": 1, "qsc_code_frac_chars_top_4grams": 1, "qsc_code_frac_chars_dupe_5grams": 1, "qsc_code_frac_chars_dupe_6grams": 1, "qsc_code_frac_chars_dupe_7grams": 1, "qsc_code_frac_chars_dupe_8grams": 1, "qsc_code_frac_chars_dupe_9grams": 1, "qsc_code_frac_chars_dupe_10grams": 1, "qsc_code_size_file_byte": 0, "qsc_code_num_lines": 0, "qsc_code_num_chars_line_max": 0, "qsc_code_num_chars_line_mean": 0, "qsc_code_frac_chars_alphabet": 1, "qsc_code_frac_chars_digital": 1, "qsc_code_frac_chars_whitespace": 0, "qsc_code_frac_chars_comments": 0, "qsc_code_cate_xml_start": 0, "qsc_code_frac_lines_dupe_lines": 0, "qsc_code_cate_autogen": 0, "qsc_code_frac_lines_long_string": 0, "qsc_code_frac_chars_string_length": 0, "qsc_code_frac_chars_long_word_length": 0, "qsc_code_cate_encoded_data": 0, "qsc_code_frac_chars_hex_words": 1, "qsc_code_frac_lines_prompt_comments": 0, "qsc_code_frac_lines_assert": 0, "qsc_codec_frac_lines_func_ratio": 0, "qsc_codec_nums_lines_main": 0, "qsc_codec_score_lines_no_logic": 0, "qsc_codec_frac_lines_preprocessor_directives": 0, "qsc_codec_frac_lines_print": 0}
0015/ESP32-OpenCV-Projects
esp32/examples/color_code/components/lvgl_gui/lvgl.c
// Copyright 2015-2018 Espressif Systems (Shanghai) PTE LTD // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /* FreeRTOS includes */ #include "freertos/FreeRTOS.h" #include "freertos/timers.h" /* LVGL includes */ #include "iot_lvgl.h" #include "app_screen.h" // wait for execute lv_task_handler and lv_tick_inc to avoid some widget don't refresh. #define LVGL_INIT_DELAY 100 // unit ms static void lv_tick_timercb(void *timer) { /* Initialize a Timer for 1 ms period and * in its interrupt call * lv_tick_inc(1); */ lv_tick_inc(1); } static void lv_task_timercb(void *timer) { /* Periodically call this function. * The timing is not critical but should be between 1..10 ms */ lv_task_handler(); } void lvgl_init() { /* LittlevGL work fine only when CONFIG_FREERTOS_HZ is 1000HZ */ assert(CONFIG_FREERTOS_HZ == 1000); /* Initialize LittlevGL */ lv_init(); esp_timer_create_args_t timer_conf = { .callback = lv_tick_timercb, .name = "lv_tick_timer" }; esp_timer_handle_t g_wifi_connect_timer = NULL; esp_timer_create(&timer_conf, &g_wifi_connect_timer); esp_timer_start_periodic(g_wifi_connect_timer, 1 * 1000U); // lv_tick_inc() called each 1 ms /* Display interface */ lvgl_lcd_hal_init(); esp_timer_create_args_t lv_task_timer_conf = { .callback = lv_task_timercb, .name = "lv_task_timer" }; esp_timer_handle_t lv_task_timer = NULL; esp_timer_create(&lv_task_timer_conf, &lv_task_timer); esp_timer_start_periodic(lv_task_timer, 5 * 1000U); // lv_task_handler() called each 5 ms vTaskDelay(LVGL_INIT_DELAY / portTICK_PERIOD_MS); // wait for execute lv_task_handler and lv_tick_inc to avoid some widget don't refresh. }
2,300
lvgl
c
en
c
code
{"qsc_code_num_words": 344, "qsc_code_num_chars": 2300.0, "qsc_code_mean_word_length": 4.47965116, "qsc_code_frac_words_unique": 0.42732558, "qsc_code_frac_chars_top_2grams": 0.04672291, "qsc_code_frac_chars_top_3grams": 0.04282933, "qsc_code_frac_chars_top_4grams": 0.03309539, "qsc_code_frac_chars_dupe_5grams": 0.21414666, "qsc_code_frac_chars_dupe_6grams": 0.11680727, "qsc_code_frac_chars_dupe_7grams": 0.08695652, "qsc_code_frac_chars_dupe_8grams": 0.08695652, "qsc_code_frac_chars_dupe_9grams": 0.08695652, "qsc_code_frac_chars_dupe_10grams": 0.08695652, "qsc_code_frac_chars_replacement_symbols": 0.0, "qsc_code_frac_chars_digital": 0.02224634, "qsc_code_frac_chars_whitespace": 0.19869565, "qsc_code_size_file_byte": 2300.0, "qsc_code_num_lines": 74.0, "qsc_code_num_chars_line_max": 145.0, "qsc_code_num_chars_line_mean": 31.08108108, "qsc_code_frac_chars_alphabet": 0.8138904, "qsc_code_frac_chars_comments": 0.53391304, "qsc_code_cate_xml_start": 0.0, "qsc_code_frac_lines_dupe_lines": 0.05882353, "qsc_code_cate_autogen": 0.0, "qsc_code_frac_lines_long_string": 0.0, "qsc_code_frac_chars_string_length": 0.07828518, "qsc_code_frac_chars_long_word_length": 0.0, "qsc_code_frac_lines_string_concat": 0.0, "qsc_code_cate_encoded_data": 0.0, "qsc_code_frac_chars_hex_words": 0.0, "qsc_code_frac_lines_prompt_comments": 0.0, "qsc_code_frac_lines_assert": 0.02941176, "qsc_codec_frac_lines_func_ratio": 0.08823529, "qsc_codec_cate_bitsstdc": 0.0, "qsc_codec_nums_lines_main": 0, "qsc_codec_frac_lines_goto": 0.0, "qsc_codec_cate_var_zero": 0.0, "qsc_codec_score_lines_no_logic": 0.20588235, "qsc_codec_frac_lines_print": 0.0, "qsc_codec_frac_lines_preprocessor_directives": 0.14705882}
1
{"qsc_code_frac_chars_replacement_symbols": 0, "qsc_code_num_words": 0, "qsc_code_num_chars": 0, "qsc_code_mean_word_length": 0, "qsc_code_frac_chars_top_2grams": 0, "qsc_code_frac_chars_top_3grams": 0, "qsc_code_frac_chars_top_4grams": 0, "qsc_code_frac_chars_dupe_5grams": 0, "qsc_code_frac_chars_dupe_6grams": 0, "qsc_code_frac_chars_dupe_7grams": 0, "qsc_code_frac_chars_dupe_8grams": 0, "qsc_code_frac_chars_dupe_9grams": 0, "qsc_code_frac_chars_dupe_10grams": 0, "qsc_code_size_file_byte": 0, "qsc_code_num_lines": 0, "qsc_code_num_chars_line_max": 0, "qsc_code_num_chars_line_mean": 0, "qsc_code_frac_chars_alphabet": 0, "qsc_code_frac_chars_digital": 0, "qsc_code_frac_chars_whitespace": 0, "qsc_code_frac_chars_comments": 0, "qsc_code_cate_xml_start": 0, "qsc_code_frac_lines_dupe_lines": 0, "qsc_code_cate_autogen": 0, "qsc_code_frac_lines_long_string": 0, "qsc_code_frac_chars_string_length": 0, "qsc_code_frac_chars_long_word_length": 0, "qsc_code_cate_encoded_data": 0, "qsc_code_frac_chars_hex_words": 0, "qsc_code_frac_lines_prompt_comments": 0, "qsc_code_frac_lines_assert": 0, "qsc_codec_frac_lines_func_ratio": 0, "qsc_codec_nums_lines_main": 0, "qsc_codec_score_lines_no_logic": 0, "qsc_codec_frac_lines_preprocessor_directives": 0, "qsc_codec_frac_lines_print": 0}
007revad/Synology_HDD_db
my-other-scripts.md
## All my scripts, tools and guides <img src="https://hitscounter.dev/api/hit?url=https%3A%2F%2F007revad.github.io%2F&label=Visitors&icon=github&color=%23198754&message=&style=flat&tz=UTC"> #### Contents - [Plex](#plex) - [Synology docker](#synology-docker) - [Synology recovery](#synology-recovery) - [Other Synology scripts](#other-synology-scripts) - [Synology hardware restrictions](#synology-hardware-restrictions) - [2025 plus models](#2025-plus-models) - [How To Guides](#how-to-guides) - [Synology dev](#synology-dev) *** ### Plex - **<a href="https://github.com/007revad/Synology_Plex_Backup">Synology_Plex_Backup</a>** - A script to backup Plex to a tgz file foror DSM 7 and DSM 6. - Works for Plex Synology package and Plex in docker. - **<a href="https://github.com/007revad/Asustor_Plex_Backup">Asustor_Plex_Backup</a>** - Backup your Asustor's Plex Media Server settings and database. - **<a href="https://github.com/007revad/Linux_Plex_Backup">Linux_Plex_Backup</a>** - Backup your Linux Plex Media Server's settings and database. - **<a href="https://github.com/007revad/Plex_Server_Sync">Plex_Server_Sync</a>** - Sync your main Plex server database & metadata to a backup Plex server. - Works for Synology, Asustor, Linux and supports Plex package or Plex in docker. &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; [Back to Contents](#contents) ### Synology docker - **<a href="https://github.com/007revad/Synology_Docker_Export">Synology_Docker_export</a>** - Export all Synology Container Manager or Docker containers' settings as json files to your docker shared folder. - **<a href="https://github.com/007revad/Synology_ContainerManager_IPv6">Synology_ContainerManager_IPv6</a>** - Enable IPv6 for Container Manager's bridge network. - **<a href="https://github.com/007revad/ContainerManager_for_all_armv8">ContainerManager_for_all_armv8</a>** - Script to install Container Manager on a RS819, DS119j, DS418, DS418j, DS218, DS218play or DS118. - **<a href="https://github.com/007revad/Docker_Autocompose">Docker_Autocompose</a>** - Create .yml files from your docker existing containers. - **<a href="https://github.com/007revad/Synology_docker_cleanup">Synology_docker_cleanup</a>** - Remove orphan docker btrfs subvolumes and images in Synology DSM 7 and DSM 6. &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; [Back to Contents](#contents) ### Synology recovery - **<a href="https://github.com/007revad/Synology_DSM_reinstall">Synology_DSM_reinstall</a>** - Easily re-install the same DSM version without losing any data or settings. - **<a href="https://github.com/007revad/Synology_Recover_Data">Synology_Recover_Data</a>** - A script to make it easy to recover your data from your Synology's drives using a computer. - **<a href="https://github.com/007revad/Synology_clear_drive_error">Synology clear drive error</a>** - Clear drive critical errors so DSM will let you use the drive. - **<a href="https://github.com/007revad/Synology_DSM_Telnet_Password">Synology_DSM_Telnet_Password</a>** - Synology DSM Recovery Telnet Password of the Day generator. - **<a href="https://github.com/007revad/Syno_DSM_Extractor_GUI">Syno_DSM_Extractor_GUI</a>** - Windows GUI for extracting Synology DSM 7 pat files and spk package files. - **<a href="https://github.com/007revad/Synoboot_backup">Synoboot_backup</a>** - Back up synoboot after each DSM update so you can recover from a corrupt USBDOM. &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; [Back to Contents](#contents) ### Other Synology scripts - **<a href="https://github.com/007revad/Synology_app_mover">Synology_app_mover</a>** - Easily move Synology packages from one volume to another volume. - **<a href="https://github.com/007revad/Video_Station_for_DSM_722">Video_Station_for_DSM_722</a>** - Script to install Video Station in DSM 7.2.2 - **<a href="https://github.com/007revad/SS_Motion_Detection">SS_Motion_Detection</a>** - Installs previous Surveillance Station and Advanced Media Extensions versions so motion detection and HEVC are supported. - **<a href="https://github.com/007revad/Synology_Config_Backup">Synology_Config_Backup</a>** - Backup and export your Synology DSM configuration. - **<a href="https://github.com/007revad/Synology_CPU_temperature">Synology_CPU_temperature</a>** - Get and log Synology NAS CPU temperature via SSH. - **<a href="https://github.com/007revad/Synology_SMART_info">Synology_SMART_info</a>** - Show Synology smart test progress or smart health and attributes. - **<a href="https://github.com/007revad/Synology_Cleanup_Coredumps">Synology_Cleanup_Coredumps</a>** - Cleanup memory core dumps from crashed processes. - **<a href="https://github.com/007revad/Synology_toggle_reset_button">Synology_toggle_reset_button</a>** - Script to disable or enable the reset button and show current setting. - **<a href="https://github.com/007revad/Synology_Download_Station_Chrome_Extension">Synology_Download_Station_Chrome_Extension</a>** - Download Station Chrome Extension. - **<a href="https://github.com/007revad/Seagate_lowCurrentSpinup">Seagate_lowCurrentSpinup</a>** - This script avoids the need to buy and install a higher wattage power supply when using multiple large Seagate SATA HDDs. &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; [Back to Contents](#contents) ### Synology hardware restrictions - **<a href="https://github.com/007revad/Synology_HDD_db">Synology_HDD_db</a>** - Add your SATA or SAS HDDs and SSDs plus SATA and NVMe M.2 drives to your Synology's compatible drive databases, including your Synology M.2 PCIe card and Expansion Unit databases. - **<a href="https://github.com/007revad/Synology_enable_M2_volume">Synology_enable_M2_volume</a>** - Enable creating volumes with non-Synology M.2 drives. - Enable Health Info for non-Synology NVMe drives (not in DSM 7.2.1 or later). - **<a href="https://github.com/007revad/Synology_M2_volume">Synology_M2_volume</a>** - Easily create an M.2 volume on Synology NAS. - **<a href="https://github.com/007revad/Synology_enable_M2_card">Synology_enable_M2_card</a>** - Enable Synology M.2 PCIe cards in Synology NAS that don't officially support them. - **<a href="https://github.com/007revad/Synology_enable_eunit">Synology_enable_eunit</a>** - Enable an unsupported Synology eSATA Expansion Unit models. - **<a href="https://github.com/007revad/Synology_enable_Deduplication">Synology_enable_Deduplication</a>** - Enable deduplication with non-Synology SSDs and unsupported NAS models. - **<a href="https://github.com/007revad/Synology_SHR_switch">Synology_SHR_switch</a>** - Easily switch between SHR and RAID Groups, or enable RAID F1. - **<a href="https://github.com/007revad/Synology_enable_sequential_IO">Synology_enable_sequential_IO</a>** - Enables sequential I/O for your SSD caches, like DSM 6 had. - **<a href="https://github.com/007revad/Synology_Information_Wiki">Synology_Information_Wiki</a>** - Information about Synology hardware. &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; [Back to Contents](#contents) ### 2025 plus models - **<a href="https://github.com/007revad/Transcode_for_x25">Transcode_for_x25</a>** - Installs the modules needed for Plex or Jellyfin hardware transcoding in DS425+ and DS225+. - **<a href="https://github.com/007revad/Synology_HDD_db/blob/main/2025_plus_models.md">2025 series or later Plus models</a>** - Unverified 3rd party drive limitations and unofficial solutions. - **<a href="https://github.com/007revad/Synology_HDD_db/blob/main/2025_plus_models.md#setting-up-a-new-2025-or-later-plus-model-with-only-unverified-hdds">Setup with only 3rd party drives</a>** - Setting up a new 2025 or later plus model with only unverified HDDs. - **<a href="https://github.com/007revad/Synology_HDD_db/blob/main/2025_plus_models.md#deleting-and-recreating-your-storage-pool-on-unverified-hdds">Recreating storage pool on migrated drives</a>** - Deleting and recreating your storage pool on unverified HDDs. &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; [Back to Contents](#contents) ### How To Guides - **<a href="https://github.com/007revad/Synology_SSH_key_setup">Synology_SSH_key_setup</a>** - How to setup SSH key authentication for your Synology. &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; [Back to Contents](#contents) ### Synology dev - **<a href="https://github.com/007revad/Download_Synology_Archive">Download_Synology_Archive</a>** - Download all or part of the Synology archive. - **<a href="https://github.com/007revad/Syno_DSM_Extractor_GUI">Syno_DSM_Extractor_GUI</a>** - Windows GUI for extracting Synology DSM 7 pat files and spk package files. - **<a href="https://github.com/007revad/ScriptNotify">ScriptNotify</a>** - DSM 7 package to allow your scripts to send DSM notifications. - **<a href="https://github.com/007revad/DTC_GUI_for_Windows">DTC_GUI_for_Windows</a>** - GUI for DTC.exe for Windows. &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; [Back to Contents](#contents)
9,099
my-other-scripts
md
en
markdown
text
{"qsc_doc_frac_chars_curly_bracket": 0.0, "qsc_doc_frac_words_redpajama_stop": 0.16632653, "qsc_doc_num_sentences": 107.0, "qsc_doc_num_words": 1341, "qsc_doc_num_chars": 9099.0, "qsc_doc_num_lines": 180.0, "qsc_doc_mean_word_length": 4.94630872, "qsc_doc_frac_words_full_bracket": 0.0, "qsc_doc_frac_lines_end_with_readmore": 0.0, "qsc_doc_frac_lines_start_with_bullet": 0.0, "qsc_doc_frac_words_unique": 0.23191648, "qsc_doc_entropy_unigram": 4.76529845, "qsc_doc_frac_words_all_caps": 0.02908163, "qsc_doc_frac_lines_dupe_lines": 0.1025641, "qsc_doc_frac_chars_dupe_lines": 0.10911978, "qsc_doc_frac_chars_top_2grams": 0.05789236, "qsc_doc_frac_chars_top_3grams": 0.06482738, "qsc_doc_frac_chars_top_4grams": 0.10372381, "qsc_doc_frac_chars_dupe_5grams": 0.39981909, "qsc_doc_frac_chars_dupe_6grams": 0.36891301, "qsc_doc_frac_chars_dupe_7grams": 0.34041912, "qsc_doc_frac_chars_dupe_8grams": 0.25569124, "qsc_doc_frac_chars_dupe_9grams": 0.20624152, "qsc_doc_frac_chars_dupe_10grams": 0.15829941, "qsc_doc_frac_chars_replacement_symbols": 0.0, "qsc_doc_cate_code_related_file_name": 0.0, "qsc_doc_num_chars_sentence_length_mean": 30.70731707, "qsc_doc_frac_chars_hyperlink_html_tag": 0.34762062, "qsc_doc_frac_chars_alphabet": 0.79007303, "qsc_doc_frac_chars_digital": 0.03094442, "qsc_doc_frac_chars_whitespace": 0.11210023, "qsc_doc_frac_chars_hex_words": 0.0}
1
{"qsc_doc_frac_chars_replacement_symbols": 0, "qsc_doc_entropy_unigram": 0, "qsc_doc_frac_chars_top_2grams": 0, "qsc_doc_frac_chars_top_3grams": 0, "qsc_doc_frac_chars_top_4grams": 0, "qsc_doc_frac_chars_dupe_5grams": 0, "qsc_doc_frac_chars_dupe_6grams": 0, "qsc_doc_frac_chars_dupe_7grams": 0, "qsc_doc_frac_chars_dupe_8grams": 0, "qsc_doc_frac_chars_dupe_9grams": 0, "qsc_doc_frac_chars_dupe_10grams": 0, "qsc_doc_frac_chars_dupe_lines": 0, "qsc_doc_frac_lines_dupe_lines": 0, "qsc_doc_frac_lines_end_with_readmore": 0, "qsc_doc_frac_lines_start_with_bullet": 0, "qsc_doc_frac_words_all_caps": 0, "qsc_doc_mean_word_length": 0, "qsc_doc_num_chars": 0, "qsc_doc_num_lines": 0, "qsc_doc_num_sentences": 0, "qsc_doc_num_words": 0, "qsc_doc_frac_chars_hex_words": 0, "qsc_doc_frac_chars_hyperlink_html_tag": 0, "qsc_doc_frac_chars_alphabet": 0, "qsc_doc_frac_chars_digital": 0, "qsc_doc_frac_chars_whitespace": 0}
007revad/Synology_Download_Station_Chrome_Extension
js/options.js
/// <reference path="../../typings/jquery/jquery.d.ts"/> /// <reference path="../../typings/showdown/showdown.d.ts"/> $(document).ready(function() { if(location.hash.length > 0) $("#menu a[href='" + location.hash + "']").tab("show"); // !Localize page $('[data-message]').each(function() { var name = $(this).data('message'); $(this).text(extension.getLocalizedString(name)); }); $('[data-attr-message]').each(function() { var attributes = $(this).data('attr-message').split(','); for(var i = 0; i < attributes.length; i++) { var parts = attributes[i].split('|'); var attr = parts[0]; var name = parts[1]; $(this).attr(attr, extension.getLocalizedString(name)); } }); $("#about-extension-version").text(extension.getExtensionVersion()); $('#donate-button').attr('href', DONATION_URL); loadChangelog(); // Creating custom :external selector $.expr[':'].external = function(obj){ return !obj.href.match(/^mailto\:/) && (obj.hostname != location.hostname); }; // External links $('a:external').click(function(evt) { evt.preventDefault(); var url = $(this).attr('href'); if(url) _gaq.push(['_trackEvent' , 'Button' , 'External link', url ] ); window.open(url, '_blank'); }); $("a").each(function(index, element) { var url = $(this).prop('href'); if(url.indexOf("download-station-extension.com") != -1) { var medium = "unknown"; if(IS_OPERA) medium = "Opera"; else if(IS_CHROME) medium = "Chrome"; else if(IS_SAFARI) medium = "Safari"; url = url + "?utm_source=extension&utm_medium=" + medium + "&utm_campaign=settings"; $(this).prop("href", url); } }); $("[title], #options-form select[title], #options-form label[title]").popover({ placement: "right", trigger: "hover", container: "body" }); $("#enableQuickConnect").on("click", function() { toggleQuickConnect(true); }); $("#disableQuickConnect").on("click", function() { toggleQuickConnect(false); }); $("#updateInBackground").on("change", function() { var disabled = !$(this).is(":checked"); $("#backgroundUpdateInterval").prop("disabled", disabled); }); $('input[name=protocol]').change(function(){ var value = $('input[name=protocol]:checked').val(); var port = $('#port').val(); if(port == '' || port == '5000' || port == '5001') { if(value == 'http://') $('#port').val('5000'); else $('#port').val('5001'); } }); $('#test-connection').click(function(event) { event.preventDefault(); if(IS_SAFARI && $("#connection")[0].checkValidity() == false) { showDialog("Warning", "Not all fields have been entered correctly. Please make sure that you have entered all information correctly."); return; } var $this = $(this); $(".fa-flask", $this).hide(); $(".fa-spinner", $this).show(); $("form#connection button").prop("disabled", true); var newOptions = getConnectionFormData(); extension.sendMessageToBackground("testConnection", newOptions, function(response) { var form = $("form#connection"); $("#test-connection .fa-spinner", form).hide(); $("#test-connection .fa-flask", form).show(); $("button", form).prop("disabled", false); if(response.success === true) showDialog(extension.getLocalizedString("testDialogSuccess"), response.message, "fa-check-circle"); else showDialog(extension.getLocalizedString("testDialogFailed"), response.message, "fa-exclamation-triangle"); }); }); $(document.body).on("submit", "#connection", function(evt) { evt.preventDefault(); if(IS_SAFARI && $(this)[0].checkValidity() == false) { showDialog("Warning", "Not all fields have been entered correctly. Please make sure that you have entered all information correctly."); return; } var newOptions = getConnectionFormData(); $("button", this).attr("disabled", true); $("button[type=submit] .fa-spinner", this).show(); $("button[type=submit] .fa-save", this).hide(); extension.sendMessageToBackground("saveConnectionSettings", newOptions, function(response) { var form = $("form#connection"); $("button .fa-save", form).show(); $("button .fa-spinner", form).hide(); $("button", form).prop("disabled", false); if(response.success == true) showDialog(extension.getLocalizedString("settingsSaved"), extension.getLocalizedString("settingsSavedMessage"), "fa-check-circle"); else showDialog(extension.getLocalizedString("testDialogFailed"), response.message, "fa-exclamation-triangle"); }); }); var emailCheckXhr = null; var emailCheckTimeout = null; $(document.body).on("input", "#email", function(evt) { clearTimeout(emailCheckTimeout); if(emailCheckXhr != null) { emailCheckXhr.abort(); } var input = $(this); var formgroup = input.closest(".form-group"); $("#email-addon").addClass("hidden"); $("#email-addon-success").addClass("hidden"); $("#email-addon-checking").removeClass("hidden"); $("#email-check-failed").addClass("hidden"); formgroup.removeClass("has-success"); var email = input.val(); if(email) { emailCheckTimeout = setTimeout(function(){ emailCheckXhr = $.post(DONATION_CHECK_URL, { email: email }) .done(function(data) { if(data.result == true) { $("#email-addon").addClass("hidden"); $("#email-addon-success").removeClass("hidden"); $("#email-addon-checking").addClass("hidden"); $("#email-check-failed").addClass("hidden"); formgroup.addClass("has-success"); } else { $("#email-addon").removeClass("hidden"); $("#email-addon-success").addClass("hidden"); $("#email-addon-checking").addClass("hidden"); $("#email-check-failed").removeClass("hidden"); formgroup.removeClass("has-success"); } }).fail(function(jqXHR, textStatus, errorThrown) { if (textStatus != "abort") { $("#email-addon").removeClass("hidden"); $("#email-addon-success").addClass("hidden"); $("#email-addon-checking").addClass("hidden"); $("#email-check-failed").addClass("hidden"); formgroup.removeClass("has-success"); _gaq.push(['_trackEvent', 'Donation check', 'Check failed', textStatus + ' - ' + errorThrown]); } }) .always(function(){ emailCheckXhr = null; }); }, 1000); } else { $("#email-addon").removeClass("hidden"); $("#email-addon-success").addClass("hidden"); $("#email-addon-checking").addClass("hidden"); $("#email-check-failed").addClass("hidden"); formgroup.removeClass("has-success"); } }); $(document.body).on("submit", "#other-settings", function(evt) { evt.preventDefault(); if(IS_SAFARI && $(this)[0].checkValidity() == false) { showDialog("Warning", "Not all fields have been entered correctly. Please make sure that you have entered all information correctly."); return; } var newOptions = getOtherSettingsFormData(); $("button", this).attr("disabled", true); $("button[type=submit] .fa-spinner", this).show(); $("button[type=submit] .fa-save", this).hide(); extension.sendMessageToBackground("saveOtherSettings", newOptions, function(response) { var form = $("form#other-settings"); $("button .fa-save", form).show(); $("button .fa-spinner", form).hide(); $("button", form).prop("disabled", false); if(response.success == true) showDialog(extension.getLocalizedString("settingsSaved"), extension.getLocalizedString("settingsSavedMessage"), "fa-check-circle"); else showDialog(extension.getLocalizedString("testDialogFailed"), response.message, "fa-exclamation-triangle"); }); }); if(IS_CHROME) { extension.storage.addEventListener(function(changes) { for(var key in changes) { var elements = $("[name='" + key + "']"); var inputType = elements.prop("type"); var newValue = changes[key].newValue; if(["text", "email", "password", "number"].indexOf(inputType) != -1) { elements.val(newValue); } else if(inputType == "checkbox" && typeof(newValue) === "boolean") elements.prop("checked", newValue); else if(inputType == "checkbox" && Array.isArray(newValue)) { elements.prop("checked", false); elements.each(function(index, element) { $(element).prop("checked", newValue.contains($(element).val())); }); } else if(inputType == "radio") { elements.each(function(index, element) { $(element).prop("checked", newValue == $(element).val()); }); } } $("#updateInBackground").trigger("change"); }); } // !Load settings extension.sendMessageToBackground("getSettings", null, function(response) { setOptionFields(response); }); }); function toggleQuickConnect(enabled) { $("#enableQuickConnect").toggleClass("btn-primary active disabled", enabled); $("#disableQuickConnect").toggleClass("btn-primary active disabled", !enabled); $("#manual-settings").toggle(enabled == false); $("#manual-settings input").prop("disabled", enabled); $("#quickconnect-settings").toggle(enabled); $("#quickconnect-settings input").prop("disabled", enabled == false); $("#quickConnectId").prop("required", enabled); $("#url").prop("required", enabled == false); $("#port").prop("required", enabled == false); $("input[name=protocol]").prop("required", enabled == false); } function getConnectionFormData() { var data = $("form#connection").serializeArray(); var newOptions = {}; $.each(data, function(index, field) { newOptions[field.name] = field.value; }); newOptions.updateInBackground = newOptions.updateInBackground == "on"; newOptions.backgroundUpdateInterval = parseInt(newOptions.backgroundUpdateInterval); if(isNaN(newOptions.backgroundUpdateInterval) || newOptions.backgroundUpdateInterval < 5) newOptions.backgroundUpdateInterval = 20; return newOptions; } function getOtherSettingsFormData() { var data = $("form#other-settings").serializeArray(); var newOptions = {}; $.each(data, function(index, field) { newOptions[field.name] = field.value; }); newOptions.hideSeedingTorrents = newOptions.hideSeedingTorrents == "on"; newOptions.openProtocols = []; $("input[type=checkbox][name=openProtocols]:checked").each(function(index, element) { newOptions.openProtocols.push($(element).val()); }); return newOptions; } function setOptionFields(options) { var quickConnectEnabled = options.quickConnectId != null && options.quickConnectId.length > 0; toggleQuickConnect(quickConnectEnabled); if(quickConnectEnabled) { $('#quickConnectId').val(options.quickConnectId); } else { $("input[name=protocol][type=radio][value='" + options.protocol + "']").prop("checked", true); $('#url').val(options['url']); $('#port').val(options['port'] || 5000); } $('#username').val(options.username); $('#password').val(options.password); $('#email').val(options.email); $('#backgroundUpdateInterval').val(options.backgroundUpdateInterval); $('#hideSeedingTorrents').prop('checked', options.hideSeedingTorrents); $('#updateInBackground').prop('checked', options.updateInBackground); for(var i = 0; i < options.openProtocols.length; i++) { $("input[name='openProtocols'][value='" + options.openProtocols[i] + "']").prop("checked", true); } $("#updateInBackground").trigger("change"); $("#email").trigger("input"); } function showDialog(title, text, icon) { var html = '<div class="modal fade out">\ <div class="modal-dialog">\ <div class="modal-content">\ <div class="modal-header">\ <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>\ <h3 class="modal-title">' + title + '</h3>\ </div>\ <div class="modal-body">\ <p>'+ (typeof icon === "string" ? '<i class="fa ' + icon + '"></i> ' : '') + text + '</p>\ </div>\ <div class="modal-footer">\ <a href="#" class="btn btn-primary" data-dismiss="modal">Ok</a>\ </div>\ </div>\ </div>\ </div>'; $(html).modal().on("hidden", function() { $(this).remove(); }); } function loadChangelog() { var xhr = new XMLHttpRequest(); xhr.onreadystatechange = function() { if( xhr.readyState === XMLHttpRequest.DONE ) { if ( (xhr.status >= 200 && xhr.status < 300 ) || xhr.status === 0 ) { var converter = new showdown.Converter(); var html = converter.makeHtml(xhr.responseText); $("#changelog-content").html(html); } } }; xhr.open("GET", extension.getResourceURL("changelog.md"), true); xhr.send(); } // !Google Analytics var _gaq = _gaq || []; _gaq.push(['_setAccount', ANALYTICS_ID]); _gaq.push(['_trackPageview']); (function() { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = 'https://ssl.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })();
12,990
options
js
en
javascript
code
{"qsc_code_num_words": 1296, "qsc_code_num_chars": 12990.0, "qsc_code_mean_word_length": 6.35339506, "qsc_code_frac_words_unique": 0.21604938, "qsc_code_frac_chars_top_2grams": 0.01821715, "qsc_code_frac_chars_top_3grams": 0.02307505, "qsc_code_frac_chars_top_4grams": 0.01748846, "qsc_code_frac_chars_dupe_5grams": 0.35207675, "qsc_code_frac_chars_dupe_6grams": 0.33021618, "qsc_code_frac_chars_dupe_7grams": 0.31552101, "qsc_code_frac_chars_dupe_8grams": 0.29693952, "qsc_code_frac_chars_dupe_9grams": 0.29693952, "qsc_code_frac_chars_dupe_10grams": 0.27617197, "qsc_code_frac_chars_replacement_symbols": 0.0, "qsc_code_frac_chars_digital": 0.00437158, "qsc_code_frac_chars_whitespace": 0.15473441, "qsc_code_size_file_byte": 12990.0, "qsc_code_num_lines": 415.0, "qsc_code_num_chars_line_max": 139.0, "qsc_code_num_chars_line_mean": 31.30120482, "qsc_code_frac_chars_alphabet": 0.74553734, "qsc_code_frac_chars_comments": 0.01724403, "qsc_code_cate_xml_start": 0.0, "qsc_code_frac_lines_dupe_lines": 0.32835821, "qsc_code_cate_autogen": 0.0, "qsc_code_frac_lines_long_string": 0.00597015, "qsc_code_frac_chars_string_length": 0.26294353, "qsc_code_frac_chars_long_word_length": 0.04307982, "qsc_code_frac_lines_string_concat": 0.0, "qsc_code_cate_encoded_data": 0.0, "qsc_code_frac_chars_hex_words": 0.0, "qsc_code_frac_lines_prompt_comments": 0.0, "qsc_code_frac_lines_assert": 0.0, "qsc_codejavascript_cate_ast": 1.0, "qsc_codejavascript_cate_var_zero": 0.0, "qsc_codejavascript_frac_lines_func_ratio": 0.01791045, "qsc_codejavascript_num_statement_line": 0.03283582, "qsc_codejavascript_score_lines_no_logic": 0.05373134, "qsc_codejavascript_frac_words_legal_var_name": 0.97560976, "qsc_codejavascript_frac_words_legal_func_name": 1.0, "qsc_codejavascript_frac_words_legal_class_name": null, "qsc_codejavascript_frac_lines_print": 0.0}
1
{"qsc_code_frac_chars_replacement_symbols": 0, "qsc_code_num_words": 0, "qsc_code_num_chars": 0, "qsc_code_mean_word_length": 0, "qsc_code_frac_chars_top_2grams": 0, "qsc_code_frac_chars_top_3grams": 0, "qsc_code_frac_chars_top_4grams": 0, "qsc_code_frac_chars_dupe_5grams": 0, "qsc_code_frac_chars_dupe_6grams": 0, "qsc_code_frac_chars_dupe_7grams": 0, "qsc_code_frac_chars_dupe_8grams": 0, "qsc_code_frac_chars_dupe_9grams": 0, "qsc_code_frac_chars_dupe_10grams": 0, "qsc_code_size_file_byte": 0, "qsc_code_num_lines": 0, "qsc_code_num_chars_line_max": 0, "qsc_code_num_chars_line_mean": 0, "qsc_code_frac_chars_alphabet": 0, "qsc_code_frac_chars_digital": 0, "qsc_code_frac_chars_whitespace": 0, "qsc_code_frac_chars_comments": 0, "qsc_code_cate_xml_start": 0, "qsc_code_frac_lines_dupe_lines": 0, "qsc_code_cate_autogen": 0, "qsc_code_frac_lines_long_string": 0, "qsc_code_frac_chars_string_length": 0, "qsc_code_frac_chars_long_word_length": 0, "qsc_code_cate_encoded_data": 0, "qsc_code_frac_chars_hex_words": 0, "qsc_code_frac_lines_prompt_comments": 0, "qsc_code_frac_lines_assert": 0, "qsc_codejavascript_cate_ast": 0, "qsc_codejavascript_cate_var_zero": 0, "qsc_codejavascript_frac_lines_func_ratio": 0, "qsc_codejavascript_score_lines_no_logic": 0, "qsc_codejavascript_frac_lines_print": 0}
007revad/Synology_Download_Station_Chrome_Extension
js/browser-functions.js
/// <reference path="../../typings/index.d.ts"/> var IS_SAFARI = (typeof (safari) != "undefined"); var IS_CHROME = (typeof (chrome) != "undefined"); var IS_OPERA = navigator.vendor.indexOf("Opera") != -1; var SAFARI_UPDATE_MANIFEST = SAFARI_UPDATE_MANIFEST; if (IS_CHROME && chrome.tabs && !chrome.tabs.sendMessage) { chrome.tabs.sendMessage = chrome.tabs.sendRequest; } var extension; (function (extension) { var _locales = {}; var _version = null; function getExtensionVersion() { if (_version != null) return _version; // Safari if (IS_SAFARI) { var r = new XMLHttpRequest(); r.open("GET", "Info.plist", false); r.send(null); var data = r.responseText; var currentVersion; $.each($(data).find("key"), function (index, key) { if ($(key).text() == 'CFBundleShortVersionString') { currentVersion = $(key).next().text(); } }); _version = currentVersion; } else if (IS_CHROME) { var manifest = chrome.runtime.getManifest(); _version = manifest.version; } return _version; } extension.getExtensionVersion = getExtensionVersion; function getExtensionBundleVersion() { var r = new XMLHttpRequest(); r.open("GET", extension.getResourceURL("Info.plist"), false); r.send(null); var data = r.responseText; var currentVersion; $.each($(data).find("key"), function (index, key) { if ($(key).text() == 'CFBundleVersion') { currentVersion = parseInt($(key).next().text()); } }); return currentVersion; } extension.getExtensionBundleVersion = getExtensionBundleVersion; function getLocalizedString(name, substitutions, language) { if (!Array.isArray(substitutions)) { substitutions = new Array(); } // Safari if (IS_SAFARI) { if (!language) { language = _getBrowserLanguage(); } var locale = _getLocale(language); if (locale !== null && typeof locale[name] === 'object' && typeof locale[name].message === 'string') { return prepareLocalizedMessage(locale[name], substitutions); } else if (language.split('_').length == 2) { return getLocalizedString(name, substitutions, language.split('_')[0]); } else if (language != "en") { console.warn("Could not find a translation for '%s' for language %s, falling back to English.", name, language); return getLocalizedString(name, substitutions, "en"); } else { console.warn("Could not find a message for '%s.'", name); return name; } } else if (IS_CHROME) { var message = chrome.i18n.getMessage(name, substitutions); if (message == null || message.length == 0 || message == name) { console.warn("Could not find an translation for '" + name + "'."); message = name; } return message; } return name; } extension.getLocalizedString = getLocalizedString; function _getBrowserLanguage() { var language = navigator.language.toLowerCase(); var parts = language.split('-'); if (parts.length === 2) language = parts[0].toLowerCase() + '_' + parts[1].toUpperCase(); return language; } function prepareLocalizedMessage(localization, substitutions) { var message = localization.message; if (localization.placeholders) { var placeholders = localization.placeholders; for (var placeholder in localization.placeholders) { if (localization.placeholders.hasOwnProperty(placeholder) && typeof placeholders[placeholder].content === "string") { var parameterIndex = parseInt(placeholders[placeholder].content.replace("$", "")) - 1; if (!isNaN(parameterIndex)) { var substitution = substitutions[parameterIndex] ? substitutions[parameterIndex] : ""; message = message.replace("$" + placeholder + "$", substitution); } } } } return message; } /** * Returns the object with localizations for the specified language and * caches the localization file to limit file read actions. Returns null * if the localization is not available. **/ function _getLocale(language) { if (typeof _locales[language] === 'object') return _locales[language]; else { try { var url = safari.extension.baseURI + "_locales/" + language + "/messages.json"; var r = new XMLHttpRequest(); r.open("GET", url, false); r.send(null); var data = JSON.parse(r.responseText); _locales[language] = data; } catch (e) { _locales[language] = null; } return _locales[language]; } } function getResourceURL(file) { if (IS_SAFARI) return safari.extension.baseURI + file; if (IS_CHROME) return chrome.runtime.getURL(file); } extension.getResourceURL = getResourceURL; function createTab(url) { // Safari if (IS_SAFARI) { if (!url.match(/^http/)) { url = safari.extension.baseURI + url; } var browserWindow = safari.application.activeBrowserWindow; if (browserWindow == null) { browserWindow = safari.application.openBrowserWindow(); } var tab = browserWindow.activeTab; if (tab == null || tab.url != null) { tab = browserWindow.openTab(); } tab.url = url; browserWindow.activate(); tab.activate(); } else if (IS_CHROME) { chrome.tabs.create({ "url": url }); } } extension.createTab = createTab; function setBadge(value) { if (IS_SAFARI) { var toolbarItems = safari.extension.toolbarItems; for (var i = 0; i < toolbarItems.length; i++) { if (toolbarItems[i].identifier == "toolbarButton") toolbarItems[i].badge = value; } } else if (IS_CHROME) { var text = value === 0 ? "" : value.toString(); chrome.browserAction.setBadgeBackgroundColor({ color: [0, 200, 0, 100] }); chrome.browserAction.setBadgeText({ text: text }); } } extension.setBadge = setBadge; function getPopovers() { var popovers = new Array(); if (IS_SAFARI) { $.each(safari.extension.popovers, function (index, popover) { popovers.push(popover.contentWindow); }); } else if (IS_CHROME) { popovers = chrome.extension.getViews({ type: 'popup' }); } return popovers; } extension.getPopovers = getPopovers; function hidePopovers() { if (IS_SAFARI) { var popovers = getSafariPopoverObjects(); for (var i = 0; i < popovers.length; i++) { popovers[i].hide(); } } else if (IS_CHROME) { var popoverWindows = getPopovers(); for (var i = 0; i < popoverWindows.length; i++) { popoverWindows[i].close(); } } } extension.hidePopovers = hidePopovers; function getSafariPopoverObjects() { var popovers = new Array(); if (IS_SAFARI) { $.each(safari.extension.popovers, function (index, popover) { popovers.push(popover); }); } return popovers; } extension.getSafariPopoverObjects = getSafariPopoverObjects; function getSafariPopoverObject(identifier) { var popovers = getSafariPopoverObjects(); for (var i = 0; i < popovers.length; i++) { if (popovers[i].identifier == identifier) return popovers[i]; } return null; } extension.getSafariPopoverObject = getSafariPopoverObject; function onPopoverVisible(eventHandler, identifier) { if (IS_SAFARI) { safari.application.addEventListener("popover", function (event /*SafariValidateEvent<SafariExtensionPopover>*/) { if (event.target.identifier == identifier) { eventHandler(event); } }, true); } else if (IS_CHROME) { $(document).ready(eventHandler); } } extension.onPopoverVisible = onPopoverVisible; function onPopoverHidden(eventHandler, identifier) { if (IS_SAFARI) { safari.application.addEventListener("popover", function (event /*SafariValidateEvent<SafariExtensionPopover>*/) { if (event.target.identifier == identifier) { var safariPopover = getSafariPopoverObject(identifier); if (safariPopover != null) { var popoverVisibilityTimer = setInterval(function () { if (safariPopover.visible === false) { eventHandler(); clearInterval(popoverVisibilityTimer); } }, 1000); } } }); } else if (IS_CHROME) { $(window).unload(eventHandler); } } extension.onPopoverHidden = onPopoverHidden; function getBackgroundPage() { var backgroundPage; if (IS_SAFARI) { backgroundPage = safari.extension.globalPage.contentWindow; } else if (IS_CHROME) { backgroundPage = chrome.extension.getBackgroundPage(); } return backgroundPage; } extension.getBackgroundPage = getBackgroundPage; // !Context menus var contextMenuItems = {}; if (IS_SAFARI && typeof safari.application === "object") { safari.application.addEventListener("contextmenu", function (event) { for (var id in contextMenuItems) { if (contextMenuItems.hasOwnProperty(id)) { event.contextMenu.appendContextMenuItem(id, contextMenuItems[id].title); } } }, false); safari.application.addEventListener("validate", function (event /*SafariExtensionContextMenuItemValidateEvent*/) { if (contextMenuItems.hasOwnProperty(event.command)) { event.target.disabled = false; //!contextMenuItems[event.command].enabled; } }, false); safari.application.addEventListener("command", function (event) { if (contextMenuItems.hasOwnProperty(event.command) && typeof contextMenuItems[event.command].onclick === "function") { contextMenuItems[event.command].onclick(event.userInfo, null); } }, false); } function createContextMenuItem(options) { if (contextMenuItems.hasOwnProperty(options.id)) { var id = options.id; delete options.id; updateContextMenuItem(id, options); } else { contextMenuItems[options.id] = options; if (IS_CHROME) { chrome.contextMenus.create(options); } } } extension.createContextMenuItem = createContextMenuItem; function updateContextMenuItem(id, newOptions) { if (contextMenuItems.hasOwnProperty(id)) { for (var key in newOptions) { contextMenuItems[id][key] = newOptions[key]; } if (IS_CHROME) { chrome.contextMenus.update(id, newOptions); } } } extension.updateContextMenuItem = updateContextMenuItem; function removeContextMenuItem(id) { if (contextMenuItems.hasOwnProperty(id)) { delete contextMenuItems[id]; if (IS_CHROME) { chrome.contextMenus.remove(id); } } } extension.removeContextMenuItem = removeContextMenuItem; // !Safari extension update check function safariCheckForUpdate() { if (IS_SAFARI) { var currentVersion = extension.getExtensionBundleVersion(); $.ajax({ type: 'GET', url: SAFARI_UPDATE_MANIFEST, dataType: 'xml' }).done(function (data) { // Find dictionary for this extension $.each($(data).find("key"), function (index, key) { if ($(key).text() == 'CFBundleIdentifier' && $(key).next().text() == 'nl.luukdobber.safaridownloadstation') { var dict = $(key).closest('dict'); var updateUrl; // Find the latest version $.each(dict.find("key"), function (index, key) { if ($(key).text() == 'URL') { updateUrl = $(key).next().text(); } }); $.each(dict.find("key"), function (index, key) { if ($(key).text() == 'CFBundleVersion') { var latestVersion = parseInt($(key).next().text()); if (currentVersion < latestVersion) { showNotification("Synology Download Station", getLocalizedString("newVersionAvailable"), true, updateUrl); } } }); } }); }); } } extension.safariCheckForUpdate = safariCheckForUpdate; ; var notificationOnClickUrls = {}; // !Notifications function showNotification(title, text, keepVisible, onclickUrl) { var keepVisible = keepVisible || false; var textDirection = (extension.getLocalizedString("textDirection") == "rtl" ? "rtl" : "ltr"); var icon = "Icon-48.png"; if (window.chrome && chrome.notifications && chrome.notifications.create) { var options = { type: "basic", title: title, message: text, iconUrl: extension.getResourceURL("Icon-64.png"), }; if (onclickUrl) { options.isClickable = true; } options.requireInteraction = keepVisible; chrome.notifications.create(options, function (notificationId) { if (onclickUrl) { notificationOnClickUrls[notificationId] = onclickUrl; } }); } else if ("Notification" in window) { var notification = new window["Notification"](title, { dir: textDirection, body: text, icon: icon, }); if (onclickUrl) { notification.onclick = function () { extension.createTab(onclickUrl); this.close(); }; } if (keepVisible == false) { setTimeout(function () { notification.close(); }, 5000); } return notification; } return null; } extension.showNotification = showNotification; if (window.chrome && chrome.notifications && chrome.notifications.onClicked) { chrome.notifications.onClicked.addListener(function (notificationId) { if (notificationOnClickUrls[notificationId]) { extension.createTab(notificationOnClickUrls[notificationId]); chrome.notifications.clear(notificationId); delete notificationOnClickUrls[notificationId]; } }); } /* // !Message passing extension.sendMessageFromContent = function(name, message) { var messageData = { id: Math.random().toString(36).substring(7), name: name, message: message }; if(IS_CHROME) { if(chrome.runtime && chrome.runtime.sendMessage){ chrome.runtime.sendMessage(messageData); } else if(chrome.extension && chrome.extension.sendRequest) { chrome.extension.sendRequest(messageData); } } if(IS_SAFARI) { if(typeof safari.self.tab == "object" && safari.self.tab instanceof SafariContentBrowserTabProxy) safari.self.tab.dispatchMessage("extensionMessage", messageData, false); else if(safari.application.activeBrowserWindow && safari.application.activeBrowserWindow.activeTab.page instanceof SafariWebPageProxy) safari.application.activeBrowserWindow.activeTab.page.dispatchMessage("extensionMessage", messageData, false); } }; */ var safariMessageResponseHandlers = {}; function sendMessageToBackground(name, message, responseCallback) { var messageData = { id: Math.random().toString(36).substring(7), name: name, message: message, acceptsCallback: responseCallback != null }; if (responseCallback) { safariMessageResponseHandlers[messageData.id] = responseCallback; } if (IS_CHROME) { chrome.runtime.sendMessage(messageData); } else if (IS_SAFARI) { if (typeof safari.self.tab == "object" && safari.self.tab instanceof window["SafariContentBrowserTabProxy"]) { safari.self.tab.dispatchMessage("extensionMessage", messageData, false); } else if (safari.application.activeBrowserWindow && safari.application.activeBrowserWindow.activeTab.page instanceof window["SafariWebPageProxy"]) { safari.application.activeBrowserWindow.activeTab.page.dispatchMessage("extensionMessage", messageData); } } } extension.sendMessageToBackground = sendMessageToBackground; ; function sendMessageToContent(name, message, responseCallback) { var messageData = { id: Math.random().toString(36).substring(7), name: name, message: message, acceptsCallback: responseCallback != null }; if (responseCallback) { safariMessageResponseHandlers[messageData.id] = responseCallback; } if (IS_CHROME) { if (chrome.tabs) { chrome.tabs.query({ active: true }, function (tabs) { if (tabs.length > 0) { chrome.tabs.sendMessage(tabs[0].id, messageData); } }); } } if (IS_SAFARI) { if (typeof safari.self.tab == "object" && safari.self.tab instanceof window["SafariContentBrowserTabProxy"]) safari.self.tab.dispatchMessage("extensionMessage", messageData, false); else if (safari.application.activeBrowserWindow != null && safari.application.activeBrowserWindow.activeTab.page instanceof window["SafariWebPageProxy"]) safari.application.activeBrowserWindow.activeTab.page.dispatchMessage("extensionMessage", messageData); } } extension.sendMessageToContent = sendMessageToContent; var receivedMessages = []; function onMessage(callback) { var messageHandler = function (messageData, sendResponse) { if (!messageData || !messageData.id) return; if (receivedMessages.indexOf(messageData.id) != -1) return; callback({ name: messageData.name, message: messageData.message }, sendResponse); }; if (IS_CHROME) { if (chrome.runtime && chrome.runtime.onMessage) { chrome.runtime.onMessage.addListener(function (request, sender, sendResponse) { if (request.id) { messageHandler(request, function (responseMessage) { var messageData = { responseTo: request.id, message: responseMessage }; if (sender.tab && sender.frameId) { chrome.tabs.sendMessage(sender.tab.id, messageData, { frameId: sender.frameId }); } else if (sender.tab) { chrome.tabs.sendMessage(sender.tab.id, messageData); } else { chrome.runtime.sendMessage(messageData); } }); } }); } } if (IS_SAFARI) { var eventHandler = function (event) { if (event.name === "extensionMessage") { messageHandler(event.message, function (responseMessage) { var messageData = { responseTo: event.message.id, message: responseMessage }; if (typeof safari.self.tab == "object" && safari.self.tab instanceof window["SafariContentBrowserTabProxy"]) safari.self.tab.dispatchMessage("extensionMessageResponse", messageData, false); else if (safari.application.activeBrowserWindow != null && safari.application.activeBrowserWindow.activeTab.page instanceof window["SafariWebPageProxy"]) safari.application.activeBrowserWindow.activeTab.page.dispatchMessage("extensionMessageResponse", messageData); }); } }; if (typeof safari.application === "object") safari.application.addEventListener("message", eventHandler, false); else if (typeof safari.self === "object") { safari.self.addEventListener("message", eventHandler, false); } else { console.warn("Could not find safari.application or safari.self to add message event listener."); } } } extension.onMessage = onMessage; ; // Handle message responses if (IS_CHROME) { chrome.runtime.onMessage.addListener(function (request, sender, sendResponse) { if (request.responseTo) { var responseHandler = safariMessageResponseHandlers[request.responseTo]; if (responseHandler) { responseHandler(request.message); delete safariMessageResponseHandlers[request.responseTo]; } } }); } else if (IS_SAFARI) { var eventHandler = function (event) { if (event.name === "extensionMessageResponse") { var responseHandler = safariMessageResponseHandlers[event.message.responseTo]; if (responseHandler) { responseHandler(event.message.message); delete safariMessageResponseHandlers[event.message.responseTo]; } } }; if (typeof safari.application === "object") safari.application.addEventListener("message", eventHandler, false); else if (typeof safari.self === "object") { safari.self.addEventListener("message", eventHandler, false); } else { console.warn("Could not find safari.application or safari.self to add message event listener."); } } })(extension || (extension = {})); /* !Storage */ var extension; (function (extension) { var storage; (function (storage) { function set(object, callback) { if (IS_SAFARI) { for (var key in object) { try { var json = JSON.stringify(object[key]); safari.extension.secureSettings.setItem(key, json); } catch (exception) { console.warn("Error while storing item with key %s", key); } } if (callback) { callback(); } } if (IS_CHROME) { chrome.storage.local.set(object, callback); } } storage.set = set; ; function get(keys, callback) { if (!Array.isArray(keys)) { var key = keys; keys = [key]; } if (IS_SAFARI) { var result = {}; for (var i = 0; i < keys.length; i++) { try { var json = safari.extension.secureSettings.getItem(keys[i]); result[keys[i]] = JSON.parse(json); } catch (exception) { console.log("Error while retreving storage item with key %s", keys[i]); result[keys[i]] = null; } } callback(result); } if (IS_CHROME) { chrome.storage.local.get(keys, function (storageItems) { if (!storageItems) { storageItems = {}; } for (var i = 0; i < keys.length; i++) { if (typeof storageItems[keys[i]] === "undefined") storageItems[keys[i]] = null; } callback(storageItems); }); } } storage.get = get; ; function remove(keys, callback) { if (!Array.isArray(keys)) { var key = keys; keys = [key]; } if (IS_SAFARI) { for (var i = 0; i < keys.length; i++) { safari.extension.secureSettings.removeItem(keys[i]); } if (callback) { callback(); } } if (IS_CHROME) { chrome.storage.local.remove(keys, callback); } } storage.remove = remove; ; function clear(callback) { if (IS_SAFARI) { safari.extension.secureSettings.clear(); if (callback) { callback(); } } if (IS_CHROME) { chrome.storage.local.clear(callback); } } storage.clear = clear; ; function addEventListener(eventHandler) { if (IS_SAFARI) { if (!safari.extension.secureSettings) return; var cachedChanges = {}; safari.extension.secureSettings.addEventListener("change", function (event) { if (event.oldValue != event.newValue) { // Wait for other changes so they can be bundled in 1 event if (Object.keys(cachedChanges).length == 0) { setTimeout(function () { eventHandler(cachedChanges); cachedChanges = {}; }, 1000); } cachedChanges[event.key] = { oldValue: event.oldValue, newValue: event.newValue }; } }, false); } if (IS_CHROME) { chrome.storage.onChanged.addListener(function (changes, areaName) { if (areaName == "local") { eventHandler(changes); } }); } } storage.addEventListener = addEventListener; ; })(storage = extension.storage || (extension.storage = {})); })(extension || (extension = {})); //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbImpzL2Jyb3dzZXItZnVuY3Rpb25zLnRzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiJBQUFBLGdEQUFnRDtBQUNoRCxJQUFJLFNBQVMsR0FBRyxDQUFDLE9BQU0sQ0FBQyxNQUFNLENBQUMsSUFBSSxXQUFXLENBQUMsQ0FBQztBQUNoRCxJQUFJLFNBQVMsR0FBRyxDQUFDLE9BQU0sQ0FBQyxNQUFNLENBQUMsSUFBSSxXQUFXLENBQUMsQ0FBQztBQUNoRCxJQUFJLFFBQVEsR0FBSSxTQUFTLENBQUMsTUFBTSxDQUFDLE9BQU8sQ0FBQyxPQUFPLENB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leSBjYW4gYmUgYnVuZGxlZCBpbiAxIGV2ZW50XG5cdFx0XHRcdFx0aWYoT2JqZWN0LmtleXMoY2FjaGVkQ2hhbmdlcykubGVuZ3RoID09IDApIHtcblx0XHRcdFx0XHRcdHNldFRpbWVvdXQoKCkgPT4ge1xuXHRcdFx0XHRcdFx0XHRldmVudEhhbmRsZXIoY2FjaGVkQ2hhbmdlcyk7XG5cdFx0XHRcdFx0XHRcdGNhY2hlZENoYW5nZXMgPSB7fTtcblx0XHRcdFx0XHRcdH0sIDEwMDApO1xuXHRcdFx0XHRcdH1cblx0XHRcdFx0XHRcblx0XHRcdFx0XHRjYWNoZWRDaGFuZ2VzW2V2ZW50LmtleV0gPSB7IG9sZFZhbHVlOiBldmVudC5vbGRWYWx1ZSwgbmV3VmFsdWU6IGV2ZW50Lm5ld1ZhbHVlIH07XG5cdFx0XHRcdH1cblx0XHRcdH0sIGZhbHNlKTtcblx0XHR9XG5cdFx0XG5cdFx0aWYoSVNfQ0hST01FKSB7XG5cdFx0XHRjaHJvbWUuc3RvcmFnZS5vbkNoYW5nZWQuYWRkTGlzdGVuZXIoKGNoYW5nZXMsIGFyZWFOYW1lKSA9PiB7XG5cdFx0XHRcdGlmKGFyZWFOYW1lID09IFwibG9jYWxcIikge1xuXHRcdFx0XHRcdGV2ZW50SGFuZGxlcihjaGFuZ2VzKTtcblx0XHRcdFx0fVxuXHRcdFx0fSk7XG5cdFx0fVxuXHR9O1xufSJdLCJzb3VyY2VSb290IjoiL3NvdXJjZS8ifQ==
98,670
browser-functions
js
en
javascript
code
{"qsc_code_num_words": 2132, "qsc_code_num_chars": 98670.0, "qsc_code_mean_word_length": 39.70919325, "qsc_code_frac_words_unique": 0.1641651, "qsc_code_frac_chars_top_2grams": 0.00222065, "qsc_code_frac_chars_top_3grams": 0.00283487, "qsc_code_frac_chars_top_4grams": 0.0022679, "qsc_code_frac_chars_dupe_5grams": 0.06400898, "qsc_code_frac_chars_dupe_6grams": 0.05439405, "qsc_code_frac_chars_dupe_7grams": 0.05225608, "qsc_code_frac_chars_dupe_8grams": 0.04825183, "qsc_code_frac_chars_dupe_9grams": 0.04664541, "qsc_code_frac_chars_dupe_10grams": 0.04337349, "qsc_code_frac_chars_replacement_symbols": 0.0, "qsc_code_frac_chars_digital": 0.07751956, "qsc_code_frac_chars_whitespace": 0.1099321, "qsc_code_size_file_byte": 98670.0, "qsc_code_num_lines": 705.0, "qsc_code_num_chars_line_max": 69859.0, "qsc_code_num_chars_line_mean": 139.95744681, "qsc_code_frac_chars_alphabet": 0.88646482, "qsc_code_frac_chars_comments": 0.72696868, "qsc_code_cate_xml_start": 0.0, "qsc_code_frac_lines_dupe_lines": 0.30711044, "qsc_code_cate_autogen": 0.0, "qsc_code_frac_lines_long_string": 0.0, "qsc_code_frac_chars_string_length": 0.04487751, "qsc_code_frac_chars_long_word_length": 0.00805494, "qsc_code_frac_lines_string_concat": 0.0, "qsc_code_cate_encoded_data": 1.0, "qsc_code_frac_chars_hex_words": 0.0, "qsc_code_frac_lines_prompt_comments": 0.0, "qsc_code_frac_lines_assert": 0.0, "qsc_codejavascript_cate_ast": 1.0, "qsc_codejavascript_cate_var_zero": 0.0, "qsc_codejavascript_frac_lines_func_ratio": 0.0484115, "qsc_codejavascript_num_statement_line": 0.01361573, "qsc_codejavascript_score_lines_no_logic": 0.10892587, "qsc_codejavascript_frac_words_legal_var_name": 0.92105263, "qsc_codejavascript_frac_words_legal_func_name": 0.9375, "qsc_codejavascript_frac_words_legal_class_name": null, "qsc_codejavascript_frac_lines_print": 0.00151286}
0
{"qsc_code_frac_chars_replacement_symbols": 0, "qsc_code_num_words": 0, "qsc_code_num_chars": 0, "qsc_code_mean_word_length": 1, "qsc_code_frac_chars_top_2grams": 0, "qsc_code_frac_chars_top_3grams": 0, "qsc_code_frac_chars_top_4grams": 0, "qsc_code_frac_chars_dupe_5grams": 0, "qsc_code_frac_chars_dupe_6grams": 0, "qsc_code_frac_chars_dupe_7grams": 0, "qsc_code_frac_chars_dupe_8grams": 0, "qsc_code_frac_chars_dupe_9grams": 0, "qsc_code_frac_chars_dupe_10grams": 0, "qsc_code_size_file_byte": 0, "qsc_code_num_lines": 0, "qsc_code_num_chars_line_max": 1, "qsc_code_num_chars_line_mean": 1, "qsc_code_frac_chars_alphabet": 0, "qsc_code_frac_chars_digital": 0, "qsc_code_frac_chars_whitespace": 0, "qsc_code_frac_chars_comments": 0, "qsc_code_cate_xml_start": 0, "qsc_code_frac_lines_dupe_lines": 0, "qsc_code_cate_autogen": 0, "qsc_code_frac_lines_long_string": 0, "qsc_code_frac_chars_string_length": 0, "qsc_code_frac_chars_long_word_length": 0, "qsc_code_cate_encoded_data": 1, "qsc_code_frac_chars_hex_words": 0, "qsc_code_frac_lines_prompt_comments": 0, "qsc_code_frac_lines_assert": 0, "qsc_codejavascript_cate_ast": 0, "qsc_codejavascript_cate_var_zero": 0, "qsc_codejavascript_frac_lines_func_ratio": 0, "qsc_codejavascript_score_lines_no_logic": 0, "qsc_codejavascript_frac_lines_print": 0}
007revad/Synology_HDD_db
2025_plus_models.md
## 2025 series or later Plus models ### Unverified 3rd party drive limitations and unofficial solutions | Action | Works | Result | Solution | |--------|--------------|--------|----------| | Setup the NAS with Synology drives | yes | | | | Setup the NAS with 3rd party SSDs | yes | Lots of warnings | Remove warnings with [Synology HDD db](https://github.com/007revad/Synology_HDD_db) | | Setup the NAS with unverified 3rd party HDDs | **No!** | | See <a href="#setting-up-a-new-2025-or-later-plus-model-with-only-unverified-hdds">Setup with unverifed HDDs</a> | | Migrate unverified 3rd party drives from other Synology | yes | Lots of warnings | Remove warnings with [Synology HDD db](https://github.com/007revad/Synology_HDD_db) | | Migrate unverified 3rd party drives and NVMe cache from other Synology | yes | Lots of warnings | Remove warnings with [Synology HDD db](https://github.com/007revad/Synology_HDD_db) | | Replace migrated 3rd party drives with 3rd party drives | **No!** | | Use [Synology HDD db](https://github.com/007revad/Synology_HDD_db) | | Gradually replace migrated 3rd party drives with Synology drives | yes | Lots of warnings until all 3rd party drives replaced | Use [Synology HDD db](https://github.com/007revad/Synology_HDD_db) See [Migration and Drive Replacement](https://github.com/007revad/Synology_HDD_db/discussions/468#discussioncomment-13086639) | | Expand migrated 3rd party storage pool with 3rd party drives | **No!** | | Use [Synology HDD db](https://github.com/007revad/Synology_HDD_db) | | Use 3rd party drive as hot spare | **No!** | | Use [Synology HDD db](https://github.com/007revad/Synology_HDD_db) | | Create a cache with 3rd party SSDs | **No!** | | Use [Synology HDD db](https://github.com/007revad/Synology_HDD_db) | | Delete and create storage pool on migrated 3rd party drives | **No!** | | See <a href="#deleting-and-recreating-your-storage-pool-on-unverified-hdds">Recreating storage pool</a> | <br> ### Setting up a new 2025 or later plus model with only unverified HDDs Credit to Alex_of_Chaos on reddit DSM won't install on a 2025 or later series plus model if you only have unverified HDDs. But we can get around that. 1. Start telnet by entering `http://<NAS-IP>:5000/webman/start_telnet.cgi` into your browser's address bar. - Replace `<NAS-IP>` with the IP address of the Synology NAS. 2. Open a telnet client (powershell, PuTTY etc) on your computer and connect to the Synology with 'telnet <NAS-IP>`. - Replace `<NAS-IP>` with the IP address of the Synology NAS. 3. Log into telnet with: - `root` for the login - `101-0101` for the password 4. Execute the following command: (using a while loop in case DSM is running in a VM) ``` while true; do touch /tmp/installable_check_pass; sleep 1; done ``` 5. Refresh the web installation page and install DSM. 6. Then in the telnet window, or via SSH, execute the following command: ``` /usr/syno/bin/synosetkeyvalue /etc.defaults/synoinfo.conf support_disk_compatibility no ``` 7. If Storage Manager is already open close then open it, or refresh the web page. If refreshing the page or restarting Storage Manager is not working, try restarting your Synology NAS. 8. You can now create your storage pool from Storage Manager. <br> ### Deleting and recreating your storage pool on unverified HDDs You can't download Synology HDD db to a volume because you've just deleted your storage pool. So you'd first need to download Synology HDD db to a system folder and run it from there. You can do this via SSH or via a scheduled task. #### Via SSH 1. Create and cd to /opt ``` sudo mkdir /opt && sudo chmod 775 /opt ``` 2. Create /opt ``` sudo mkdir -m775 /opt ``` 2. cd to /opt ``` cd /opt || (echo "Failed to CD to /opt"; exit 1) ``` 3. Download syno_hdd_db.sh to /opt ``` sudo curl -O "https://raw.githubusercontent.com/007revad/Synology_HDD_db/refs/heads/main/syno_hdd_db.sh" ``` 4. Download syno_hdd_vendor_ids.txt to /opt ``` sudo curl -O "https://raw.githubusercontent.com/007revad/Synology_HDD_db/refs/heads/main/syno_hdd_vendor_ids.txt" ``` 5. Then set permissions on /opt/syno_hdd_db.sh ``` sudo chmod 750 /opt/syno_hdd_db.sh ``` 6. Finally run syno_hdd_db. You don't need any options at this point. ``` sudo -s /opt/syno_hdd_db.sh ``` 8. If Storage Manager is already open close then open it, or refresh the web page. 9. You can now create your storage pool from Storage Manager. #### Via a scheduled task First setup email notifications (if you haven't already): 1. Go to **Control Panel** > **Notification** > **Email** > click **Setup**. Then create the scheduled task: 1. Go to **Control Panel** > **Task Scheduler** > click **Create** > **Scheduled Task** > **User-defined script**. 2. Enter a task name. 3. Select **root** as the user (The script needs to run as root). 4. Untick **Enable**. 5. Click **Task Settings**. 6. Tick **Send run details by email** and enter your email address. 7. In the box under **User-defined script** paste the following: ``` mkdir -m775 /opt cd /opt || (echo "Failed to CD to /opt"; exit 1) curl -O "https://raw.githubusercontent.com/007revad/Synology_HDD_db/refs/heads/main/syno_hdd_db.sh" curl -O "https://raw.githubusercontent.com/007revad/Synology_HDD_db/refs/heads/main/syno_hdd_vendor_ids.txt" chmod 750 /opt/syno_hdd_db.sh /opt/syno_hdd_db.sh -e ``` 8. Click **OK** > **OK** > type your password > **Submit** to save the scheduled task. 9. Now select the scheduld task and click **Run** > **OK**. 10. Check your emails to make sure the scheduled task ran without any error. 11. If Storage Manager is already open close then open it, or refresh the web page. 12. You can now create your storage pool from Storage Manager.
5,873
2025_plus_models
md
en
markdown
text
{"qsc_doc_frac_chars_curly_bracket": 0.0, "qsc_doc_frac_words_redpajama_stop": 0.18856719, "qsc_doc_num_sentences": 96.0, "qsc_doc_num_words": 940, "qsc_doc_num_chars": 5873.0, "qsc_doc_num_lines": 122.0, "qsc_doc_mean_word_length": 4.36595745, "qsc_doc_frac_words_full_bracket": 0.0, "qsc_doc_frac_lines_end_with_readmore": 0.0, "qsc_doc_frac_lines_start_with_bullet": 0.0, "qsc_doc_frac_words_unique": 0.28510638, "qsc_doc_entropy_unigram": 5.04023638, "qsc_doc_frac_words_all_caps": 0.0311804, "qsc_doc_frac_lines_dupe_lines": 0.27083333, "qsc_doc_frac_chars_dupe_lines": 0.05111707, "qsc_doc_frac_chars_top_2grams": 0.03898635, "qsc_doc_frac_chars_top_3grams": 0.07285575, "qsc_doc_frac_chars_top_4grams": 0.06968811, "qsc_doc_frac_chars_dupe_5grams": 0.48075049, "qsc_doc_frac_chars_dupe_6grams": 0.44249513, "qsc_doc_frac_chars_dupe_7grams": 0.41569201, "qsc_doc_frac_chars_dupe_8grams": 0.3964425, "qsc_doc_frac_chars_dupe_9grams": 0.3964425, "qsc_doc_frac_chars_dupe_10grams": 0.37110136, "qsc_doc_frac_chars_replacement_symbols": 0.0, "qsc_doc_cate_code_related_file_name": 0.0, "qsc_doc_num_chars_sentence_length_mean": 25.82191781, "qsc_doc_frac_chars_hyperlink_html_tag": 0.11016516, "qsc_doc_frac_chars_alphabet": 0.81707569, "qsc_doc_frac_chars_digital": 0.02928439, "qsc_doc_frac_chars_whitespace": 0.17435723, "qsc_doc_frac_chars_hex_words": 0.0}
1
{"qsc_doc_frac_chars_replacement_symbols": 0, "qsc_doc_entropy_unigram": 0, "qsc_doc_frac_chars_top_2grams": 0, "qsc_doc_frac_chars_top_3grams": 0, "qsc_doc_frac_chars_top_4grams": 0, "qsc_doc_frac_chars_dupe_5grams": 0, "qsc_doc_frac_chars_dupe_6grams": 0, "qsc_doc_frac_chars_dupe_7grams": 0, "qsc_doc_frac_chars_dupe_8grams": 0, "qsc_doc_frac_chars_dupe_9grams": 0, "qsc_doc_frac_chars_dupe_10grams": 0, "qsc_doc_frac_chars_dupe_lines": 0, "qsc_doc_frac_lines_dupe_lines": 0, "qsc_doc_frac_lines_end_with_readmore": 0, "qsc_doc_frac_lines_start_with_bullet": 0, "qsc_doc_frac_words_all_caps": 0, "qsc_doc_mean_word_length": 0, "qsc_doc_num_chars": 0, "qsc_doc_num_lines": 0, "qsc_doc_num_sentences": 0, "qsc_doc_num_words": 0, "qsc_doc_frac_chars_hex_words": 0, "qsc_doc_frac_chars_hyperlink_html_tag": 0, "qsc_doc_frac_chars_alphabet": 0, "qsc_doc_frac_chars_digital": 0, "qsc_doc_frac_chars_whitespace": 0}
007revad/Synology_HDD_db
README.md
# Synology HDD db <a href="https://github.com/007revad/Synology_HDD_db/releases"><img src="https://img.shields.io/github/release/007revad/Synology_HDD_db.svg"></a> ![Badge](https://hitscounter.dev/api/hit?url=https%3A%2F%2Fgithub.com%2F007revad%2FSynology_HDD_db&label=Visitors&icon=github&color=%23198754&message=&style=flat&tz=Australia%2FSydney) [![Donate](https://img.shields.io/badge/Donate-PayPal-green.svg)](https://www.paypal.com/paypalme/007revad) [![](https://img.shields.io/static/v1?label=Sponsor&message=%E2%9D%A4&logo=GitHub&color=%23fe8e86)](https://github.com/sponsors/007revad) [![committers.top badge](https://user-badge.committers.top/australia/007revad.svg)](https://user-badge.committers.top/australia/007revad) <!-- [![committers.top badge](https://user-badge.committers.top/australia_public/007revad.svg)](https://user-badge.committers.top/australia_public/007revad) --> <!-- [![committers.top badge](https://user-badge.committers.top/australia_private/007revad.svg)](https://user-badge.committers.top/australia_private/007revad) --> <!-- [![Github Releases](https://img.shields.io/github/downloads/007revad/synology_hdd_db/total.svg)](https://github.com/007revad/Synology_HDD_db/releases) --> ### Description Add your SATA or SAS HDDs and SSDs plus SATA and NVMe M.2 drives to your Synology's compatible drive databases, including your Synology M.2 PCIe card and Expansion Unit databases. The script works in DSM 7, including DSM 7.2, and DSM 6. It also has a restore option to undo all the changes made by the script. Also works for 2025 series or later Plus models. See [2025_plus_models.md](https://github.com/007revad/Synology_HDD_db/blob/main/2025_plus_models.md) #### What the script does: * Gets the Synology NAS model and DSM version (so it knows which db files to edit). * Gets a list of the HDD, SSD, SAS and NVMe drives installed in your Synology NAS. * Gets each drive's model number and firmware version. * Backs up the database files if there is no backup already. * Checks if each drive is already in the Synology's compatible-drive database. * Adds any missing drives to the Synology's compatible-drive database. * Optionally prevents DSM auto updating the drive database. * Optionally disable DSM's "support_disk_compatibility". * Optionally disable DSM's "support_memory_compatibility" to prevent <a href=images/ram_warning.png/>non-Synology memory notifications</a>. * Optionally edits max supported memory to match the amount of memory installed, if installed memory is greater than the current max memory setting. * DSM only uses the max memory setting when calculating the reserved RAM area size for SSD caches. * Optionally set write_mostly for your internal HDDs so DSM will normally read from your faster internal SSD(s). * It can automatically set DSM to read from your internal SSDs. * Or you can tell the script which internal drive(s) DSM should read from. * Optionally disables Western Digital Device Analytics (aka WDDA) to prevent DSM showing a [warning for WD drives that are 3 years old](https://arstechnica.com/gadgets/2023/06/clearly-predatory-western-digital-sparks-panic-anger-for-age-shaming-hdds). * DSM 7.2.1 already has WDDA disabled. * Enables M2D20, M2D18, M2D17 and E10M20-T1 if present on Synology NAS that don't officially support them. * Newer NAS models may also need [Synology_enable_M2_card](https://github.com/007revad/Synology_enable_M2_card) * Checks that M.2 volume support is enabled (on models that have M.2 slots or PCIe slots). * Enables creating M.2 storage pools and volumes from within Storage Manager in DSM 7.2 and later **(newer models only?)**. * Including M.2 drives in PCIe adaptor cards like M2D20, M2D18, M2D17 and E10M20-T1 for DSM 7.2 and above **(schedule the script to run boot)**. * Optionally update IronWolf Health Monitor to v2.5.1 to support recent model IronWolf and IronWolf Pro drives. **(NAS with x86_64 CPUs only)**. * Also installs IronWolf Health Management on '22 series and newer models that don't have IronWolf Health Management **(untested)**. * Makes DSM recheck disk compatibility so rebooting is not needed if you don't have M.2 drives (DSM 7 only). * **If you have M.2 drives you may need to reboot.** * Reminds you that you may need to reboot the Synology after running the script. * Checks if there is a newer version of this script and offers to download it for you. * The new version available messages time out so they don't prevent the script running if it is scheduled to run unattended. ### Download the script 1. Download the latest version _Source code (zip)_ from https://github.com/007revad/Synology_HDD_db/releases 2. Save the download zip file to a folder on the Synology. - Do ***NOT*** save the script to a M.2 volume. After a DSM or Storage Manager update the M.2 volume won't be available until after the script has run. 3. Unzip the zip file. Or via SSH as your regular user: ``` cd $HOME wget https://github.com/007revad/Synology_HDD_db/archive/refs/heads/main.zip -O syno_hdd_db.zip 7z x syno_hdd_db.zip cd Synology_HDD_db-main && ls -ali ``` ### Required files The following files from the downloaded zip file must be in the same folder: 1. syno_hdd_db.sh 2. syno_hdd_vendor_ids.txt 3. dtc or the bin folder containing dtc (only required if you have a E10M20-T1, M2D20 or M2D18 in a NAS that does not support them). ### When to run the script You would need to re-run the script after a DSM update. If you have DSM set to auto update the best option is to run the script every time the Synology boots, and the best way to do that is to <a href=how_to_schedule.md/>setup a scheduled task</a> to run the the script at boot-up. **Note:** After you first run the script you may need to reboot the Synology to see the effect of the changes. ### Options when running the script <a name="options"></a> There are optional flags you can use when running the script: ```YAML -s, --showedits Show edits made to <model>_host db and db.new file(s) -n, --noupdate Prevent DSM updating the compatible drive databases -r, --ram Disable memory compatibility checking (DSM 7.x only) and sets max memory to the amount of installed memory -f, --force Force DSM to not check drive compatibility Do not use this option unless absolutely needed -i, --incompatible Change incompatible drives to supported Do not use this option unless absolutely needed -w, --wdda Disable WD Device Analytics to prevent DSM showing a false warning for WD drives that are 3 years old DSM 7.2.1 and later already has WDDA disabled -p, --pcie Enable creating volumes on M2 in unknown PCIe adaptor -e, --email Disable colored text in output scheduler emails -S, --ssd=DRIVE Enable write_mostly on internal HDDs so DSM primarily reads from internal SSDs or your specified drives -S automatically sets internal SSDs as DSM preferred --ssd=DRIVE requires the fast drive(s) as argument, or restore as the argument to reset drives to default --ssd=sata1 or --ssd=sata1,sata2 or --ssd=sda etc --ssd=restore --restore Undo all changes made by the script (except -S --ssd) To restore all changes including write_mostly use --restore --ssd=restore --autoupdate=AGE Auto update script (useful when script is scheduled) AGE is how many days old a release must be before auto-updating. AGE must be a number: 0 or greater -I, --ihm Update IronWolf Health Management to 2.5.1 to support recent model IronWolf and IronWolf Pro drives. For NAS with x86_64 CPUs only. Also installs IHM on '22 series and newer models (untested) -h, --help Show this help message -v, --version Show the script version ``` **Notes:** - The -f or --force option is only needed if for some reason your drives still show as unsupported in storage manager. - Only use this option as last resort. - Using this option will prevent data deduplication from being available, and prevent firmware updates on Synology brand drives. - If you have some Synology drives and want to update their firmware run the script **without** --noupdate or -n then do the drive database update from Storage Manager and finally run the script again with your preferred options. ### Scheduling the script in Synology's Task Scheduler See <a href=how_to_schedule.md/>How to schedule a script in Synology Task Scheduler</a> ### Running the script via SSH [How to enable SSH and login to DSM via SSH](https://kb.synology.com/en-global/DSM/tutorial/How_to_login_to_DSM_with_root_permission_via_SSH_Telnet) You run the script in a shell with sudo -s or as root. ```YAML sudo -s /path-to-script/syno_hdd_db.sh -nr ``` **Note:** Replace /path-to-script/ with the actual path to the script on your Synology. <p align="left"><img src="images/syno_hdd_db1.png"></p> If you run the script with the --showedits flag it will show you the changes it made to the Synology's compatible-drive database. Obviously this is only useful if you run the script in a shell. ```YAML sudo -s /path-to-script/syno_hdd_db.sh -nr --showedits ``` **Note:** Replace /path-to-script/ with the actual path to the script on your Synology. <p align="left"><img src="images/syno_hdd_db.png"></p> ### Troubleshooting | Issue | Cause | Solution | |-------|-------|----------| | /usr/bin/env: ‘bash\r’: No such file or directory | File has Mac line endings! | [Download latest zip file](https://github.com/007revad/Synology_HDD_db/releases) | | Cursor sits there doing nothing | File has Windows line endings! | [Download latest zip file](https://github.com/007revad/Synology_HDD_db/releases) | | syntax error near unexpected token | You downloaded the webpage! | [Download latest zip file](https://github.com/007revad/Synology_HDD_db/releases) | If you get a "No such file or directory" error check the following: 1. Make sure you downloaded the zip or rar file to a folder on your Synology (not on your computer). 2. Make sure you unpacked the zip or rar file that you downloaded and are trying to run the syno_hdd_db.sh file. 3. If the path to the script contains any spaces you need to enclose the path/scriptname in double quotes: ```YAML sudo -s "/volume1/my scripts/syno_hdd_db.sh -n" ``` 4. Set the script file as executable: ```YAML sudo chmod +x "/volume1/scripts/syno_hdd_db.sh" ``` ### vendor_ids.txt You only need to edit syno_hdd_vendor_ids.txt if the script warns you about a missing vendor id. If DSM doesn't know the brand of your NVMe drives they will show up in Storage Manager as Unknown brand, and Unrecognised firmware version. <p align="left"><img src="images/unknown.png"></p> In this case the script will show you the vendor ID and advise you to add it to the syno_hdd_vendor_ids.txt file. <p align="left"><img src="images/vendor_ids.png"></p> ### Ironwolf Health Ironwolf Health working with the latest version of Ironwolf Health Monitor. <p align="left"><img src="images/ihm.png"></p> <br> ### Credits - The idea for this script came from a comment made by Empyrealist on the Synology subreddit. - Thanks for the assistance from Alex_of_Chaos on the Synology subreddit. - Thanks to dwabraxus and aferende for help detecting connected expansion units. - Thanks to bartoque on the Synology subreddit for the tip on making the script download the latest release from GitHub. - Thanks to nicolerenee for pointing out the easiest way to enable creating M.2 storage pools and volumes in Storage Manager. - Thanks to Xeroxxx for the writemostly suggestion and their writeup here: https://www.techspark.de/speed-up-synology-dsm-with-hdd-ssd/ ### Donators Thank you to the PayPal and Buy Me a Coffee donators, GitHub sponsors and hardware donators | | | | | |--------------------|--------------------|----------------------|----------------------| | | | | David Koch | | EVOX S.R.L.S | Adam | Danny Schoonderwoert | Andrew Ward | | nickcolea | Bruno | eColombel | LordGardenGnome | | Dennis Struck | matthewslack | Adrien | Florian Hinhamer | | Patrick Witon | Sonwoa1 | apbirch67 | Tim | | Robert | Moritz Bloser | Jason Huang | James Welsh | | robinhood1995 | Paul Fiorento | Gwystyl | Matt Hann | | Robert Šega | Marco Brenke | Martinus Humblet | Dirk Köhler | | KryoFlux GmbH | Frederic Gobry | bizIT Hirschberg | Alexander Ziemann | | Chris Black Media | Brent Bertram | Carsten Schmidt | Christopher Nichols | | Roland Thätig | Sebastian Brandt | HFB2022 | jtrouzes | | stove | Simon Küest | Oliver Weber | Kevin Randino | | Alex Tripp | Peter Kleissner | Dominic Lee | Daniel Boecker | | Pat A Phillips | Craikeybaby | Jason DeCorte | Salovaara Antti Sakari | | Jérôme MORIN | Sven Bauer | Fabien Vallet | Fabio Petgola | | lonestar6262 | Netchoice | Fabio Cecchinato | Jacek | | Dugan Audio LLC | MikeSx | Toregev | M. Verhoef | | Philipp Ehmeier | Adrian Playle | Daniel Meda | Richard Wilhelm | | Mika255 | Ralf Edelwein | Martin | Alexander Habisreitinger | | jrn | Marcus Wojtusik | Will (war59312) | Christopher Maglio | | Flow | Jake Morrison | tsnyder | zhangchi198 | | leadadri | Gary Plumbridge | frogger1805 | ctrlaltdelete | | CannotTouch | Kevin Staude | Alistair Hathaway | 8347 | | BrattishPlaque | Chris Bunnell | dansimau | Bsih | | Tim Trace | Michel VIEUX-PERNON | R De Jong | Rick | | Klaus-Dieter Fahlbusch | Amarand Agasi | someone61986 | Alexander Machatschek | | Yeong​Nuno | Joe | Torben Schreiter | Anthony McMurray | | Abhishek | Steven Haskell | Malte Müller | Aaron Thomas | | DENNIS BRAZIL | kunvanimals | Arnaud Costermans | dealchecker | | Michael Carras | Alan | speedyyyyyy | Jordi Chavarria Fibla | | Qwerty.xyz | Max | Mark Rohde | Someone | | vaadmin | Sebastiaan Mulder | Nico Stark | Oleksandr Antonishak | | Marcel Siemienowski | Dave Smart | dweagle79 | lingyinsam | | Vojtech Filkorn | Craig Sadler | Po-Chia Chen | Jean-François Fruhauf | | Sven 'ctraltdelete' | Thomas Horn | Christian | Simon Azzouni | | Lee Booy | Bünyamin Olgun | Hartmut Heinbach | Alexander Gundermann | | Björn Schöninger | Nico Scherer | Patrick Hoekstra | Alex Joyce | | Marcus Ackermann | Lorenz Schmid | enil-kil | Xaver Zöllner | | Jan Bublitz | Darren O'Connor | Charles Young | J Davis | | Jürg Baiker | Joshua Gillispie | bizIT Hirschberg | Jordan Crawford | | Tyler Teal | Voluntary Commerce LLC | Ez Hosting | Alec Wilhere | | Reece Lyne | Enric Escudé Santana | Yunhao Zhang | Matthias Gerhardt | | Darryl Harper | Mikescher | Matthias Pfaff | cpharada | | Neil Tapp | zen1605 | Kleissner Investments | Angel Scandinavia | | B Collins | Peter jackson | Mir Hekmat | Andrew Tapp | | Peter Weißflog | Joseph Skup | Dirk Kurfuerst | Gareth Locke | | Rory de Ruijter | Nathan O'Farrell | Harry Bos | Mark-Philipp Wolfger | | Filip Kraus | John Pham | Alejandro Bribian Rix | Daniel Hofer | | Bogdan-Stefan Rotariu | Kevin Boatswain | anschluss-org | Yemeth | | Patrick Thomas | Manuel Marquez Corral | Evrard Franck | Chad Palmer | | 侯​永政 | CHEN​HAN-YING | Eric Wells | Massimiliano Pesce | | JasonEMartin | Gerrit Klussmann | Alain Aube | Robert Kraut | | Charles-Edouard Poisnel | Oliver Busch | anonymous donors | private sponsors |
15,725
README
md
en
markdown
text
{"qsc_doc_frac_chars_curly_bracket": 0.0, "qsc_doc_frac_words_redpajama_stop": 0.2027972, "qsc_doc_num_sentences": 186.0, "qsc_doc_num_words": 2363, "qsc_doc_num_chars": 15725.0, "qsc_doc_num_lines": 262.0, "qsc_doc_mean_word_length": 4.74354634, "qsc_doc_frac_words_full_bracket": 0.0, "qsc_doc_frac_lines_end_with_readmore": 0.0, "qsc_doc_frac_lines_start_with_bullet": 0.0, "qsc_doc_frac_words_unique": 0.36055861, "qsc_doc_entropy_unigram": 6.01646258, "qsc_doc_frac_words_all_caps": 0.03952569, "qsc_doc_frac_lines_dupe_lines": 0.07582938, "qsc_doc_frac_chars_dupe_lines": 0.02175665, "qsc_doc_frac_chars_top_2grams": 0.02649657, "qsc_doc_frac_chars_top_3grams": 0.01391739, "qsc_doc_frac_chars_top_4grams": 0.01873495, "qsc_doc_frac_chars_dupe_5grams": 0.20742261, "qsc_doc_frac_chars_dupe_6grams": 0.16281559, "qsc_doc_frac_chars_dupe_7grams": 0.14131501, "qsc_doc_frac_chars_dupe_8grams": 0.11348024, "qsc_doc_frac_chars_dupe_9grams": 0.07351236, "qsc_doc_frac_chars_dupe_10grams": 0.0674458, "qsc_doc_frac_chars_replacement_symbols": 0.0, "qsc_doc_cate_code_related_file_name": 1.0, "qsc_doc_num_chars_sentence_length_mean": 33.7920354, "qsc_doc_frac_chars_hyperlink_html_tag": 0.15465819, "qsc_doc_frac_chars_alphabet": 0.86030624, "qsc_doc_frac_chars_digital": 0.01986651, "qsc_doc_frac_chars_whitespace": 0.19014308, "qsc_doc_frac_chars_hex_words": 0.0}
1
{"qsc_doc_frac_chars_replacement_symbols": 0, "qsc_doc_entropy_unigram": 0, "qsc_doc_frac_chars_top_2grams": 0, "qsc_doc_frac_chars_top_3grams": 0, "qsc_doc_frac_chars_top_4grams": 0, "qsc_doc_frac_chars_dupe_5grams": 0, "qsc_doc_frac_chars_dupe_6grams": 0, "qsc_doc_frac_chars_dupe_7grams": 0, "qsc_doc_frac_chars_dupe_8grams": 0, "qsc_doc_frac_chars_dupe_9grams": 0, "qsc_doc_frac_chars_dupe_10grams": 0, "qsc_doc_frac_chars_dupe_lines": 0, "qsc_doc_frac_lines_dupe_lines": 0, "qsc_doc_frac_lines_end_with_readmore": 0, "qsc_doc_frac_lines_start_with_bullet": 0, "qsc_doc_frac_words_all_caps": 0, "qsc_doc_mean_word_length": 0, "qsc_doc_num_chars": 0, "qsc_doc_num_lines": 0, "qsc_doc_num_sentences": 0, "qsc_doc_num_words": 0, "qsc_doc_frac_chars_hex_words": 0, "qsc_doc_frac_chars_hyperlink_html_tag": 0, "qsc_doc_frac_chars_alphabet": 0, "qsc_doc_frac_chars_digital": 0, "qsc_doc_frac_chars_whitespace": 0}
007revad/Synology_HDD_db
how_to_schedule.md
# How to schedule a script in Synology Task Scheduler To schedule a script to run on your Synology at boot-up or shut-down follow these steps: **Note:** You can setup a schedule task and leave it disabled, so it only runs when you select the task in the Task Scheduler and click on the Run button. 1. Go to **Control Panel** > **Task Scheduler** > click **Create** > and select **Triggered Task**. 2. Select **User-defined script**. 3. Enter a task name. 4. Select **root** as the user (The script needs to run as root). 5. Select **Boot-up** as the event that triggers the task. 6. Leave **Enable** ticked. 7. Click **Task Settings**. 8. Optionally you can tick **Send run details by email** and **Send run details only when the script terminates abnormally** then enter your email address. 9. In the box under **User-defined script** type the path to the script. - e.g. If you saved the script to a shared folder on volume1 called "scripts" you'd type: - **/volume1/scripts/syno_hdd_db.sh -nr --autoupdate=3** - For information on the options see [Options](README.md#options) 11. Click **OK** to save the settings. Here's some screenshots showing what needs to be set: <p align="leftr"><img src="images/schedule1.png"></p> <p align="leftr"><img src="images/schedule2.png"></p> <p align="leftr"><img src="images/schedule3-2.png"></p>
1,355
how_to_schedule
md
en
markdown
text
{"qsc_doc_frac_chars_curly_bracket": 0.0, "qsc_doc_frac_words_redpajama_stop": 0.23964497, "qsc_doc_num_sentences": 29.0, "qsc_doc_num_words": 233, "qsc_doc_num_chars": 1355.0, "qsc_doc_num_lines": 27.0, "qsc_doc_mean_word_length": 4.13304721, "qsc_doc_frac_words_full_bracket": 0.0, "qsc_doc_frac_lines_end_with_readmore": 0.0, "qsc_doc_frac_lines_start_with_bullet": 0.0, "qsc_doc_frac_words_unique": 0.5193133, "qsc_doc_entropy_unigram": 4.49500522, "qsc_doc_frac_words_all_caps": 0.00591716, "qsc_doc_frac_lines_dupe_lines": 0.0, "qsc_doc_frac_chars_dupe_lines": 0.0, "qsc_doc_frac_chars_top_2grams": 0.03738318, "qsc_doc_frac_chars_top_3grams": 0.03426791, "qsc_doc_frac_chars_top_4grams": 0.04361371, "qsc_doc_frac_chars_dupe_5grams": 0.07995846, "qsc_doc_frac_chars_dupe_6grams": 0.07995846, "qsc_doc_frac_chars_dupe_7grams": 0.05607477, "qsc_doc_frac_chars_dupe_8grams": 0.05607477, "qsc_doc_frac_chars_dupe_9grams": 0.0, "qsc_doc_frac_chars_dupe_10grams": 0.0, "qsc_doc_frac_chars_replacement_symbols": 0.0, "qsc_doc_cate_code_related_file_name": 0.0, "qsc_doc_num_chars_sentence_length_mean": 23.21428571, "qsc_doc_frac_chars_hyperlink_html_tag": 0.11881919, "qsc_doc_frac_chars_alphabet": 0.83554377, "qsc_doc_frac_chars_digital": 0.01591512, "qsc_doc_frac_chars_whitespace": 0.16531365, "qsc_doc_frac_chars_hex_words": 0.0}
1
{"qsc_doc_frac_chars_replacement_symbols": 0, "qsc_doc_entropy_unigram": 0, "qsc_doc_frac_chars_top_2grams": 0, "qsc_doc_frac_chars_top_3grams": 0, "qsc_doc_frac_chars_top_4grams": 0, "qsc_doc_frac_chars_dupe_5grams": 0, "qsc_doc_frac_chars_dupe_6grams": 0, "qsc_doc_frac_chars_dupe_7grams": 0, "qsc_doc_frac_chars_dupe_8grams": 0, "qsc_doc_frac_chars_dupe_9grams": 0, "qsc_doc_frac_chars_dupe_10grams": 0, "qsc_doc_frac_chars_dupe_lines": 0, "qsc_doc_frac_lines_dupe_lines": 0, "qsc_doc_frac_lines_end_with_readmore": 0, "qsc_doc_frac_lines_start_with_bullet": 0, "qsc_doc_frac_words_all_caps": 0, "qsc_doc_mean_word_length": 0, "qsc_doc_num_chars": 0, "qsc_doc_num_lines": 0, "qsc_doc_num_sentences": 0, "qsc_doc_num_words": 0, "qsc_doc_frac_chars_hex_words": 0, "qsc_doc_frac_chars_hyperlink_html_tag": 0, "qsc_doc_frac_chars_alphabet": 0, "qsc_doc_frac_chars_digital": 0, "qsc_doc_frac_chars_whitespace": 0}
007revad/Synology_Download_Station_Chrome_Extension
js/downloadstation.js
var DownloadStation = (function () { function DownloadStation(options) { this._sid = null; this._interval = null; this._disconnectTimeout = null; this._isManager = false; this._version = null; this._versionString = null; this._listeners = {}; this.connected = false; this.tasks = new Array(); this._settings = $.extend({ quickConnectId: null, protocol: 'http', url: null, port: null, username: null, password: null, backgroundUpdateInterval: 20, updateInBackground: false }, options); this.deviceInfo = { status: "notConnected", loggedIn: false, dsmVersion: null, dsmVersionString: null, modelName: null, deviceName: this._settings.quickConnectId != null ? this._settings.quickConnectId : (this._settings.url != null ? this._settings.url : "DiskStation"), fullUrl: (this._settings.protocol != null && this._settings.url != null && this._settings.port != null) ? this._settings.protocol + this._settings.url + ":" + this._settings.port : null }; var self = this; window.addEventListener("online", function () { self.startBackgroundUpdate(); }, false); window.addEventListener("offline", function () { if (self.connected) { clearTimeout(self._disconnectTimeout); self._sid = null; self.deviceInfo.loggedIn = false; self.tasks = []; self.connected = false; self.trigger(["connectionLost", "tasksUpdated"]); } self.stopBackgroundUpdate(); }, false); } DownloadStation.prototype._setStatus = function (newStatus) { if (newStatus !== this.deviceInfo.status) { this.deviceInfo.status = newStatus; this.trigger("connectionStatusUpdated"); } }; DownloadStation.prototype._isTorrentOrNzbUrl = function (url, username, password, callback) { url = $.trim(url); // Only check for protocol schemes that Chrome extensions can make XHR calls for if (url.toLowerCase().substr(0, 7) !== "http://" && url.toLowerCase().substr(0, 8) !== "https://" && url.toLowerCase().substr(0, 6) !== "ftp://") { callback(false); return; } if (url.indexOf("http://dl.rutracker.org/forum/dl.php?t=") === 0) { callback(true); return; } var xhr = $.ajax({ url: url, username: username, password: password, timeout: 5000, type: "HEAD" }); xhr.done(function () { var contentType = xhr.getResponseHeader('Content-Type') || ''; var contentLength = xhr.getResponseHeader('Content-Length'); var urlWithoutParameters = url.removeUrlParameters(); var fileSize = (typeof contentLength === 'number') ? contentLength : 0; var isTorrentFile = (contentType.toLowerCase().indexOf('application/x-bittorrent') != -1) || urlWithoutParameters.toLowerCase().substr(-8, 8) == '.torrent'; var isNzbFile = (contentType.toLowerCase().indexOf('application/x-nzb') != -1) || urlWithoutParameters.toLowerCase().substr(-4, 4) == '.nzb'; if ((isTorrentFile || isNzbFile) && fileSize < 2480000) callback(true); else callback(false); }) .fail(function () { callback(false); }); }; DownloadStation.prototype._getDsmVersionString = function (number) { if (isNaN(number)) return "unknown version"; else if (number < 803) return "2.0"; else if (number < 959) return "2.1"; else if (number < 1118) return "2.2"; else if (number < 1285) return "2.3"; else if (number < 1553) return "3.0"; else if (number < 1869) return "3.1"; else if (number < 2166) return "3.2"; else if (number < 2300) return "4.0"; else if (number < 3100) return "4.1"; else if (number < 3700) return "4.2"; else if (number < 4000) return "4.3"; else return "5.0 or later"; }; DownloadStation.prototype._bytesToString = function (bytes) { var KILOBYTE = 1024; var MEGABYTE = KILOBYTE * 1024; var GIGABYTE = MEGABYTE * 1024; var TERABYTE = GIGABYTE * 1024; if (isNaN(bytes)) { return "0"; } if (bytes < KILOBYTE) { return Math.round(bytes * 100) / 100 + ' B'; } else if (bytes < MEGABYTE) { return Math.round(bytes / KILOBYTE * 100) / 100 + ' KB'; } else if (bytes < GIGABYTE) { return Math.round(bytes / MEGABYTE * 100) / 100 + ' MB'; } else if (bytes < TERABYTE) { return Math.round(bytes / GIGABYTE * 100) / 100 + ' GB'; } else { return Math.round(bytes / TERABYTE * 100) / 100 + ' TB'; } }; DownloadStation.prototype._stringToBytes = function (size) { var KILOBYTE = 1024; var MEGABYTE = KILOBYTE * 1024; var GIGABYTE = MEGABYTE * 1024; var TERABYTE = GIGABYTE * 1024; var unit = size.substr(-2); var factor = 1; switch (unit) { case "TB": factor = TERABYTE; break; case "GB": factor = GIGABYTE; break; case "MB": factor = MEGABYTE; break; case "KB": factor = KILOBYTE; break; } size = size.replace(/[A-Za-z\s]+/g, ''); var bytes = parseFloat(size) * factor; if (isNaN(bytes)) return 0; return Math.round(bytes); }; DownloadStation.prototype.addEventListener = function (type, listener) { if (Array.isArray(type)) { for (var i = 0; i < type.length; i++) { this.addEventListener(type[i], listener); } return; } var eventType = type; if (typeof this._listeners[eventType] === 'undefined') this._listeners[eventType] = []; this._listeners[eventType].push(listener); }; DownloadStation.prototype.removeEventListener = function (type, listener) { if (Array.isArray(this._listeners[type])) { var listeners = this._listeners[type]; for (var i = 0, len = listeners.length; i < len; i++) { if (listeners[i] === listener) { listeners.splice(i, 1); break; } } } }; DownloadStation.prototype.trigger = function (event) { if (Array.isArray(event)) { for (var i = 0; i < event.length; i++) { this.trigger(event[i]); } return; } var eventObj = { type: event }; if (!eventObj.target) eventObj.target = this; if (!eventObj.type) throw new Error("Event object missing 'type' property."); if (Array.isArray(this._listeners[eventObj.type])) { var listeners = this._listeners[eventObj.type]; for (var i = 0, len = listeners.length; i < len; i++) { listeners[i].call(this, eventObj); } } }; DownloadStation.prototype.startBackgroundUpdate = function (seconds) { var _this = this; var self = this; // Clear old interval this.stopBackgroundUpdate(); var newInterval = null; if (typeof seconds === "number") newInterval = seconds; else if (this._settings.updateInBackground) newInterval = this._settings.backgroundUpdateInterval; if (newInterval !== null) { var loading = true; this._interval = setInterval(function () { if (!loading) { _this.loadTasks(function (success, data) { loading = false; }); } }, newInterval * 1000); this.loadTasks(function (success, data) { loading = false; }); } }; DownloadStation.prototype.stopBackgroundUpdate = function () { clearInterval(this._interval); }; DownloadStation.prototype.setBackgroundUpdate = function (updateInBackground, newIntervalSeconds) { this._settings.backgroundUpdateInterval = newIntervalSeconds; this._settings.updateInBackground = updateInBackground; this.stopBackgroundUpdate(); this.startBackgroundUpdate(); }; DownloadStation.prototype.createTask = function (url, username, password, unzipPassword, destinationFolder, callback) { var _this = this; var urls = this.extractURLs(url); var urlTasks = new Array(); var fileTasks = new Array(); var typeCheckResultCount = 0; $.each(urls, function (i, url) { _this._isTorrentOrNzbUrl(url, username, password, function (result) { if (result) fileTasks.push(url); else urlTasks.push(url); typeCheckResultCount++; if (typeCheckResultCount < urls.length) return; var fileTasksFinished = (fileTasks.length == 0); var urlTasksFinished = (urlTasks.length == 0); var overallResult = true; var createResultHandler = function (success, data) { if (success == false) overallResult = false; if (fileTasksFinished && urlTasksFinished && typeof callback === "function") { callback(overallResult, data); } }; if (urlTasks.length > 0) { _this.createTaskFromUrl(urlTasks, username, password, unzipPassword, destinationFolder, function (success, data) { urlTasksFinished = true; createResultHandler(success, data); }); } if (fileTasks.length > 0) { var fileTasksResult = true; var fileTasksCounter = 0; var fileTaskAddCallback = function (success, data) { fileTasksCounter++; if (success == false) fileTasksResult = false; if (fileTasksCounter == fileTasks.length) { fileTasksFinished = true; createResultHandler(fileTasksResult, data); } }; $.each(fileTasks, function (j, fileTask) { _this._downloadFile(fileTask, username, password, function (success, file) { if (success === true) _this.createTaskFromFile(file, unzipPassword, destinationFolder, fileTaskAddCallback); else _this.createTaskFromUrl(url, username, password, unzipPassword, destinationFolder, fileTaskAddCallback); }); }); } }); }); }; DownloadStation.prototype._downloadFile = function (url, username, password, callback) { var _this = this; try { var xhr = new XMLHttpRequest(); xhr.open('GET', url, true, username, password); xhr.responseType = 'arraybuffer'; xhr.onload = function () { if (xhr.status >= 200 && xhr.status < 300) { var filename = _this._getFilenameFromContentDisposition(xhr.getResponseHeader("Content-Disposition")); if (!filename) filename = url.removeUrlParameters().substring(url.lastIndexOf('/') + 1); var contentType = xhr.getResponseHeader('Content-Type') || "application/octet-stream"; var file = new DSFile(filename, contentType, xhr.response, url); if (file.isValidFile()) { callback(true, file); } else { callback(false); } } else callback(false); }; xhr.onerror = function () { callback(false); }; xhr.send(); } catch (exc) { callback(false); } }; DownloadStation.prototype._getFilenameFromContentDisposition = function (contentDisposition) { if (!contentDisposition || contentDisposition.indexOf("filename=") === -1) return null; var filename = contentDisposition.split('filename=')[1]; if (filename.indexOf('"') !== -1) { filename = filename.split('"')[1]; } else { filename = filename.split(" ")[0]; } return filename; }; DownloadStation.prototype.extractURLs = function (text) { var patt = new RegExp("(https?|magnet|thunder|flashget|qqdl|s?ftps?|ed2k)(://|:?)\\S+", "ig"); var urls = new Array(); do { var result = patt.exec(text); if (result != null) { var url = result[0]; if (url.charAt(url.length - 1) === ",") url = url.substring(0, url.length - 1); urls.push(url); } } while (result != null); if (urls.length > 0) return urls; else return [text]; }; DownloadStation.prototype.getFinishedTasks = function () { var finishedTasks = new Array(); for (var i = 0; i < this.tasks.length; i++) { var task = this.tasks[i]; if (task.status == "finished" || (task.sizeDownloaded >= task.size && task.status == "seeding")) finishedTasks.push(task); } return finishedTasks; }; DownloadStation.prototype.destroy = function (callback) { var _this = this; this.logout(function () { _this.connected = false; _this.trigger("destroy"); if (callback) { callback(); } }); }; return DownloadStation; }()); var DSFile = (function () { function DSFile(filename, mimeType, data, url) { this.blob = null; this.filename = $.trim(filename); this.mimeType = mimeType; this.url = url; this.data = data; // Fix filename if (this.mimeType == "application/x-bittorrent" && this.filename.substr(-8, 8).toLowerCase() != ".torrent") this.filename = "download.torrent"; else if (this.mimeType == "application/x-nzb" && this.filename.substr(-4, 4).toLowerCase() != ".nzb") this.filename = "download.nzb"; // Fix mime-type if (this.filename.substr(-8, 8).toLowerCase() == '.torrent') this.mimeType = "application/x-bittorrent"; else if (this.filename.substr(-4, 4).toLowerCase() == ".nzb") this.mimeType = "application/x-nzb"; } DSFile.prototype.isValidFile = function () { if (this.mimeType != "application/x-nzb" && this.mimeType != "application/x-bittorrent" && this.filename.substr(-8, 8).toLowerCase() != '.torrent' && this.filename.substr(-4, 4).toLowerCase() != ".nzb") { return false; } else if (this.getBlob() == null) { return false; } return true; }; DSFile.prototype.getBlob = function () { if (this.blob instanceof Blob === false) this.createBlob(); return this.blob; }; DSFile.prototype.createBlob = function () { try { this.blob = new Blob([this.data], { type: this.mimeType }); } catch (e) { console.log("Blob constructor not supported, falling back to BlobBuilder"); // Old browsers var w = window; var blobBuilder = w.BlobBuilder || w.WebKitBlobBuilder || w.MozBlobBuilder || w.MSBlobBuilder; if (w.BlobBuilder) { try { var bb = new blobBuilder(); bb.append(this.data); this.blob = bb.getBlob(this.mimeType); } catch (bbException) { console.warn("Error in BlobBuilder"); console.log(bbException); } } else { console.log("BlobBuilder not supported"); } } }; return DSFile; }()); //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbImpzL2Rvd25sb2Fkc3RhdGlvbi50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiQUE4Q0E7SUFvQkkseUJBQVksT0FBaUM7UUFsQm5DLFNBQUksR0FBVyxJQUFJLENBQUM7UUFDdEIsY0FBUyxHQUFXLElBQUksQ0FBQztRQUN2Qix1QkFBa0IsR0FBVyxJQUFJLENBQUM7UUFDbEMsZUFBVSxHQUFZLEtBQUssQ0FB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9ydW0vZGwucGhwP3Q9XCIpID09PSAwKSB7XG4gICAgICAgICAgICBjYWxsYmFjayh0cnVlKTtcbiAgICAgICAgICAgIHJldHVybjtcbiAgICAgICAgfVxuICAgICAgICBcbiAgICBcbiAgICAgICAgdmFyIHhociA9ICQuYWpheCh7XG4gICAgICAgICAgICB1cmw6IHVybCxcbiAgICAgICAgICAgIHVzZXJuYW1lOiB1c2VybmFtZSxcbiAgICAgICAgICAgIHBhc3N3b3JkOiBwYXNzd29yZCxcbiAgICAgICAgICAgIHRpbWVvdXQ6IDUwMDAsXG4gICAgICAgICAgICB0eXBlOiBcIkhFQURcIlxuICAgICAgICB9KTtcbiAgICAgICAgeGhyLmRvbmUoZnVuY3Rpb24gKCkge1xuICAgICAgICAgICAgdmFyIGNvbnRlbnRUeXBlID0geGhyLmdldFJlc3BvbnNlSGVhZGVyKCdDb250ZW50LVR5cGUnKSB8fCAnJztcbiAgICAgICAgICAgIHZhciBjb250ZW50TGVuZ3RoID0geGhyLmdldFJlc3BvbnNlSGVhZGVyKCdDb250ZW50LUxlbmd0aCcpO1xuICAgICAgICAgICAgdmFyIHVybFdpdGhvdXRQYXJhbWV0ZXJzOiBzdHJpbmcgPSAoPGFueT51cmwpLnJlbW92ZVVybFBhcmFtZXRlcnMoKTtcbiAgICBcbiAgICAgICAgICAgIHZhciBmaWxlU2l6ZSA9ICh0eXBlb2YgY29udGVudExlbmd0aCA9PT0gJ251bWJlcicpID8gY29udGVudExlbmd0aCA6IDA7XG4gICAgICAgICAgICB2YXIgaXNUb3JyZW50RmlsZSA9IChjb250ZW50VHlwZS50b0xvd2VyQ2FzZSgpLmluZGV4T2YoJ2FwcGxpY2F0aW9uL3gtYml0dG9ycmVudCcpICE9IC0xKSB8fCB1cmxXaXRob3V0UGFyYW1ldGVycy50b0xvd2VyQ2FzZSgpLnN1YnN0cigtOCwgOCkgPT0gJy50b3JyZW50JztcbiAgICAgICAgICAgIHZhciBpc056YkZpbGUgPSAoY29udGVudFR5cGUudG9Mb3dlckNhc2UoKS5pbmRleE9mKCdhcHBsaWNhdGlvbi94LW56YicpICE9IC0xKSB8fCB1cmxXaXRob3V0UGFyYW1ldGVycy50b0xvd2VyQ2FzZSgpLnN1YnN0cigtNCwgNCkgPT0gJy5uemInO1xuICAgIFxuICAgICAgICAgICAgaWYgKChpc1RvcnJlbnRGaWxlIHx8IGlzTnpiRmlsZSkgJiYgZmlsZVNpemUgPCAyNDgwMDAwKVxuICAgICAgICAgICAgICAgIGNhbGxiYWNrKHRydWUpO1xuICAgICAgICAgICAgZWxzZVxuICAgICAgICAgICAgICAgIGNhbGxiYWNrKGZhbHNlKTtcbiAgICAgICAgfSlcbiAgICAgICAgLmZhaWwoZnVuY3Rpb24gKCkge1xuICAgICAgICAgICAgY2FsbGJhY2soZmFsc2UpO1xuICAgICAgICB9KTtcbiAgICB9XG4gICAgXG4gICAgcHJvdGVjdGVkIF9nZXREc21WZXJzaW9uU3RyaW5nKG51bWJlcjogbnVtYmVyKSB7XG4gICAgICAgIGlmIChpc05hTihudW1iZXIpKVxuICAgICAgICAgICAgcmV0dXJuIFwidW5rbm93biB2ZXJzaW9uXCI7XG4gICAgICAgIGVsc2UgaWYgKG51bWJlciA8IDgwMylcbiAgICAgICAgICAgIHJldHVybiBcIjIuMFwiO1xuICAgICAgICBlbHNlIGlmIChudW1iZXIgPCA5NTkpXG4gICAgICAgICAgICByZXR1cm4gXCIyLjFcIjtcbiAgICAgICAgZWxzZSBpZiAobnVtYmVyIDwgMTExOClcbiAgICAgICAgICAgIHJldHVybiBcIjIuMlwiO1xuICAgICAgICBlbHNlIGlmIChudW1iZXIgPCAxMjg1KVxuICAgICAgICAgICAgcmV0dXJuIFwiMi4zXCI7XG4gICAgICAgIGVsc2UgaWYgKG51bWJlciA8IDE1NTMpXG4gICAgICAgICAgICByZXR1cm4gXCIzLjBcIjtcbiAgICAgICAgZWxzZSBpZiAobnVtYmVyIDwgMTg2OSlcbiAgICAgICAgICAgIHJldHVybiBcIjMuMVwiO1xuICAgICAgICBlbHNlIGlmIChudW1iZXIgPCAyMTY2KVxuICAgICAgICAgICAgcmV0dXJuIFwiMy4yXCI7XG4gICAgICAgIGVsc2UgaWYgKG51bWJlciA8IDIzMDApXG4gICAgICAgICAgICByZXR1cm4gXCI0LjBcIjtcbiAgICAgICAgZWxzZSBpZiAobnVtYmVyIDwgMzEwMClcbiAgICAgICAgICAgIHJldHVybiBcIjQuMVwiO1xuICAgICAgICBlbHNlIGlmIChudW1iZXIgPCAzNzAwKVxuICAgICAgICAgICAgcmV0dXJuIFwiNC4yXCI7XG4gICAgICAgIGVsc2UgaWYgKG51bWJlciA8IDQwMDApXG4gICAgICAgICAgICByZXR1cm4gXCI0LjNcIjtcbiAgICAgICAgZWxzZVxuICAgICAgICAgICAgcmV0dXJuIFwiNS4wIG9yIGxhdGVyXCI7XG4gICAgfVxuICAgIFxuICAgIHByb3RlY3RlZCBfYnl0ZXNUb1N0cmluZyhieXRlczogbnVtYmVyKSB7XG4gICAgICAgIHZhciBLSUxPQllURSA9IDEwMjQ7XG4gICAgICAgIHZhciBNRUdBQllURSA9IEtJTE9CWVRFICogMTAyNDtcbiAgICAgICAgdmFyIEdJR0FCWVRFID0gTUVHQUJZVEUgKiAxMDI0O1xuICAgICAgICB2YXIgVEVSQUJZVEUgPSBHSUdBQllURSAqIDEwMjQ7XG4gICAgXG4gICAgICAgIGlmIChpc05hTihieXRlcykpIHtcbiAgICAgICAgICAgIHJldHVybiBcIjBcIjtcbiAgICAgICAgfSBpZiAoYnl0ZXMgPCBLSUxPQllURSkge1xuICAgICAgICAgICAgcmV0dXJuIE1hdGgucm91bmQoYnl0ZXMgKiAxMDApIC8gMTAwICsgJyBCJztcbiAgICAgICAgfSBlbHNlIGlmIChieXRlcyA8IE1FR0FCWVRFKSB7XG4gICAgICAgICAgICByZXR1cm4gTWF0aC5yb3VuZChieXRlcyAvIEtJTE9CWVRFICogMTAwKSAvIDEwMCArICcgS0InO1xuICAgICAgICB9IGVsc2UgaWYgKGJ5dGVzIDwgR0lHQUJZVEUpIHtcbiAgICAgICAgICAgIHJldHVybiBNYXRoLnJvdW5kKGJ5dGVzIC8gTUVHQUJZVEUgKiAxMDApIC8gMTAwICsgJyBNQic7XG4gICAgICAgIH0gZWxzZSBpZiAoYnl0ZXMgPCBURVJBQllURSkge1xuICAgICAgICAgICAgcmV0dXJuIE1hdGgucm91bmQoYnl0ZXMgLyBHSUdBQllURSAqIDEwMCkgLyAxMDAgKyAnIEdCJztcbiAgICAgICAgfSBlbHNlIHtcbiAgICAgICAgICAgIHJldHVybiBNYXRoLnJvdW5kKGJ5dGVzIC8gVEVSQUJZVEUgKiAxMDApIC8gMTAwICsgJyBUQic7XG4gICAgICAgIH1cbiAgICB9XG4gICAgXG4gICAgcHJpdmF0ZSBfc3RyaW5nVG9CeXRlcyhzaXplOiBzdHJpbmcpIHtcbiAgICAgICAgdmFyIEtJTE9CWVRFID0gMTAyNDtcbiAgICAgICAgdmFyIE1FR0FCWVRFID0gS0lMT0JZVEUgKiAxMDI0O1xuICAgICAgICB2YXIgR0lHQUJZVEUgPSBNRUdBQllURSAqIDEwMjQ7XG4gICAgICAgIHZhciBURVJBQllURSA9IEdJR0FCWVRFICogMTAyNDtcbiAgICAgICAgXG4gICAgICAgIHZhciB1bml0ID0gc2l6ZS5zdWJzdHIoLTIpO1xuICAgICAgICB2YXIgZmFjdG9yID0gMTtcbiAgICAgICAgXG4gICAgICAgIHN3aXRjaCAodW5pdCkge1xuICAgICAgICAgICAgY2FzZSBcIlRCXCI6XG4gICAgICAgICAgICBmYWN0b3IgPSBURVJBQllURTtcbiAgICAgICAgICAgIGJyZWFrO1xuICAgICAgICAgICAgY2FzZSBcIkdCXCI6XG4gICAgICAgICAgICBmYWN0b3IgPSBHSUdBQllURTtcbiAgICAgICAgICAgIGJyZWFrO1xuICAgICAgICAgICAgY2FzZSBcIk1CXCI6XG4gICAgICAgICAgICBmYWN0b3IgPSBNRUdBQllURTtcbiAgICAgICAgICAgIGJyZWFrO1xuICAgICAgICAgICAgY2FzZSBcIktCXCI6XG4gICAgICAgICAgICBmYWN0b3IgPSBLSUxPQllURTtcbiAgICAgICAgICAgIGJyZWFrO1xuICAgICAgICB9XG4gICAgICAgIFxuICAgICAgICBzaXplID0gc2l6ZS5yZXBsYWNlKC9bQS1aYS16XFxzXSsvZywgJycpO1xuICAgICAgICB2YXIgYnl0ZXMgPSBwYXJzZUZsb2F0KHNpemUpICogZmFjdG9yO1xuICAgICAgICBcbiAgICAgICAgaWYoaXNOYU4oYnl0ZXMpKVxuICAgICAgICAgICAgcmV0dXJuIDA7XG4gICAgICAgIFxuICAgICAgICByZXR1cm4gTWF0aC5yb3VuZChieXRlcyk7XG4gICAgfVxuICAgIFxuICAgIHB1YmxpYyBhZGRFdmVudExpc3RlbmVyKHR5cGU6IHN0cmluZ3xBcnJheTxzdHJpbmc+LCBsaXN0ZW5lcjogKCkgPT4gdm9pZCkge1xuICAgICAgICBpZihBcnJheS5pc0FycmF5KHR5cGUpKVxuICAgICAgICB7XG4gICAgICAgICAgICBmb3IodmFyIGkgPSAwOyBpIDwgdHlwZS5sZW5ndGg7IGkrKylcbiAgICAgICAgICAgIHtcbiAgICAgICAgICAgICAgICB0aGlzLmFkZEV2ZW50TGlzdGVuZXIodHlwZVtpXSwgbGlzdGVuZXIpO1xuICAgICAgICAgICAgfVxuICAgICAgICAgICAgcmV0dXJuO1xuICAgICAgICB9XG4gICAgICAgIFxuICAgICAgICB2YXIgZXZlbnRUeXBlID0gPHN0cmluZz50eXBlO1xuICAgICAgICBpZiAodHlwZW9mIHRoaXMuX2xpc3RlbmVyc1tldmVudFR5cGVdID09PSAndW5kZWZpbmVkJylcbiAgICAgICAgICAgIHRoaXMuX2xpc3RlbmVyc1tldmVudFR5cGVdID0gW107XG4gICAgXG4gICAgICAgIHRoaXMuX2xpc3RlbmVyc1tldmVudFR5cGVdLnB1c2gobGlzdGVuZXIpO1xuICAgIH1cbiAgICBcbiAgICBwdWJsaWMgcmVtb3ZlRXZlbnRMaXN0ZW5lcih0eXBlOiBzdHJpbmcsIGxpc3RlbmVyOiAoKSA9PiB2b2lkKSB7XG4gICAgICAgIGlmIChBcnJheS5pc0FycmF5KHRoaXMuX2xpc3RlbmVyc1t0eXBlXSkpIHtcbiAgICAgICAgICAgIHZhciBsaXN0ZW5lcnMgPSB0aGlzLl9saXN0ZW5lcnNbdHlwZV07XG4gICAgICAgICAgICBmb3IgKHZhciBpID0gMCwgbGVuID0gbGlzdGVuZXJzLmxlbmd0aDsgaSA8IGxlbjsgaSsrKSB7XG4gICAgICAgICAgICAgICAgaWYgKGxpc3RlbmVyc1tpXSA9PT0gbGlzdGVuZXIpIHtcbiAgICAgICAgICAgICAgICAgICAgbGlzdGVuZXJzLnNwbGljZShpLCAxKTtcbiAgICAgICAgICAgICAgICAgICAgYnJlYWs7XG4gICAgICAgICAgICAgICAgfVxuICAgICAgICAgICAgfVxuICAgICAgICB9XG4gICAgfVxuICAgIFxuICAgIHB1YmxpYyB0cmlnZ2VyKGV2ZW50OiBhbnkpIHtcbiAgICAgICAgaWYoQXJyYXkuaXNBcnJheShldmVudCkpXG4gICAgICAgIHtcbiAgICAgICAgICAgIGZvcih2YXIgaSA9IDA7IGkgPCBldmVudC5sZW5ndGg7IGkrKylcbiAgICAgICAgICAgIHtcbiAgICAgICAgICAgICAgICB0aGlzLnRyaWdnZXIoZXZlbnRbaV0pO1xuICAgICAgICAgICAgfVxuICAgICAgICAgICAgcmV0dXJuO1xuICAgICAgICB9XG4gICAgICAgIFxuICAgICAgICB2YXIgZXZlbnRPYmo6IGFueSA9IHsgdHlwZTogZXZlbnQgfTtcbiAgICBcbiAgICAgICAgaWYgKCFldmVudE9iai50YXJnZXQpXG4gICAgICAgICAgICBldmVudE9iai50YXJnZXQgPSB0aGlzO1xuICAgIFxuICAgICAgICBpZiAoIWV2ZW50T2JqLnR5cGUpXG4gICAgICAgICAgICB0aHJvdyBuZXcgRXJyb3IoXCJFdmVudCBvYmplY3QgbWlzc2luZyAndHlwZScgcHJvcGVydHkuXCIpO1xuICAgIFxuICAgICAgICBpZiAoQXJyYXkuaXNBcnJheSh0aGlzLl9saXN0ZW5lcnNbZXZlbnRPYmoudHlwZV0pKSB7XG4gICAgICAgICAgICB2YXIgbGlzdGVuZXJzID0gdGhpcy5fbGlzdGVuZXJzW2V2ZW50T2JqLnR5cGVdO1xuICAgICAgICAgICAgZm9yICh2YXIgaSA9IDAsIGxlbiA9IGxpc3RlbmVycy5sZW5ndGg7IGkgPCBsZW47IGkrKykge1xuICAgICAgICAgICAgICAgIGxpc3RlbmVyc1tpXS5jYWxsKHRoaXMsIGV2ZW50T2JqKTtcbiAgICAgICAgICAgIH1cbiAgICAgICAgfVxuICAgIH1cblxuICAgIHB1YmxpYyBzdGFydEJhY2tncm91bmRVcGRhdGUoc2Vjb25kcz86IG51bWJlcikge1xuICAgICAgICB2YXIgc2VsZiA9IHRoaXM7XG4gICAgICAgIC8vIENsZWFyIG9sZCBpbnRlcnZhbFxuICAgICAgICB0aGlzLnN0b3BCYWNrZ3JvdW5kVXBkYXRlKCk7XG4gICAgXG4gICAgICAgIHZhciBuZXdJbnRlcnZhbDogbnVtYmVyID0gbnVsbDtcbiAgICAgICAgaWYgKHR5cGVvZiBzZWNvbmRzID09PSBcIm51bWJlclwiKVxuICAgICAgICAgICAgbmV3SW50ZXJ2YWwgPSBzZWNvbmRzO1xuICAgICAgICBlbHNlIGlmICh0aGlzLl9zZXR0aW5ncy51cGRhdGVJbkJhY2tncm91bmQpXG4gICAgICAgICAgICBuZXdJbnRlcnZhbCA9IHRoaXMuX3NldHRpbmdzLmJhY2tncm91bmRVcGRhdGVJbnRlcnZhbDtcbiAgICBcbiAgICAgICAgaWYgKG5ld0ludGVydmFsICE9PSBudWxsKSB7XG4gICAgICAgICAgICB2YXIgbG9hZGluZyA9IHRydWU7XG4gICAgICAgICAgICB0aGlzLl9pbnRlcnZhbCA9ICg8YW55PnNldEludGVydmFsKCgpID0+IHtcbiAgICAgICAgICAgICAgICBpZighbG9hZGluZylcbiAgICAgICAgICAgICAgICB7XG4gICAgICAgICAgICAgICAgICAgIHRoaXMubG9hZFRhc2tzKChzdWNjZXNzLCBkYXRhKSA9PiB7XG4gICAgICAgICAgICAgICAgICAgICAgICBsb2FkaW5nID0gZmFsc2U7XG4gICAgICAgICAgICAgICAgICAgIH0pO1xuICAgICAgICAgICAgICAgIH1cbiAgICAgICAgICAgIH0sIG5ld0ludGVydmFsICogMTAwMCkpO1xuICAgICAgICAgICAgXG4gICAgICAgICAgICB0aGlzLmxvYWRUYXNrcygoc3VjY2VzcywgZGF0YSkgPT4ge1xuICAgICAgICAgICAgICAgIGxvYWRpbmcgPSBmYWxzZTtcbiAgICAgICAgICAgIH0pO1xuICAgICAgICB9XG4gICAgfVxuICAgIFxuICAgIHB1YmxpYyBzdG9wQmFja2dyb3VuZFVwZGF0ZSgpIHtcbiAgICAgICAgY2xlYXJJbnRlcnZhbCh0aGlzLl9pbnRlcnZhbCk7XG4gICAgfVxuICAgIFxuICAgIHB1YmxpYyBzZXRCYWNrZ3JvdW5kVXBkYXRlKHVwZGF0ZUluQmFja2dyb3VuZDogYm9vbGVhbiwgbmV3SW50ZXJ2YWxTZWNvbmRzOiBudW1iZXIpIHtcbiAgICAgICAgdGhpcy5fc2V0dGluZ3MuYmFja2dyb3VuZFVwZGF0ZUludGVydmFsID0gbmV3SW50ZXJ2YWxTZWNvbmRzO1xuICAgICAgICB0aGlzLl9zZXR0aW5ncy51cGRhdGVJbkJhY2tncm91bmQgPSB1cGRhdGVJbkJhY2tncm91bmQ7XG4gICAgICAgIFxuICAgICAgICB0aGlzLnN0b3BCYWNrZ3JvdW5kVXBkYXRlKCk7XG4gICAgICAgIHRoaXMuc3RhcnRCYWNrZ3JvdW5kVXBkYXRlKCk7XG4gICAgfVxuICAgIFxuICAgIHB1YmxpYyBjcmVhdGVUYXNrKHVybDogc3RyaW5nLCB1c2VybmFtZTogc3RyaW5nLCBwYXNzd29yZDogc3RyaW5nLCB1bnppcFBhc3N3b3JkOiBzdHJpbmcsIGRlc3RpbmF0aW9uRm9sZGVyOiBzdHJpbmcsIGNhbGxiYWNrOiAoc3VjY2VzczogYm9vbGVhbiwgcmVzdWx0OiBhbnkgfCBzdHJpbmcpID0+IHZvaWQpIHtcbiAgICAgICAgdmFyIHVybHMgPSB0aGlzLmV4dHJhY3RVUkxzKHVybCk7XG4gICAgICAgIHZhciB1cmxUYXNrcyA9IG5ldyBBcnJheTxzdHJpbmc+KCk7XG4gICAgICAgIHZhciBmaWxlVGFza3MgPSBuZXcgQXJyYXk8c3RyaW5nPigpO1xuICAgICAgICB2YXIgdHlwZUNoZWNrUmVzdWx0Q291bnQgPSAwO1xuICAgIFxuICAgICAgICAkLmVhY2godXJscywgKGksIHVybCkgPT4ge1xuICAgICAgICAgICAgdGhpcy5faXNUb3JyZW50T3JOemJVcmwodXJsLCB1c2VybmFtZSwgcGFzc3dvcmQsIChyZXN1bHQpID0+IHtcbiAgICAgICAgICAgICAgICBpZiAocmVzdWx0KVxuICAgICAgICAgICAgICAgICAgICBmaWxlVGFza3MucHVzaCh1cmwpO1xuICAgICAgICAgICAgICAgIGVsc2VcbiAgICAgICAgICAgICAgICAgICAgdXJsVGFza3MucHVzaCh1cmwpO1xuICAgIFxuICAgICAgICAgICAgICAgIHR5cGVDaGVja1Jlc3VsdENvdW50Kys7XG4gICAgXG4gICAgICAgICAgICAgICAgaWYgKHR5cGVDaGVja1Jlc3VsdENvdW50IDwgdXJscy5sZW5ndGgpXG4gICAgICAgICAgICAgICAgICAgIHJldHVybjtcbiAgICBcbiAgICAgICAgICAgICAgICB2YXIgZmlsZVRhc2tzRmluaXNoZWQgPSAoZmlsZVRhc2tzLmxlbmd0aCA9PSAwKTtcbiAgICAgICAgICAgICAgICB2YXIgdXJsVGFza3NGaW5pc2hlZCA9ICh1cmxUYXNrcy5sZW5ndGggPT0gMCk7XG4gICAgICAgICAgICAgICAgdmFyIG92ZXJhbGxSZXN1bHQgPSB0cnVlO1xuICAgIFxuICAgICAgICAgICAgICAgIHZhciBjcmVhdGVSZXN1bHRIYW5kbGVyID0gKHN1Y2Nlc3M6IGJvb2xlYW4sIGRhdGE6IGFueSkgPT4ge1xuICAgICAgICAgICAgICAgICAgICBpZiAoc3VjY2VzcyA9PSBmYWxzZSlcbiAgICAgICAgICAgICAgICAgICAgICAgIG92ZXJhbGxSZXN1bHQgPSBmYWxzZTtcbiAgICBcbiAgICAgICAgICAgICAgICAgICAgaWYgKGZpbGVUYXNrc0ZpbmlzaGVkICYmIHVybFRhc2tzRmluaXNoZWQgJiYgdHlwZW9mIGNhbGxiYWNrID09PSBcImZ1bmN0aW9uXCIpIHtcbiAgICAgICAgICAgICAgICAgICAgICAgIGNhbGxiYWNrKG92ZXJhbGxSZXN1bHQsIGRhdGEpO1xuICAgICAgICAgICAgICAgICAgICB9XG4gICAgICAgICAgICAgICAgfVxuICAgIFxuICAgICAgICAgICAgICAgIGlmICh1cmxUYXNrcy5sZW5ndGggPiAwKSB7XG4gICAgICAgICAgICAgICAgICAgIHRoaXMuY3JlYXRlVGFza0Zyb21VcmwodXJsVGFza3MsIHVzZXJuYW1lLCBwYXNzd29yZCwgdW56aXBQYXNzd29yZCwgZGVzdGluYXRpb25Gb2xkZXIsIChzdWNjZXNzLCBkYXRhKSA9PiB7XG4gICAgICAgICAgICAgICAgICAgICAgICB1cmxUYXNrc0ZpbmlzaGVkID0gdHJ1ZTtcbiAgICAgICAgICAgICAgICAgICAgICAgIGNyZWF0ZVJlc3VsdEhhbmRsZXIoc3VjY2VzcywgZGF0YSk7XG4gICAgICAgICAgICAgICAgICAgIH0pO1xuICAgICAgICAgICAgICAgIH1cbiAgICBcbiAgICAgICAgICAgICAgICBpZiAoZmlsZVRhc2tzLmxlbmd0aCA+IDApIHtcbiAgICAgICAgICAgICAgICAgICAgdmFyIGZpbGVUYXNrc1Jlc3VsdCA9IHRydWU7XG4gICAgICAgICAgICAgICAgICAgIHZhciBmaWxlVGFza3NDb3VudGVyID0gMDtcbiAgICBcbiAgICAgICAgICAgICAgICAgICAgdmFyIGZpbGVUYXNrQWRkQ2FsbGJhY2sgPSAoc3VjY2VzczogYm9vbGVhbiwgZGF0YTogYW55KSA9PiB7XG4gICAgICAgICAgICAgICAgICAgICAgICBmaWxlVGFza3NDb3VudGVyKys7XG4gICAgICAgICAgICAgICAgICAgICAgICBpZiAoc3VjY2VzcyA9PSBmYWxzZSlcbiAgICAgICAgICAgICAgICAgICAgICAgICAgICBmaWxlVGFza3NSZXN1bHQgPSBmYWxzZTtcbiAgICAgICAgICAgICAgICAgICAgICAgIFxuICAgICAgICAgICAgICAgICAgICAgICAgaWYgKGZpbGVUYXNrc0NvdW50ZXIgPT0gZmlsZVRhc2tzLmxlbmd0aCkge1xuICAgICAgICAgICAgICAgICAgICAgICAgICAgIGZpbGVUYXNrc0ZpbmlzaGVkID0gdHJ1ZTtcbiAgICAgICAgICAgICAgICAgICAgICAgICAgICBjcmVhdGVSZXN1bHRIYW5kbGVyKGZpbGVUYXNrc1Jlc3VsdCwgZGF0YSk7XG4gICAgICAgICAgICAgICAgICAgICAgICB9XG4gICAgICAgICAgICAgICAgICAgIH07XG4gICAgXG4gICAgICAgICAgICAgICAgICAgICQuZWFjaChmaWxlVGFza3MsIChqLCBmaWxlVGFzaykgPT4ge1xuICAgICAgICAgICAgICAgICAgICAgICAgdGhpcy5fZG93bmxvYWRGaWxlKGZpbGVUYXNrLCB1c2VybmFtZSwgcGFzc3dvcmQsIChzdWNjZXNzLCBmaWxlKSA9PntcbiAgICAgICAgICAgICAgICAgICAgICAgICAgICBpZiAoc3VjY2VzcyA9PT0gdHJ1ZSlcbiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgdGhpcy5jcmVhdGVUYXNrRnJvbUZpbGUoZmlsZSwgdW56aXBQYXNzd29yZCwgZGVzdGluYXRpb25Gb2xkZXIsIGZpbGVUYXNrQWRkQ2FsbGJhY2spO1xuICAgICAgICAgICAgICAgICAgICAgICAgICAgIGVsc2VcbiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgdGhpcy5jcmVhdGVUYXNrRnJvbVVybCh1cmwsIHVzZXJuYW1lLCBwYXNzd29yZCwgdW56aXBQYXNzd29yZCwgZGVzdGluYXRpb25Gb2xkZXIsIGZpbGVUYXNrQWRkQ2FsbGJhY2spO1xuICAgICAgICAgICAgICAgICAgICAgICAgfSk7XG4gICAgICAgICAgICAgICAgICAgIH0pO1xuICAgICAgICAgICAgICAgIH1cbiAgICAgICAgICAgIH0pO1xuICAgICAgICB9KTtcbiAgICB9XG4gICAgXG4gICAgcHJpdmF0ZSBfZG93bmxvYWRGaWxlKHVybDogc3RyaW5nLCB1c2VybmFtZTogc3RyaW5nLCBwYXNzd29yZDogc3RyaW5nLCBjYWxsYmFjazogKHN1Y2Nlc3M6IGJvb2xlYW4sIGZpbGU/OiBEU0ZpbGUpID0+IHZvaWQpIHtcbiAgICAgICAgdHJ5IHtcbiAgICAgICAgICAgIHZhciB4aHIgPSBuZXcgWE1MSHR0cFJlcXVlc3QoKTtcbiAgICAgICAgICAgIHhoci5vcGVuKCdHRVQnLCB1cmwsIHRydWUsIHVzZXJuYW1lLCBwYXNzd29yZCk7XG4gICAgICAgICAgICB4aHIucmVzcG9uc2VUeXBlID0gJ2FycmF5YnVmZmVyJztcbiAgICAgICAgICAgIHhoci5vbmxvYWQgPSAoKSA9PiB7XG4gICAgICAgICAgICAgICAgaWYgKHhoci5zdGF0dXMgPj0gMjAwICYmIHhoci5zdGF0dXMgPCAzMDApIHtcbiAgICAgICAgICAgICAgICAgICAgdmFyIGZpbGVuYW1lOiBzdHJpbmcgPSB0aGlzLl9nZXRGaWxlbmFtZUZyb21Db250ZW50RGlzcG9zaXRpb24oeGhyLmdldFJlc3BvbnNlSGVhZGVyKFwiQ29udGVudC1EaXNwb3NpdGlvblwiKSk7XG4gICAgICAgICAgICAgICAgICAgIFxuICAgICAgICAgICAgICAgICAgICBpZighZmlsZW5hbWUpXG4gICAgICAgICAgICAgICAgICAgICAgICBmaWxlbmFtZSA9ICg8YW55PnVybCkucmVtb3ZlVXJsUGFyYW1ldGVycygpLnN1YnN0cmluZyh1cmwubGFzdEluZGV4T2YoJy8nKSArIDEpO1xuICAgICAgICAgICAgICAgICAgICBcbiAgICAgICAgICAgICAgICAgICAgdmFyIGNvbnRlbnRUeXBlID0geGhyLmdldFJlc3BvbnNlSGVhZGVyKCdDb250ZW50LVR5cGUnKSB8fCBcImFwcGxpY2F0aW9uL29jdGV0LXN0cmVhbVwiO1xuICAgICAgICAgICAgICAgICAgICB2YXIgZmlsZSA9IG5ldyBEU0ZpbGUoZmlsZW5hbWUsIGNvbnRlbnRUeXBlLCB4aHIucmVzcG9uc2UsIHVybCk7XG4gICAgICAgICAgICAgICAgICAgIFxuICAgICAgICAgICAgICAgICAgICBpZihmaWxlLmlzVmFsaWRGaWxlKCkpIHtcbiAgICAgICAgICAgICAgICAgICAgICAgIGNhbGxiYWNrKHRydWUsIGZpbGUpO1xuICAgICAgICAgICAgICAgICAgICB9XG4gICAgICAgICAgICAgICAgICAgIGVsc2Uge1xuICAgICAgICAgICAgICAgICAgICAgICAgY2FsbGJhY2soZmFsc2UpO1xuICAgICAgICAgICAgICAgICAgICB9XG4gICAgICAgICAgICAgICAgfVxuICAgICAgICAgICAgICAgIGVsc2VcbiAgICAgICAgICAgICAgICAgICAgY2FsbGJhY2soZmFsc2UpO1xuICAgICAgICAgICAgfTtcbiAgICAgICAgICAgIHhoci5vbmVycm9yID0gKCkgPT4ge1xuICAgICAgICAgICAgICAgIGNhbGxiYWNrKGZhbHNlKTtcbiAgICAgICAgICAgIH1cbiAgICAgICAgICAgIHhoci5zZW5kKCk7XG4gICAgICAgIH1cbiAgICAgICAgY2F0Y2ggKGV4Yykge1xuICAgICAgICAgICAgY2FsbGJhY2soZmFsc2UpO1xuICAgICAgICB9XG4gICAgfVxuICAgIFxuICAgIHByaXZhdGUgX2dldEZpbGVuYW1lRnJvbUNvbnRlbnREaXNwb3NpdGlvbiAoY29udGVudERpc3Bvc2l0aW9uOiBzdHJpbmcpOiBzdHJpbmcge1xuICAgICAgICBpZighY29udGVudERpc3Bvc2l0aW9uIHx8IGNvbnRlbnREaXNwb3NpdGlvbi5pbmRleE9mKFwiZmlsZW5hbWU9XCIpID09PSAtMSlcbiAgICAgICAgICAgIHJldHVybiBudWxsO1xuICAgICAgICBcbiAgICAgICAgdmFyIGZpbGVuYW1lID0gY29udGVudERpc3Bvc2l0aW9uLnNwbGl0KCdmaWxlbmFtZT0nKVsxXTtcbiAgICAgICAgaWYoZmlsZW5hbWUuaW5kZXhPZignXCInKSAhPT0gLTEpXG4gICAgICAgIHtcbiAgICAgICAgICAgIGZpbGVuYW1lID0gZmlsZW5hbWUuc3BsaXQoJ1wiJylbMV07XG4gICAgICAgIH1cbiAgICAgICAgZWxzZSB7XG4gICAgICAgICAgICBmaWxlbmFtZSA9IGZpbGVuYW1lLnNwbGl0KFwiIFwiKVswXTtcbiAgICAgICAgfVxuICAgICAgICByZXR1cm4gZmlsZW5hbWU7XG4gICAgfVxuICAgIFxuICAgIHByaXZhdGUgZXh0cmFjdFVSTHModGV4dDogc3RyaW5nKSB7XG4gICAgICAgIHZhciBwYXR0ID0gbmV3IFJlZ0V4cChcIihodHRwcz98bWFnbmV0fHRodW5kZXJ8Zmxhc2hnZXR8cXFkbHxzP2Z0cHM/fGVkMmspKDovL3w6PylcXFxcUytcIiwgXCJpZ1wiKTtcbiAgICAgICAgdmFyIHVybHMgPSBuZXcgQXJyYXk8c3RyaW5nPigpO1xuICAgICAgICBkbyB7XG4gICAgICAgICAgICB2YXIgcmVzdWx0ID0gcGF0dC5leGVjKHRleHQpO1xuICAgICAgICAgICAgaWYgKHJlc3VsdCAhPSBudWxsKSB7XG4gICAgICAgICAgICAgICAgdmFyIHVybCA9IHJlc3VsdFswXTtcbiAgICAgICAgICAgICAgICBpZiAodXJsLmNoYXJBdCh1cmwubGVuZ3RoIC0gMSkgPT09IFwiLFwiKVxuICAgICAgICAgICAgICAgICAgICB1cmwgPSB1cmwuc3Vic3RyaW5nKDAsIHVybC5sZW5ndGggLSAxKTtcbiAgICAgICAgICAgICAgICB1cmxzLnB1c2godXJsKTtcbiAgICAgICAgICAgIH1cbiAgICAgICAgfSB3aGlsZSAocmVzdWx0ICE9IG51bGwpO1xuICAgICAgICBpZiAodXJscy5sZW5ndGggPiAwKVxuICAgICAgICAgICAgcmV0dXJuIHVybHM7XG4gICAgICAgIGVsc2VcbiAgICAgICAgICAgIHJldHVybiBbdGV4dF07XG4gICAgfVxuICAgIFxuICAgIHB1YmxpYyBnZXRGaW5pc2hlZFRhc2tzKCk6IEFycmF5PElEb3dubG9hZFN0YXRpb25UYXNrPiB7XG4gICAgICAgIHZhciBmaW5pc2hlZFRhc2tzID0gbmV3IEFycmF5PElEb3dubG9hZFN0YXRpb25UYXNrPigpO1xuICAgICAgICBmb3IgKHZhciBpID0gMDsgaSA8IHRoaXMudGFza3MubGVuZ3RoOyBpKyspIHtcbiAgICAgICAgICAgIHZhciB0YXNrID0gdGhpcy50YXNrc1tpXTtcbiAgICAgICAgICAgIGlmICh0YXNrLnN0YXR1cyA9PSBcImZpbmlzaGVkXCIgfHwgKHRhc2suc2l6ZURvd25sb2FkZWQgPj0gdGFzay5zaXplICYmIHRhc2suc3RhdHVzID09IFwic2VlZGluZ1wiKSkgLy9DaGVjayBmb3Igc2l6ZURvd25sb2FkZWQgdG8gZGV0ZWN0IHNlZWRpbmcgdG9ycmVudHNcbiAgICAgICAgICAgICAgICBmaW5pc2hlZFRhc2tzLnB1c2godGFzayk7XG4gICAgICAgIH1cbiAgICAgICAgcmV0dXJuIGZpbmlzaGVkVGFza3M7XG4gICAgfVxuICAgIFxuICAgIHB1YmxpYyBkZXN0cm95KGNhbGxiYWNrPzogRnVuY3Rpb24pIHtcbiAgICAgICAgdGhpcy5sb2dvdXQoKCkgPT4ge1xuICAgICAgICAgICAgdGhpcy5jb25uZWN0ZWQgPSBmYWxzZTtcbiAgICAgICAgICAgIHRoaXMudHJpZ2dlcihcImRlc3Ryb3lcIik7XG4gICAgICAgICAgICBpZihjYWxsYmFjaykge1xuICAgICAgICAgICAgICAgIGNhbGxiYWNrKCk7XG4gICAgICAgICAgICB9XG4gICAgICAgIH0pO1xuICAgIH1cbn1cblxuY2xhc3MgRFNGaWxlIHsgXG4gICAgXG4gICAgcHVibGljIGZpbGVuYW1lOiBzdHJpbmc7XG4gICAgcHVibGljIG1pbWVUeXBlOiBzdHJpbmc7XG4gICAgcHVibGljIHVybDogc3RyaW5nO1xuICAgIFxuICAgIHByaXZhdGUgZGF0YTogYW55O1xuICAgIHByaXZhdGUgYmxvYjogQmxvYiA9IG51bGw7XG4gICAgXG4gICAgY29uc3RydWN0b3IoZmlsZW5hbWU6IHN0cmluZywgbWltZVR5cGU6IHN0cmluZywgZGF0YTogYW55LCB1cmw6IHN0cmluZykge1xuICAgICAgICB0aGlzLmZpbGVuYW1lID0gJC50cmltKGZpbGVuYW1lKTtcbiAgICAgICAgdGhpcy5taW1lVHlwZSA9IG1pbWVUeXBlO1xuICAgICAgICB0aGlzLnVybCA9IHVybDtcbiAgICAgICAgdGhpcy5kYXRhID0gZGF0YTtcbiAgICAgICAgXG4gICAgICAgIC8vIEZpeCBmaWxlbmFtZVxuICAgICAgICBpZih0aGlzLm1pbWVUeXBlID09IFwiYXBwbGljYXRpb24veC1iaXR0b3JyZW50XCIgJiYgdGhpcy5maWxlbmFtZS5zdWJzdHIoLTgsIDgpLnRvTG93ZXJDYXNlKCkgIT0gXCIudG9ycmVudFwiKVxuICAgICAgICAgICAgdGhpcy5maWxlbmFtZSA9IFwiZG93bmxvYWQudG9ycmVudFwiO1xuICAgICAgICBlbHNlIGlmKHRoaXMubWltZVR5cGUgPT0gXCJhcHBsaWNhdGlvbi94LW56YlwiICYmIHRoaXMuZmlsZW5hbWUuc3Vic3RyKC00LCA0KS50b0xvd2VyQ2FzZSgpICE9IFwiLm56YlwiKVxuICAgICAgICAg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xuXHRcdFx0fVxuXHRcdFx0ZWxzZSB7XG5cdFx0XHRcdGNvbnNvbGUubG9nKFwiQmxvYkJ1aWxkZXIgbm90IHN1cHBvcnRlZFwiKTtcblx0XHRcdH1cblx0XHR9XG5cdH1cbn0iXSwic291cmNlUm9vdCI6Ii9zb3VyY2UvIn0=
66,860
downloadstation
js
en
javascript
code
{"qsc_code_num_words": 1448, "qsc_code_num_chars": 66860.0, "qsc_code_mean_word_length": 40.17196133, "qsc_code_frac_words_unique": 0.21339779, "qsc_code_frac_chars_top_2grams": 0.00185666, "qsc_code_frac_chars_top_3grams": 0.00226925, "qsc_code_frac_chars_top_4grams": 0.00206295, "qsc_code_frac_chars_dupe_5grams": 0.02379274, "qsc_code_frac_chars_dupe_6grams": 0.01567845, "qsc_code_frac_chars_dupe_7grams": 0.01189637, "qsc_code_frac_chars_dupe_8grams": 0.00900823, "qsc_code_frac_chars_dupe_9grams": 0.00697966, "qsc_code_frac_chars_dupe_10grams": 0.00697966, "qsc_code_frac_chars_replacement_symbols": 0.0, "qsc_code_frac_chars_digital": 0.06719944, "qsc_code_frac_chars_whitespace": 0.09792103, "qsc_code_size_file_byte": 66860.0, "qsc_code_num_lines": 445.0, "qsc_code_num_chars_line_max": 49475.0, "qsc_code_num_chars_line_mean": 150.24719101, "qsc_code_frac_chars_alphabet": 0.89725267, "qsc_code_frac_chars_comments": 0.74216273, "qsc_code_cate_xml_start": 0.0, "qsc_code_frac_lines_dupe_lines": 0.21689498, "qsc_code_cate_autogen": 0.0, "qsc_code_frac_lines_long_string": 0.0, "qsc_code_frac_chars_string_length": 0.04936481, "qsc_code_frac_chars_long_word_length": 0.01189164, "qsc_code_frac_lines_string_concat": 0.0, "qsc_code_cate_encoded_data": 1.0, "qsc_code_frac_chars_hex_words": 0.0, "qsc_code_frac_lines_prompt_comments": 0.0, "qsc_code_frac_lines_assert": 0.0, "qsc_codejavascript_cate_ast": 1.0, "qsc_codejavascript_cate_var_zero": 0.0, "qsc_codejavascript_frac_lines_func_ratio": 0.00913242, "qsc_codejavascript_num_statement_line": 0.00456621, "qsc_codejavascript_score_lines_no_logic": 0.11187215, "qsc_codejavascript_frac_words_legal_var_name": 0.77419355, "qsc_codejavascript_frac_words_legal_func_name": 1.0, "qsc_codejavascript_frac_words_legal_class_name": null, "qsc_codejavascript_frac_lines_print": 0.00684932}
0
{"qsc_code_frac_chars_replacement_symbols": 0, "qsc_code_num_words": 0, "qsc_code_num_chars": 0, "qsc_code_mean_word_length": 1, "qsc_code_frac_chars_top_2grams": 0, "qsc_code_frac_chars_top_3grams": 0, "qsc_code_frac_chars_top_4grams": 0, "qsc_code_frac_chars_dupe_5grams": 0, "qsc_code_frac_chars_dupe_6grams": 0, "qsc_code_frac_chars_dupe_7grams": 0, "qsc_code_frac_chars_dupe_8grams": 0, "qsc_code_frac_chars_dupe_9grams": 0, "qsc_code_frac_chars_dupe_10grams": 0, "qsc_code_size_file_byte": 0, "qsc_code_num_lines": 0, "qsc_code_num_chars_line_max": 1, "qsc_code_num_chars_line_mean": 1, "qsc_code_frac_chars_alphabet": 0, "qsc_code_frac_chars_digital": 0, "qsc_code_frac_chars_whitespace": 0, "qsc_code_frac_chars_comments": 0, "qsc_code_cate_xml_start": 0, "qsc_code_frac_lines_dupe_lines": 0, "qsc_code_cate_autogen": 0, "qsc_code_frac_lines_long_string": 0, "qsc_code_frac_chars_string_length": 0, "qsc_code_frac_chars_long_word_length": 0, "qsc_code_cate_encoded_data": 1, "qsc_code_frac_chars_hex_words": 0, "qsc_code_frac_lines_prompt_comments": 0, "qsc_code_frac_lines_assert": 0, "qsc_codejavascript_cate_ast": 0, "qsc_codejavascript_cate_var_zero": 0, "qsc_codejavascript_frac_lines_func_ratio": 0, "qsc_codejavascript_score_lines_no_logic": 0, "qsc_codejavascript_frac_lines_print": 0}
007revad/Synology_Download_Station_Chrome_Extension
js/safari-contextmenu.js
document.addEventListener("contextmenu", function (event) { var onClickData = { menuItemId: null, editable: null, pageUrl: location.href }; var currentElement = event.target; var selection = window.getSelection().toString(); if (selection.length > 0) onClickData.selectionText = selection; while (currentElement != null) { if (currentElement.nodeType == Node.ELEMENT_NODE) { var nodeName = currentElement.nodeName.toLowerCase(); var currentElementAnchor = currentElement; var currentElementMedia = currentElement; // Anchor if (!onClickData.linkUrl && (nodeName == 'a' || nodeName == 'area') && typeof currentElementAnchor.href === "string" && currentElementAnchor.href.length > 0) { onClickData.linkUrl = currentElementAnchor.href; } if (!onClickData.srcUrl && ["video", "audio"].indexOf(nodeName) != -1 && typeof currentElementMedia.currentSrc === "string" && currentElementMedia.currentSrc.length > 0) { onClickData.srcUrl = currentElementMedia.currentSrc; } if (!onClickData.srcUrl && ["video", "source", "audio", "img"].indexOf(nodeName) != -1 && typeof currentElementMedia.src === "string" && currentElementMedia.src.length > 0) { onClickData.srcUrl = currentElementMedia.src; } } currentElement = currentElement.parentNode; } safari.self.tab.setContextMenuEventUserInfo(event, onClickData); }, false); //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbImpzL3NhZmFyaS1jb250ZXh0bWVudS50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiQUFBQSxRQUFRLENBQUMsZ0JBQWdCLENBQUMsYUFBYSxFQUFFLFVBQVMsS0FBSztJQUN0RCxJQUFJLFdBQVcsR0FBb0M7UUFDNUMsVUFBVSxFQUFFLElBQUk7UUFDaEIsUUFBUSxFQUFFLElBQUk7UUFDcEIsT0FBTyxFQUFFLFFBQVEsQ0FBQyxJQUFJO0tBQ3RCLENBQUM7SUFFRixJQUFJLGNBQWMsR0FBZSxLQUFLLENBQUMsTUFBTSxDQUFDO0lBQzlDLElBQUksU0FBUyxHQUFHLE1BQU0sQ0FBQyxZQUFZLEVBQUUsQ0FBQyxRQUFRLEVBQUUsQ0FBQztJQUVqRCxFQUFFLENBQUEsQ0FBQyxTQUFTLENBQUMsTUFBTSxHQUFHLENBQUMsQ0FBQztRQUN2QixXQUFXLENBQUMsYUFBY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PiAwKSB7XG5cdFx0XHRcdG9uQ2xpY2tEYXRhLnNyY1VybCA9IGN1cnJlbnRFbGVtZW50TWVkaWEuY3VycmVudFNyYztcblx0XHRcdH1cblx0XHRcdFxuXHRcdFx0aWYoIW9uQ2xpY2tEYXRhLnNyY1VybCAmJiBbXCJ2aWRlb1wiLCBcInNvdXJjZVwiLCBcImF1ZGlvXCIsIFwiaW1nXCJdLmluZGV4T2Yobm9kZU5hbWUpICE9IC0xICYmIHR5cGVvZiBjdXJyZW50RWxlbWVudE1lZGlhLnNyYyA9PT0gXCJzdHJpbmdcIiAmJiBjdXJyZW50RWxlbWVudE1lZGlhLnNyYy5sZW5ndGggPiAwKSB7XG5cdFx0XHRcdG9uQ2xpY2tEYXRhLnNyY1VybCA9IGN1cnJlbnRFbGVtZW50TWVkaWEuc3JjO1xuXHRcdFx0fVxuXHRcdH1cblx0XHRjdXJyZW50RWxlbWVudCA9IGN1cnJlbnRFbGVtZW50LnBhcmVudE5vZGU7XG5cdH1cblx0XG5cdCg8YW55PnNhZmFyaS5zZWxmKS50YWIuc2V0Q29udGV4dE1lbnVFdmVudFVzZXJJbmZvKGV2ZW50LCBvbkNsaWNrRGF0YSk7XG59LCBmYWxzZSk7Il0sInNvdXJjZVJvb3QiOiIvc291cmNlLyJ9
6,057
safari-contextmenu
js
en
javascript
code
{"qsc_code_num_words": 130, "qsc_code_num_chars": 6057.0, "qsc_code_mean_word_length": 42.00769231, "qsc_code_frac_words_unique": 0.46153846, "qsc_code_frac_chars_top_2grams": 0.00512727, "qsc_code_frac_chars_top_3grams": 0.0131844, "qsc_code_frac_chars_top_4grams": 0.0087896, "qsc_code_frac_chars_dupe_5grams": 0.0307636, "qsc_code_frac_chars_dupe_6grams": 0.0, "qsc_code_frac_chars_dupe_7grams": 0.0, "qsc_code_frac_chars_dupe_8grams": 0.0, "qsc_code_frac_chars_dupe_9grams": 0.0, "qsc_code_frac_chars_dupe_10grams": 0.0, "qsc_code_frac_chars_replacement_symbols": 0.0, "qsc_code_frac_chars_digital": 0.08011293, "qsc_code_frac_chars_whitespace": 0.06438831, "qsc_code_size_file_byte": 6057.0, "qsc_code_num_lines": 32.0, "qsc_code_num_chars_line_max": 4491.0, "qsc_code_num_chars_line_mean": 189.28125, "qsc_code_frac_chars_alphabet": 0.88353626, "qsc_code_frac_chars_comments": 0.74277695, "qsc_code_cate_xml_start": 0.0, "qsc_code_frac_lines_dupe_lines": 0.0, "qsc_code_cate_autogen": 0.0, "qsc_code_frac_lines_long_string": 0.0, "qsc_code_frac_chars_string_length": 0.04043646, "qsc_code_frac_chars_long_word_length": 0.0, "qsc_code_frac_lines_string_concat": 0.0, "qsc_code_cate_encoded_data": 1.0, "qsc_code_frac_chars_hex_words": 0.0, "qsc_code_frac_lines_prompt_comments": 0.0, "qsc_code_frac_lines_assert": 0.0, "qsc_codejavascript_cate_ast": 1.0, "qsc_codejavascript_cate_var_zero": 0.0, "qsc_codejavascript_frac_lines_func_ratio": 0.0, "qsc_codejavascript_num_statement_line": 0.03448276, "qsc_codejavascript_score_lines_no_logic": 0.06896552, "qsc_codejavascript_frac_words_legal_var_name": 1.0, "qsc_codejavascript_frac_words_legal_func_name": null, "qsc_codejavascript_frac_words_legal_class_name": null, "qsc_codejavascript_frac_lines_print": 0.0}
0
{"qsc_code_frac_chars_replacement_symbols": 0, "qsc_code_num_words": 0, "qsc_code_num_chars": 0, "qsc_code_mean_word_length": 1, "qsc_code_frac_chars_top_2grams": 0, "qsc_code_frac_chars_top_3grams": 0, "qsc_code_frac_chars_top_4grams": 0, "qsc_code_frac_chars_dupe_5grams": 0, "qsc_code_frac_chars_dupe_6grams": 0, "qsc_code_frac_chars_dupe_7grams": 0, "qsc_code_frac_chars_dupe_8grams": 0, "qsc_code_frac_chars_dupe_9grams": 0, "qsc_code_frac_chars_dupe_10grams": 0, "qsc_code_size_file_byte": 0, "qsc_code_num_lines": 0, "qsc_code_num_chars_line_max": 1, "qsc_code_num_chars_line_mean": 1, "qsc_code_frac_chars_alphabet": 0, "qsc_code_frac_chars_digital": 0, "qsc_code_frac_chars_whitespace": 0, "qsc_code_frac_chars_comments": 0, "qsc_code_cate_xml_start": 0, "qsc_code_frac_lines_dupe_lines": 0, "qsc_code_cate_autogen": 0, "qsc_code_frac_lines_long_string": 0, "qsc_code_frac_chars_string_length": 0, "qsc_code_frac_chars_long_word_length": 0, "qsc_code_cate_encoded_data": 1, "qsc_code_frac_chars_hex_words": 0, "qsc_code_frac_lines_prompt_comments": 0, "qsc_code_frac_lines_assert": 0, "qsc_codejavascript_cate_ast": 0, "qsc_codejavascript_cate_var_zero": 0, "qsc_codejavascript_frac_lines_func_ratio": 0, "qsc_codejavascript_score_lines_no_logic": 0, "qsc_codejavascript_frac_lines_print": 0}
0015/esp_rlottie
rlottie/src/vector/freetype/v_ft_raster.h
#ifndef V_FT_IMG_H #define V_FT_IMG_H /***************************************************************************/ /* */ /* ftimage.h */ /* */ /* FreeType glyph image formats and default raster interface */ /* (specification). */ /* */ /* Copyright 1996-2010, 2013 by */ /* David Turner, Robert Wilhelm, and Werner Lemberg. */ /* */ /* This file is part of the FreeType project, and may only be used, */ /* modified, and distributed under the terms of the FreeType project */ /* license, LICENSE.TXT. By continuing to use, modify, or distribute */ /* this file you indicate that you have read the license and */ /* understand and accept it fully. */ /* */ /***************************************************************************/ /*************************************************************************/ /* */ /* Note: A `raster' is simply a scan-line converter, used to render */ /* SW_FT_Outlines into SW_FT_Bitmaps. */ /* */ /*************************************************************************/ #include "v_ft_types.h" /*************************************************************************/ /* */ /* <Struct> */ /* FT_BBox */ /* */ /* <Description> */ /* A structure used to hold an outline's bounding box, i.e., the */ /* coordinates of its extrema in the horizontal and vertical */ /* directions. */ /* */ /* <Fields> */ /* xMin :: The horizontal minimum (left-most). */ /* */ /* yMin :: The vertical minimum (bottom-most). */ /* */ /* xMax :: The horizontal maximum (right-most). */ /* */ /* yMax :: The vertical maximum (top-most). */ /* */ /* <Note> */ /* The bounding box is specified with the coordinates of the lower */ /* left and the upper right corner. In PostScript, those values are */ /* often called (llx,lly) and (urx,ury), respectively. */ /* */ /* If `yMin' is negative, this value gives the glyph's descender. */ /* Otherwise, the glyph doesn't descend below the baseline. */ /* Similarly, if `ymax' is positive, this value gives the glyph's */ /* ascender. */ /* */ /* `xMin' gives the horizontal distance from the glyph's origin to */ /* the left edge of the glyph's bounding box. If `xMin' is negative, */ /* the glyph extends to the left of the origin. */ /* */ typedef struct SW_FT_BBox_ { SW_FT_Pos xMin, yMin; SW_FT_Pos xMax, yMax; } SW_FT_BBox; /*************************************************************************/ /* */ /* <Struct> */ /* SW_FT_Outline */ /* */ /* <Description> */ /* This structure is used to describe an outline to the scan-line */ /* converter. */ /* */ /* <Fields> */ /* n_contours :: The number of contours in the outline. */ /* */ /* n_points :: The number of points in the outline. */ /* */ /* points :: A pointer to an array of `n_points' @SW_FT_Vector */ /* elements, giving the outline's point coordinates. */ /* */ /* tags :: A pointer to an array of `n_points' chars, giving */ /* each outline point's type. */ /* */ /* If bit~0 is unset, the point is `off' the curve, */ /* i.e., a Bézier control point, while it is `on' if */ /* set. */ /* */ /* Bit~1 is meaningful for `off' points only. If set, */ /* it indicates a third-order Bézier arc control point; */ /* and a second-order control point if unset. */ /* */ /* If bit~2 is set, bits 5-7 contain the drop-out mode */ /* (as defined in the OpenType specification; the value */ /* is the same as the argument to the SCANMODE */ /* instruction). */ /* */ /* Bits 3 and~4 are reserved for internal purposes. */ /* */ /* contours :: An array of `n_contours' shorts, giving the end */ /* point of each contour within the outline. For */ /* example, the first contour is defined by the points */ /* `0' to `contours[0]', the second one is defined by */ /* the points `contours[0]+1' to `contours[1]', etc. */ /* */ /* flags :: A set of bit flags used to characterize the outline */ /* and give hints to the scan-converter and hinter on */ /* how to convert/grid-fit it. See @SW_FT_OUTLINE_FLAGS.*/ /* */ typedef struct SW_FT_Outline_ { short n_contours; /* number of contours in glyph */ short n_points; /* number of points in the glyph */ SW_FT_Vector* points; /* the outline's points */ char* tags; /* the points flags */ short* contours; /* the contour end points */ char* contours_flag; /* the contour open flags */ int flags; /* outline masks */ } SW_FT_Outline; /*************************************************************************/ /* */ /* <Enum> */ /* SW_FT_OUTLINE_FLAGS */ /* */ /* <Description> */ /* A list of bit-field constants use for the flags in an outline's */ /* `flags' field. */ /* */ /* <Values> */ /* SW_FT_OUTLINE_NONE :: */ /* Value~0 is reserved. */ /* */ /* SW_FT_OUTLINE_OWNER :: */ /* If set, this flag indicates that the outline's field arrays */ /* (i.e., `points', `flags', and `contours') are `owned' by the */ /* outline object, and should thus be freed when it is destroyed. */ /* */ /* SW_FT_OUTLINE_EVEN_ODD_FILL :: */ /* By default, outlines are filled using the non-zero winding rule. */ /* If set to 1, the outline will be filled using the even-odd fill */ /* rule (only works with the smooth rasterizer). */ /* */ /* SW_FT_OUTLINE_REVERSE_FILL :: */ /* By default, outside contours of an outline are oriented in */ /* clock-wise direction, as defined in the TrueType specification. */ /* This flag is set if the outline uses the opposite direction */ /* (typically for Type~1 fonts). This flag is ignored by the scan */ /* converter. */ /* */ /* */ /* */ /* There exists a second mechanism to pass the drop-out mode to the */ /* B/W rasterizer; see the `tags' field in @SW_FT_Outline. */ /* */ /* Please refer to the description of the `SCANTYPE' instruction in */ /* the OpenType specification (in file `ttinst1.doc') how simple */ /* drop-outs, smart drop-outs, and stubs are defined. */ /* */ #define SW_FT_OUTLINE_NONE 0x0 #define SW_FT_OUTLINE_OWNER 0x1 #define SW_FT_OUTLINE_EVEN_ODD_FILL 0x2 #define SW_FT_OUTLINE_REVERSE_FILL 0x4 /* */ #define SW_FT_CURVE_TAG( flag ) ( flag & 3 ) #define SW_FT_CURVE_TAG_ON 1 #define SW_FT_CURVE_TAG_CONIC 0 #define SW_FT_CURVE_TAG_CUBIC 2 #define SW_FT_Curve_Tag_On SW_FT_CURVE_TAG_ON #define SW_FT_Curve_Tag_Conic SW_FT_CURVE_TAG_CONIC #define SW_FT_Curve_Tag_Cubic SW_FT_CURVE_TAG_CUBIC /*************************************************************************/ /* */ /* A raster is a scan converter, in charge of rendering an outline into */ /* a a bitmap. This section contains the public API for rasters. */ /* */ /* Note that in FreeType 2, all rasters are now encapsulated within */ /* specific modules called `renderers'. See `ftrender.h' for more */ /* details on renderers. */ /* */ /*************************************************************************/ /*************************************************************************/ /* */ /* <Type> */ /* SW_FT_Raster */ /* */ /* <Description> */ /* A handle (pointer) to a raster object. Each object can be used */ /* independently to convert an outline into a bitmap or pixmap. */ /* */ typedef struct SW_FT_RasterRec_* SW_FT_Raster; /*************************************************************************/ /* */ /* <Struct> */ /* SW_FT_Span */ /* */ /* <Description> */ /* A structure used to model a single span of gray (or black) pixels */ /* when rendering a monochrome or anti-aliased bitmap. */ /* */ /* <Fields> */ /* x :: The span's horizontal start position. */ /* */ /* len :: The span's length in pixels. */ /* */ /* coverage :: The span color/coverage, ranging from 0 (background) */ /* to 255 (foreground). Only used for anti-aliased */ /* rendering. */ /* */ /* <Note> */ /* This structure is used by the span drawing callback type named */ /* @SW_FT_SpanFunc that takes the y~coordinate of the span as a */ /* parameter. */ /* */ /* The coverage value is always between 0 and 255. If you want less */ /* gray values, the callback function has to reduce them. */ /* */ typedef struct SW_FT_Span_ { short x; short y; unsigned short len; unsigned char coverage; } SW_FT_Span; /*************************************************************************/ /* */ /* <FuncType> */ /* SW_FT_SpanFunc */ /* */ /* <Description> */ /* A function used as a call-back by the anti-aliased renderer in */ /* order to let client applications draw themselves the gray pixel */ /* spans on each scan line. */ /* */ /* <Input> */ /* y :: The scanline's y~coordinate. */ /* */ /* count :: The number of spans to draw on this scanline. */ /* */ /* spans :: A table of `count' spans to draw on the scanline. */ /* */ /* user :: User-supplied data that is passed to the callback. */ /* */ /* <Note> */ /* This callback allows client applications to directly render the */ /* gray spans of the anti-aliased bitmap to any kind of surfaces. */ /* */ /* This can be used to write anti-aliased outlines directly to a */ /* given background bitmap, and even perform translucency. */ /* */ /* Note that the `count' field cannot be greater than a fixed value */ /* defined by the `SW_FT_MAX_GRAY_SPANS' configuration macro in */ /* `ftoption.h'. By default, this value is set to~32, which means */ /* that if there are more than 32~spans on a given scanline, the */ /* callback is called several times with the same `y' parameter in */ /* order to draw all callbacks. */ /* */ /* Otherwise, the callback is only called once per scan-line, and */ /* only for those scanlines that do have `gray' pixels on them. */ /* */ typedef void (*SW_FT_SpanFunc)( int count, const SW_FT_Span* spans, void* user ); typedef void (*SW_FT_BboxFunc)( int x, int y, int w, int h, void* user); #define SW_FT_Raster_Span_Func SW_FT_SpanFunc /*************************************************************************/ /* */ /* <Enum> */ /* SW_FT_RASTER_FLAG_XXX */ /* */ /* <Description> */ /* A list of bit flag constants as used in the `flags' field of a */ /* @SW_FT_Raster_Params structure. */ /* */ /* <Values> */ /* SW_FT_RASTER_FLAG_DEFAULT :: This value is 0. */ /* */ /* SW_FT_RASTER_FLAG_AA :: This flag is set to indicate that an */ /* anti-aliased glyph image should be */ /* generated. Otherwise, it will be */ /* monochrome (1-bit). */ /* */ /* SW_FT_RASTER_FLAG_DIRECT :: This flag is set to indicate direct */ /* rendering. In this mode, client */ /* applications must provide their own span */ /* callback. This lets them directly */ /* draw or compose over an existing bitmap. */ /* If this bit is not set, the target */ /* pixmap's buffer _must_ be zeroed before */ /* rendering. */ /* */ /* Note that for now, direct rendering is */ /* only possible with anti-aliased glyphs. */ /* */ /* SW_FT_RASTER_FLAG_CLIP :: This flag is only used in direct */ /* rendering mode. If set, the output will */ /* be clipped to a box specified in the */ /* `clip_box' field of the */ /* @SW_FT_Raster_Params structure. */ /* */ /* Note that by default, the glyph bitmap */ /* is clipped to the target pixmap, except */ /* in direct rendering mode where all spans */ /* are generated if no clipping box is set. */ /* */ #define SW_FT_RASTER_FLAG_DEFAULT 0x0 #define SW_FT_RASTER_FLAG_AA 0x1 #define SW_FT_RASTER_FLAG_DIRECT 0x2 #define SW_FT_RASTER_FLAG_CLIP 0x4 /*************************************************************************/ /* */ /* <Struct> */ /* SW_FT_Raster_Params */ /* */ /* <Description> */ /* A structure to hold the arguments used by a raster's render */ /* function. */ /* */ /* <Fields> */ /* target :: The target bitmap. */ /* */ /* source :: A pointer to the source glyph image (e.g., an */ /* @SW_FT_Outline). */ /* */ /* flags :: The rendering flags. */ /* */ /* gray_spans :: The gray span drawing callback. */ /* */ /* black_spans :: The black span drawing callback. UNIMPLEMENTED! */ /* */ /* bit_test :: The bit test callback. UNIMPLEMENTED! */ /* */ /* bit_set :: The bit set callback. UNIMPLEMENTED! */ /* */ /* user :: User-supplied data that is passed to each drawing */ /* callback. */ /* */ /* clip_box :: An optional clipping box. It is only used in */ /* direct rendering mode. Note that coordinates here */ /* should be expressed in _integer_ pixels (and not in */ /* 26.6 fixed-point units). */ /* */ /* <Note> */ /* An anti-aliased glyph bitmap is drawn if the @SW_FT_RASTER_FLAG_AA */ /* bit flag is set in the `flags' field, otherwise a monochrome */ /* bitmap is generated. */ /* */ /* If the @SW_FT_RASTER_FLAG_DIRECT bit flag is set in `flags', the */ /* raster will call the `gray_spans' callback to draw gray pixel */ /* spans, in the case of an aa glyph bitmap, it will call */ /* `black_spans', and `bit_test' and `bit_set' in the case of a */ /* monochrome bitmap. This allows direct composition over a */ /* pre-existing bitmap through user-provided callbacks to perform the */ /* span drawing/composition. */ /* */ /* Note that the `bit_test' and `bit_set' callbacks are required when */ /* rendering a monochrome bitmap, as they are crucial to implement */ /* correct drop-out control as defined in the TrueType specification. */ /* */ typedef struct SW_FT_Raster_Params_ { const void* source; int flags; SW_FT_SpanFunc gray_spans; SW_FT_BboxFunc bbox_cb; void* user; SW_FT_BBox clip_box; } SW_FT_Raster_Params; /*************************************************************************/ /* */ /* <Function> */ /* SW_FT_Outline_Check */ /* */ /* <Description> */ /* Check the contents of an outline descriptor. */ /* */ /* <Input> */ /* outline :: A handle to a source outline. */ /* */ /* <Return> */ /* FreeType error code. 0~means success. */ /* */ SW_FT_Error SW_FT_Outline_Check( SW_FT_Outline* outline ); /*************************************************************************/ /* */ /* <Function> */ /* SW_FT_Outline_Get_CBox */ /* */ /* <Description> */ /* Return an outline's `control box'. The control box encloses all */ /* the outline's points, including Bézier control points. Though it */ /* coincides with the exact bounding box for most glyphs, it can be */ /* slightly larger in some situations (like when rotating an outline */ /* that contains Bézier outside arcs). */ /* */ /* Computing the control box is very fast, while getting the bounding */ /* box can take much more time as it needs to walk over all segments */ /* and arcs in the outline. To get the latter, you can use the */ /* `ftbbox' component, which is dedicated to this single task. */ /* */ /* <Input> */ /* outline :: A pointer to the source outline descriptor. */ /* */ /* <Output> */ /* acbox :: The outline's control box. */ /* */ /* <Note> */ /* See @SW_FT_Glyph_Get_CBox for a discussion of tricky fonts. */ /* */ void SW_FT_Outline_Get_CBox( const SW_FT_Outline* outline, SW_FT_BBox *acbox ); /*************************************************************************/ /* */ /* <FuncType> */ /* SW_FT_Raster_NewFunc */ /* */ /* <Description> */ /* A function used to create a new raster object. */ /* */ /* <Input> */ /* memory :: A handle to the memory allocator. */ /* */ /* <Output> */ /* raster :: A handle to the new raster object. */ /* */ /* <Return> */ /* Error code. 0~means success. */ /* */ /* <Note> */ /* The `memory' parameter is a typeless pointer in order to avoid */ /* un-wanted dependencies on the rest of the FreeType code. In */ /* practice, it is an @SW_FT_Memory object, i.e., a handle to the */ /* standard FreeType memory allocator. However, this field can be */ /* completely ignored by a given raster implementation. */ /* */ typedef int (*SW_FT_Raster_NewFunc)( SW_FT_Raster* raster ); #define SW_FT_Raster_New_Func SW_FT_Raster_NewFunc /*************************************************************************/ /* */ /* <FuncType> */ /* SW_FT_Raster_DoneFunc */ /* */ /* <Description> */ /* A function used to destroy a given raster object. */ /* */ /* <Input> */ /* raster :: A handle to the raster object. */ /* */ typedef void (*SW_FT_Raster_DoneFunc)( SW_FT_Raster raster ); #define SW_FT_Raster_Done_Func SW_FT_Raster_DoneFunc /*************************************************************************/ /* */ /* <FuncType> */ /* SW_FT_Raster_ResetFunc */ /* */ /* <Description> */ /* FreeType provides an area of memory called the `render pool', */ /* available to all registered rasters. This pool can be freely used */ /* during a given scan-conversion but is shared by all rasters. Its */ /* content is thus transient. */ /* */ /* This function is called each time the render pool changes, or just */ /* after a new raster object is created. */ /* */ /* <Input> */ /* raster :: A handle to the new raster object. */ /* */ /* pool_base :: The address in memory of the render pool. */ /* */ /* pool_size :: The size in bytes of the render pool. */ /* */ /* <Note> */ /* Rasters can ignore the render pool and rely on dynamic memory */ /* allocation if they want to (a handle to the memory allocator is */ /* passed to the raster constructor). However, this is not */ /* recommended for efficiency purposes. */ /* */ typedef void (*SW_FT_Raster_ResetFunc)( SW_FT_Raster raster, unsigned char* pool_base, unsigned long pool_size ); #define SW_FT_Raster_Reset_Func SW_FT_Raster_ResetFunc /*************************************************************************/ /* */ /* <FuncType> */ /* SW_FT_Raster_RenderFunc */ /* */ /* <Description> */ /* Invoke a given raster to scan-convert a given glyph image into a */ /* target bitmap. */ /* */ /* <Input> */ /* raster :: A handle to the raster object. */ /* */ /* params :: A pointer to an @SW_FT_Raster_Params structure used to */ /* store the rendering parameters. */ /* */ /* <Return> */ /* Error code. 0~means success. */ /* */ /* <Note> */ /* The exact format of the source image depends on the raster's glyph */ /* format defined in its @SW_FT_Raster_Funcs structure. It can be an */ /* @SW_FT_Outline or anything else in order to support a large array of */ /* glyph formats. */ /* */ /* Note also that the render function can fail and return a */ /* `SW_FT_Err_Unimplemented_Feature' error code if the raster used does */ /* not support direct composition. */ /* */ /* XXX: For now, the standard raster doesn't support direct */ /* composition but this should change for the final release (see */ /* the files `demos/src/ftgrays.c' and `demos/src/ftgrays2.c' */ /* for examples of distinct implementations that support direct */ /* composition). */ /* */ typedef int (*SW_FT_Raster_RenderFunc)( SW_FT_Raster raster, const SW_FT_Raster_Params* params ); #define SW_FT_Raster_Render_Func SW_FT_Raster_RenderFunc /*************************************************************************/ /* */ /* <Struct> */ /* SW_FT_Raster_Funcs */ /* */ /* <Description> */ /* A structure used to describe a given raster class to the library. */ /* */ /* <Fields> */ /* glyph_format :: The supported glyph format for this raster. */ /* */ /* raster_new :: The raster constructor. */ /* */ /* raster_reset :: Used to reset the render pool within the raster. */ /* */ /* raster_render :: A function to render a glyph into a given bitmap. */ /* */ /* raster_done :: The raster destructor. */ /* */ typedef struct SW_FT_Raster_Funcs_ { SW_FT_Raster_NewFunc raster_new; SW_FT_Raster_ResetFunc raster_reset; SW_FT_Raster_RenderFunc raster_render; SW_FT_Raster_DoneFunc raster_done; } SW_FT_Raster_Funcs; extern const SW_FT_Raster_Funcs sw_ft_grays_raster; #endif // V_FT_IMG_H
39,671
v_ft_raster
h
en
c
code
{"qsc_code_num_words": 2595, "qsc_code_num_chars": 39671.0, "qsc_code_mean_word_length": 4.43583815, "qsc_code_frac_words_unique": 0.21618497, "qsc_code_frac_chars_top_2grams": 0.03822431, "qsc_code_frac_chars_top_3grams": 0.04343671, "qsc_code_frac_chars_top_4grams": 0.01337851, "qsc_code_frac_chars_dupe_5grams": 0.16227956, "qsc_code_frac_chars_dupe_6grams": 0.08035792, "qsc_code_frac_chars_dupe_7grams": 0.03926679, "qsc_code_frac_chars_dupe_8grams": 0.03388064, "qsc_code_frac_chars_dupe_9grams": 0.0, "qsc_code_frac_chars_dupe_10grams": 0.0, "qsc_code_frac_chars_replacement_symbols": 0.0, "qsc_code_frac_chars_digital": 0.00433839, "qsc_code_frac_chars_whitespace": 0.59327973, "qsc_code_size_file_byte": 39671.0, "qsc_code_num_lines": 607.0, "qsc_code_num_chars_line_max": 84.0, "qsc_code_num_chars_line_mean": 65.35584843, "qsc_code_frac_chars_alphabet": 0.70907964, "qsc_code_frac_chars_comments": 0.89221346, "qsc_code_cate_xml_start": 0.0, "qsc_code_frac_lines_dupe_lines": 0.11494253, "qsc_code_cate_autogen": 0.0, "qsc_code_frac_lines_long_string": 0.0, "qsc_code_frac_chars_string_length": 0.00280636, "qsc_code_frac_chars_long_word_length": 0.0, "qsc_code_frac_lines_string_concat": 0.0, "qsc_code_cate_encoded_data": 0.0, "qsc_code_frac_chars_hex_words": 0.00561272, "qsc_code_frac_lines_prompt_comments": 0.0, "qsc_code_frac_lines_assert": 0.0, "qsc_codec_frac_lines_func_ratio": 0.03448276, "qsc_codec_cate_bitsstdc": 0.0, "qsc_codec_nums_lines_main": 0, "qsc_codec_frac_lines_goto": 0.0, "qsc_codec_cate_var_zero": 0.0, "qsc_codec_score_lines_no_logic": 0.08045977, "qsc_codec_frac_lines_print": 0.0, "qsc_codec_frac_lines_preprocessor_directives": null}
0
{"qsc_code_frac_chars_replacement_symbols": 0, "qsc_code_num_words": 0, "qsc_code_num_chars": 0, "qsc_code_mean_word_length": 0, "qsc_code_frac_chars_top_2grams": 0, "qsc_code_frac_chars_top_3grams": 0, "qsc_code_frac_chars_top_4grams": 0, "qsc_code_frac_chars_dupe_5grams": 0, "qsc_code_frac_chars_dupe_6grams": 0, "qsc_code_frac_chars_dupe_7grams": 0, "qsc_code_frac_chars_dupe_8grams": 0, "qsc_code_frac_chars_dupe_9grams": 0, "qsc_code_frac_chars_dupe_10grams": 0, "qsc_code_size_file_byte": 0, "qsc_code_num_lines": 0, "qsc_code_num_chars_line_max": 0, "qsc_code_num_chars_line_mean": 0, "qsc_code_frac_chars_alphabet": 0, "qsc_code_frac_chars_digital": 0, "qsc_code_frac_chars_whitespace": 1, "qsc_code_frac_chars_comments": 1, "qsc_code_cate_xml_start": 0, "qsc_code_frac_lines_dupe_lines": 0, "qsc_code_cate_autogen": 0, "qsc_code_frac_lines_long_string": 0, "qsc_code_frac_chars_string_length": 0, "qsc_code_frac_chars_long_word_length": 0, "qsc_code_cate_encoded_data": 0, "qsc_code_frac_chars_hex_words": 0, "qsc_code_frac_lines_prompt_comments": 0, "qsc_code_frac_lines_assert": 0, "qsc_codec_frac_lines_func_ratio": 0, "qsc_codec_nums_lines_main": 0, "qsc_codec_score_lines_no_logic": 0, "qsc_codec_frac_lines_preprocessor_directives": 0, "qsc_codec_frac_lines_print": 0}
0015/esp_rlottie
rlottie/src/vector/freetype/v_ft_math.h
#ifndef V_FT_MATH_H #define V_FT_MATH_H /***************************************************************************/ /* */ /* fttrigon.h */ /* */ /* FreeType trigonometric functions (specification). */ /* */ /* Copyright 2001, 2003, 2005, 2007, 2013 by */ /* David Turner, Robert Wilhelm, and Werner Lemberg. */ /* */ /* This file is part of the FreeType project, and may only be used, */ /* modified, and distributed under the terms of the FreeType project */ /* license, LICENSE.TXT. By continuing to use, modify, or distribute */ /* this file you indicate that you have read the license and */ /* understand and accept it fully. */ /* */ /***************************************************************************/ #include "v_ft_types.h" /*************************************************************************/ /* */ /* The min and max functions missing in C. As usual, be careful not to */ /* write things like SW_FT_MIN( a++, b++ ) to avoid side effects. */ /* */ #define SW_FT_MIN( a, b ) ( (a) < (b) ? (a) : (b) ) #define SW_FT_MAX( a, b ) ( (a) > (b) ? (a) : (b) ) #define SW_FT_ABS( a ) ( (a) < 0 ? -(a) : (a) ) /* * Approximate sqrt(x*x+y*y) using the `alpha max plus beta min' * algorithm. We use alpha = 1, beta = 3/8, giving us results with a * largest error less than 7% compared to the exact value. */ #define SW_FT_HYPOT( x, y ) \ ( x = SW_FT_ABS( x ), \ y = SW_FT_ABS( y ), \ x > y ? x + ( 3 * y >> 3 ) \ : y + ( 3 * x >> 3 ) ) /*************************************************************************/ /* */ /* <Function> */ /* SW_FT_MulFix */ /* */ /* <Description> */ /* A very simple function used to perform the computation */ /* `(a*b)/0x10000' with maximum accuracy. Most of the time this is */ /* used to multiply a given value by a 16.16 fixed-point factor. */ /* */ /* <Input> */ /* a :: The first multiplier. */ /* b :: The second multiplier. Use a 16.16 factor here whenever */ /* possible (see note below). */ /* */ /* <Return> */ /* The result of `(a*b)/0x10000'. */ /* */ /* <Note> */ /* This function has been optimized for the case where the absolute */ /* value of `a' is less than 2048, and `b' is a 16.16 scaling factor. */ /* As this happens mainly when scaling from notional units to */ /* fractional pixels in FreeType, it resulted in noticeable speed */ /* improvements between versions 2.x and 1.x. */ /* */ /* As a conclusion, always try to place a 16.16 factor as the */ /* _second_ argument of this function; this can make a great */ /* difference. */ /* */ SW_FT_Long SW_FT_MulFix( SW_FT_Long a, SW_FT_Long b ); /*************************************************************************/ /* */ /* <Function> */ /* SW_FT_MulDiv */ /* */ /* <Description> */ /* A very simple function used to perform the computation `(a*b)/c' */ /* with maximum accuracy (it uses a 64-bit intermediate integer */ /* whenever necessary). */ /* */ /* This function isn't necessarily as fast as some processor specific */ /* operations, but is at least completely portable. */ /* */ /* <Input> */ /* a :: The first multiplier. */ /* b :: The second multiplier. */ /* c :: The divisor. */ /* */ /* <Return> */ /* The result of `(a*b)/c'. This function never traps when trying to */ /* divide by zero; it simply returns `MaxInt' or `MinInt' depending */ /* on the signs of `a' and `b'. */ /* */ SW_FT_Long SW_FT_MulDiv( SW_FT_Long a, SW_FT_Long b, SW_FT_Long c ); /*************************************************************************/ /* */ /* <Function> */ /* SW_FT_DivFix */ /* */ /* <Description> */ /* A very simple function used to perform the computation */ /* `(a*0x10000)/b' with maximum accuracy. Most of the time, this is */ /* used to divide a given value by a 16.16 fixed-point factor. */ /* */ /* <Input> */ /* a :: The numerator. */ /* b :: The denominator. Use a 16.16 factor here. */ /* */ /* <Return> */ /* The result of `(a*0x10000)/b'. */ /* */ SW_FT_Long SW_FT_DivFix( SW_FT_Long a, SW_FT_Long b ); /*************************************************************************/ /* */ /* <Section> */ /* computations */ /* */ /*************************************************************************/ /************************************************************************* * * @type: * SW_FT_Angle * * @description: * This type is used to model angle values in FreeType. Note that the * angle is a 16.16 fixed-point value expressed in degrees. * */ typedef SW_FT_Fixed SW_FT_Angle; /************************************************************************* * * @macro: * SW_FT_ANGLE_PI * * @description: * The angle pi expressed in @SW_FT_Angle units. * */ #define SW_FT_ANGLE_PI ( 180L << 16 ) /************************************************************************* * * @macro: * SW_FT_ANGLE_2PI * * @description: * The angle 2*pi expressed in @SW_FT_Angle units. * */ #define SW_FT_ANGLE_2PI ( SW_FT_ANGLE_PI * 2 ) /************************************************************************* * * @macro: * SW_FT_ANGLE_PI2 * * @description: * The angle pi/2 expressed in @SW_FT_Angle units. * */ #define SW_FT_ANGLE_PI2 ( SW_FT_ANGLE_PI / 2 ) /************************************************************************* * * @macro: * SW_FT_ANGLE_PI4 * * @description: * The angle pi/4 expressed in @SW_FT_Angle units. * */ #define SW_FT_ANGLE_PI4 ( SW_FT_ANGLE_PI / 4 ) /************************************************************************* * * @function: * SW_FT_Sin * * @description: * Return the sinus of a given angle in fixed-point format. * * @input: * angle :: * The input angle. * * @return: * The sinus value. * * @note: * If you need both the sinus and cosinus for a given angle, use the * function @SW_FT_Vector_Unit. * */ SW_FT_Fixed SW_FT_Sin( SW_FT_Angle angle ); /************************************************************************* * * @function: * SW_FT_Cos * * @description: * Return the cosinus of a given angle in fixed-point format. * * @input: * angle :: * The input angle. * * @return: * The cosinus value. * * @note: * If you need both the sinus and cosinus for a given angle, use the * function @SW_FT_Vector_Unit. * */ SW_FT_Fixed SW_FT_Cos( SW_FT_Angle angle ); /************************************************************************* * * @function: * SW_FT_Tan * * @description: * Return the tangent of a given angle in fixed-point format. * * @input: * angle :: * The input angle. * * @return: * The tangent value. * */ SW_FT_Fixed SW_FT_Tan( SW_FT_Angle angle ); /************************************************************************* * * @function: * SW_FT_Atan2 * * @description: * Return the arc-tangent corresponding to a given vector (x,y) in * the 2d plane. * * @input: * x :: * The horizontal vector coordinate. * * y :: * The vertical vector coordinate. * * @return: * The arc-tangent value (i.e. angle). * */ SW_FT_Angle SW_FT_Atan2( SW_FT_Fixed x, SW_FT_Fixed y ); /************************************************************************* * * @function: * SW_FT_Angle_Diff * * @description: * Return the difference between two angles. The result is always * constrained to the ]-PI..PI] interval. * * @input: * angle1 :: * First angle. * * angle2 :: * Second angle. * * @return: * Constrained value of `value2-value1'. * */ SW_FT_Angle SW_FT_Angle_Diff( SW_FT_Angle angle1, SW_FT_Angle angle2 ); /************************************************************************* * * @function: * SW_FT_Vector_Unit * * @description: * Return the unit vector corresponding to a given angle. After the * call, the value of `vec.x' will be `sin(angle)', and the value of * `vec.y' will be `cos(angle)'. * * This function is useful to retrieve both the sinus and cosinus of a * given angle quickly. * * @output: * vec :: * The address of target vector. * * @input: * angle :: * The input angle. * */ void SW_FT_Vector_Unit( SW_FT_Vector* vec, SW_FT_Angle angle ); /************************************************************************* * * @function: * SW_FT_Vector_Rotate * * @description: * Rotate a vector by a given angle. * * @inout: * vec :: * The address of target vector. * * @input: * angle :: * The input angle. * */ void SW_FT_Vector_Rotate( SW_FT_Vector* vec, SW_FT_Angle angle ); /************************************************************************* * * @function: * SW_FT_Vector_Length * * @description: * Return the length of a given vector. * * @input: * vec :: * The address of target vector. * * @return: * The vector length, expressed in the same units that the original * vector coordinates. * */ SW_FT_Fixed SW_FT_Vector_Length( SW_FT_Vector* vec ); /************************************************************************* * * @function: * SW_FT_Vector_Polarize * * @description: * Compute both the length and angle of a given vector. * * @input: * vec :: * The address of source vector. * * @output: * length :: * The vector length. * * angle :: * The vector angle. * */ void SW_FT_Vector_Polarize( SW_FT_Vector* vec, SW_FT_Fixed *length, SW_FT_Angle *angle ); /************************************************************************* * * @function: * SW_FT_Vector_From_Polar * * @description: * Compute vector coordinates from a length and angle. * * @output: * vec :: * The address of source vector. * * @input: * length :: * The vector length. * * angle :: * The vector angle. * */ void SW_FT_Vector_From_Polar( SW_FT_Vector* vec, SW_FT_Fixed length, SW_FT_Angle angle ); #endif // V_FT_MATH_H
14,680
v_ft_math
h
en
c
code
{"qsc_code_num_words": 1190, "qsc_code_num_chars": 14680.0, "qsc_code_mean_word_length": 4.0907563, "qsc_code_frac_words_unique": 0.2302521, "qsc_code_frac_chars_top_2grams": 0.07148726, "qsc_code_frac_chars_top_3grams": 0.05546426, "qsc_code_frac_chars_top_4grams": 0.02588332, "qsc_code_frac_chars_dupe_5grams": 0.42296631, "qsc_code_frac_chars_dupe_6grams": 0.37777321, "qsc_code_frac_chars_dupe_7grams": 0.34593262, "qsc_code_frac_chars_dupe_8grams": 0.32990961, "qsc_code_frac_chars_dupe_9grams": 0.31511915, "qsc_code_frac_chars_dupe_10grams": 0.26766639, "qsc_code_frac_chars_replacement_symbols": 0.0, "qsc_code_frac_chars_digital": 0.01442006, "qsc_code_frac_chars_whitespace": 0.45674387, "qsc_code_size_file_byte": 14680.0, "qsc_code_num_lines": 438.0, "qsc_code_num_chars_line_max": 79.0, "qsc_code_num_chars_line_mean": 33.51598174, "qsc_code_frac_chars_alphabet": 0.59598746, "qsc_code_frac_chars_comments": 0.86771117, "qsc_code_cate_xml_start": 0.0, "qsc_code_frac_lines_dupe_lines": 0.32727273, "qsc_code_cate_autogen": 0.0, "qsc_code_frac_lines_long_string": 0.0, "qsc_code_frac_chars_string_length": 0.0061792, "qsc_code_frac_chars_long_word_length": 0.0, "qsc_code_frac_lines_string_concat": 0.0, "qsc_code_cate_encoded_data": 0.0, "qsc_code_frac_chars_hex_words": 0.0, "qsc_code_frac_lines_prompt_comments": 0.0, "qsc_code_frac_lines_assert": 0.0, "qsc_codec_frac_lines_func_ratio": 0.30909091, "qsc_codec_cate_bitsstdc": 0.0, "qsc_codec_nums_lines_main": 0, "qsc_codec_frac_lines_goto": 0.0, "qsc_codec_cate_var_zero": 0.0, "qsc_codec_score_lines_no_logic": 0.32727273, "qsc_codec_frac_lines_print": 0.0, "qsc_codec_frac_lines_preprocessor_directives": null}
0
{"qsc_code_frac_chars_replacement_symbols": 0, "qsc_code_num_words": 0, "qsc_code_num_chars": 0, "qsc_code_mean_word_length": 0, "qsc_code_frac_chars_top_2grams": 0, "qsc_code_frac_chars_top_3grams": 0, "qsc_code_frac_chars_top_4grams": 0, "qsc_code_frac_chars_dupe_5grams": 0, "qsc_code_frac_chars_dupe_6grams": 0, "qsc_code_frac_chars_dupe_7grams": 0, "qsc_code_frac_chars_dupe_8grams": 0, "qsc_code_frac_chars_dupe_9grams": 0, "qsc_code_frac_chars_dupe_10grams": 0, "qsc_code_size_file_byte": 0, "qsc_code_num_lines": 0, "qsc_code_num_chars_line_max": 0, "qsc_code_num_chars_line_mean": 0, "qsc_code_frac_chars_alphabet": 0, "qsc_code_frac_chars_digital": 0, "qsc_code_frac_chars_whitespace": 0, "qsc_code_frac_chars_comments": 1, "qsc_code_cate_xml_start": 0, "qsc_code_frac_lines_dupe_lines": 0, "qsc_code_cate_autogen": 0, "qsc_code_frac_lines_long_string": 0, "qsc_code_frac_chars_string_length": 0, "qsc_code_frac_chars_long_word_length": 0, "qsc_code_cate_encoded_data": 0, "qsc_code_frac_chars_hex_words": 0, "qsc_code_frac_lines_prompt_comments": 0, "qsc_code_frac_lines_assert": 0, "qsc_codec_frac_lines_func_ratio": 1, "qsc_codec_nums_lines_main": 0, "qsc_codec_score_lines_no_logic": 0, "qsc_codec_frac_lines_preprocessor_directives": 0, "qsc_codec_frac_lines_print": 0}
0015/esp_rlottie
rlottie/src/vector/freetype/v_ft_raster.cpp
/***************************************************************************/ /* */ /* ftgrays.c */ /* */ /* A new `perfect' anti-aliasing renderer (body). */ /* */ /* Copyright 2000-2003, 2005-2014 by */ /* David Turner, Robert Wilhelm, and Werner Lemberg. */ /* */ /* This file is part of the FreeType project, and may only be used, */ /* modified, and distributed under the terms of the FreeType project */ /* license, LICENSE.TXT. By continuing to use, modify, or distribute */ /* this file you indicate that you have read the license and */ /* understand and accept it fully. */ /* */ /***************************************************************************/ /*************************************************************************/ /* */ /* This is a new anti-aliasing scan-converter for FreeType 2. The */ /* algorithm used here is _very_ different from the one in the standard */ /* `ftraster' module. Actually, `ftgrays' computes the _exact_ */ /* coverage of the outline on each pixel cell. */ /* */ /* It is based on ideas that I initially found in Raph Levien's */ /* excellent LibArt graphics library (see http://www.levien.com/libart */ /* for more information, though the web pages do not tell anything */ /* about the renderer; you'll have to dive into the source code to */ /* understand how it works). */ /* */ /* Note, however, that this is a _very_ different implementation */ /* compared to Raph's. Coverage information is stored in a very */ /* different way, and I don't use sorted vector paths. Also, it doesn't */ /* use floating point values. */ /* */ /* This renderer has the following advantages: */ /* */ /* - It doesn't need an intermediate bitmap. Instead, one can supply a */ /* callback function that will be called by the renderer to draw gray */ /* spans on any target surface. You can thus do direct composition on */ /* any kind of bitmap, provided that you give the renderer the right */ /* callback. */ /* */ /* - A perfect anti-aliaser, i.e., it computes the _exact_ coverage on */ /* each pixel cell. */ /* */ /* - It performs a single pass on the outline (the `standard' FT2 */ /* renderer makes two passes). */ /* */ /* - It can easily be modified to render to _any_ number of gray levels */ /* cheaply. */ /* */ /* - For small (< 20) pixel sizes, it is faster than the standard */ /* renderer. */ /* */ /*************************************************************************/ #include "v_ft_raster.h" #include "v_ft_math.h" /* Auxiliary macros for token concatenation. */ #define SW_FT_ERR_XCAT(x, y) x##y #define SW_FT_ERR_CAT(x, y) SW_FT_ERR_XCAT(x, y) #define SW_FT_BEGIN_STMNT do { #define SW_FT_END_STMNT \ } \ while (0) #include <limits.h> #include <setjmp.h> #include <stddef.h> #include <string.h> #define SW_FT_UINT_MAX UINT_MAX #define SW_FT_INT_MAX INT_MAX #define SW_FT_ULONG_MAX ULONG_MAX #define SW_FT_CHAR_BIT CHAR_BIT #define ft_memset memset #define ft_setjmp setjmp #define ft_longjmp longjmp #define ft_jmp_buf jmp_buf typedef ptrdiff_t SW_FT_PtrDist; #define ErrRaster_Invalid_Mode -2 #define ErrRaster_Invalid_Outline -1 #define ErrRaster_Invalid_Argument -3 #define ErrRaster_Memory_Overflow -4 #define SW_FT_BEGIN_HEADER #define SW_FT_END_HEADER /* This macro is used to indicate that a function parameter is unused. */ /* Its purpose is simply to reduce compiler warnings. Note also that */ /* simply defining it as `(void)x' doesn't avoid warnings with certain */ /* ANSI compilers (e.g. LCC). */ #define SW_FT_UNUSED(x) (x) = (x) #define SW_FT_THROW(e) SW_FT_ERR_CAT(ErrRaster_, e) /* The size in bytes of the render pool used by the scan-line converter */ /* to do all of its work. */ #define SW_FT_RENDER_POOL_SIZE 16384L typedef int (*SW_FT_Outline_MoveToFunc)(const SW_FT_Vector* to, void* user); #define SW_FT_Outline_MoveTo_Func SW_FT_Outline_MoveToFunc typedef int (*SW_FT_Outline_LineToFunc)(const SW_FT_Vector* to, void* user); #define SW_FT_Outline_LineTo_Func SW_FT_Outline_LineToFunc typedef int (*SW_FT_Outline_ConicToFunc)(const SW_FT_Vector* control, const SW_FT_Vector* to, void* user); #define SW_FT_Outline_ConicTo_Func SW_FT_Outline_ConicToFunc typedef int (*SW_FT_Outline_CubicToFunc)(const SW_FT_Vector* control1, const SW_FT_Vector* control2, const SW_FT_Vector* to, void* user); #define SW_FT_Outline_CubicTo_Func SW_FT_Outline_CubicToFunc typedef struct SW_FT_Outline_Funcs_ { SW_FT_Outline_MoveToFunc move_to; SW_FT_Outline_LineToFunc line_to; SW_FT_Outline_ConicToFunc conic_to; SW_FT_Outline_CubicToFunc cubic_to; int shift; SW_FT_Pos delta; } SW_FT_Outline_Funcs; #define SW_FT_DEFINE_OUTLINE_FUNCS(class_, move_to_, line_to_, conic_to_, \ cubic_to_, shift_, delta_) \ static const SW_FT_Outline_Funcs class_ = {move_to_, line_to_, conic_to_, \ cubic_to_, shift_, delta_}; #define SW_FT_DEFINE_RASTER_FUNCS(class_, raster_new_, raster_reset_, \ raster_render_, raster_done_) \ const SW_FT_Raster_Funcs class_ = {raster_new_, raster_reset_, \ raster_render_, raster_done_}; #ifndef SW_FT_MEM_SET #define SW_FT_MEM_SET(d, s, c) ft_memset(d, s, c) #endif #ifndef SW_FT_MEM_ZERO #define SW_FT_MEM_ZERO(dest, count) SW_FT_MEM_SET(dest, 0, count) #endif /* as usual, for the speed hungry :-) */ #undef RAS_ARG #undef RAS_ARG_ #undef RAS_VAR #undef RAS_VAR_ #ifndef SW_FT_STATIC_RASTER #define RAS_ARG gray_PWorker worker #define RAS_ARG_ gray_PWorker worker, #define RAS_VAR worker #define RAS_VAR_ worker, #else /* SW_FT_STATIC_RASTER */ #define RAS_ARG /* empty */ #define RAS_ARG_ /* empty */ #define RAS_VAR /* empty */ #define RAS_VAR_ /* empty */ #endif /* SW_FT_STATIC_RASTER */ /* must be at least 6 bits! */ #define PIXEL_BITS 8 #undef FLOOR #undef CEILING #undef TRUNC #undef SCALED #define ONE_PIXEL (1L << PIXEL_BITS) #define PIXEL_MASK (-1L << PIXEL_BITS) #define TRUNC(x) ((TCoord)((x) >> PIXEL_BITS)) #define SUBPIXELS(x) ((TPos)(x) << PIXEL_BITS) #define FLOOR(x) ((x) & -ONE_PIXEL) #define CEILING(x) (((x) + ONE_PIXEL - 1) & -ONE_PIXEL) #define ROUND(x) (((x) + ONE_PIXEL / 2) & -ONE_PIXEL) #if PIXEL_BITS >= 6 #define UPSCALE(x) ((x) << (PIXEL_BITS - 6)) #define DOWNSCALE(x) ((x) >> (PIXEL_BITS - 6)) #else #define UPSCALE(x) ((x) >> (6 - PIXEL_BITS)) #define DOWNSCALE(x) ((x) << (6 - PIXEL_BITS)) #endif /* Compute `dividend / divisor' and return both its quotient and */ /* remainder, cast to a specific type. This macro also ensures that */ /* the remainder is always positive. */ #define SW_FT_DIV_MOD(type, dividend, divisor, quotient, remainder) \ SW_FT_BEGIN_STMNT(quotient) = (type)((dividend) / (divisor)); \ (remainder) = (type)((dividend) % (divisor)); \ if ((remainder) < 0) { \ (quotient)--; \ (remainder) += (type)(divisor); \ } \ SW_FT_END_STMNT #ifdef __arm__ /* Work around a bug specific to GCC which make the compiler fail to */ /* optimize a division and modulo operation on the same parameters */ /* into a single call to `__aeabi_idivmod'. See */ /* */ /* http://gcc.gnu.org/bugzilla/show_bug.cgi?id=43721 */ #undef SW_FT_DIV_MOD #define SW_FT_DIV_MOD(type, dividend, divisor, quotient, remainder) \ SW_FT_BEGIN_STMNT(quotient) = (type)((dividend) / (divisor)); \ (remainder) = (type)((dividend) - (quotient) * (divisor)); \ if ((remainder) < 0) { \ (quotient)--; \ (remainder) += (type)(divisor); \ } \ SW_FT_END_STMNT #endif /* __arm__ */ /* These macros speed up repetitive divisions by replacing them */ /* with multiplications and right shifts. */ #define SW_FT_UDIVPREP(b) \ long b##_r = (long)(SW_FT_ULONG_MAX >> PIXEL_BITS) / (b) #define SW_FT_UDIV(a, b) \ (((unsigned long)(a) * (unsigned long)(b##_r)) >> \ (sizeof(long) * SW_FT_CHAR_BIT - PIXEL_BITS)) /*************************************************************************/ /* */ /* TYPE DEFINITIONS */ /* */ /* don't change the following types to SW_FT_Int or SW_FT_Pos, since we might */ /* need to define them to "float" or "double" when experimenting with */ /* new algorithms */ typedef long TCoord; /* integer scanline/pixel coordinate */ typedef long TPos; /* sub-pixel coordinate */ /* determine the type used to store cell areas. This normally takes at */ /* least PIXEL_BITS*2 + 1 bits. On 16-bit systems, we need to use */ /* `long' instead of `int', otherwise bad things happen */ #if PIXEL_BITS <= 7 typedef int TArea; #else /* PIXEL_BITS >= 8 */ /* approximately determine the size of integers using an ANSI-C header */ #if SW_FT_UINT_MAX == 0xFFFFU typedef long TArea; #else typedef int TArea; #endif #endif /* PIXEL_BITS >= 8 */ /* maximum number of gray spans in a call to the span callback */ #define SW_FT_MAX_GRAY_SPANS 256 typedef struct TCell_* PCell; typedef struct TCell_ { TPos x; /* same with gray_TWorker.ex */ TCoord cover; /* same with gray_TWorker.cover */ TArea area; PCell next; } TCell; #if defined(_MSC_VER) /* Visual C++ (and Intel C++) */ /* We disable the warning `structure was padded due to */ /* __declspec(align())' in order to compile cleanly with */ /* the maximum level of warnings. */ #pragma warning(push) #pragma warning(disable : 4324) #endif /* _MSC_VER */ typedef struct gray_TWorker_ { TCoord ex, ey; TPos min_ex, max_ex; TPos min_ey, max_ey; TPos count_ex, count_ey; TArea area; TCoord cover; int invalid; PCell cells; SW_FT_PtrDist max_cells; SW_FT_PtrDist num_cells; TPos x, y; SW_FT_Vector bez_stack[32 * 3 + 1]; int lev_stack[32]; SW_FT_Outline outline; SW_FT_BBox clip_box; int bound_left; int bound_top; int bound_right; int bound_bottom; SW_FT_Span gray_spans[SW_FT_MAX_GRAY_SPANS]; int num_gray_spans; SW_FT_Raster_Span_Func render_span; void* render_span_data; int band_size; int band_shoot; ft_jmp_buf jump_buffer; void* buffer; long buffer_size; PCell* ycells; TPos ycount; } gray_TWorker, *gray_PWorker; #if defined(_MSC_VER) #pragma warning(pop) #endif #ifndef SW_FT_STATIC_RASTER #define ras (*worker) #else static gray_TWorker ras; #endif typedef struct gray_TRaster_ { void* memory; } gray_TRaster, *gray_PRaster; /*************************************************************************/ /* */ /* Initialize the cells table. */ /* */ static void gray_init_cells(RAS_ARG_ void* buffer, long byte_size) { ras.buffer = buffer; ras.buffer_size = byte_size; ras.ycells = (PCell*)buffer; ras.cells = NULL; ras.max_cells = 0; ras.num_cells = 0; ras.area = 0; ras.cover = 0; ras.invalid = 1; ras.bound_left = INT_MAX; ras.bound_top = INT_MAX; ras.bound_right = INT_MIN; ras.bound_bottom = INT_MIN; } /*************************************************************************/ /* */ /* Compute the outline bounding box. */ /* */ static void gray_compute_cbox(RAS_ARG) { SW_FT_Outline* outline = &ras.outline; SW_FT_Vector* vec = outline->points; SW_FT_Vector* limit = vec + outline->n_points; if (outline->n_points <= 0) { ras.min_ex = ras.max_ex = 0; ras.min_ey = ras.max_ey = 0; return; } ras.min_ex = ras.max_ex = vec->x; ras.min_ey = ras.max_ey = vec->y; vec++; for (; vec < limit; vec++) { TPos x = vec->x; TPos y = vec->y; if (x < ras.min_ex) ras.min_ex = x; if (x > ras.max_ex) ras.max_ex = x; if (y < ras.min_ey) ras.min_ey = y; if (y > ras.max_ey) ras.max_ey = y; } /* truncate the bounding box to integer pixels */ ras.min_ex = ras.min_ex >> 6; ras.min_ey = ras.min_ey >> 6; ras.max_ex = (ras.max_ex + 63) >> 6; ras.max_ey = (ras.max_ey + 63) >> 6; } /*************************************************************************/ /* */ /* Record the current cell in the table. */ /* */ static PCell gray_find_cell(RAS_ARG) { PCell *pcell, cell; TPos x = ras.ex; if (x > ras.count_ex) x = ras.count_ex; pcell = &ras.ycells[ras.ey]; for (;;) { cell = *pcell; if (cell == NULL || cell->x > x) break; if (cell->x == x) goto Exit; pcell = &cell->next; } if (ras.num_cells >= ras.max_cells) ft_longjmp(ras.jump_buffer, 1); cell = ras.cells + ras.num_cells++; cell->x = x; cell->area = 0; cell->cover = 0; cell->next = *pcell; *pcell = cell; Exit: return cell; } static void gray_record_cell(RAS_ARG) { if (ras.area | ras.cover) { PCell cell = gray_find_cell(RAS_VAR); cell->area += ras.area; cell->cover += ras.cover; } } /*************************************************************************/ /* */ /* Set the current cell to a new position. */ /* */ static void gray_set_cell(RAS_ARG_ TCoord ex, TCoord ey) { /* Move the cell pointer to a new position. We set the `invalid' */ /* flag to indicate that the cell isn't part of those we're interested */ /* in during the render phase. This means that: */ /* */ /* . the new vertical position must be within min_ey..max_ey-1. */ /* . the new horizontal position must be strictly less than max_ex */ /* */ /* Note that if a cell is to the left of the clipping region, it is */ /* actually set to the (min_ex-1) horizontal position. */ /* All cells that are on the left of the clipping region go to the */ /* min_ex - 1 horizontal position. */ ey -= ras.min_ey; if (ex > ras.max_ex) ex = ras.max_ex; ex -= ras.min_ex; if (ex < 0) ex = -1; /* are we moving to a different cell ? */ if (ex != ras.ex || ey != ras.ey) { /* record the current one if it is valid */ if (!ras.invalid) gray_record_cell(RAS_VAR); ras.area = 0; ras.cover = 0; ras.ex = ex; ras.ey = ey; } ras.invalid = ((unsigned)ey >= (unsigned)ras.count_ey || ex >= ras.count_ex); } /*************************************************************************/ /* */ /* Start a new contour at a given cell. */ /* */ static void gray_start_cell(RAS_ARG_ TCoord ex, TCoord ey) { if (ex > ras.max_ex) ex = (TCoord)(ras.max_ex); if (ex < ras.min_ex) ex = (TCoord)(ras.min_ex - 1); ras.area = 0; ras.cover = 0; ras.ex = ex - ras.min_ex; ras.ey = ey - ras.min_ey; ras.invalid = 0; gray_set_cell(RAS_VAR_ ex, ey); } /*************************************************************************/ /* */ /* Render a straight line across multiple cells in any direction. */ /* */ static void gray_render_line(RAS_ARG_ TPos to_x, TPos to_y) { TPos dx, dy, fx1, fy1, fx2, fy2; TCoord ex1, ex2, ey1, ey2; ex1 = TRUNC(ras.x); ex2 = TRUNC(to_x); ey1 = TRUNC(ras.y); ey2 = TRUNC(to_y); /* perform vertical clipping */ if ((ey1 >= ras.max_ey && ey2 >= ras.max_ey) || (ey1 < ras.min_ey && ey2 < ras.min_ey)) goto End; dx = to_x - ras.x; dy = to_y - ras.y; fx1 = ras.x - SUBPIXELS(ex1); fy1 = ras.y - SUBPIXELS(ey1); if (ex1 == ex2 && ey1 == ey2) /* inside one cell */ ; else if (dy == 0) /* ex1 != ex2 */ /* any horizontal line */ { ex1 = ex2; gray_set_cell(RAS_VAR_ ex1, ey1); } else if (dx == 0) { if (dy > 0) /* vertical line up */ do { fy2 = ONE_PIXEL; ras.cover += (fy2 - fy1); ras.area += (fy2 - fy1) * fx1 * 2; fy1 = 0; ey1++; gray_set_cell(RAS_VAR_ ex1, ey1); } while (ey1 != ey2); else /* vertical line down */ do { fy2 = 0; ras.cover += (fy2 - fy1); ras.area += (fy2 - fy1) * fx1 * 2; fy1 = ONE_PIXEL; ey1--; gray_set_cell(RAS_VAR_ ex1, ey1); } while (ey1 != ey2); } else /* any other line */ { TArea prod = dx * fy1 - dy * fx1; SW_FT_UDIVPREP(dx); SW_FT_UDIVPREP(dy); /* The fundamental value `prod' determines which side and the */ /* exact coordinate where the line exits current cell. It is */ /* also easily updated when moving from one cell to the next. */ do { if (prod <= 0 && prod - dx * ONE_PIXEL > 0) /* left */ { fx2 = 0; fy2 = (TPos)SW_FT_UDIV(-prod, -dx); prod -= dy * ONE_PIXEL; ras.cover += (fy2 - fy1); ras.area += (fy2 - fy1) * (fx1 + fx2); fx1 = ONE_PIXEL; fy1 = fy2; ex1--; } else if (prod - dx * ONE_PIXEL <= 0 && prod - dx * ONE_PIXEL + dy * ONE_PIXEL > 0) /* up */ { prod -= dx * ONE_PIXEL; fx2 = (TPos)SW_FT_UDIV(-prod, dy); fy2 = ONE_PIXEL; ras.cover += (fy2 - fy1); ras.area += (fy2 - fy1) * (fx1 + fx2); fx1 = fx2; fy1 = 0; ey1++; } else if (prod - dx * ONE_PIXEL + dy * ONE_PIXEL <= 0 && prod + dy * ONE_PIXEL >= 0) /* right */ { prod += dy * ONE_PIXEL; fx2 = ONE_PIXEL; fy2 = (TPos)SW_FT_UDIV(prod, dx); ras.cover += (fy2 - fy1); ras.area += (fy2 - fy1) * (fx1 + fx2); fx1 = 0; fy1 = fy2; ex1++; } else /* ( prod + dy * ONE_PIXEL < 0 && prod > 0 ) down */ { fx2 = (TPos)SW_FT_UDIV(prod, -dy); fy2 = 0; prod += dx * ONE_PIXEL; ras.cover += (fy2 - fy1); ras.area += (fy2 - fy1) * (fx1 + fx2); fx1 = fx2; fy1 = ONE_PIXEL; ey1--; } gray_set_cell(RAS_VAR_ ex1, ey1); } while (ex1 != ex2 || ey1 != ey2); } fx2 = to_x - SUBPIXELS(ex2); fy2 = to_y - SUBPIXELS(ey2); ras.cover += (fy2 - fy1); ras.area += (fy2 - fy1) * (fx1 + fx2); End: ras.x = to_x; ras.y = to_y; } static void gray_split_conic(SW_FT_Vector* base) { TPos a, b; base[4].x = base[2].x; a = base[0].x + base[1].x; b = base[1].x + base[2].x; base[3].x = b >> 1; base[2].x = ( a + b ) >> 2; base[1].x = a >> 1; base[4].y = base[2].y; a = base[0].y + base[1].y; b = base[1].y + base[2].y; base[3].y = b >> 1; base[2].y = ( a + b ) >> 2; base[1].y = a >> 1; } static void gray_render_conic(RAS_ARG_ const SW_FT_Vector* control, const SW_FT_Vector* to) { TPos dx, dy; TPos min, max, y; int top, level; int* levels; SW_FT_Vector* arc; levels = ras.lev_stack; arc = ras.bez_stack; arc[0].x = UPSCALE(to->x); arc[0].y = UPSCALE(to->y); arc[1].x = UPSCALE(control->x); arc[1].y = UPSCALE(control->y); arc[2].x = ras.x; arc[2].y = ras.y; top = 0; dx = SW_FT_ABS(arc[2].x + arc[0].x - 2 * arc[1].x); dy = SW_FT_ABS(arc[2].y + arc[0].y - 2 * arc[1].y); if (dx < dy) dx = dy; if (dx < ONE_PIXEL / 4) goto Draw; /* short-cut the arc that crosses the current band */ min = max = arc[0].y; y = arc[1].y; if (y < min) min = y; if (y > max) max = y; y = arc[2].y; if (y < min) min = y; if (y > max) max = y; if (TRUNC(min) >= ras.max_ey || TRUNC(max) < ras.min_ey) goto Draw; level = 0; do { dx >>= 2; level++; } while (dx > ONE_PIXEL / 4); levels[0] = level; do { level = levels[top]; if (level > 0) { gray_split_conic(arc); arc += 2; top++; levels[top] = levels[top - 1] = level - 1; continue; } Draw: gray_render_line(RAS_VAR_ arc[0].x, arc[0].y); top--; arc -= 2; } while (top >= 0); } static void gray_split_cubic(SW_FT_Vector* base) { TPos a, b, c; base[6].x = base[3].x; a = base[0].x + base[1].x; b = base[1].x + base[2].x; c = base[2].x + base[3].x; base[5].x = c >> 1; c += b; base[4].x = c >> 2; base[1].x = a >> 1; a += b; base[2].x = a >> 2; base[3].x = ( a + c ) >> 3; base[6].y = base[3].y; a = base[0].y + base[1].y; b = base[1].y + base[2].y; c = base[2].y + base[3].y; base[5].y = c >> 1; c += b; base[4].y = c >> 2; base[1].y = a >> 1; a += b; base[2].y = a >> 2; base[3].y = ( a + c ) >> 3; } static void gray_render_cubic(RAS_ARG_ const SW_FT_Vector* control1, const SW_FT_Vector* control2, const SW_FT_Vector* to) { SW_FT_Vector* arc = ras.bez_stack; arc[0].x = UPSCALE( to->x ); arc[0].y = UPSCALE( to->y ); arc[1].x = UPSCALE( control2->x ); arc[1].y = UPSCALE( control2->y ); arc[2].x = UPSCALE( control1->x ); arc[2].y = UPSCALE( control1->y ); arc[3].x = ras.x; arc[3].y = ras.y; /* short-cut the arc that crosses the current band */ if ( ( TRUNC( arc[0].y ) >= ras.max_ey && TRUNC( arc[1].y ) >= ras.max_ey && TRUNC( arc[2].y ) >= ras.max_ey && TRUNC( arc[3].y ) >= ras.max_ey ) || ( TRUNC( arc[0].y ) < ras.min_ey && TRUNC( arc[1].y ) < ras.min_ey && TRUNC( arc[2].y ) < ras.min_ey && TRUNC( arc[3].y ) < ras.min_ey ) ) { ras.x = arc[0].x; ras.y = arc[0].y; return; } for (;;) { /* with each split, control points quickly converge towards */ /* chord trisection points and the vanishing distances below */ /* indicate when the segment is flat enough to draw */ if ( SW_FT_ABS( 2 * arc[0].x - 3 * arc[1].x + arc[3].x ) > ONE_PIXEL / 2 || SW_FT_ABS( 2 * arc[0].y - 3 * arc[1].y + arc[3].y ) > ONE_PIXEL / 2 || SW_FT_ABS( arc[0].x - 3 * arc[2].x + 2 * arc[3].x ) > ONE_PIXEL / 2 || SW_FT_ABS( arc[0].y - 3 * arc[2].y + 2 * arc[3].y ) > ONE_PIXEL / 2 ) goto Split; gray_render_line( RAS_VAR_ arc[0].x, arc[0].y ); if ( arc == ras.bez_stack ) return; arc -= 3; continue; Split: gray_split_cubic( arc ); arc += 3; } } static int gray_move_to(const SW_FT_Vector* to, gray_PWorker worker) { TPos x, y; /* record current cell, if any */ if (!ras.invalid) gray_record_cell(RAS_VAR); /* start to a new position */ x = UPSCALE(to->x); y = UPSCALE(to->y); gray_start_cell(RAS_VAR_ TRUNC(x), TRUNC(y)); worker->x = x; worker->y = y; return 0; } static int gray_line_to(const SW_FT_Vector* to, gray_PWorker worker) { gray_render_line(RAS_VAR_ UPSCALE(to->x), UPSCALE(to->y)); return 0; } static int gray_conic_to(const SW_FT_Vector* control, const SW_FT_Vector* to, gray_PWorker worker) { gray_render_conic(RAS_VAR_ control, to); return 0; } static int gray_cubic_to(const SW_FT_Vector* control1, const SW_FT_Vector* control2, const SW_FT_Vector* to, gray_PWorker worker) { gray_render_cubic(RAS_VAR_ control1, control2, to); return 0; } static void gray_hline(RAS_ARG_ TCoord x, TCoord y, TPos area, TCoord acount) { int coverage; /* compute the coverage line's coverage, depending on the */ /* outline fill rule */ /* */ /* the coverage percentage is area/(PIXEL_BITS*PIXEL_BITS*2) */ /* */ coverage = (int)(area >> (PIXEL_BITS * 2 + 1 - 8)); /* use range 0..256 */ if (coverage < 0) coverage = -coverage; if (ras.outline.flags & SW_FT_OUTLINE_EVEN_ODD_FILL) { coverage &= 511; if (coverage > 256) coverage = 512 - coverage; else if (coverage == 256) coverage = 255; } else { /* normal non-zero winding rule */ if (coverage >= 256) coverage = 255; } y += (TCoord)ras.min_ey; x += (TCoord)ras.min_ex; /* SW_FT_Span.x is a 16-bit short, so limit our coordinates appropriately */ if (x >= 32767) x = 32767; /* SW_FT_Span.y is an integer, so limit our coordinates appropriately */ if (y >= SW_FT_INT_MAX) y = SW_FT_INT_MAX; if (coverage) { SW_FT_Span* span; int count; // update bounding box. if (x < ras.bound_left) ras.bound_left = x; if (y < ras.bound_top) ras.bound_top = y; if (y > ras.bound_bottom) ras.bound_bottom = y; if (x + acount > ras.bound_right) ras.bound_right = x + acount; /* see whether we can add this span to the current list */ count = ras.num_gray_spans; span = ras.gray_spans + count - 1; if (count > 0 && span->y == y && (int)span->x + span->len == (int)x && span->coverage == coverage) { span->len = (unsigned short)(span->len + acount); return; } if (count >= SW_FT_MAX_GRAY_SPANS) { if (ras.render_span && count > 0) ras.render_span(count, ras.gray_spans, ras.render_span_data); #ifdef DEBUG_GRAYS if (1) { int n; fprintf(stderr, "count = %3d ", count); span = ras.gray_spans; for (n = 0; n < count; n++, span++) fprintf(stderr, "[%d , %d..%d] : %d ", span->y, span->x, span->x + span->len - 1, span->coverage); fprintf(stderr, "\n"); } #endif /* DEBUG_GRAYS */ ras.num_gray_spans = 0; span = ras.gray_spans; } else span++; /* add a gray span to the current list */ span->x = (short)x; span->y = (short)y; span->len = (unsigned short)acount; span->coverage = (unsigned char)coverage; ras.num_gray_spans++; } } static void gray_sweep(RAS_ARG) { int yindex; if (ras.num_cells == 0) return; ras.num_gray_spans = 0; for (yindex = 0; yindex < ras.ycount; yindex++) { PCell cell = ras.ycells[yindex]; TCoord cover = 0; TCoord x = 0; for (; cell != NULL; cell = cell->next) { TPos area; if (cell->x > x && cover != 0) gray_hline(RAS_VAR_ x, yindex, cover * (ONE_PIXEL * 2), cell->x - x); cover += cell->cover; area = cover * (ONE_PIXEL * 2) - cell->area; if (area != 0 && cell->x >= 0) gray_hline(RAS_VAR_ cell->x, yindex, area, 1); x = cell->x + 1; } if (cover != 0) gray_hline(RAS_VAR_ x, yindex, cover * (ONE_PIXEL * 2), ras.count_ex - x); } if (ras.render_span && ras.num_gray_spans > 0) ras.render_span(ras.num_gray_spans, ras.gray_spans, ras.render_span_data); } /*************************************************************************/ /* */ /* The following function should only compile in stand-alone mode, */ /* i.e., when building this component without the rest of FreeType. */ /* */ /*************************************************************************/ /*************************************************************************/ /* */ /* <Function> */ /* SW_FT_Outline_Decompose */ /* */ /* <Description> */ /* Walk over an outline's structure to decompose it into individual */ /* segments and Bézier arcs. This function is also able to emit */ /* `move to' and `close to' operations to indicate the start and end */ /* of new contours in the outline. */ /* */ /* <Input> */ /* outline :: A pointer to the source target. */ /* */ /* func_interface :: A table of `emitters', i.e., function pointers */ /* called during decomposition to indicate path */ /* operations. */ /* */ /* <InOut> */ /* user :: A typeless pointer which is passed to each */ /* emitter during the decomposition. It can be */ /* used to store the state during the */ /* decomposition. */ /* */ /* <Return> */ /* Error code. 0 means success. */ /* */ static int SW_FT_Outline_Decompose(const SW_FT_Outline* outline, const SW_FT_Outline_Funcs* func_interface, void* user) { #undef SCALED #define SCALED(x) (((x) << shift) - delta) SW_FT_Vector v_last; SW_FT_Vector v_control; SW_FT_Vector v_start; SW_FT_Vector* point; SW_FT_Vector* limit; char* tags; int error; int n; /* index of contour in outline */ int first; /* index of first point in contour */ char tag; /* current point's state */ int shift; TPos delta; if (!outline || !func_interface) return SW_FT_THROW(Invalid_Argument); shift = func_interface->shift; delta = func_interface->delta; first = 0; for (n = 0; n < outline->n_contours; n++) { int last; /* index of last point in contour */ last = outline->contours[n]; if (last < 0) goto Invalid_Outline; limit = outline->points + last; v_start = outline->points[first]; v_start.x = SCALED(v_start.x); v_start.y = SCALED(v_start.y); v_last = outline->points[last]; v_last.x = SCALED(v_last.x); v_last.y = SCALED(v_last.y); v_control = v_start; point = outline->points + first; tags = outline->tags + first; tag = SW_FT_CURVE_TAG(tags[0]); /* A contour cannot start with a cubic control point! */ if (tag == SW_FT_CURVE_TAG_CUBIC) goto Invalid_Outline; /* check first point to determine origin */ if (tag == SW_FT_CURVE_TAG_CONIC) { /* first point is conic control. Yes, this happens. */ if (SW_FT_CURVE_TAG(outline->tags[last]) == SW_FT_CURVE_TAG_ON) { /* start at last point if it is on the curve */ v_start = v_last; limit--; } else { /* if both first and last points are conic, */ /* start at their middle and record its position */ /* for closure */ v_start.x = (v_start.x + v_last.x) / 2; v_start.y = (v_start.y + v_last.y) / 2; } point--; tags--; } error = func_interface->move_to(&v_start, user); if (error) goto Exit; while (point < limit) { point++; tags++; tag = SW_FT_CURVE_TAG(tags[0]); switch (tag) { case SW_FT_CURVE_TAG_ON: /* emit a single line_to */ { SW_FT_Vector vec; vec.x = SCALED(point->x); vec.y = SCALED(point->y); error = func_interface->line_to(&vec, user); if (error) goto Exit; continue; } case SW_FT_CURVE_TAG_CONIC: /* consume conic arcs */ v_control.x = SCALED(point->x); v_control.y = SCALED(point->y); Do_Conic: if (point < limit) { SW_FT_Vector vec; SW_FT_Vector v_middle; point++; tags++; tag = SW_FT_CURVE_TAG(tags[0]); vec.x = SCALED(point->x); vec.y = SCALED(point->y); if (tag == SW_FT_CURVE_TAG_ON) { error = func_interface->conic_to(&v_control, &vec, user); if (error) goto Exit; continue; } if (tag != SW_FT_CURVE_TAG_CONIC) goto Invalid_Outline; v_middle.x = (v_control.x + vec.x) / 2; v_middle.y = (v_control.y + vec.y) / 2; error = func_interface->conic_to(&v_control, &v_middle, user); if (error) goto Exit; v_control = vec; goto Do_Conic; } error = func_interface->conic_to(&v_control, &v_start, user); goto Close; default: /* SW_FT_CURVE_TAG_CUBIC */ { SW_FT_Vector vec1, vec2; if (point + 1 > limit || SW_FT_CURVE_TAG(tags[1]) != SW_FT_CURVE_TAG_CUBIC) goto Invalid_Outline; point += 2; tags += 2; vec1.x = SCALED(point[-2].x); vec1.y = SCALED(point[-2].y); vec2.x = SCALED(point[-1].x); vec2.y = SCALED(point[-1].y); if (point <= limit) { SW_FT_Vector vec; vec.x = SCALED(point->x); vec.y = SCALED(point->y); error = func_interface->cubic_to(&vec1, &vec2, &vec, user); if (error) goto Exit; continue; } error = func_interface->cubic_to(&vec1, &vec2, &v_start, user); goto Close; } } } /* close the contour with a line segment */ error = func_interface->line_to(&v_start, user); Close: if (error) goto Exit; first = last + 1; } return 0; Exit: return error; Invalid_Outline: return SW_FT_THROW(Invalid_Outline); } typedef struct gray_TBand_ { TPos min, max; } gray_TBand; SW_FT_DEFINE_OUTLINE_FUNCS(func_interface, (SW_FT_Outline_MoveTo_Func)gray_move_to, (SW_FT_Outline_LineTo_Func)gray_line_to, (SW_FT_Outline_ConicTo_Func)gray_conic_to, (SW_FT_Outline_CubicTo_Func)gray_cubic_to, 0, 0) static int gray_convert_glyph_inner(RAS_ARG) { volatile int error = 0; if (ft_setjmp(ras.jump_buffer) == 0) { error = SW_FT_Outline_Decompose(&ras.outline, &func_interface, &ras); if (!ras.invalid) gray_record_cell(RAS_VAR); } else error = SW_FT_THROW(Memory_Overflow); return error; } static int gray_convert_glyph(RAS_ARG) { gray_TBand bands[40]; gray_TBand* volatile band; int volatile n, num_bands; TPos volatile min, max, max_y; SW_FT_BBox* clip; /* Set up state in the raster object */ gray_compute_cbox(RAS_VAR); /* clip to target bitmap, exit if nothing to do */ clip = &ras.clip_box; if (ras.max_ex <= clip->xMin || ras.min_ex >= clip->xMax || ras.max_ey <= clip->yMin || ras.min_ey >= clip->yMax) return 0; if (ras.min_ex < clip->xMin) ras.min_ex = clip->xMin; if (ras.min_ey < clip->yMin) ras.min_ey = clip->yMin; if (ras.max_ex > clip->xMax) ras.max_ex = clip->xMax; if (ras.max_ey > clip->yMax) ras.max_ey = clip->yMax; ras.count_ex = ras.max_ex - ras.min_ex; ras.count_ey = ras.max_ey - ras.min_ey; /* set up vertical bands */ num_bands = (int)((ras.max_ey - ras.min_ey) / ras.band_size); if (num_bands == 0) num_bands = 1; if (num_bands >= 39) num_bands = 39; ras.band_shoot = 0; min = ras.min_ey; max_y = ras.max_ey; for (n = 0; n < num_bands; n++, min = max) { max = min + ras.band_size; if (n == num_bands - 1 || max > max_y) max = max_y; bands[0].min = min; bands[0].max = max; band = bands; while (band >= bands) { TPos bottom, top, middle; int error; { PCell cells_max; int yindex; long cell_start, cell_end, cell_mod; ras.ycells = (PCell*)ras.buffer; ras.ycount = band->max - band->min; cell_start = sizeof(PCell) * ras.ycount; cell_mod = cell_start % sizeof(TCell); if (cell_mod > 0) cell_start += sizeof(TCell) - cell_mod; cell_end = ras.buffer_size; cell_end -= cell_end % sizeof(TCell); cells_max = (PCell)((char*)ras.buffer + cell_end); ras.cells = (PCell)((char*)ras.buffer + cell_start); if (ras.cells >= cells_max) goto ReduceBands; ras.max_cells = cells_max - ras.cells; if (ras.max_cells < 2) goto ReduceBands; for (yindex = 0; yindex < ras.ycount; yindex++) ras.ycells[yindex] = NULL; } ras.num_cells = 0; ras.invalid = 1; ras.min_ey = band->min; ras.max_ey = band->max; ras.count_ey = band->max - band->min; error = gray_convert_glyph_inner(RAS_VAR); if (!error) { gray_sweep(RAS_VAR); band--; continue; } else if (error != ErrRaster_Memory_Overflow) return 1; ReduceBands: /* render pool overflow; we will reduce the render band by half */ bottom = band->min; top = band->max; middle = bottom + ((top - bottom) >> 1); /* This is too complex for a single scanline; there must */ /* be some problems. */ if (middle == bottom) { return 1; } if (bottom - top >= ras.band_size) ras.band_shoot++; band[1].min = bottom; band[1].max = middle; band[0].min = middle; band[0].max = top; band++; } } if (ras.band_shoot > 8 && ras.band_size > 16) ras.band_size = ras.band_size / 2; return 0; } static int gray_raster_render(gray_PRaster raster, const SW_FT_Raster_Params* params) { SW_FT_UNUSED(raster); const SW_FT_Outline* outline = (const SW_FT_Outline*)params->source; gray_TWorker worker[1]; TCell buffer[SW_FT_RENDER_POOL_SIZE / sizeof(TCell)]; long buffer_size = sizeof(buffer); int band_size = (int)(buffer_size / (long)(sizeof(TCell) * 8)); if (!outline) return SW_FT_THROW(Invalid_Outline); /* return immediately if the outline is empty */ if (outline->n_points == 0 || outline->n_contours <= 0) return 0; if (!outline->contours || !outline->points) return SW_FT_THROW(Invalid_Outline); if (outline->n_points != outline->contours[outline->n_contours - 1] + 1) return SW_FT_THROW(Invalid_Outline); /* this version does not support monochrome rendering */ if (!(params->flags & SW_FT_RASTER_FLAG_AA)) return SW_FT_THROW(Invalid_Mode); if (params->flags & SW_FT_RASTER_FLAG_CLIP) ras.clip_box = params->clip_box; else { ras.clip_box.xMin = -32768L; ras.clip_box.yMin = -32768L; ras.clip_box.xMax = 32767L; ras.clip_box.yMax = 32767L; } gray_init_cells(RAS_VAR_ buffer, buffer_size); ras.outline = *outline; ras.num_cells = 0; ras.invalid = 1; ras.band_size = band_size; ras.num_gray_spans = 0; ras.render_span = (SW_FT_Raster_Span_Func)params->gray_spans; ras.render_span_data = params->user; gray_convert_glyph(RAS_VAR); params->bbox_cb(ras.bound_left, ras.bound_top, ras.bound_right - ras.bound_left, ras.bound_bottom - ras.bound_top + 1, params->user); return 1; } /**** RASTER OBJECT CREATION: In stand-alone mode, we simply use *****/ /**** a static object. *****/ static int gray_raster_new(SW_FT_Raster* araster) { static gray_TRaster the_raster; *araster = (SW_FT_Raster)&the_raster; SW_FT_MEM_ZERO(&the_raster, sizeof(the_raster)); return 0; } static void gray_raster_done(SW_FT_Raster raster) { /* nothing */ SW_FT_UNUSED(raster); } static void gray_raster_reset(SW_FT_Raster raster, char* pool_base, long pool_size) { SW_FT_UNUSED(raster); SW_FT_UNUSED(pool_base); SW_FT_UNUSED(pool_size); } SW_FT_DEFINE_RASTER_FUNCS(sw_ft_grays_raster, (SW_FT_Raster_New_Func)gray_raster_new, (SW_FT_Raster_Reset_Func)gray_raster_reset, (SW_FT_Raster_Render_Func)gray_raster_render, (SW_FT_Raster_Done_Func)gray_raster_done) /* END */
46,944
v_ft_raster
cpp
en
cpp
code
{"qsc_code_num_words": 5582, "qsc_code_num_chars": 46944.0, "qsc_code_mean_word_length": 3.77696166, "qsc_code_frac_words_unique": 0.11895378, "qsc_code_frac_chars_top_2grams": 0.03434046, "qsc_code_frac_chars_top_3grams": 0.01707537, "qsc_code_frac_chars_top_4grams": 0.013518, "qsc_code_frac_chars_dupe_5grams": 0.32466916, "qsc_code_frac_chars_dupe_6grams": 0.23507091, "qsc_code_frac_chars_dupe_7grams": 0.1874496, "qsc_code_frac_chars_dupe_8grams": 0.14096666, "qsc_code_frac_chars_dupe_9grams": 0.11582792, "qsc_code_frac_chars_dupe_10grams": 0.10188303, "qsc_code_frac_chars_replacement_symbols": 0.0, "qsc_code_frac_chars_digital": 0.01947802, "qsc_code_frac_chars_whitespace": 0.39193507, "qsc_code_size_file_byte": 46944.0, "qsc_code_num_lines": 1423.0, "qsc_code_num_chars_line_max": 82.0, "qsc_code_num_chars_line_mean": 32.98945889, "qsc_code_frac_chars_alphabet": 0.71911018, "qsc_code_frac_chars_comments": 0.31437457, "qsc_code_cate_xml_start": 0.0, "qsc_code_frac_lines_dupe_lines": 0.22927879, "qsc_code_cate_autogen": 0.0, "qsc_code_frac_lines_long_string": 0.0, "qsc_code_frac_chars_string_length": 0.00177096, "qsc_code_frac_chars_long_word_length": 0.0, "qsc_code_frac_lines_string_concat": 0.0, "qsc_code_cate_encoded_data": 0.0, "qsc_code_frac_chars_hex_words": 0.0, "qsc_code_frac_lines_prompt_comments": 0.0, "qsc_code_frac_lines_assert": 0.0, "qsc_codecpp_frac_lines_preprocessor_directives": 0.11625404, "qsc_codecpp_frac_lines_func_ratio": 0.06350915, "qsc_codecpp_cate_bitsstdc": 0.0, "qsc_codecpp_nums_lines_main": 0.0, "qsc_codecpp_frac_lines_goto": 0.02152853, "qsc_codecpp_cate_var_zero": 0.0, "qsc_codecpp_score_lines_no_logic": 0.11194833, "qsc_codecpp_frac_lines_print": 0.00322928}
1
{"qsc_code_frac_chars_replacement_symbols": 0, "qsc_code_num_words": 0, "qsc_code_num_chars": 0, "qsc_code_mean_word_length": 0, "qsc_code_frac_chars_top_2grams": 0, "qsc_code_frac_chars_top_3grams": 0, "qsc_code_frac_chars_top_4grams": 0, "qsc_code_frac_chars_dupe_5grams": 0, "qsc_code_frac_chars_dupe_6grams": 0, "qsc_code_frac_chars_dupe_7grams": 0, "qsc_code_frac_chars_dupe_8grams": 0, "qsc_code_frac_chars_dupe_9grams": 0, "qsc_code_frac_chars_dupe_10grams": 0, "qsc_code_frac_lines_dupe_lines": 0, "qsc_code_size_file_byte": 0, "qsc_code_num_lines": 0, "qsc_code_num_chars_line_max": 0, "qsc_code_num_chars_line_mean": 0, "qsc_code_frac_chars_alphabet": 0, "qsc_code_frac_chars_digital": 0, "qsc_code_frac_chars_whitespace": 0, "qsc_code_frac_chars_comments": 0, "qsc_code_cate_xml_start": 0, "qsc_code_cate_autogen": 0, "qsc_code_frac_lines_long_string": 0, "qsc_code_frac_chars_string_length": 0, "qsc_code_frac_chars_long_word_length": 0, "qsc_code_cate_encoded_data": 0, "qsc_code_frac_chars_hex_words": 0, "qsc_code_frac_lines_prompt_comments": 0, "qsc_code_frac_lines_assert": 0, "qsc_codecpp_frac_lines_func_ratio": 0, "qsc_codecpp_nums_lines_main": 0, "qsc_codecpp_score_lines_no_logic": 0, "qsc_codecpp_frac_lines_preprocessor_directives": 0, "qsc_codecpp_frac_lines_print": 0}
0015/esp_rlottie
rlottie/src/vector/freetype/v_ft_math.cpp
/***************************************************************************/ /* */ /* fttrigon.c */ /* */ /* FreeType trigonometric functions (body). */ /* */ /* Copyright 2001-2005, 2012-2013 by */ /* David Turner, Robert Wilhelm, and Werner Lemberg. */ /* */ /* This file is part of the FreeType project, and may only be used, */ /* modified, and distributed under the terms of the FreeType project */ /* license, LICENSE.TXT. By continuing to use, modify, or distribute */ /* this file you indicate that you have read the license and */ /* understand and accept it fully. */ /* */ /***************************************************************************/ #include "v_ft_math.h" #include <math.h> //form https://github.com/chromium/chromium/blob/59afd8336009c9d97c22854c52e0382b62b3aa5e/third_party/abseil-cpp/absl/base/internal/bits.h #if defined(_MSC_VER) #include <intrin.h> static unsigned int __inline clz(unsigned int x) { unsigned long r = 0; if (x != 0) { _BitScanReverse(&r, x); } return r; } #define SW_FT_MSB(x) (clz(x)) #elif defined(__GNUC__) #define SW_FT_MSB(x) (31 - __builtin_clz(x)) #else static unsigned int __inline clz(unsigned int x) { int c = 31; x &= ~x + 1; if (n & 0x0000FFFF) c -= 16; if (n & 0x00FF00FF) c -= 8; if (n & 0x0F0F0F0F) c -= 4; if (n & 0x33333333) c -= 2; if (n & 0x55555555) c -= 1; return c; } #define SW_FT_MSB(x) (clz(x)) #endif #define SW_FT_PAD_FLOOR(x, n) ((x) & ~((n)-1)) #define SW_FT_PAD_ROUND(x, n) SW_FT_PAD_FLOOR((x) + ((n) / 2), n) #define SW_FT_PAD_CEIL(x, n) SW_FT_PAD_FLOOR((x) + ((n)-1), n) #define SW_FT_BEGIN_STMNT do { #define SW_FT_END_STMNT \ } \ while (0) /* transfer sign leaving a positive number */ #define SW_FT_MOVE_SIGN(x, s) \ SW_FT_BEGIN_STMNT \ if (x < 0) { \ x = -x; \ s = -s; \ } \ SW_FT_END_STMNT SW_FT_Long SW_FT_MulFix(SW_FT_Long a, SW_FT_Long b) { SW_FT_Int s = 1; SW_FT_Long c; SW_FT_MOVE_SIGN(a, s); SW_FT_MOVE_SIGN(b, s); c = (SW_FT_Long)(((SW_FT_Int64)a * b + 0x8000L) >> 16); return (s > 0) ? c : -c; } SW_FT_Long SW_FT_MulDiv(SW_FT_Long a, SW_FT_Long b, SW_FT_Long c) { SW_FT_Int s = 1; SW_FT_Long d; SW_FT_MOVE_SIGN(a, s); SW_FT_MOVE_SIGN(b, s); SW_FT_MOVE_SIGN(c, s); d = (SW_FT_Long)(c > 0 ? ((SW_FT_Int64)a * b + (c >> 1)) / c : 0x7FFFFFFFL); return (s > 0) ? d : -d; } SW_FT_Long SW_FT_DivFix(SW_FT_Long a, SW_FT_Long b) { SW_FT_Int s = 1; SW_FT_Long q; SW_FT_MOVE_SIGN(a, s); SW_FT_MOVE_SIGN(b, s); q = (SW_FT_Long)(b > 0 ? (((SW_FT_UInt64)a << 16) + (b >> 1)) / b : 0x7FFFFFFFL); return (s < 0 ? -q : q); } /*************************************************************************/ /* */ /* This is a fixed-point CORDIC implementation of trigonometric */ /* functions as well as transformations between Cartesian and polar */ /* coordinates. The angles are represented as 16.16 fixed-point values */ /* in degrees, i.e., the angular resolution is 2^-16 degrees. Note that */ /* only vectors longer than 2^16*180/pi (or at least 22 bits) on a */ /* discrete Cartesian grid can have the same or better angular */ /* resolution. Therefore, to maintain this precision, some functions */ /* require an interim upscaling of the vectors, whereas others operate */ /* with 24-bit long vectors directly. */ /* */ /*************************************************************************/ /* the Cordic shrink factor 0.858785336480436 * 2^32 */ #define SW_FT_TRIG_SCALE 0xDBD95B16UL /* the highest bit in overflow-safe vector components, */ /* MSB of 0.858785336480436 * sqrt(0.5) * 2^30 */ #define SW_FT_TRIG_SAFE_MSB 29 /* this table was generated for SW_FT_PI = 180L << 16, i.e. degrees */ #define SW_FT_TRIG_MAX_ITERS 23 static const SW_FT_Fixed ft_trig_arctan_table[] = { 1740967L, 919879L, 466945L, 234379L, 117304L, 58666L, 29335L, 14668L, 7334L, 3667L, 1833L, 917L, 458L, 229L, 115L, 57L, 29L, 14L, 7L, 4L, 2L, 1L}; /* multiply a given value by the CORDIC shrink factor */ static SW_FT_Fixed ft_trig_downscale(SW_FT_Fixed val) { SW_FT_Fixed s; SW_FT_Int64 v; s = val; val = SW_FT_ABS(val); v = (val * (SW_FT_Int64)SW_FT_TRIG_SCALE) + 0x100000000UL; val = (SW_FT_Fixed)(v >> 32); return (s >= 0) ? val : -val; } /* undefined and never called for zero vector */ static SW_FT_Int ft_trig_prenorm(SW_FT_Vector* vec) { SW_FT_Pos x, y; SW_FT_Int shift; x = vec->x; y = vec->y; shift = SW_FT_MSB(SW_FT_ABS(x) | SW_FT_ABS(y)); if (shift <= SW_FT_TRIG_SAFE_MSB) { shift = SW_FT_TRIG_SAFE_MSB - shift; vec->x = (SW_FT_Pos)((SW_FT_ULong)x << shift); vec->y = (SW_FT_Pos)((SW_FT_ULong)y << shift); } else { shift -= SW_FT_TRIG_SAFE_MSB; vec->x = x >> shift; vec->y = y >> shift; shift = -shift; } return shift; } static void ft_trig_pseudo_rotate(SW_FT_Vector* vec, SW_FT_Angle theta) { SW_FT_Int i; SW_FT_Fixed x, y, xtemp, b; const SW_FT_Fixed* arctanptr; x = vec->x; y = vec->y; /* Rotate inside [-PI/4,PI/4] sector */ while (theta < -SW_FT_ANGLE_PI4) { xtemp = y; y = -x; x = xtemp; theta += SW_FT_ANGLE_PI2; } while (theta > SW_FT_ANGLE_PI4) { xtemp = -y; y = x; x = xtemp; theta -= SW_FT_ANGLE_PI2; } arctanptr = ft_trig_arctan_table; /* Pseudorotations, with right shifts */ for (i = 1, b = 1; i < SW_FT_TRIG_MAX_ITERS; b <<= 1, i++) { SW_FT_Fixed v1 = ((y + b) >> i); SW_FT_Fixed v2 = ((x + b) >> i); if (theta < 0) { xtemp = x + v1; y = y - v2; x = xtemp; theta += *arctanptr++; } else { xtemp = x - v1; y = y + v2; x = xtemp; theta -= *arctanptr++; } } vec->x = x; vec->y = y; } static void ft_trig_pseudo_polarize(SW_FT_Vector* vec) { SW_FT_Angle theta; SW_FT_Int i; SW_FT_Fixed x, y, xtemp, b; const SW_FT_Fixed* arctanptr; x = vec->x; y = vec->y; /* Get the vector into [-PI/4,PI/4] sector */ if (y > x) { if (y > -x) { theta = SW_FT_ANGLE_PI2; xtemp = y; y = -x; x = xtemp; } else { theta = y > 0 ? SW_FT_ANGLE_PI : -SW_FT_ANGLE_PI; x = -x; y = -y; } } else { if (y < -x) { theta = -SW_FT_ANGLE_PI2; xtemp = -y; y = x; x = xtemp; } else { theta = 0; } } arctanptr = ft_trig_arctan_table; /* Pseudorotations, with right shifts */ for (i = 1, b = 1; i < SW_FT_TRIG_MAX_ITERS; b <<= 1, i++) { SW_FT_Fixed v1 = ((y + b) >> i); SW_FT_Fixed v2 = ((x + b) >> i); if (y > 0) { xtemp = x + v1; y = y - v2; x = xtemp; theta += *arctanptr++; } else { xtemp = x - v1; y = y + v2; x = xtemp; theta -= *arctanptr++; } } /* round theta */ if (theta >= 0) theta = SW_FT_PAD_ROUND(theta, 32); else theta = -SW_FT_PAD_ROUND(-theta, 32); vec->x = x; vec->y = theta; } /* documentation is in fttrigon.h */ SW_FT_Fixed SW_FT_Cos(SW_FT_Angle angle) { SW_FT_Vector v; v.x = SW_FT_TRIG_SCALE >> 8; v.y = 0; ft_trig_pseudo_rotate(&v, angle); return (v.x + 0x80L) >> 8; } /* documentation is in fttrigon.h */ SW_FT_Fixed SW_FT_Sin(SW_FT_Angle angle) { return SW_FT_Cos(SW_FT_ANGLE_PI2 - angle); } /* documentation is in fttrigon.h */ SW_FT_Fixed SW_FT_Tan(SW_FT_Angle angle) { SW_FT_Vector v; v.x = SW_FT_TRIG_SCALE >> 8; v.y = 0; ft_trig_pseudo_rotate(&v, angle); return SW_FT_DivFix(v.y, v.x); } /* documentation is in fttrigon.h */ SW_FT_Angle SW_FT_Atan2(SW_FT_Fixed dx, SW_FT_Fixed dy) { SW_FT_Vector v; if (dx == 0 && dy == 0) return 0; v.x = dx; v.y = dy; ft_trig_prenorm(&v); ft_trig_pseudo_polarize(&v); return v.y; } /* documentation is in fttrigon.h */ void SW_FT_Vector_Unit(SW_FT_Vector* vec, SW_FT_Angle angle) { vec->x = SW_FT_TRIG_SCALE >> 8; vec->y = 0; ft_trig_pseudo_rotate(vec, angle); vec->x = (vec->x + 0x80L) >> 8; vec->y = (vec->y + 0x80L) >> 8; } /* these macros return 0 for positive numbers, and -1 for negative ones */ #define SW_FT_SIGN_LONG(x) ((x) >> (SW_FT_SIZEOF_LONG * 8 - 1)) #define SW_FT_SIGN_INT(x) ((x) >> (SW_FT_SIZEOF_INT * 8 - 1)) #define SW_FT_SIGN_INT32(x) ((x) >> 31) #define SW_FT_SIGN_INT16(x) ((x) >> 15) /* documentation is in fttrigon.h */ void SW_FT_Vector_Rotate(SW_FT_Vector* vec, SW_FT_Angle angle) { SW_FT_Int shift; SW_FT_Vector v; v.x = vec->x; v.y = vec->y; if (angle && (v.x != 0 || v.y != 0)) { shift = ft_trig_prenorm(&v); ft_trig_pseudo_rotate(&v, angle); v.x = ft_trig_downscale(v.x); v.y = ft_trig_downscale(v.y); if (shift > 0) { SW_FT_Int32 half = (SW_FT_Int32)1L << (shift - 1); vec->x = (v.x + half + SW_FT_SIGN_LONG(v.x)) >> shift; vec->y = (v.y + half + SW_FT_SIGN_LONG(v.y)) >> shift; } else { shift = -shift; vec->x = (SW_FT_Pos)((SW_FT_ULong)v.x << shift); vec->y = (SW_FT_Pos)((SW_FT_ULong)v.y << shift); } } } /* documentation is in fttrigon.h */ SW_FT_Fixed SW_FT_Vector_Length(SW_FT_Vector* vec) { SW_FT_Int shift; SW_FT_Vector v; v = *vec; /* handle trivial cases */ if (v.x == 0) { return SW_FT_ABS(v.y); } else if (v.y == 0) { return SW_FT_ABS(v.x); } /* general case */ shift = ft_trig_prenorm(&v); ft_trig_pseudo_polarize(&v); v.x = ft_trig_downscale(v.x); if (shift > 0) return (v.x + (1 << (shift - 1))) >> shift; return (SW_FT_Fixed)((SW_FT_UInt32)v.x << -shift); } /* documentation is in fttrigon.h */ void SW_FT_Vector_Polarize(SW_FT_Vector* vec, SW_FT_Fixed* length, SW_FT_Angle* angle) { SW_FT_Int shift; SW_FT_Vector v; v = *vec; if (v.x == 0 && v.y == 0) return; shift = ft_trig_prenorm(&v); ft_trig_pseudo_polarize(&v); v.x = ft_trig_downscale(v.x); *length = (shift >= 0) ? (v.x >> shift) : (SW_FT_Fixed)((SW_FT_UInt32)v.x << -shift); *angle = v.y; } /* documentation is in fttrigon.h */ void SW_FT_Vector_From_Polar(SW_FT_Vector* vec, SW_FT_Fixed length, SW_FT_Angle angle) { vec->x = length; vec->y = 0; SW_FT_Vector_Rotate(vec, angle); } /* documentation is in fttrigon.h */ SW_FT_Angle SW_FT_Angle_Diff( SW_FT_Angle angle1, SW_FT_Angle angle2 ) { SW_FT_Angle delta = angle2 - angle1; while ( delta <= -SW_FT_ANGLE_PI ) delta += SW_FT_ANGLE_2PI; while ( delta > SW_FT_ANGLE_PI ) delta -= SW_FT_ANGLE_2PI; return delta; } /* END */
12,132
v_ft_math
cpp
en
cpp
code
{"qsc_code_num_words": 1736, "qsc_code_num_chars": 12132.0, "qsc_code_mean_word_length": 3.30990783, "qsc_code_frac_words_unique": 0.1733871, "qsc_code_frac_chars_top_2grams": 0.1204316, "qsc_code_frac_chars_top_3grams": 0.0438566, "qsc_code_frac_chars_top_4grams": 0.04350853, "qsc_code_frac_chars_dupe_5grams": 0.50991994, "qsc_code_frac_chars_dupe_6grams": 0.46658545, "qsc_code_frac_chars_dupe_7grams": 0.41559346, "qsc_code_frac_chars_dupe_8grams": 0.38757396, "qsc_code_frac_chars_dupe_9grams": 0.34963453, "qsc_code_frac_chars_dupe_10grams": 0.31186913, "qsc_code_frac_chars_replacement_symbols": 0.0, "qsc_code_frac_chars_digital": 0.04860252, "qsc_code_frac_chars_whitespace": 0.33349819, "qsc_code_size_file_byte": 12132.0, "qsc_code_num_lines": 461.0, "qsc_code_num_chars_line_max": 139.0, "qsc_code_num_chars_line_mean": 26.31670282, "qsc_code_frac_chars_alphabet": 0.66200841, "qsc_code_frac_chars_comments": 0.28066271, "qsc_code_cate_xml_start": 0.0, "qsc_code_frac_lines_dupe_lines": 0.33876221, "qsc_code_cate_autogen": 0.0, "qsc_code_frac_lines_long_string": 0.0, "qsc_code_frac_chars_string_length": 0.00126046, "qsc_code_frac_chars_long_word_length": 0.0, "qsc_code_frac_lines_string_concat": 0.0, "qsc_code_cate_encoded_data": 0.0, "qsc_code_frac_chars_hex_words": 0.00572935, "qsc_code_frac_lines_prompt_comments": 0.0, "qsc_code_frac_lines_assert": 0.0, "qsc_codecpp_frac_lines_preprocessor_directives": 0.07491857, "qsc_codecpp_frac_lines_func_ratio": 0.11726384, "qsc_codecpp_cate_bitsstdc": 0.0, "qsc_codecpp_nums_lines_main": 0.0, "qsc_codecpp_frac_lines_goto": 0.0, "qsc_codecpp_cate_var_zero": 0.0, "qsc_codecpp_score_lines_no_logic": 0.14006515, "qsc_codecpp_frac_lines_print": 0.0}
1
{"qsc_code_frac_chars_replacement_symbols": 0, "qsc_code_num_words": 0, "qsc_code_num_chars": 0, "qsc_code_mean_word_length": 0, "qsc_code_frac_chars_top_2grams": 0, "qsc_code_frac_chars_top_3grams": 0, "qsc_code_frac_chars_top_4grams": 0, "qsc_code_frac_chars_dupe_5grams": 0, "qsc_code_frac_chars_dupe_6grams": 0, "qsc_code_frac_chars_dupe_7grams": 0, "qsc_code_frac_chars_dupe_8grams": 0, "qsc_code_frac_chars_dupe_9grams": 0, "qsc_code_frac_chars_dupe_10grams": 0, "qsc_code_frac_lines_dupe_lines": 0, "qsc_code_size_file_byte": 0, "qsc_code_num_lines": 0, "qsc_code_num_chars_line_max": 0, "qsc_code_num_chars_line_mean": 0, "qsc_code_frac_chars_alphabet": 0, "qsc_code_frac_chars_digital": 0, "qsc_code_frac_chars_whitespace": 0, "qsc_code_frac_chars_comments": 0, "qsc_code_cate_xml_start": 0, "qsc_code_cate_autogen": 0, "qsc_code_frac_lines_long_string": 0, "qsc_code_frac_chars_string_length": 0, "qsc_code_frac_chars_long_word_length": 0, "qsc_code_cate_encoded_data": 0, "qsc_code_frac_chars_hex_words": 0, "qsc_code_frac_lines_prompt_comments": 0, "qsc_code_frac_lines_assert": 0, "qsc_codecpp_frac_lines_func_ratio": 0, "qsc_codecpp_nums_lines_main": 0, "qsc_codecpp_score_lines_no_logic": 0, "qsc_codecpp_frac_lines_preprocessor_directives": 0, "qsc_codecpp_frac_lines_print": 0}