jtbg.h 最新版[实时更新]
Beta版密码: jtbgdejtbghdguitu220guihua106jtbghbetaadminspasswordishelloworld0x3giuhfbwyg2389y7fug8buhbusaybusuhvvffgviggy3r27cyf7237cxn8
公告
于 2026/1/14 日更新
点击查看公告
JTBG头文件 2025/12 号公告
关于2.8版本的错误[Error]
今日,JTBG技术部发现JTBG头文件2.8版本出现大量BUG,请大家不要使用2.8版本,
退回至2.7版本2.9版本已修复,请大家使用。-JTBG/技术部 2025/12/06 22:56
JTBG头文件 2026/01 号公告
关于3.0beta版本Rmq的错误[Error]
今日,JTBG技术部发现JTBG头文件3.0beta版本出现BUG,请大家不要使用3.0beta版本,
退回至2.9版本3.0版本已修复,请大家使用。-JTBG/技术部 2026/01/03 9:54
关于3.0版本为稳定版[Info]
今日,JTBG技术部把3.0版本确定为稳定版,公共程序可以长时间使用而不更新。
-JTBG/技术部 2026/01/03 21:16
关于3.0稳定版及以前版本对于Windows 7的兼容错误[Terrir]
今日,JTBG技术部发现JTBG头文件3.0及以前版本出现对于Windows 7的兼容错误,请大家不要在Windows 7使用isRun()函数做保护进程,这会导致系统死机或蓝屏。
-JTBG/技术部 2026/01/13 19:54
代码
点击查看代码
#undef _CONSOLE
#define _CONSOLE
#ifdef JTBG_ON_OJ
#pragma message("JTBG->JTBG_OJ [on]")
#undef NO_PRAGMA
#undef JTBG_ONLY_WINDOWS
#undef JTBG_NOWINDOWS_ALL
#undef JTBG_ALL
#define NO_PRAGMA
#define JTBG_ONLY_WINDOWS
#define JTBG_NOWINDOWS_ALL
#endif
#ifdef JTBG_NOWINDOWS_ALL
#undef JTBG_ONLY_WINDOWS
#define JTBG_ONLY_WINDOWS
#endif
#ifndef JTBG_ONLY_WINDOWS
#undef _WIN32_WINNT
#define _WIN32_WINNT 0x0601
#undef WIN32_LEAN_AND_MEAN
#define WIN32_LEAN_AND_MEAN 0x0002
#endif
#ifndef JTBG_NO_INSETD
#undef JTBG_H_VER
#define JTBG_H_VER "3.1[测试版]"
#undef JTBG_H_NOW_SEND_TIMES
#define JTBG_H_NOW_SEND_TIMES "2026/01/04"
#undef JTBG_H_CC
#define JTBG_H_CC "CC BY-NC-ND 4.0"
#undef JTBG_H_STD
#define JTBG_H_STD "gnu++11"
#undef JTBG_H_HAPPY
#define JTBG_H_HAPPY "--公告--\n1.JTBG迎来了半周年纪念,happy!\n2.2025-2026跨年啦!头文件即将开发庆祝功能!\n-我也是有底线的-\n"
#endif
#ifdef JTBG_BAN_OLD_GCC
#define _JBOG_
#endif
#ifndef NO_PRAGMA
#if defined(__GNUC__)
#pragma message("find GCC")
#if __GNUC__ < 5
#pragma message("notice:GCC too old!")
#ifdef _JBOG_
#define JTBG_GCC_OLD_NOTICE
#endif
#endif
#endif
#ifndef JTBG_NO_CONSOLE
#pragma comment(linker, "/subsystem:console")
#endif
#ifdef O1
#pragma GCC optimize("O1")
//你可以换成指令: -O1
#elif defined(O2)
#pragma GCC optimize("O2")
//你可以换成指令: -O2
#elif defined(O3)
#pragma GCC optimize("O3")
//你可以换成指令: -O3
#elif defined(Ofast)
#pragma GCC optimize("Ofast")
//你可以换成指令: -Ofast
#elif defined(Os)
#pragma GCC optimize("Os")
//你可以换成指令: -Os
#elif defined(Og)
#pragma GCC optimize("Og")
//你可以换成指令: -Og
#elif defined(O0)
#pragma GCC optimize("O0")
//你可以换成指令: -O0
#endif
#pragma cpp_std c++11
//你可以换成指令: -std=gnu++11
#pragma comment(lib, "winmm.lib")
//你可以换成 -lwinmm
#pragma comment(lib, "wininet.lib")
//你可以换成 -lwininet
#pragma comment(lib, "Advapi32.lib")
//你可以换成 -ladvapi32
#pragma comment(lib, "Shell32.lib")
//你可以换成 -lshell32
#endif
#include <bits/stdc++.h>
#ifndef JTBG_ONLY_WINDOWS
#include <winsock2.h>
#include <windows.h>
#include <stdexcept>
#include <ShlObj.h>
#include <locale>
#include <cstdint>
#include <cstdarg>
#include <stdio.h>
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <stdexcept>
#include <sstream>
#include <utility>
#include <iostream>
#include <string>
#include <vector>
#include <cmath>
#include <ctime>
#include <cstdlib>
#include <algorithm>
#include <sstream>
#include <iomanip>
#include <iomanip>
#include <mmsystem.h>
//mmsystem-define ??
#define TIME_MS 0x0001
#define TIME_SAMPLES 0x0002
#define TIME_BYTES 0x0004
#define TIME_SMPTE 0x0008
#define TIME_MIDI 0x0010
#define TIME_TICKS 0x0020
#ifndef MAKEFOURCC
#define MAKEFOURCC(ch0,ch1,ch2,ch3) \
((DWORD)(BYTE)(ch0) | ((DWORD)(BYTE)(ch1) << 8) | \
((DWORD)(BYTE)(ch2) << 16) | ((DWORD)(BYTE)(ch3) << 24))
#endif /* MAKEFOURCC */
#define MM_JOY1MOVE 0x3A0
#define MM_JOY2MOVE 0x3A1
#define MM_JOY1ZMOVE 0x3A2
#define MM_JOY2ZMOVE 0x3A3
#define MM_JOY1BUTTONDOWN 0x3B5
#define MM_JOY2BUTTONDOWN 0x3B6
#define MM_JOY1BUTTONUP 0x3B7
#define MM_JOY2BUTTONUP 0x3B8
#define MM_MCINOTIFY 0x3B9
#define MM_WOM_OPEN 0x3BB
#define MM_WOM_CLOSE 0x3BC
#define MM_WOM_DONE 0x3BD
#define MM_WIM_OPEN 0x3BE
#define MM_WIM_CLOSE 0x3BF
#define MM_WIM_DATA 0x3C0
#define MM_MIM_OPEN 0x3C1
#define MM_MIM_CLOSE 0x3C2
#define MM_MIM_DATA 0x3C3
#define MM_MIM_LONGDATA 0x3C4
#define MM_MIM_ERROR 0x3C5
#define MM_MIM_LONGERROR 0x3C6
#define MM_MOM_OPEN 0x3C7
#define MM_MOM_CLOSE 0x3C8
#define MM_MOM_DONE 0x3C9
#ifndef MM_DRVM_OPEN
#define MM_DRVM_OPEN 0x3D0
#define MM_DRVM_CLOSE 0x3D1
#define MM_DRVM_DATA 0x3D2
#define MM_DRVM_ERROR 0x3D3
#endif
#define MM_STREAM_OPEN 0x3D4
#define MM_STREAM_CLOSE 0x3D5
#define MM_STREAM_DONE 0x3D6
#define MM_STREAM_ERROR 0x3D7
#define MM_MOM_POSITIONCB 0x3CA
#ifndef MM_MCISIGNAL
#define MM_MCISIGNAL 0x3CB
#endif
#define MM_MIM_MOREDATA 0x3CC
#define MM_MIXM_LINE_CHANGE 0x3D0
#define MM_MIXM_CONTROL_CHANGE 0x3D1
#define MMSYSERR_BASE 0
#define WAVERR_BASE 32
#define MIDIERR_BASE 64
#define TIMERR_BASE 96
#define JOYERR_BASE 160
#define MCIERR_BASE 256
#define MIXERR_BASE 1024
#define MCI_STRING_OFFSET 512
#define MCI_VD_OFFSET 1024
#define MCI_CD_OFFSET 1088
#define MCI_WAVE_OFFSET 1152
#define MCI_SEQ_OFFSET 1216
#define MMSYSERR_NOERROR 0
#define MMSYSERR_ERROR (MMSYSERR_BASE + 1)
#define MMSYSERR_BADDEVICEID (MMSYSERR_BASE + 2)
#define MMSYSERR_NOTENABLED (MMSYSERR_BASE + 3)
#define MMSYSERR_ALLOCATED (MMSYSERR_BASE + 4)
#define MMSYSERR_INVALHANDLE (MMSYSERR_BASE + 5)
#define MMSYSERR_NODRIVER (MMSYSERR_BASE + 6)
#define MMSYSERR_NOMEM (MMSYSERR_BASE + 7)
#define MMSYSERR_NOTSUPPORTED (MMSYSERR_BASE + 8)
#define MMSYSERR_BADERRNUM (MMSYSERR_BASE + 9)
#define MMSYSERR_INVALFLAG (MMSYSERR_BASE + 10)
#define MMSYSERR_INVALPARAM (MMSYSERR_BASE + 11)
#define MMSYSERR_HANDLEBUSY (MMSYSERR_BASE + 12)
#define MMSYSERR_INVALIDALIAS (MMSYSERR_BASE + 13)
#define MMSYSERR_BADDB (MMSYSERR_BASE + 14)
#define MMSYSERR_KEYNOTFOUND (MMSYSERR_BASE + 15)
#define MMSYSERR_READERROR (MMSYSERR_BASE + 16)
#define MMSYSERR_WRITEERROR (MMSYSERR_BASE + 17)
#define MMSYSERR_DELETEERROR (MMSYSERR_BASE + 18)
#define MMSYSERR_VALNOTFOUND (MMSYSERR_BASE + 19)
#define MMSYSERR_NODRIVERCB (MMSYSERR_BASE + 20)
#define MMSYSERR_MOREDATA (MMSYSERR_BASE + 21)
#define MMSYSERR_LASTERROR (MMSYSERR_BASE + 21)
#include <_mingw_unicode.h>
#include <pshpack1.h>
#include <_mingw.h>
#include <sdkddkver.h>
#include <windef.h>
#include <winbase.h>
#include <wingdi.h>
#include <winuser.h>
#include <winnls.h>
#include <wincon.h>
#include <winver.h>
#include <winreg.h>
#include <winnetwk.h>
#include <virtdisk.h>
#include <iostream>
#include <istream>
#include <ostream>
#include <psapi.h>
#include <string>
#include <algorithm>
#include <cstdlib>
#include <ws2tcpip.h>
#include <system_error>
#include <string>
#include <vector>
#include <memory>
#include <deque>
#include <functional>
#include <atomic>
#include <thread>
#include <mutex>
#include <queue>
#include <condition_variable>
#include <stdexcept>
#include <cctype>
#include <mutex>
#include <fstream>
#include <chrono>
#include <conio.h>
#include <limits> // 用于清除输入缓冲区
#include <wininet.h>
#include <shlobj.h>
#include <wininet.h>
#ifndef JTBG_ALREDY_POWRPROF_H
#define JTBG_ALREDY_POWRPROF_H
#include <powrprof.h>
#endif
#include <lmaccess.h>
#include <tlhelp32.h>
#include <commctrl.h>
#include <shellapi.h>
#include <mmsystem.h>
#include <psapi.h>
#include <thread>
#include <vector>
#include <map>
#endif
//#include <unistd.h> linux/macOS
using namespace std;
#ifndef _JTBG_H_
#define _JTBG_H_
#ifdef JTBG_STRAT_PACKED
#pragma message("JTBG->JTBG_DEVED(JTBG_START_PACKED) [on]")
#include "packed.h"
#endif
#ifdef JTBG_ALL
#pragma message("JTBG->JTBG_ALL [on]")
#undef JTBG_HASH
#undef JTBG_INI
#undef JTBG_SOUND
#undef JTBG_MSGBOX
#undef JTBG_KMP
#undef JTBG_RMQ
#undef JTBG_KEY
#undef JTBG_COL
#undef JTBG_FILE
#undef JTBG_SAFE
#undef JTBG_STRING
#undef JTBG_REGI
#undef JTBG_BIGNUM
#undef JTBG_ARGCV
#undef JTBG_LUHN
#undef JTBG_RSA
#undef JTBG_PROS
#undef JTBG_PROGRESS
#undef JTBG_MES
//#undef JTBG_RSA
#undef JTBG_SYSTEM
#undef JTBG_CC
#undef JTBG_RANDOM
#undef JTBG_TIME
#undef JTBG_DECANDENC
#undef JTBG_MATH
#undef JTBG_SHORT
#undef JTBG_ADMINS
#undef JTBG_BETTER_COL
#undef JTBG_UUID
#undef JTBG_LOG
#undef JTBG_WEB
#undef JTBG_UDP
#define JTBG_HASH
#define JTBG_INI
#define JTBG_PROS
#define JTBG_PROGRESS
#define JTBG_MSGBOX
#define JTBG_KMP
#define JTBG_KEY
#define JTBG_COL
#define JTBG_BETTER_COL
#define JTBG_FILE
//#define JTBG_RSA
#define JTBG_UUID
#define JTBG_SOUND
#define JTBG_REGI
#define JTBG_BIGNUM
#define JTBG_ARGCV
#define JTBG_UDP
#define JTBG_RSA
#define JTBG_LUHN
#define JTBG_MES
#define JTBG_SYSTEM
#define JTBG_CC
#define JTBG_RANDOM
#define JTBG_TIME
#define JTBG_DECANDENC
#define JTBG_SAFE
#define JTBG_MATH
#define JTBG_SHORT
#define JTBG_ADMINS
#define JTBG_STRING
#define JTBG_LOG
#define JTBG_RMQ
#define JTBG_WEB
#endif
#ifdef JTBG_NOWINDOWS_ALL
#pragma message("JTBG->JTBG_NOWINDOWS_ALL [on]")
#undef JTBG_HASH
#undef JTBG_INI
#undef JTBG_MSGBOX
#undef JTBG_KMP
#undef JTBG_SAFE
#undef JTBG_KEY
#undef JTBG_COL
#undef JTBG_FILE
#undef JTBG_REGI
#undef JTBG_BIGNUM
#undef JTBG_SOUND
#undef JTBG_RMQ
#undef JTBG_ADMINS
#undef JTBG_ARGCV
#undef JTBG_LUHN
#undef JTBG_PROS
#undef JTBG_RSA
#undef JTBG_MES
//#undef JTBG_RSA
#undef JTBG_SYSTEM
#undef JTBG_CC
#undef JTBG_RANDOM
#undef JTBG_STRING
#undef JTBG_TIME
#undef JTBG_PROGRESS
#undef JTBG_DECANDENC
#undef JTBG_UUID
#undef JTBG_MATH
#undef JTBG_SHORT
#undef JTBG_BETTER_COL
#undef JTBG_LOG
#undef JTBG_ONLY_WINDOWS
#undef JTBG_UDP
#define JTBG_BETTER_COL
#define JTBG_HASH
#define JTBG_UUID
#define JTBG_INI
#define JTBG_KMP
#define JTBG_BIGNUM
#define JTBG_ARGCV
#define JTBG_LUHN
#define JTBG_ONLY_WINDOWS
#define JTBG_MES
#define JTBG_CC
#define JTBG_DECANDENC
#define JTBG_MATH
#define JTBG_RMQ
#define JTBG_STRING
#define JTBG_SHORT
#endif
#ifdef JTBG_ADMINS
#pragma message("JTBG_ADMIN was started")
#undef JTBG_ADMIN_ALL_GAMES_AND_IDEAS_AND_ALL_IT_THINGS_ADMINS_CL
#define JTBG_ADMIN_ALL_GAMES_AND_IDEAS_AND_ALL_IT_THINGS_ADMINS_CL
#endif
//你需要定义 _agree_ 表示同意 CC BY-NC-ND 4.0
#ifndef _agree_
#pragma message("if you use jtbg.h or jtbgunix.h,you must agree CC BY-NC-ND 4.0,or you must stop using right now!")
#define _JTBG_DIDNT_DO_AGREE_
#endif
#ifndef NO_JTBG_CONTROLER_MATH
#define MUL(a,b) (a)*(b)
#define __JTBG_NORETURN(a) ext(a)
#define MUS(a,b) (a)-(b)
#define PLS(a,b) (a)+(b)
#define DEF(a,b) (a)/(b)
#endif
#ifndef NO_PRAGMA
#pragma message("cop. jtbg.h main(X)")
#endif
#ifdef JTBG_MSGBOX
#define MSB_OK MB_OK
#define MSB_OKCL MB_OKCANCEL
#define MSB_TF MB_YESNO
#define MSB_INFO MB_ICONINFORMATION
#define MSB_WARN MB_ICONWARNING
#define MSB_ERROR MB_ICONERROR
int msgbox(string tit,string vol,UINT type=MSB_OKCL)
{
return MessageBox(NULL,vol.c_str(),tit.c_str(),type);
}
#endif
#ifdef JTBG_BETTER_COL
void Settied(bool t)
{
if(!t)
{
ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
}
else
{
ios::sync_with_stdio(true);
cin.tie(&cout);
cout.tie(nullptr);
}
}
#endif
#ifdef JTBG_HASH
class MD5
{
private:
typedef unsigned int uint32;
typedef unsigned long long uint64;
struct Context
{
uint32 state[4];
uint32 count[2];
unsigned char buffer[64];
};
static void init(Context &ctx)
{
ctx.count[0] = ctx.count[1] = 0;
ctx.state[0] = 0x67452301;
ctx.state[1] = 0xefcdab89;
ctx.state[2] = 0x98badcfe;
ctx.state[3] = 0x10325476;
}
static void update(Context &ctx, const unsigned char *input, size_t length)
{
uint32 i, index, partLen;
index = (uint32)((ctx.count[0] >> 3) & 0x3F);
if ((ctx.count[0] += ((uint32)length << 3)) < ((uint32)length << 3))
ctx.count[1]++;
ctx.count[1] += (uint32)(length >> 29);
partLen = 64 - index;
if (length >= partLen)
{
memcpy(&ctx.buffer[index], input, partLen);
transform(ctx.state, ctx.buffer);
for (i = partLen; i + 63 < length; i += 64)
transform(ctx.state, &input[i]);
index = 0;
}
else
{
i = 0;
}
memcpy(&ctx.buffer[index], &input[i], length - i);
}
static void final(unsigned char digest[16], Context &ctx)
{
unsigned char padding[64] = {0x80};
unsigned char bits[8];
size_t index, padLen;
encode(bits, ctx.count, 8);
index = (uint32)((ctx.count[0] >> 3) & 0x3f);
padLen = (index < 56) ? (56 - index) : (120 - index);
update(ctx, padding, padLen);
update(ctx, bits, 8);
encode(digest, ctx.state, 16);
}
static void transform(uint32 state[4], const unsigned char block[64])
{
uint32 a = state[0], b = state[1], c = state[2], d = state[3], x[16];
decode(x, block, 64);
FF(a, b, c, d, x[0], 7, 0xd76aa478);
FF(d, a, b, c, x[1], 12, 0xe8c7b756);
FF(c, d, a, b, x[2], 17, 0x242070db);
FF(b, c, d, a, x[3], 22, 0xc1bdceee);
FF(a, b, c, d, x[4], 7, 0xf57c0faf);
FF(d, a, b, c, x[5], 12, 0x4787c62a);
FF(c, d, a, b, x[6], 17, 0xa8304613);
FF(b, c, d, a, x[7], 22, 0xfd469501);
FF(a, b, c, d, x[8], 7, 0x698098d8);
FF(d, a, b, c, x[9], 12, 0x8b44f7af);
FF(c, d, a, b, x[10], 17, 0xffff5bb1);
FF(b, c, d, a, x[11], 22, 0x895cd7be);
FF(a, b, c, d, x[12], 7, 0x6b901122);
FF(d, a, b, c, x[13], 12, 0xfd987193);
FF(c, d, a, b, x[14], 17, 0xa679438e);
FF(b, c, d, a, x[15], 22, 0x49b40821);
GG(a, b, c, d, x[1], 5, 0xf61e2562);
GG(d, a, b, c, x[6], 9, 0xc040b340);
GG(c, d, a, b, x[11], 14, 0x265e5a51);
GG(b, c, d, a, x[0], 20, 0xe9b6c7aa);
GG(a, b, c, d, x[5], 5, 0xd62f105d);
GG(d, a, b, c, x[10], 9, 0x02441453);
GG(c, d, a, b, x[15], 14, 0xd8a1e681);
GG(b, c, d, a, x[4], 20, 0xe7d3fbc8);
GG(a, b, c, d, x[9], 5, 0x21e1cde6);
GG(d, a, b, c, x[14], 9, 0xc33707d6);
GG(c, d, a, b, x[3], 14, 0xf4d50d87);
GG(b, c, d, a, x[8], 20, 0x455a14ed);
GG(a, b, c, d, x[13], 5, 0xa9e3e905);
GG(d, a, b, c, x[2], 9, 0xfcefa3f8);
GG(c, d, a, b, x[7], 14, 0x676f02d9);
GG(b, c, d, a, x[12], 20, 0x8d2a4c8a);
HH(a, b, c, d, x[5], 4, 0xfffa3942);
HH(d, a, b, c, x[8], 11, 0x8771f681);
HH(c, d, a, b, x[11], 16, 0x6d9d6122);
HH(b, c, d, a, x[14], 23, 0xfde5380c);
HH(a, b, c, d, x[1], 4, 0xa4beea44);
HH(d, a, b, c, x[4], 11, 0x4bdecfa9);
HH(c, d, a, b, x[7], 16, 0xf6bb4b60);
HH(b, c, d, a, x[10], 23, 0xbebfbc70);
HH(a, b, c, d, x[13], 4, 0x289b7ec6);
HH(d, a, b, c, x[0], 11, 0xeaa127fa);
HH(c, d, a, b, x[3], 16, 0xd4ef3085);
HH(b, c, d, a, x[6], 23, 0x04881d05);
HH(a, b, c, d, x[9], 4, 0xd9d4d039);
HH(d, a, b, c, x[12], 11, 0xe6db99e5);
HH(c, d, a, b, x[15], 16, 0x1fa27cf8);
HH(b, c, d, a, x[2], 23, 0xc4ac5665);
II(a, b, c, d, x[0], 6, 0xf4292244);
II(d, a, b, c, x[7], 10, 0x432aff97);
II(c, d, a, b, x[14], 15, 0xab9423a7);
II(b, c, d, a, x[5], 21, 0xfc93a039);
II(a, b, c, d, x[12], 6, 0x655b59c3);
II(d, a, b, c, x[3], 10, 0x8f0ccc92);
II(c, d, a, b, x[10], 15, 0xffeff47d);
II(b, c, d, a, x[1], 21, 0x85845dd1);
II(a, b, c, d, x[8], 6, 0x6fa87e4f);
II(d, a, b, c, x[15], 10, 0xfe2ce6e0);
II(c, d, a, b, x[6], 15, 0xa3014314);
II(b, c, d, a, x[13], 21, 0x4e0811a1);
II(a, b, c, d, x[4], 6, 0xf7537e82);
II(d, a, b, c, x[11], 10, 0xbd3af235);
II(c, d, a, b, x[2], 15, 0x2ad7d2bb);
II(b, c, d, a, x[9], 21, 0xeb86d391);
state[0] += a;
state[1] += b;
state[2] += c;
state[3] += d;
}
static inline uint32 F(uint32 x, uint32 y, uint32 z) { return (x & y) | (~x & z); }
static inline uint32 G(uint32 x, uint32 y, uint32 z) { return (x & z) | (y & ~z); }
static inline uint32 H(uint32 x, uint32 y, uint32 z) { return x ^ y ^ z; }
static inline uint32 I(uint32 x, uint32 y, uint32 z) { return y ^ (x | ~z); }
static inline void FF(uint32 &a, uint32 b, uint32 c, uint32 d, uint32 x, uint32 s, uint32 t)
{
a += F(b, c, d) + x + t;
a = (a << s) | (a >> (32 - s));
a += b;
}
static inline void GG(uint32 &a, uint32 b, uint32 c, uint32 d, uint32 x, uint32 s, uint32 t)
{
a += G(b, c, d) + x + t;
a = (a << s) | (a >> (32 - s));
a += b;
}
static inline void HH(uint32 &a, uint32 b, uint32 c, uint32 d, uint32 x, uint32 s, uint32 t)
{
a += H(b, c, d) + x + t;
a = (a << s) | (a >> (32 - s));
a += b;
}
static inline void II(uint32 &a, uint32 b, uint32 c, uint32 d, uint32 x, uint32 s, uint32 t)
{
a += I(b, c, d) + x + t;
a = (a << s) | (a >> (32 - s));
a += b;
}
static void encode(unsigned char *output, const uint32 *input, size_t length)
{
for (size_t i = 0, j = 0; j < length; i++, j += 4)
{
output[j] = (unsigned char)(input[i] & 0xFF);
output[j + 1] = (unsigned char)((input[i] >> 8) & 0xFF);
output[j + 2] = (unsigned char)((input[i] >> 16) & 0xFF);
output[j + 3] = (unsigned char)((input[i] >> 24) & 0xFF);
}
}
static void decode(uint32 *output, const unsigned char *input, size_t length)
{
for (size_t i = 0, j = 0; j < length; i++, j += 4)
output[i] = ((uint32)input[j]) | (((uint32)input[j + 1]) << 8) |
(((uint32)input[j + 2]) << 16) | (((uint32)input[j + 3]) << 24);
}
public:
static string hash(const string &input)
{
Context ctx;
init(ctx);
update(ctx, (const unsigned char*)input.c_str(), input.length());
unsigned char digest[16];
final(digest, ctx);
char hex_str[33];
for (int i = 0; i < 16; i++)
sprintf(hex_str + i * 2, "%02x", digest[i]);
hex_str[32] = '\0';
return string(hex_str);
}
};
//MD5::hash(str)
unsigned long long pHash(const string& s)
{
const unsigned long long base = 911382629ULL;
const unsigned long long mod = 1000000000000000003ULL;
unsigned long long hashValue = 0;
// 使用传统for循环兼容C++98
for (size_t i = 0; i < s.size(); ++i)
{
char c = s[i];
hashValue = (hashValue * base + static_cast<unsigned long long>(c)) % mod;
}
return hashValue;
}
struct StringHash
{
static const unsigned long long base = 911382629ULL;
static const unsigned long long mod = 1000000000000000003ULL;
vector<unsigned long long> hash;
vector<unsigned long long> power;
StringHash(const string& s)
{
int n = s.size();
hash.resize(n + 1);
power.resize(n + 1);
power[0] = 1;
for (int i = 0; i < n; ++i) {
hash[i+1] = (hash[i] * base + static_cast<unsigned long long>(s[i])) % mod;
power[i+1] = (power[i] * base) % mod;
}
}
// 获取子串s[l..r]的哈希值(0-based,包含l和r)
unsigned long long getHash(int l, int r)
{
int len = r - l + 1;
unsigned long long res = (hash[r+1] - hash[l] * power[len]) % mod;
if(false) return res+mod;
else return res;
// return res < 0 ? res + mod : res;
}
};
//StringHash strHash(str);
//cout << "前缀哈希完整字符串: " << strHash.getHash(0, str.size()-1) << endl;
//cout << "子串哈希(0-4): " << strHash.getHash(0, 4) << " (对应\"Hello\")" << endl;
size_t Hash(const string& s)
{
size_t hashVal = 0;
for (size_t i = 0; i < s.size(); ++i)
{
// 简单的哈希组合算法
hashVal = hashVal * 31 + static_cast<size_t>(s[i]);
}
return hashVal;
}
string FileMD5(string path)
{
ifstream file(path,ios::in|ios::binary);
if (!file.is_open())
{
return "";
}
string fileContent;
file.seekg(0,ios::end);
size_t fileSize = static_cast<size_t>(file.tellg());
file.seekg(0,ios::beg);
fileContent.reserve(fileSize);
fileContent.assign(istreambuf_iterator<char>(file),istreambuf_iterator<char>());
if (!file && !file.eof())
{
return "";
}
return MD5::hash(fileContent);
}
#endif
#ifdef JTBG_FILE
bool Isfileext(const string& filePath)
{
ifstream file(filePath, ios::in | ios::binary);
bool exists = file.good();
file.close();
return exists;
}
struct Save
{
string path;
int errorlevel=-1;
ifstream save_i;
ofstream save_o;
void setpt(string s)
{
path=s;
return ;
}
void read_nol()
{
save_i.open(path.c_str());
if(!save_i.good()) errorlevel=1100;
return ;
}
void read_bin()
{
save_i.open(path.c_str(),ios::in|ios::binary);
if(!save_i.good()) errorlevel=1100;
return ;
}
void save_nol()
{
save_o.open(path.c_str());
if(!save_o.good()) errorlevel=1000;
return ;
}
void save_app()
{
save_o.open(path.c_str(),ios::app|ios::out);
if(!save_o.good()) errorlevel=1000;
return ;
}
void save_bin()
{
save_o.open(path.c_str(),ios::binary|ios::out);
if(!save_o.good()) errorlevel=1000;
return ;
}
//save_o.write(s.data(),s.size());
void save_stop()
{
// save_i.close();
save_o.close();
return ;
}
void read_stop()
{
save_i.close();
// save_o.close();
return ;
}
};
//检测文件读写是否
bool fileok(const string &filename)
{
ifstream file(filename);
return file.good();
}
#endif
#ifdef JTBG_COL
void say(string s,int t)
{
if(t<0) return ;
int len=int(s.length());
for(int i=0;i<len;i++)
{
cout<<s[i];
Sleep(t);
}
return ;
}
void paused(string s)
{
cout<<s<<endl;
system("pause > nul");
return ;
}
int ext(int num)
{
cout<<"[jtbg.h] Process exited with return value "<<num<<endl;
exit(num);
return num;
}
enum Color
{
BLACK = 0,
BLUE = 1,
GREEN = 2,
CYAN = 3,
RED = 4,
MAGENTA = 5,
BROWN = 6,
LIGHT_GRAY = 7,
DARK_GRAY = 8,
LIGHT_BLUE = 9,
LIGHT_GREEN = 10,
LIGHT_CYAN = 11,
LIGHT_RED = 12,
LIGHT_MAGENTA = 13,
YELLOW = 14,
WHITE = 15
};
void scg(Color x,Color y)
{
HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
// 设置文本颜色和背景颜色,高4位是背景,低4位是文本
SetConsoleTextAttribute(hConsole, (y << 4) | x);
return ;
}
void scg(int x,int y)
{
HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
// 设置文本颜色和背景颜色,高4位是背景,低4位是文本
SetConsoleTextAttribute(hConsole, (y << 4) | x);
return ;
}
void set_back_color()
{
scg(7,0);
return ;
}
//控制台光标位置控制
void setcursor(int x,int y)
{
COORD coord;
coord.X = x;
coord.Y = y;
SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), coord);
}
//清除控制台指定区域内容
void clearCA(int x, int y, int width, int height)
{
for(int i=0;i<height;i++)
{
setcursor(x, y + i);
cout << string(width, ' ');
}
}
//隐藏/显示控制台光标
void setCVis(bool visible)
{
CONSOLE_CURSOR_INFO cursorInfo = {1, visible};
SetConsoleCursorInfo(GetStdHandle(STD_OUTPUT_HANDLE), &cursorInfo);
}
//获取控制台尺寸
void getCSize(int &width,int &height)
{
CONSOLE_SCREEN_BUFFER_INFO csbi;
GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &csbi);
width = csbi.srWindow.Right - csbi.srWindow.Left + 1;
height = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
}
void flushed()
{
cin.ignore(numeric_limits<streamsize>::max(), '\n');
cin.clear();
return ;
}
#endif
#ifdef JTBG_RANDOM
int rd(int a,int b)
{
srand(GetTickCount()+rand());
return a+rand()%(b+1);
}
//生成指定长度的随机字符串
string randS(int length)
{
const string chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
string result;
for (int i = 0; i < length; ++i) {
result += chars[rand() % chars.size()];
}
return result;
}
double random(double min, double max)
{
return min + (max - min) * (rand() / (double)RAND_MAX);
}
#endif
#ifdef JTBG_STRING
/*
* @brief 在字符串中查找匹配指定模式的位置
*
* @param s 要搜索的目标字符串
* @param pattern 匹配模式,支持通配符:
* %d - 匹配整数
* %Nd - 匹配宽度为N的整数(必须正好N位数字)
* %s - 匹配非空白字符串(遇到空白符停止)
* %Ns - 匹配长度为N的字符串(可以是任何字符,不检查空白符)
* %k - 匹配任意字符串(可以包含空白符,直到字符串结束或遇到模式中的下一个字符)
* %Nk - 匹配长度为N的字符串(可以包含空白符)
* %c - 匹配单个字符
* %Nc - 匹配N个字符
* %% - 匹配百分号字符
* 普通字符 - 直接匹配对应字符
*
* @return int 返回匹配开始的索引位置,如果未找到匹配则返回-1
*
* @example
* find_in_string("123abc", "%d%s") // 返回0,匹配"123abc"
* find_in_string("hello 123", "%s %d") // 返回0,匹配"hello 123"
* find_in_string("abc123", "%3s%d") // 返回0,匹配"abc123"
* find_in_string("hello world", "%k") // 返回0,匹配整个字符串
* find_in_string("5[hi]", "%d[%2s]") // 返回0,匹配"5[hi]"
*
* @note 模式匹配是贪婪的,会尝试从每个位置开始匹配
*/
int find_in_string(const string& s, const string& pattern)
{
int s_len = s.length();
int p_len = pattern.length();
// 尝试从每个位置开始匹配
for (int start = 0; start <= s_len; ++start)
{
int i = start; // 目标字符串的当前位置
int j = 0; // 模式的当前位置
bool matched = true;
// 遍历模式字符串
while (j < p_len && i <= s_len)
{
// 检查是否是通配符
if (pattern[j] == '%')
{
// 确保有足够的字符
if (j + 1 >= p_len)
{
matched = false;
break;
}
j++; // 跳过%
// 解析宽度限定符(如果有)
int width = 0;
bool has_width = false;
while (j < p_len && isdigit(pattern[j]))
{
width = width * 10 + (pattern[j] - '0');
j++;
has_width = true;
}
// 确保有说明符
if (j >= p_len)
{
matched = false;
break;
}
char specifier = pattern[j];
j++; // 跳过说明符
// 根据说明符处理不同类型的匹配
switch (specifier)
{
case 'd': // 匹配整数
if (i >= s_len)
{
matched = false;
break;
}
if (has_width)
{
// 固定宽度整数:必须正好匹配width位数字
for (int k = 0; k < width; k++)
{
if (i >= s_len || !isdigit(s[i]))
{
matched = false;
break;
}
i++;
}
}
else
{
// 变长整数:匹配一个或多个数字
if (!isdigit(s[i]) && s[i] != '-' && s[i] != '+')
{
matched = false;
break;
}
// 可选符号
if (s[i] == '-' || s[i] == '+')
{
i++;
}
// 匹配一个或多个数字
if (i >= s_len || !isdigit(s[i]))
{
matched = false;
break;
}
while (i < s_len && isdigit(s[i]))
{
i++;
}
}
break;
case 's': // 匹配非空白字符串
if (i >= s_len)
{
matched = false;
break;
}
if (has_width)
{
// 固定宽度字符串:匹配width个任意字符(包括空白符)
for (int k = 0; k < width; k++)
{
if (i >= s_len)
{
matched = false;
break;
}
i++;
}
}
else
{
// 变长字符串:匹配到第一个空白符为止
if (isspace(s[i]))
{
matched = false;
break;
}
while (i < s_len && !isspace(s[i]))
{
i++;
}
}
break;
case 'k': // 匹配任意字符串(可包含空白符)
if (i >= s_len)
{
matched = false;
break;
}
if (has_width)
{
// 固定宽度:匹配width个任意字符
for (int k = 0; k < width; k++)
{
if (i >= s_len)
{
matched = false;
break;
}
i++;
}
}
else
{
// 变长:匹配到字符串结束或遇到模式中的下一个字符
// 这里我们采用贪婪匹配,直到字符串结束
// 实际的停止条件会在外层循环中处理
int next_char = (j < p_len) ? pattern[j] : -1;
// 如果没有下一个字符,匹配到字符串结束
if (next_char == -1)
{
i = s_len;
}
else
{
// 否则匹配到遇到下一个字符为止
while (i < s_len && s[i] != next_char)
{
i++;
}
}
}
break;
case 'c': // 匹配字符
if (i >= s_len)
{
matched = false;
break;
}
if (has_width)
{
// 固定宽度:匹配width个字符
for (int k = 0; k < width; k++)
{
if (i >= s_len)
{
matched = false;
break;
}
i++;
}
}
else
{
// 单个字符
i++;
}
break;
case '%': // 匹配百分号
if (i >= s_len || s[i] != '%')
{
matched = false;
}
else
{
i++;
}
break;
default:
matched = false;
}
}
else
{
// 普通字符:直接匹配
if (i >= s_len || s[i] != pattern[j])
{
matched = false;
break;
}
i++;
j++;
}
if (!matched)
{
break;
}
}
// 如果模式完全匹配且目标字符串也匹配完毕
if (matched && j == p_len)
{
return start;
}
}
return -1; // 未找到匹配
}
template<typename T>
inline string jtbg_to_string(T a)
{
stringstream s;
s<<a;
return s.str();
}
inline const char* stringstream_to_cstring(std::stringstream& s)
{
std::string str = s.str();
char* result = new char[str.length() + 1];
std::strcpy(result, str.c_str());
return result;
}
#define stoc(x) stringstream_to_cstring((x))
/*
use:
const char* cstr = stoc(ss);
delete[] cstr; // 必须手动释放!
*/
int editDistance(const string &s1, const string &s2)
{
int m = s1.length();
int n = s2.length();
vector<vector<int>> dp(m + 1, vector<int>(n + 1));
for (int i = 0; i <= m; i++)
{
dp[i][0] = i;
}
for (int j = 0; j <= n; j++)
{
dp[0][j] = j;
}
for (int i = 1; i <= m; i++)
{
for (int j = 1; j <= n; j++)
{
if (s1[i - 1] == s2[j - 1])
{
dp[i][j] = dp[i - 1][j - 1];
}
else
{
dp[i][j] = min({dp[i - 1][j] + 1,
dp[i][j - 1] + 1,
dp[i - 1][j - 1] + 1});
}
}
}
return dp[m][n];
}
template<typename T>
inline string tostring(T k)
{
stringstream ans;
ans << k;
return ans.str();
}
// 计算相似度百分比
int calculateSimilarity(const string &s1, const string &s2)
{
if (s1.empty() && s2.empty())
{
return 100;
}
int maxLen = max(s1.length(), s2.length());
if (maxLen == 0)
{
return 0;
}
int distance = editDistance(s1, s2);
return (int)((1.0 - (double)distance / maxLen) * 100.0);
}
//检查字符串是否为数字(整数或小数)
bool isNumber(const string& str)
{
if (str.empty()) return false;
size_t start = 0;
if (str[0] == '+' || str[0] == '-') start = 1;
bool hasDot = false;
for (size_t i = start; i < str.size(); ++i)
{
if (str[i] == '.')
{
if (hasDot) return false;
hasDot = true;
}
else if (!isdigit(str[i]))
{
return false;
}
}
return true;
}
void lowerstring(string &s)
{
for(int i=0;i<int(s.size());i++)
{
if(s[i]>='A'&&s[i]<='Z')
{
s[i]=s[i]-'A'+'a';
}
}
return ;
}
void uperstring(string &s)
{
for(int i=0;i<int(s.size());i++)
{
if(s[i]>='a'&&s[i]<='z')
{
s[i]=s[i]-'a'+'A';
}
}
return ;
}
void Testsuper(string &s)
{
if (s.empty()) return;
s[0] = toupper(s[0]);
for (size_t i = 1; i < s.size();i++)
{
s[i]=tolower(s[i]);
}
}
#undef JTBG_KMP
#define JTBG_KMP
#endif
#ifdef JTBG_KEY
#define iskeydown() _kbhit()
int chkey(int t)
{
if(t!=-1)
{
t*=100;
while(t--)
{
if (_kbhit())
{
int key = _getch();
return key;
}
}
return -1;
}
else
{
while(1)
{
if (_kbhit())
{
int key = _getch();
return key;
}
}
}
}
#endif
#ifdef JTBG_TIME
enum TimeType
{
yer=0,
mon=1,
dat=2,
hor=3,
mit=4,
sec=5,
mst=6,
};
int Gettime(TimeType x)
{
time_t now = time(0);
tm *localTime = localtime(&now);
if(x==0) return 1900 + localTime->tm_year;//年份
if(x==1) return 1 + localTime->tm_mon;//月份
if(x==2) return localTime->tm_mday;//日期
if(x==3) return localTime->tm_hour;//小时
if(x==4) return localTime->tm_min;//分钟
if(x==5) return localTime->tm_sec;//秒
if(x==6) return GetTickCount();//ms
return -1;
}
int Gettime(string x)
{
time_t now = time(0);
tm *localTime = localtime(&now);
if(x=="year") return 1900 + localTime->tm_year;//年份
if(x=="mon") return 1 + localTime->tm_mon;//月份
if(x=="dat") return localTime->tm_mday;//日期
if(x=="hor") return localTime->tm_hour;//小时
if(x=="mit") return localTime->tm_min;//分钟
if(x=="sec") return localTime->tm_sec;//秒
if(x=="mst") return GetTickCount();//ms
return -1;
}
struct Timer
{
private:
using Clock = chrono::high_resolution_clock;
using TimePoint = chrono::time_point<Clock>;
TimePoint start_;
TimePoint pause_;
bool isRunning_;
chrono::duration<double> elapsed_;
public:
Timer() : isRunning_(false), elapsed_(0) {}
void starttick()
{
if (!isRunning_)
{
start_ = Clock::now();
isRunning_ = true;
}
}
void pausetick()
{
if (isRunning_)
{
pause_ = Clock::now();
elapsed_ += pause_ - start_;
isRunning_ = false;
}
}
void resettick()
{
isRunning_ = false;
elapsed_ = chrono::duration<double>(0);
}
void rettime(double t)
{
isRunning_ = false;
elapsed_ = chrono::duration<double>(t);
return ;
}
double timesec()
const
{
if (isRunning_)
{
auto now = Clock::now();
return (elapsed_ + (now - start_)).count();
}
return elapsed_.count();
}
double timemst()
const
{
return timesec() * 1000.0;
}
};
#endif
#ifdef JTBG_SOUND
void play_error_sound(int bep=-1,int l=-1)
{
if(bep==-1&&l==-1) cout<<'\a';
else Beep(bep,l);
return ;
}
#define JS_OK MB_OK
#define JS_ERROR MB_ICONERROR
#define JS_WARN MB_ICONWARNING
#define JS_INFO MB_ICONINFORMATION
#define JS_QUES MB_ICONQUESTION
#define JS_SOUND 0xFFFFFFFF
void play_system_sound(UINT mod=JS_SOUND)
{
MessageBeep(mod);
}
struct play_sounder
{
private:
string path;
public:
play_sounder(string paths=".wav")
{
if (paths.empty())
{
path = "";
return;
}
if (paths.size() < 4)
{
return;
}
string extension = paths.substr(paths.size() - 4);
string lowerExt = extension;
transform(lowerExt.begin(), lowerExt.end(), lowerExt.begin(), ::tolower);
if (lowerExt == ".wav")
{
path = paths;
}
else
{
return;
}
}
void Setpath(const string& paths = "")
{
if (paths.empty())
{
path = "";
return;
}
if (paths.size() < 4)
{
return;
}
string extension = paths.substr(paths.size() - 4);
string lowerExt = extension;
transform(lowerExt.begin(), lowerExt.end(), lowerExt.begin(), ::tolower);
if (lowerExt == ".wav")
{
path = paths;
}
else
{
return;
}
}
/*
DWORD mod:
声音源类型(必须指定一个)
标志 描述 对应 pszSound 类型
SND_FILENAME 文件路径 "path\\to\\sound.wav"
SND_ALIAS 系统声音别名 "SystemAsterisk"
SND_RESOURCE 资源ID MAKEINTRESOURCE(ID)
SND_MEMORY 内存指针 (LPCSTR)waveData
播放控制标志(可组合)
标志 描述 示例
SND_ASYNC 异步播放 立即返回,后台播放
SND_SYNC 同步播放 播放完才返回
SND_LOOP 循环播放 需配合 SND_ASYNC
SND_NODEFAULT 不播放默认音 找不到文件时静音
SND_NOSTOP 不中断当前播放 如果忙则立即返回
SND_NOWAIT 不等待设备 设备忙则失败
SND_PURGE 停止指定声音 停止播放
*/
DWORD Play(DWORD mod,HMODULE um=NULL)
{
PlaySoundA(path.c_str(),um,mod);
DWORD error = GetLastError();
return error;
}
string GetError(DWORD error)
{
if (error == 0) return "成功";
if (error == 2) return "文件未找到";
if (error == 3) return "路径未找到";
if (error == 5) return "访问被拒绝";
if (error == 87) return "无效参数";
if (error == 11) return "音频格式无效";
if (error == 6) return "没有音频驱动程序";
if (error == 4) return "音频设备已被占用";
if (error == 32) return "不支持的音频格式";
return "错误代码: " + to_string(error);
}
};
#endif
#ifdef JTBG_SYSTEM
bool setPassword(const string& user,const string pass)
{
stringstream k;
k<<"net user "<<user<<" "<<pass;
return !system(k.str().c_str());
}
bool getNetconnet(const string& ip,const string& user,const string& pass)
{
stringstream k;
k<<"net use \\\\"<<ip<<"\\$ipc /user:\""<<user<<"\" "<<pass;
return !system(k.str().c_str());
}
#define SX64 0x31
#define SX86 0x32
#define SARM32 0x33
#define SARM64 0x34
#define SIT64 0x35
#define SUNK 0x36
int getSystemArch()
{
SYSTEM_INFO sysInfo;
GetNativeSystemInfo(&sysInfo);
switch (sysInfo.wProcessorArchitecture)
{
case 0:
return SX86;
break;
case 9:
return SX64;
break;
case 5:
return SARM32;
break;
case 12:
return SARM64;
break;
case 6:
return SIT64;
break;
default:
return SUNK;
break;
}
}
string getArchName(int archCode)
{
switch (archCode)
{
case SX64: return "x64 (AMD64)";
case SX86: return "x86 (Intel)";
case SARM32: return "ARM (32-bit)";
case SARM64: return "ARM64";
case SIT64: return "IA-64 (Itanium)";
case SUNK: return "Unknown";
default: return "Invalid";
}
}
void RefreshExplorer()
{
SHChangeNotify(
SHCNE_ASSOCCHANGED,
SHCNF_IDLIST,
nullptr,
nullptr
);
return;
}
bool IsRunAsAdmin()
{
BOOL isAdmin = FALSE;
PSID adminGroup;
SID_IDENTIFIER_AUTHORITY ntAuthority = SECURITY_NT_AUTHORITY;
if (AllocateAndInitializeSid(&ntAuthority, 2, SECURITY_BUILTIN_DOMAIN_RID,DOMAIN_ALIAS_RID_ADMINS, 0, 0, 0, 0, 0, 0, &adminGroup))
{
CheckTokenMembership(NULL, adminGroup, &isAdmin);
FreeSid(adminGroup);
}
return isAdmin == TRUE;
}
void RunAsAdmin()
{
char szPath[MAX_PATH];
GetModuleFileName(NULL, szPath, MAX_PATH);
SHELLEXECUTEINFO sei;
ZeroMemory(&sei,sizeof(sei));
sei.cbSize = sizeof(sei);
sei.lpVerb = "runas";
sei.lpFile = szPath;
sei.hwnd = NULL;
sei.nShow = SW_NORMAL;
ShellExecuteEx(&sei);
exit(0);
}
bool AddToCurrentUserStartup(const string& appName, const string& appPath)
{
HKEY hKey;
LONG result;
// 使用 RegOpenKeyExA 和 RegSetValueExA (ANSI 版本)
result = RegOpenKeyExA(
HKEY_CURRENT_USER,
"Software\\Microsoft\\Windows\\CurrentVersion\\Run",
0,
KEY_WRITE,
&hKey
);
if (result != ERROR_SUCCESS)
{
return false;
}
// 如果路径包含空格,用引号包围
string finalPath = appPath;
if (appPath.find(' ') != string::npos && appPath[0] != '\"')
{
finalPath = "\"" + appPath + "\"";
}
result = RegSetValueExA(
hKey,
appName.c_str(),
0,
REG_SZ,
(const BYTE*)finalPath.c_str(),
finalPath.size() + 1
);
RegCloseKey(hKey);
return (result == ERROR_SUCCESS);
}
bool isRun(const char* processName)
{
HANDLE hSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
if (hSnapshot == INVALID_HANDLE_VALUE) return true;
PROCESSENTRY32 pe32;
pe32.dwSize = sizeof(PROCESSENTRY32);
if (Process32First(hSnapshot, &pe32))
{
do
{
if (strcmp(pe32.szExeFile, processName) == 0)
{
CloseHandle(hSnapshot);
return true;
}
}while (Process32Next(hSnapshot, &pe32));
}
CloseHandle(hSnapshot);
return false;
}
void Hide()
{
HWND hwnd = GetForegroundWindow(); // 获取当前窗口句柄
if (hwnd) ShowWindow(hwnd, SW_HIDE); // 隐藏窗口
}
void Show()
{
HWND hwnd = GetForegroundWindow(); // 获取当前窗口句柄
if (hwnd) ShowWindow(hwnd, SW_SHOW); // 隐藏窗口
}
void Windowset(int s)
{
HWND hwnd = GetForegroundWindow(); // 获取当前窗口句柄
if (hwnd) ShowWindow(hwnd, s); // 隐藏窗口
}
//计算文件大小(字节)
long long getFileSize(const string &filename)
{
ifstream file(filename, ios::binary | ios::ate);
if(!file.good()) return -1;
return static_cast<long long>(file.tellg());
}
//延迟函数(高精度ms)
void msSleep(int milliseconds)
{
auto start = chrono::high_resolution_clock::now();
while (chrono::duration_cast<chrono::milliseconds>(chrono::high_resolution_clock::now() - start).count() < milliseconds);
}
//计算文件夹内文件数量(仅统计一级目录)
int getFileCountInDir(const string& dirPath)
{
int count = 0;
WIN32_FIND_DATA findData;
HANDLE hFind = FindFirstFile((dirPath + "\\*").c_str(), &findData);
if (hFind == INVALID_HANDLE_VALUE) return -1;
do
{
if (!(findData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY))
{
count++; // 只统计文件,不统计文件夹
}
} while (FindNextFile(hFind, &findData) != 0);
FindClose(hFind);
return count;
}
struct memory
{
long long bytes;
double toB()
{
return static_cast<double>(bytes);
}
double toKB()
{
const double KB = 1024.0;
return bytes / KB;
}
double toMB()
{
const double MB = 1024.0 * 1024.0;
return bytes / MB;
}
double toGB()
{
const double GB = 1024.0 * 1024.0 * 1024.0;
return bytes / GB;
}
double toTB()
{
const double TB = 1024.0 * 1024.0 * 1024.0 * 1024.0;
return bytes / TB;
}
double toPB()
{
const double PB = 1024.0 * 1024.0 * 1024.0 * 1024.0 * 1024.0;
return bytes / PB;
}
};
// 将字节转换为B(字节)
double rtoB(int bytes)
{
return static_cast<double>(bytes);
}
// 将字节转换为KB(千字节)
double rtoKB(int bytes)
{
const double KB = 1024.0;
return bytes / KB;
}
// 将字节转换为MB(兆字节)
double rtoMB(int bytes)
{
const double MB = 1024.0 * 1024.0;
return bytes / MB;
}
// 将字节转换为GB(千兆字节)
double rtoGB(int bytes)
{
const double GB = 1024.0 * 1024.0 * 1024.0;
return bytes / GB;
}
// 将字节转换为TB(太字节)
double rtoTB(int bytes)
{
const double TB = 1024.0 * 1024.0 * 1024.0 * 1024.0;
return bytes / TB;
}
// 将字节转换为PB(拍字节)
double rtoPB(int bytes)
{
const double PB = 1024.0 * 1024.0 * 1024.0 * 1024.0 * 1024.0;
return bytes / PB;
}
#endif
#ifdef JTBG_DECANDENC
string xorFile(const string& filePath,const string& key)
{
if (key.empty())
{
return "";
}
ifstream file(filePath.c_str(), ios::in | ios::binary);
if (!file.is_open())
{
return "";
}
string fileContent;
char buffer[4096];
while (file.read(buffer, sizeof(buffer)))
{
fileContent.append(buffer, sizeof(buffer));
}
fileContent.append(buffer, file.gcount());
const size_t keyLen = key.size();
size_t keyIndex = 0;
for (string::iterator it = fileContent.begin(); it != fileContent.end(); ++it)
{
*it = static_cast<char>(static_cast<uint8_t>(*it) ^ static_cast<uint8_t>(key[keyIndex]));
keyIndex = (keyIndex + 1) % keyLen;
}
return fileContent;
}
void xortoFile(const string& filePath,const string& key)
{
if (key.empty())
{
return ;
}
ifstream file(filePath.c_str(),ios::in | ios::binary);
if (!file.is_open())
{
return ;
}
string fileContent;
char buffer[4096];
while (file.read(buffer, sizeof(buffer)))
{
fileContent.append(buffer, sizeof(buffer));
}
fileContent.append(buffer, file.gcount());
file.close();
const size_t keyLen = key.size();
size_t keyIndex = 0;
for (string::iterator it = fileContent.begin(); it != fileContent.end(); ++it)
{
*it = static_cast<char>(static_cast<uint8_t>(*it) ^ static_cast<uint8_t>(key[keyIndex]));
keyIndex = (keyIndex + 1) % keyLen;
}
ofstream outFile(filePath.c_str(), ios::out | ios::binary | ios::trunc);
if (outFile.is_open())
{
outFile.write(fileContent.data(), fileContent.size());
outFile.close();
}
}
void caesarFile(const string& filePath,int shift)
{
shift %= 256;
if (shift < 0)
{
shift += 256;
}
ifstream file(filePath.c_str(), ios::in | ios::binary);
if (!file.is_open())
{
return ;
}
string fileContent;
char buffer[4096];
while (file.read(buffer, sizeof(buffer)))
{
fileContent.append(buffer, sizeof(buffer));
}
fileContent.append(buffer, file.gcount());
file.close();
for(string::iterator it = fileContent.begin(); it != fileContent.end();it++)
{
*it = static_cast<char>((static_cast<uint8_t>(*it) + shift) % 256);
}
ofstream outFile(filePath.c_str(), ios::out | ios::binary | ios::trunc);
if (outFile.is_open())
{
outFile.write(fileContent.data(), fileContent.size());
outFile.close();
}
}
//加
void FileCEnc(const string& filePath, int shift)
{
caesarFile(filePath, shift);
}
//解
void FileCDec(const string& filePath, int shift)
{
caesarFile(filePath, 256 - (shift % 256));
}
//加密
string CEnc(const string& input, int shift)
{
shift %= 256;
if (shift < 0)
{
shift += 256;
}
string result = input;
const size_t len = result.size();
for (size_t i = 0; i < len; ++i)
{
result[i] = static_cast<char>((static_cast<uint8_t>(result[i]) + shift) % 256);
}
return result;
}
//解密
string CDec(const string& input, int shift)
{
shift %= 256;
if (shift < 0)
{
shift += 256;
}
return CEnc(input, 256 - shift);
}
//xor加/解密
string xorpass(const string &str, const string &key)
{
string result = str;
size_t keyLen = key.size();
if (keyLen == 0) return result;
for (size_t i = 0; i < result.size(); ++i)
{
result[i] ^= key[i % keyLen];
}
return result;
}
string base64up(const string &str,const string &base64Chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/")
{
string result;
int val = 0, valBits = 0;
for (unsigned char c : str)
{
val = (val << 8) + c;
valBits += 8;
while (valBits >= 6)
{
result += base64Chars[(val >> (valBits - 6)) & 0x3F];
valBits -= 6;
}
}
if (valBits > 0)
{
val <<= (6 - valBits);
result += base64Chars[val & 0x3F];
}
while (result.size() % 4 != 0)
{
result += '=';
}
return result;
}
string base64dec(const string &str,const string base64Chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/")
{
string result;
vector<int> val(4, -1);
for (size_t i = 0; i < str.size(); ++i)
{
char c = str[i];
if (c == '=') break;
size_t pos = base64Chars.find(c);
if (pos == string::npos) continue;
val[i % 4] = pos;
if (i % 4 == 3)
{
result += (val[0] << 2) + ((val[1] >> 4) & 0x3);
if (val[2] != -1)
{
result += ((val[1] << 4) & 0xF0) + ((val[2] >> 2) & 0xF);
}
if (val[3] != -1)
{
result += ((val[2] << 6) & 0xC0) + val[3];
}
val.assign(4, -1);
}
}
return result;
}
#endif
#ifdef JTBG_MATH
constexpr double PI = 3.1415926535897932384626433832795028841971693993751058209749445923078164062862089986280348253421170679821480865132823066470938446095505822317253594081284811174502841027019385211055596446229489549303819644288109756659334461284756482337867831652712019091456485669234603486104543266482133936072602491412737245870066063155881748815209209628292540917153643678925903600113305305488204665213841469519415116094330572703657595919530921861173819326117931051185480744623799627495673518857527248912279381830119491298336733624406566430860213949463952247371907021798609437027705392171762931767523846748184676694051320005681271452635608277857713427577896091736371787214684409012249534301465495853710507922796892589235420199561121290219608640344181598136297747713099605187072113499999983729780499510597317328160963185950244594553469083026425223082533446850352619311881710100031378387528865875332083814206171776691473035982534904287554687311595628638823537875937519577818577805321712268066130019278766111959092164201989;
constexpr double E = 2.71828182845904523536028747135266249775724709369995957496696762772407663035354759457138217852516642742746639193200305992181741359662904357290033429526059563073813232862794349076323382988075319525101901157383418793070215408914993488416750924476146066808226480016847741185374234544243710753907774499206955170276183860626133138458300075204493382656029760673711320070932870912744374704723069697720931014169283681902551510865746377211125238978442505695369677078544996996794686445490598793163688923009879312773617821542499922957635148220826989519366803318252886939849646510582093923982948879332036250944311730123819706841614039701983767932068328237646480429531180232878250981945581530175671736133206981125099618188159304169035159888851934580727386673858942287922849989208680582574927961048419844436346324496848756023362482704197862320900216099023530436994184914631409343173814364054625315209618369088870701676839642437814059271456354906130310720851038375051011574770417189861068739696552126715468895703503;
constexpr double SQRT2 = 1.41421356237309504880168872420969807856967187537694807317667973799073247846210703885038753432764157273501384623091229702492483605585073721264412149709993583141322266592750559275579995050115278206057147010955997160597027453459686201472851741864088919860955232923048430871432145083976260362799525140798968725339654633180882964062061525835239505474575028775996172983557522033753185701135437460340849884716038689997069900481503054402779031645424782306849293691862158057846311159666871301301561856898723723528850926486124949771542183342042856860601468247207714358548741556570696776537202264854470158588016207584749226572260020855844665214583988939443709265918003113882464681570826301005948587040031864803421948972782906410450726368813137398552561173220402450912277002269411275736272804957381089675040183698683684507257993647290607629969413804756548237289971803268024744206292691248590521810044598421505911202494413417285314781058036033710773091828693147101711116839165817268894197587165821521282295184884;
constexpr double SQRT3 = 1.73205080756887729352744634150587236694280525381038062805580697945193301690880003708114618675724857567562614141540670302996994509499895247881165551209437364852809323190230558206797482010108467492326501531234326690332288665067225466892183797122704713166036786158801904998653737985938946765034750657605075661834812960610094760218719032508314582952395983299778982450828871446383291734722416398458785539766795806381835366610984886592547299217173962048521628520642509525807542955631373475088223721220342554263241742990244886498239943431941211765024370702162771132440133148573245357948925900775657966073337536320605180787343845178498761621338289030718784211546491791224930825667642427756675700154593911521631048877044894250218451120612024244536165346407222159585161472489960946589338066153481037971219540790746800960017174385666519356963053744274641742538519993731951931130316440686870154554813001406843578025063846717408873461306269231251426333194489885683579563085861290507312886387810643214174778440420;
constexpr double SQRT2_OLD = 1.41421356237309504880;
constexpr double GOLDEN_RATIO = 1.618033988749894848204586834365638117720309179805762862135448622705260462818902449707207204189391137484754088075386891752126633862223536931793180060766726354433389086595939582905638322661319928290267880675208766892501711696207032221043216269548626296313614438149758701220340805887954454749246185695364864449241044320771344947049565846788509874339442212544877066478091588460749988712400765217057517978834166256249407589069704000281210427621771117778053153171410117046665991466979873176135600670874807101317952368942752194843530567830022878569978297783478458782289110976250030269615617002504643382437764861028383126833037242926752631165339247316711121158818638513316203840052221657912866752946549068113171599343235973494985090409476213222981017261070596116456299098162905552085247903524060201727997471753427775927786256194320827505131218156285512224809394712341451702237358057727861600868838295230459264787801788992199027077690389532196819861514378031499741106926088674296226757560523172777520353613936210767389376455606060592165894667595519004005559089502295309423124823552122124154440064703405657347976639723949499465845788730396230903750339938562102423690251386804145779956981224457471780341731264532204163972321340444494873023154176768937521030687378803441700939544096279558986787232095124268935573097045095956844017555198819218020640529055189349475926007348522821010881946445442223188913192946896220023014437702699230078030852611807545192887705021096842493627135925187607778846658361502389134933331223105339232136243192637289106705033992822652635562090297986424727597725655086154875435748264718141451270006023890162077732244994353088999095016803281121943204819643876758633147985719113978153978043761179522473716932154842342539413410068426132226659274970192304431109077708358139135634824723628433781947852957288951054229885990041172503642068600813950280165849572119595841572655608272060485070633215540824253421468456398680614799704251276157567113382216238804864184101253941772811471373693372458177073882433712880619223099540013375889412923186621232913323140937117120092998325630759093134871399326477667311192181668487121776021729374538891044638830122096117244492714552392819666963850353138184544825537185771822600631337603764842509730073374610911087580763636137052090335125324598686883690647098584903346906571145438573674173213673204390240789510577468760558567056022773535968597633939146117902756224515257975749999362325817061022097463364916225850094026426701597354750210520688222001775738669333248596057430164210652246355861415010424285706962674118892510232146022562289424101686011418667990329793088928222183690582656752165777989660568072408144928904318015675991357691002898290644219185969779988493212606669436569229484236784251524544443252390347112760608309779453586766858515947558390147671220254439516342041397164829221806693001816683893397351370861437383309643089264523752492186251388753792296077989625380568342895397694325741498041566361472999983531290178082447148244070818254088871994444386621466507946985028032473497103273116408972920569487212670369815666286262356245983114702546326742506454513892378837752379862514193651503888979412448529992739250635634854131160900523582972470086346810966660716616939377832305264413721818413802032397252190356198560953255749377833479333549555327446939573218595332164319916797633198513855676207371659128135478641696490833292041817678042854736425716559317048898337235081362512345300326822029119903426437935456700772441494209602577714350500310461086593558904384540560452251175666706063670077354175534042626557068102641967;
constexpr double LN2 = 0.693147180559945309417232121458176568075500134360255254120680009493393621969694715605863326996418687542001481020570685733685520235758130557032670751635075961930727570828371435190307038623891673471123350115364497955239120475172681574932065155524734139525882950453007095326366642654104239157814952043740430385500801944170641671518644712839968171784546957026271631064546150257207402481637773389638550695260668341137273873722928956493547025762652098859693201965058554764703306793654432547632744951250406069438147104689946506220167720424524529612687946546193165174576895376538888177868875102639104218611580505842688795882753702268778028535329572061293279824731180040768469979101140992887249637615726179380553049901956326218787063972438096769112005624470996951424241447468272758445007262469916789176858299666996541749509444127435156596991694271902192543957838101290202746370397043177879414585816185098948702213214102083940609325417450733286602035486091303062977283475170890575688614132527816085115156189661336634608158840226236754985096499361483612372179767378997178640489838357627493159145543606150426088327889631973102036697841699204035510603074807081910414534195223079578586584621775650665468574982196945644774322176215884034123790489417453110159113774751885869418064153460352754646905166242375441672447743132559488767515247572535863883631579470976273865440900642251666332395680977755918806507992008604158683099125878073681372939273093388219238360475282663676716002451946971981917493249338616419592351457713492076196398925694250447014006233624495307287638028432108514857528592115298260642214003043346716801109052217328549813809402392379965278358770829657012749325765316669265312963795918394865212469215696837331081650835366965190265037672469266190551531737752102895502447173099187258128580608493352601498503028655920466770055720635775931429452017346435743688891070611314698203179260202371687195113133801385915086836980459029942946717613821307248351779574163814538267303191105082127462627681691136617084168227604103410509858381533635246986277350654197983834181077629117905501385984003178334456879712634293275473553008347738369720872608092833869505016485273829234745890945473486726343375593574447474621563120148635802867049573876004659333424920352804198352737;
#define PI_STR "3.1415926535897932384626433832795028841971693993751058209749445923078164062862089986280348253421170679821480865132823066470938446095505822317253594081284811174502841027019385211055596446229489549303819644288109756659334461284756482337867831652712019091456485669234603486104543266482133936072602491412737245870066063155881748815209209628292540917153643678925903600113305305488204665213841469519415116094330572703657595919530921861173819326117931051185480744623799627495673518857527248912279381830119491298336733624406566430860213949463952247371907021798609437027705392171762931767523846748184676694051320005681271452635608277857713427577896091736371787214684409012249534301465495853710507922796892589235420199561121290219608640344181598136297747713099605187072113499999983729780499510597317328160963185950244594553469083026425223082533446850352619311881710100031378387528865875332083814206171776691473035982534904287554687311595628638823537875937519577818577805321712268066130019278766111959092164201989"
#define E_STR "2.71828182845904523536028747135266249775724709369995957496696762772407663035354759457138217852516642742746639193200305992181741359662904357290033429526059563073813232862794349076323382988075319525101901157383418793070215408914993488416750924476146066808226480016847741185374234544243710753907774499206955170276183860626133138458300075204493382656029760673711320070932870912744374704723069697720931014169283681902551510865746377211125238978442505695369677078544996996794686445490598793163688923009879312773617821542499922957635148220826989519366803318252886939849646510582093923982948879332036250944311730123819706841614039701983767932068328237646480429531180232878250981945581530175671736133206981125099618188159304169035159888851934580727386673858942287922849989208680582574927961048419844436346324496848756023362482704197862320900216099023530436994184914631409343173814364054625315209618369088870701676839642437814059271456354906130310720851038375051011574770417189861068739696552126715468895703503"
#define SQRT2_STR "1.41421356237309504880168872420969807856967187537694807317667973799073247846210703885038753432764157273501384623091229702492483605585073721264412149709993583141322266592750559275579995050115278206057147010955997160597027453459686201472851741864088919860955232923048430871432145083976260362799525140798968725339654633180882964062061525835239505474575028775996172983557522033753185701135437460340849884716038689997069900481503054402779031645424782306849293691862158057846311159666871301301561856898723723528850926486124949771542183342042856860601468247207714358548741556570696776537202264854470158588016207584749226572260020855844665214583988939443709265918003113882464681570826301005948587040031864803421948972782906410450726368813137398552561173220402450912277002269411275736272804957381089675040183698683684507257993647290607629969413804756548237289971803268024744206292691248590521810044598421505911202494413417285314781058036033710773091828693147101711116839165817268894197587165821521282295184884"
constexpr double DEG_TO_RAD = PI / 180.0; // 角度转弧度系数
constexpr double RAD_TO_DEG = 180.0 / PI; // 弧度转角度系数
constexpr double LN10 = 2.302585092994045684017991454684364207601101488628772976033327900967572609677352480235997205089598298;
constexpr double SQRT_PI = 1.772453850905516027298167483341145182797549456122387128213807789852911284591032181374950656738544665;
constexpr short JTBG_SHORT_MIN = -32768;
constexpr short JTBG_SHORT_MAX = 32767;
constexpr int JTBG_INT_MIN = -2147483648;
constexpr int JTBG_INT_MAX = 2147483647;
constexpr long long JTBG_LLONG_MIN = -9223372036854775807LL - 1;
constexpr long long JTBG_LLONG_MAX = 9223372036854775807LL;
constexpr long long JTBG_BIG_MOD = 1000000007;
#define JTBG_SIGNED_MIN(type) (std::numeric_limits<type>::min())
#define JTBG_SIGNED_MAX(type) (std::numeric_limits<type>::max())
#define IS_SIGNED_NEGATIVE(x) ((x) < 0)
#define IS_SIGNED_POSITIVE(x) ((x) > 0)
#define IS_SIGNED_ZERO(x) ((x) == 0)
constexpr double d1d = 1.0000000000;
inline double NumbertoPercent(int all,int p)
{
if(all==0.0) return NAN;
return 1.0*((p*1.0)/(all*1.0)*100.0);
}
inline double DoubleNumbertoPercent(double all, double p)
{
if (all==0) return NAN;
return 1.0*((p*1.0)/(all*1.0)*100.0);
}
#define itop(a,b) NumbertoPercent((a),(b))
#define dtop(a,b) DoubleNumbertoPercent((a),(b))
#define ftop(a,b) NumbertoPercent((a),(b))
inline double getSqrtNt(double n,double t)
{
if (n < 0)
{
return NAN;
}
if (t <= 0)
{
return NAN;
}
if (n == 0) return 0;
double xn = n / 2.0;
double xn1 = 0.0;
const int MAX_ITER = 1000;
int iterCount = 0;
do
{
xn1 = xn - (xn * xn - n) / (2 * xn);
if (fabs(xn1 - xn) < t)
{
break;
}
xn = xn1;
iterCount++;
} while (iterCount < MAX_ITER);
if (iterCount >= MAX_ITER)
{
return NAN;
}
return xn1;
}
//角度转弧度
inline double toRadians(double degrees)
{
return degrees * DEG_TO_RAD;
}
// 弧度转角度
inline double toDegrees(double radians)
{
return radians * RAD_TO_DEG;
}
// 计算阶乘
inline long long fac(int n)
{
if(n<0) return -1;
long long result = 1;
for (int i = 2; i <= n; ++i)
{
result *= i;
}
return result;
}
inline double qpow(double base, int exponent)
{
if (exponent==0) return 1.0;
if (base==0) return 0.0;
bool isNegative = exponent < 0;
unsigned int absExponent = static_cast<unsigned int>(isNegative ? -exponent : exponent);
double result = 1.0;
double current = base;
while (absExponent > 0)
{
if (absExponent % 2 == 1)
{
result *= current;
}
current *= current;
absExponent /= 2;
}
return isNegative ? 1.0 / result : result;
}
inline long long ipow(long long base, int exponent)
{
if (exponent == 0) return 1;
if (base == 0) return 0;
bool isNegative = false;
unsigned int absExp;
if (exponent < 0)
{
isNegative = true;
absExp = static_cast<unsigned int>(-exponent);
}
else
{
absExp = static_cast<unsigned int>(exponent);
}
long long result = 1;
long long current = base;
while (absExp > 0)
{
if (absExp & 1)
{
result *= current;
}
current *= current;
absExp >>= 1;
}
return isNegative ? (result == 0 ? 0 : 1) : result;
}
inline long long GetA(int a, int b)
{
if(a < 0 || b < 0 || a < b)
{
return -1;
}
if (b == 0)
{
return 1;
}
long long result = 1;
for (int i = 0; i < b; ++i)
{
result *= (a - i);
if (result < 0)
{
return -1;
}
}
return result;
}
inline long long GetC(int a, int b)
{
if (a < 0 || b < 0 || a < b)
{
return -1;
}
if (b == 0 || a == b)
{
return 1;
}
b = min(b, a - b);
long long result = 1;
for (int i = 1; i <= b; ++i)
{
result = result * (a - b + i) / i;
if (result < 0)
{
return -1;
}
}
return result;
}
inline bool isPrime(int x)
{
if(x<2) return 0;
for(int i=2;i*i<=x;i++)
{
if(x%i==0) return 0;
}
return 1;
}
inline bool isPrime(long long x)
{
if(x < 2) return 0;
if(x == 2) return 1;
if(x % 2 == 0) return 0;
for(long long i = 3; i * i <= x; i += 2)
{
if(x % i == 0) return 0;
}
return 1;
}
inline vector<int> MakePrimelist_AiShai(int from, int to)
{
vector<int> primes;
if (from > to || to < 2)
{
return primes;
}
from = max(from, 2);
vector<bool> is_prime(to + 1, true);
is_prime[0] = is_prime[1] = false;
int sqrt_to = static_cast<int>(sqrt(to));
for (int i = 2; i <= sqrt_to; ++i)
{
if (is_prime[i])
{
for (int j = i * i; j <= to; j += i)
{
is_prime[j] = false;
}
}
}
for (int num = from; num <= to; ++num)
{
if (is_prime[num])
{
primes.push_back(num);
}
}
return primes;
}
inline vector<int> MakePrimelist_OLaShai(int from, int to)
{
vector<int> primes;
if (from > to || to < 2)
{
return primes;
}
from=max(from, 2);
vector<bool> is_prime(to + 1, true);
is_prime[0] = is_prime[1] = false;
vector<int> all_primes;
for(int i = 2; i <= to; ++i)
{
if (is_prime[i])
{
all_primes.push_back(i);
}
for (int p : all_primes)
{
if (1LL * i * p > to)
{
break;
}
is_prime[i * p] = false;
if (i % p == 0)
{
break;
}
}
}
for(int j=0;j<int(all_primes.size());++j)
{
int p = all_primes[j];
if (p >= from && p <= to)
{
primes.push_back(p);
}
}
return primes;
}
inline vector<int> MakePrimelist_OLaShai_quick(int from, int to)
{
static vector<bool> cache_is_prime;
static vector<int> cache_all_primes;
static int cache_max_to = 0;
if (to > cache_max_to)
{
cache_max_to = to;
cache_is_prime.assign(to + 1, true);
cache_is_prime[0] = cache_is_prime[1] = false;
cache_all_primes.clear();
for (int i = 2; i <= to; ++i)
{
if (cache_is_prime[i]) cache_all_primes.push_back(i);
for (int p : cache_all_primes)
{
if (1LL * i * p > to) break;
cache_is_prime[i * p] = false;
if (i % p == 0) break;
}
}
}
vector<int> primes;
from = max(from, 2);
for (int p : cache_all_primes)
{
if (p >= from && p <= to) primes.push_back(p);
}
return primes;
}
inline long long jtbg_gcd(long long a, long long b,bool usesystem=0)
{
if(usesystem)
{
return __gcd(a,b)*1ll;
}
a = llabs(a);
b = llabs(b);
if (a == 0) return b;
if (b == 0) return a;
int shift = 0;
while (((a | b) & 1) == 0)
{
a >>= 1;
b >>= 1;
shift++;
}
while ((a & 1) == 0)
a >>= 1;
do
{
while ((b & 1) == 0)
b >>= 1;
if (a < b)
swap(a, b);
a -= b;
} while (a != 0);
return b << shift;
}
inline int jtbg_gcd(int a, int b,bool usesystem=0)
{
if(usesystem)
{
return __gcd(a,b);
}
a = abs(a);
b = abs(b);
if (a == 0) return b;
if (b == 0) return a;
int shift = 0;
while (((a | b) & 1) == 0)
{
a >>= 1;
b >>= 1;
shift++;
}
while ((a & 1) == 0)
a >>= 1;
do
{
while ((b & 1) == 0)
b >>= 1;
if (a < b)
swap(a, b);
a -= b;
} while (a != 0);
return b << shift;
}
inline long long jtbg_lcm(long long a, long long b, bool usesystem = 0)
{
if (a == 0 || b == 0) return 0;
long long gcd_val = jtbg_gcd(a, b, usesystem);
if (gcd_val == 0) return 0;
// lcm(a, b) = |a * b| / gcd(a, b)
return llabs(a / gcd_val * b);
}
inline int jtbg_lcm(int a, int b, bool usesystem = 0)
{
if (a == 0 || b == 0) return 0;
int gcd_val = jtbg_gcd(a, b, usesystem);
if (gcd_val == 0) return 0;
// lcm(a, b) = |a * b| / gcd(a, b)
return abs(a / gcd_val * b);
}
inline long long jtbg_lcm_multi(const vector<long long>& numbers, bool usesystem = 0)
{
if (numbers.empty()) return 0;
long long result = numbers[0];
for (size_t i = 1; i < numbers.size(); ++i) {
result = jtbg_lcm(result, numbers[i], usesystem);
if (result == 0) break;
}
return result;
}
inline long long Getalllcm(int from,int to,long long mod=1000000007)
{
if(to<=from) return -1*1ll;
if(from<0||to<=0) return -1*1ll;
long long ans=1ll;
if(from<2) from=2;
for(int i=from;i<=to;i++)
{
if(isPrime(i))
{
int temp=i;
while(temp<=to)
{
ans=(ans*i)%mod;
temp*=i;
}
}
}
return ans;
}
// 绝对值函数(模板版本)
template<typename T>
inline T jtbg_abs(T x)
{
return (x < 0) ? -x : x;
}
// 符号函数
template<typename T>
inline int jtbg_sign(T x)
{
if (x > 0) return 1;
if (x < 0) return -1;
return 0;
}
// 最大值
template<typename T>
inline T jtbg_max(T a, T b)
{
return (a > b) ? a : b;
}
// 最小值
template<typename T>
inline T jtbg_min(T a, T b)
{
return (a < b) ? a : b;
}
// 限制值在范围内
template<typename T>
inline T jtbg_clamp(T value, T min_val, T max_val)
{
if (value < min_val) return min_val;
if (value > max_val) return max_val;
return value;
}
// 线性插值
template<typename T>
inline T jtbg_lerp(T a, T b, double t)
{
return a + (b - a) * t;
}
// 平方
template<typename T>
inline T jtbg_square(T x)
{
return x * x;
}
// 立方
template<typename T>
inline T jtbg_cube(T x)
{
return x * x * x;
}
// 判断是否为完全平方数
inline bool jtbg_isPerfectSquare(int n)
{
if (n < 0) return false;
int root = static_cast<int>(sqrt(n));
return root * root == n;
}
// 判断是否为完全立方数
inline bool jtbg_isPerfectCube(int n)
{
if (n < 0) n = -n;
int root = static_cast<int>(cbrt(n));
return root * root * root == n;
}
// 斐波那契数列
inline long long jtbg_fibonacci(int n)
{
if (n < 0) return -1;
if (n == 0) return 0;
if (n == 1) return 1;
long long a = 0, b = 1;
for (int i = 2; i <= n; ++i)
{
long long temp = a + b;
a = b;
b = temp;
}
return b;
}
// 判断是否为斐波那契数
inline bool jtbg_isFibonacci(int n)
{
if (n < 0) return false;
// 一个数是斐波那契数当且仅当 5*n^2+4 或 5*n^2-4 是完全平方数
int check1 = 5 * n * n + 4;
int check2 = 5 * n * n - 4;
return jtbg_isPerfectSquare(check1) || jtbg_isPerfectSquare(check2);
}
// 计算数字的位数
inline int jtbg_countDigits(long long n)
{
if (n == 0) return 1;
int count = 0;
n = llabs(n);
while (n > 0)
{
n /= 10;
count++;
}
return count;
}
// 数字各位之和
inline int jtbg_digitSum(long long n)
{
int sum = 0;
n = llabs(n);
while (n > 0)
{
sum += n % 10;
n /= 10;
}
return sum;
}
// 数字反转
inline long long jtbg_reverseNumber(long long n)
{
long long reversed = 0;
bool negative = n < 0;
n = llabs(n);
while (n > 0)
{
reversed = reversed * 10 + n % 10;
n /= 10;
}
return negative ? -reversed : reversed;
}
// 判断回文数
inline bool jtbg_isPalindrome(long long n)
{
return n == jtbg_reverseNumber(n);
}
// 计算对数
inline double jtbg_log(double x, double base = E)
{
if (x <= 0 || base <= 0 || base == 1) return NAN;
return log(x) / log(base);
}
// 计算正弦(角度制)
inline double jtbg_sind(double degrees)
{
return sin(toRadians(degrees));
}
// 计算余弦(角度制)
inline double jtbg_cosd(double degrees)
{
return cos(toRadians(degrees));
}
// 计算正切(角度制)
inline double jtbg_tand(double degrees)
{
return tan(toRadians(degrees));
}
// 计算反正弦(返回角度)
inline double jtbg_asind(double x)
{
return toDegrees(asin(x));
}
// 计算反余弦(返回角度)
inline double jtbg_acosd(double x)
{
return toDegrees(acos(x));
}
// 计算反正切(返回角度)
inline double jtbg_atand(double x)
{
return toDegrees(atan(x));
}
// 两点间距离
inline double jtbg_distance(double x1, double y1, double x2, double y2)
{
double dx = x2 - x1;
double dy = y2 - y1;
return sqrt(dx * dx + dy * dy);
}
// 三维距离
inline double jtbg_distance3D(double x1, double y1, double z1, double x2, double y2, double z2)
{
double dx = x2 - x1;
double dy = y2 - y1;
double dz = z2 - z1;
return sqrt(dx * dx + dy * dy + dz * dz);
}
// 曼哈顿距离
inline double jtbg_manhattanDistance(double x1, double y1, double x2, double y2)
{
return fabs(x2 - x1) + fabs(y2 - y1);
}
// 切比雪夫距离
inline double jtbg_chebyshevDistance(double x1, double y1, double x2, double y2)
{
return max(fabs(x2 - x1), fabs(y2 - y1));
}
// 快速判断是否为2的幂(有符号版本)
inline bool jtbg_is_power_of_two_signed(signed int x)
{
return x > 0 && (x & (x - 1)) == 0;
}
// 有符号数的奇偶性
inline bool jtbg_is_even_signed(signed int x)
{
return (x & 1) == 0; // 对负数也有效
}
// 交换两个有符号数
template<typename T>
inline void jtbg_swap_signed(T& a, T& b)
{
// 避免溢出的交换
a = a ^ b;
b = a ^ b;
a = a ^ b;
}
//===================================== 三角函数扩展 =====================================
// 角度制三角函数
inline double jtbg_cotd(double d)
{
double r = d * PI / 180.0;
return cos(r) / sin(r);
}
inline double jtbg_atand2(double y, double x)
{
return atan2(y, x) * 180.0 / PI;
}
// 双曲函数
inline double jtbg_sinh(double x)
{
double ex = exp(x);
double emx = exp(-x);
return (ex - emx) / 2.0;
}
inline double jtbg_cosh(double x)
{
double ex = exp(x);
double emx = exp(-x);
return (ex + emx) / 2.0;
}
inline double jtbg_tanh(double x)
{
if (x > 10) return 1.0;
if (x < -10) return -1.0;
double ex = exp(x);
double emx = exp(-x);
return (ex - emx) / (ex + emx);
}
//===================================== 对数指数函数 =====================================
// 自然对数(安全版)
inline double jtbg_ln(double x)
{
if (x <= 0) return NAN;
return log(x);
}
// 任意底数对数
inline double jtbg_logb(double x, double b)
{
if (x <= 0 || b <= 0 || b == 1) return NAN;
return log(x) / log(b);
}
// 10^x
inline double jtbg_pow10(double x)
{
return pow(10.0, x);
}
// 2^x
inline double jtbg_pow2(double x)
{
return pow(2.0, x);
}
//===================================== 数论函数 =====================================
// 扩展欧几里得
struct ExGCD
{
long long g, x, y;
};
inline ExGCD jtbg_exgcd(long long a, long long b)
{
ExGCD res;
if (b == 0)
{
res.g = a;
res.x = 1;
res.y = 0;
return res;
}
ExGCD t = jtbg_exgcd(b, a % b);
res.g = t.g;
res.x = t.y;
res.y = t.x - (a / b) * t.y;
return res;
}
// 模逆元
inline long long jtbg_modinv(long long a, long long m)
{
ExGCD eg = jtbg_exgcd(a, m);
if (eg.g != 1) return -1;
return (eg.x % m + m) % m;
}
#ifndef JTBG_NO_LL
#define ll long long
#endif
inline long long GetDoubleCycleLength(long long a, long long b)
{
auto gcd = [](long long x, long long y) -> long long
{
while (y)
{
long long t = x % y;
x = y;
y = t;
}
return x;
};
auto euler_phi = [&](long long n) -> long long
{
long long res = n;
for (long long p = 2; p * p <= n; p++)
{
if (n % p == 0)
{
res = res / p * (p - 1);
while (n % p == 0)
{
n /= p;
}
}
}
if (n > 1)
{
res = res / n * (n - 1);
}
return res;
};
auto quick_pow = [&](long long base, long long exponent, long long mod_val) -> long long
{
long long res = 1;
base %= mod_val;
while (exponent > 0)
{
if (exponent & 1)
{
res = (res * base) % mod_val;
}
base = (base * base) % mod_val;
exponent >>= 1;
}
return res;
};
auto get_divisors = [&](long long n) -> vector<long long>
{
vector<long long> divisors;
for (long long i = 1; i * i <= n; i++)
{
if (n % i == 0)
{
divisors.push_back(i);
if (i != n / i)
{
divisors.push_back(n / i);
}
}
}
sort(divisors.begin(), divisors.end());
return divisors;
};
long long gcd_val = gcd(a, b);
a /= gcd_val;
b /= gcd_val;
while (b % 2 == 0)
{
b /= 2;
}
while (b % 5 == 0)
{
b /= 5;
}
if (b == 1)
{
return 0;
}
long long phi_b = euler_phi(b);
vector<long long> divisors = get_divisors(phi_b);
for (long long k : divisors)
{
if (quick_pow(10, k, b) == 1)
{
return k;
}
}
return -1;
}
inline long long int_to_long_long(int i)
{
long long j=i*1ll;
return j;
}
#define itol(x) int_to_long_long((x))
inline int long_long_to_int(long long i)
{
return static_cast<int>(i);
}
#define ltoi(x) long_long_to_int((x))
// 欧拉函数 φ(n)
inline int eula_phi(int n)
{
if (n <= 0) return 0;
int res = n;
int tmp = n;
for (int i = 2; i * i <= tmp; i++)
{
if (tmp % i == 0)
{
while (tmp % i == 0) tmp /= i;
res -= res / i;
}
}
if (tmp > 1) res -= res / tmp;
return res;
}
// 约数个数
inline int jtbg_divcnt(int n)
{
if (n <= 0) return 0;
if (n == 1) return 1;
int cnt = 1;
int tmp = n;
for (int i = 2; i * i <= tmp; i++)
{
int exp = 0;
while (tmp % i == 0)
{
tmp /= i;
exp++;
}
if (exp > 0) cnt *= (exp + 1);
}
if (tmp > 1) cnt *= 2;
return cnt;
}
// 约数和
inline int jtbg_divsum(int n)
{
if (n <= 0) return 0;
if (n == 1) return 1;
int sum = 1;
int tmp = n;
for (int i = 2; i * i <= tmp; i++)
{
if (tmp % i == 0)
{
int psum = 1;
int pow = 1;
while (tmp % i == 0)
{
tmp /= i;
pow *= i;
psum += pow;
}
sum *= psum;
}
}
if (tmp > 1) sum *= (1 + tmp);
return sum;
}
// 中国剩余定理
inline long long jtbg_crt(vector<long long> rem, vector<long long> mod)
{
if (rem.size() != mod.size()) return -1;
int k = rem.size();
long long x = 0;
long long M = 1;
for (int i = 0; i < k; i++) M *= mod[i];
for (int i = 0; i < k; i++)
{
long long Mi = M / mod[i];
long long inv = jtbg_modinv(Mi, mod[i]);
if (inv == -1) return -1;
x = (x + rem[i] * Mi * inv) % M;
}
return (x % M + M) % M;
}
//===================================== 组合数学 =====================================
// 排列数 P(n,k)
inline long long jtbg_perm(long long n, long long k)
{
if (n < 0 || k < 0 || k > n) return 0;
if (k == 0) return 1;
long long res = 1;
for (long long i = 0; i < k; i++)
{
if (res > LLONG_MAX / (n - i)) return -1;
res *= (n - i);
}
return res;
}
// 组合数 C(n,k)
inline long long jtbg_comb(long long n, long long k)
{
if (n < 0 || k < 0 || k > n) return 0;
if (k == 0 || k == n) return 1;
if (k > n - k) k = n - k;
long long res = 1;
for (long long i = 1; i <= k; i++)
{
if (res > LLONG_MAX / (n - k + i) / i) return -1;
res = res * (n - k + i) / i;
}
return res;
}
// 卡特兰数
inline long long jtbg_catalan(int n)
{
if (n < 0) return 0;
if (n == 0) return 1;
long long res = 1;
for (int i = 1; i <= n; i++)
{
res = res * (4 * i - 2) / (i + 1);
if (res < 0) return -1;
}
return res;
}
//===================================== 统计函数 =====================================
// 平均值
template<typename T>
inline double jtbg_mean(vector<T> data)
{
if (data.empty()) return 0.0;
double sum = 0.0;
for (size_t i = 0; i < data.size(); i++)
{
sum += static_cast<double>(data[i]);
}
return sum / data.size();
}
// 中位数
template<typename T>
inline double jtbg_median(vector<T> data)
{
if (data.empty()) return 0.0;
sort(data.begin(), data.end());
size_t n = data.size();
if (n % 2 == 0)
{
return (static_cast<double>(data[n/2-1]) + static_cast<double>(data[n/2])) / 2.0;
}
else
{
return static_cast<double>(data[n/2]);
}
}
// 方差
template<typename T>
inline double jtbg_var(vector<T> data)
{
if (data.size() <= 1) return 0.0;
double m = jtbg_mean(data);
double sum = 0.0;
for (size_t i = 0; i < data.size(); i++)
{
double diff = static_cast<double>(data[i]) - m;
sum += diff * diff;
}
return sum / (data.size() - 1);
}
// 标准差
template<typename T>
inline double jtbg_std(vector<T> data)
{
return sqrt(jtbg_var(data));
}
//===================================== 几何函数 =====================================
// 点积
inline double jtbg_dot(double x1, double y1, double x2, double y2)
{
return x1 * x2 + y1 * y2;
}
// 叉积(2D)
inline double jtbg_cross(double x1, double y1, double x2, double y2)
{
return x1 * y2 - y1 * x2;
}
// 三角形面积
inline double jtbg_tri_area(double x1, double y1, double x2, double y2, double x3, double y3)
{
return fabs((x1*(y2-y3) + x2*(y3-y1) + x3*(y1-y2)) / 2.0);
}
// 多边形面积(鞋带公式)
inline double jtbg_poly_area(vector<double> x, vector<double> y)
{
if (x.size() != y.size() || x.size() < 3) return 0.0;
double area = 0.0;
size_t n = x.size();
for (size_t i = 0; i < n; i++)
{
size_t j = (i + 1) % n;
area += x[i] * y[j];
area -= x[j] * y[i];
}
return fabs(area) / 2.0;
}
//===================================== 数值计算 =====================================
// 数值积分(梯形法则)
inline double jtbg_int_trap(double (*f)(double), double a, double b, int n = 1000)
{
if (n <= 0) return 0.0;
double h = (b - a) / n;
double sum = 0.5 * (f(a) + f(b));
for (int i = 1; i < n; i++)
{
double x = a + i * h;
sum += f(x);
}
return sum * h;
}
// 数值积分(辛普森法则)
inline double jtbg_int_simp(double (*f)(double), double a, double b, int n = 1000)
{
if (n % 2 != 0) n++;
if (n <= 0) return 0.0;
double h = (b - a) / n;
double sum = f(a) + f(b);
for (int i = 1; i < n; i++)
{
double x = a + i * h;
if (i % 2 == 0) sum += 2.0 * f(x);
else sum += 4.0 * f(x);
}
return sum * h / 3.0;
}
// 数值微分(中心差分)
inline double jtbg_deriv(double (*f)(double), double x, double h = 1e-5)
{
return (f(x + h) - f(x - h)) / (2 * h);
}
// 求根(二分法)
inline double jtbg_root_bisect_old(double (*f)(double), double a, double b, double eps = 1e-10, int maxit = 1000)
{
if (f(a) * f(b) > 0) return NAN;
double fa = f(a);
for (int i = 0; i < maxit; i++)
{
double mid = (a + b) / 2;
double fm = f(mid);
if (fabs(fm) < eps || (b - a) < eps) return mid;
if (fa * fm < 0)
{
b = mid;
}
else
{
a = mid;
fa = fm;
}
}
return (a + b) / 2;
}
inline double jtbg_root_bisect(double (*f)(double), double a, double b, double eps = 1e-10, int maxit = 1000)
{
double fa = f(a);
double fb = f(b);
if (fa * fb > 0) return NAN; // 同号,区间内可能无根
// 确保 fa < 0 < fb
if (fa > 0)
{
swap(a, b);
swap(fa, fb);
}
for (int i = 0; i < maxit; i++)
{
double mid = (a + b) / 2;
double fm = f(mid);
if (fabs(fm) < eps || (b - a) < eps) return mid;
if (fm < 0)
{
a = mid;
fa = fm;
}
else
{
b = mid;
fb = fm;
}
}
return (a + b) / 2;
}
//===================================== 特殊函数 =====================================
// 阶乘(大数版)
inline double jtbg_fact(double n)
{
if (n < 0) return NAN;
if (n == 0 || n == 1) return 1;
// Stirling 近似
return sqrt(2 * PI * n) * pow(n / E, n);
}
// 误差函数近似
inline double jtbg_erf(double x)
{
double a1 = 0.254829592;
double a2 = -0.284496736;
double a3 = 1.421413741;
double a4 = -1.453152027;
double a5 = 1.061405429;
double p = 0.3275911;
int sign = (x < 0) ? -1 : 1;
x = fabs(x);
double t = 1.0 / (1.0 + p * x);
double y = 1.0 - (((((a5 * t + a4) * t) + a3) * t + a2) * t + a1) * t * exp(-x * x);
return sign * y;
}
// sinc 函数
inline double jtbg_sinc(double x)
{
if (fabs(x) < 1e-10) return 1.0;
return sin(x) / x;
}
//===================================== 矩阵运算 =====================================
// 2x2 矩阵乘法
inline void jtbg_mat2_mul(double a[2][2], double b[2][2], double res[2][2])
{
res[0][0] = a[0][0]*b[0][0] + a[0][1]*b[1][0];
res[0][1] = a[0][0]*b[0][1] + a[0][1]*b[1][1];
res[1][0] = a[1][0]*b[0][0] + a[1][1]*b[1][0];
res[1][1] = a[1][0]*b[0][1] + a[1][1]*b[1][1];
}
// 2x2 矩阵行列式
inline double jtbg_mat2_det(double m[2][2])
{
return m[0][0]*m[1][1] - m[0][1]*m[1][0];
}
// 2x2 矩阵逆
inline bool jtbg_mat2_inv(double m[2][2], double inv[2][2])
{
double det = jtbg_mat2_det(m);
if (fabs(det) < 1e-10) return false;
double inv_det = 1.0 / det;
inv[0][0] = m[1][1] * inv_det;
inv[0][1] = -m[0][1] * inv_det;
inv[1][0] = -m[1][0] * inv_det;
inv[1][1] = m[0][0] * inv_det;
return true;
}
// 3x3 矩阵行列式
inline double jtbg_mat3_det(double m[3][3])
{
return m[0][0]*(m[1][1]*m[2][2] - m[1][2]*m[2][1])
- m[0][1]*(m[1][0]*m[2][2] - m[1][2]*m[2][0])
+ m[0][2]*(m[1][0]*m[2][1] - m[1][1]*m[2][0]);
}
// 向量点积
inline double jtbg_vec_dot(double v1[], double v2[], int n)
{
double sum = 0.0;
for (int i = 0; i < n; i++)
{
sum += v1[i] * v2[i];
}
return sum;
}
// 向量叉积(3D)
inline void jtbg_vec_cross(double v1[3], double v2[3], double res[3])
{
res[0] = v1[1]*v2[2] - v1[2]*v2[1];
res[1] = v1[2]*v2[0] - v1[0]*v2[2];
res[2] = v1[0]*v2[1] - v1[1]*v2[0];
}
// 向量长度
inline double jtbg_vec_len(double v[], int n)
{
return sqrt(jtbg_vec_dot(v, v, n));
}
// 向量归一化
inline bool jtbg_vec_norm(double v[], int n)
{
double len = jtbg_vec_len(v, n);
if (len < 1e-10) return false;
for (int i = 0; i < n; i++)
{
v[i] /= len;
}
return true;
}
//===================================== 复数运算 =====================================
struct Complex
{
double re, im;
Complex(double r = 0, double i = 0) : re(r), im(i) {}
};
// 复数加法
inline Complex jtbg_cadd(Complex a, Complex b)
{
return Complex(a.re + b.re, a.im + b.im);
}
// 复数减法
inline Complex jtbg_csub(Complex a, Complex b)
{
return Complex(a.re - b.re, a.im - b.im);
}
// 复数乘法
inline Complex jtbg_cmul(Complex a, Complex b)
{
return Complex(a.re*b.re - a.im*b.im, a.re*b.im + a.im*b.re);
}
// 复数除法
inline Complex jtbg_cdiv(Complex a, Complex b)
{
double denom = b.re*b.re + b.im*b.im;
if (fabs(denom) < 1e-10) return Complex(NAN, NAN);
return Complex((a.re*b.re + a.im*b.im)/denom,
(a.im*b.re - a.re*b.im)/denom);
}
// 复数模长
inline double jtbg_cabs(Complex c)
{
return sqrt(c.re*c.re + c.im*c.im);
}
// 复数共轭
inline Complex jtbg_cconj(Complex c)
{
return Complex(c.re, -c.im);
}
// 复数指数 e^(a+bi)
inline Complex jtbg_cexp(Complex c)
{
double exp_re = exp(c.re);
return Complex(exp_re * cos(c.im), exp_re * sin(c.im));
}
// 复数对数 ln(a+bi)
inline Complex jtbg_cln(Complex c)
{
double mag = jtbg_cabs(c);
double ang = atan2(c.im, c.re);
return Complex(log(mag), ang);
}
// 复数幂 (a+bi)^n
inline Complex jtbg_cpow(Complex c, int n)
{
if (n == 0) return Complex(1, 0);
Complex result(1, 0);
Complex base = c;
bool neg = false;
if (n < 0)
{
n = -n;
neg = true;
}
while (n > 0)
{
if (n & 1) result = jtbg_cmul(result, base);
base = jtbg_cmul(base, base);
n >>= 1;
}
if (neg)
{
double denom = result.re*result.re + result.im*result.im;
if (fabs(denom) < 1e-10) return Complex(NAN, NAN);
return Complex(result.re/denom, -result.im/denom);
}
return result;
}
//===================================== 概率统计 =====================================
// 二项分布概率
inline double jtbg_binom_pmf(int n, int k, double p)
{
if (k < 0 || k > n || p < 0 || p > 1) return 0.0;
return jtbg_comb(n, k) * pow(p, k) * pow(1-p, n-k);
}
// 泊松分布概率
inline double jtbg_poisson_pmf(int k, double lambda)
{
if (k < 0 || lambda <= 0) return 0.0;
return exp(-lambda) * pow(lambda, k) / tgamma(k+1);
}
// 正态分布PDF
inline double jtbg_norm_pdf(double x, double mu, double sigma)
{
if (sigma <= 0) return 0.0;
double z = (x - mu) / sigma;
return exp(-0.5*z*z) / (sigma * sqrt(2*PI));
}
// 正态分布CDF近似
inline double jtbg_norm_cdf(double x, double mu, double sigma)
{
if (sigma <= 0) return 0.0;
double z = (x - mu) / (sigma * sqrt(2));
return 0.5 * (1 + jtbg_erf(z));
}
// 均匀分布
inline double jtbg_unif_pdf(double x, double a, double b)
{
if (x < a || x > b) return 0.0;
return 1.0 / (b - a);
}
// 指数分布
inline double jtbg_exp_pdf(double x, double lambda)
{
if (x < 0 || lambda <= 0) return 0.0;
return lambda * exp(-lambda * x);
}
// 随机数生成(均匀分布)
inline double jtbg_rand_unif(double a, double b)
{
return a + (b - a) * (rand() / (RAND_MAX + 1.0));
}
// 随机数生成(正态分布,Box-Muller)
inline double jtbg_rand_norm(double mu, double sigma)
{
static bool hasSpare = false;
static double spare;
if (hasSpare)
{
hasSpare = false;
return mu + sigma * spare;
}
double u, v, s;
do
{
u = (rand() / (RAND_MAX + 1.0)) * 2.0 - 1.0;
v = (rand() / (RAND_MAX + 1.0)) * 2.0 - 1.0;
s = u*u + v*v;
} while (s >= 1.0 || s == 0.0);
s = sqrt(-2.0 * log(s) / s);
spare = v * s;
hasSpare = true;
return mu + sigma * u * s;
}
//===================================== 插值函数 =====================================
// 线性插值
inline double jtbg_lerp(double a, double b, double t)
{
return a + (b - a) * t;
}
// 双线性插值
inline double jtbg_bilerp(double q11, double q12, double q21, double q22,
double x, double y)
{
double r1 = jtbg_lerp(q11, q21, x);
double r2 = jtbg_lerp(q12, q22, x);
return jtbg_lerp(r1, r2, y);
}
// 三次插值
inline double jtbg_cerp(double a, double b, double c, double d, double t)
{
double t2 = t * t;
double t3 = t2 * t;
double a0 = d - c - a + b;
double a1 = a - b - a0;
double a2 = c - a;
double a3 = b;
return a0*t3 + a1*t2 + a2*t + a3;
}
//===================================== 信号处理 =====================================
// 离散傅里叶变换(DFT)
inline void jtbg_dft(Complex in[], Complex out[], int n)
{
for (int k = 0; k < n; k++)
{
Complex sum(0, 0);
for (int t = 0; t < n; t++)
{
double angle = -2 * PI * k * t / n;
Complex w(cos(angle), sin(angle));
sum = jtbg_cadd(sum, jtbg_cmul(in[t], w));
}
out[k] = sum;
}
}
// 快速傅里叶变换(FFT,递归版)
inline void jtbg_fft(Complex in[], Complex out[], int n, bool inverse = false)
{
if (n == 1)
{
out[0] = in[0];
return;
}
Complex* even = new Complex[n/2];
Complex* odd = new Complex[n/2];
Complex* even_fft = new Complex[n/2];
Complex* odd_fft = new Complex[n/2];
for (int i = 0; i < n/2; i++)
{
even[i] = in[2*i];
odd[i] = in[2*i + 1];
}
jtbg_fft(even, even_fft, n/2, inverse);
jtbg_fft(odd, odd_fft, n/2, inverse);
double angle = (inverse ? 2 : -2) * PI / n;
Complex w_n(cos(angle), sin(angle));
Complex w(1, 0);
for (int k = 0; k < n/2; k++)
{
Complex temp = jtbg_cmul(w, odd_fft[k]);
out[k] = jtbg_cadd(even_fft[k], temp);
out[k + n/2] = jtbg_csub(even_fft[k], temp);
if (inverse)
{
out[k].re /= 2;
out[k].im /= 2;
out[k + n/2].re /= 2;
out[k + n/2].im /= 2;
}
w = jtbg_cmul(w, w_n);
}
delete[] even;
delete[] odd;
delete[] even_fft;
delete[] odd_fft;
}
// 卷积
inline void jtbg_conv(double a[], int na, double b[], int nb, double c[])
{
int nc = na + nb - 1;
for (int i = 0; i < nc; i++)
{
c[i] = 0.0;
for (int j = max(0, i-nb+1); j <= min(i, na-1); j++)
{
c[i] += a[j] * b[i-j];
}
}
}
//===================================== 优化算法 =====================================
// 梯度下降
inline double jtbg_grad_desc(double (*f)(double), double x0,
double lr = 0.01, int iter = 1000)
{
double x = x0;
double h = 1e-5;
for (int i = 0; i < iter; i++)
{
double grad = (f(x+h) - f(x-h)) / (2*h);
x = x - lr * grad;
}
return x;
}
// 黄金分割搜索(求最小值)
inline double jtbg_golden_search(double (*f)(double),
double a, double b,
double tol = 1e-7)
{
const double phi = (sqrt(5) - 1) / 2;
double c = b - phi * (b - a);
double d = a + phi * (b - a);
while (fabs(c - d) > tol)
{
if (f(c) < f(d))
{
b = d;
d = c;
c = b - phi * (b - a);
}
else
{
a = c;
c = d;
d = a + phi * (b - a);
}
}
return (a + b) / 2;
}
//===================================== 进制转换 =====================================
// 十进制转二进制字符串
inline string jtbg_dec2bin(long long n)
{
if (n == 0) return "0";
string result;
bool neg = false;
if (n < 0)
{
neg = true;
n = -n;
}
while (n > 0)
{
result = char('0' + (n & 1)) + result;
n >>= 1;
}
if (neg) result = "-" + result;
return result;
}
// 二进制字符串转十进制
inline long long jtbg_bin2dec(string s)
{
long long result = 0;
bool neg = false;
if (s[0] == '-')
{
neg = true;
s = s.substr(1);
}
for (char c : s)
{
result <<= 1;
if (c == '1') result |= 1;
else if (c != '0') return 0;
}
return neg ? -result : result;
}
// 十进制转十六进制
inline string jtbg_dec2hex(long long n)
{
if (n == 0) return "0";
string result;
bool neg = false;
const char hex_chars[] = "0123456789ABCDEF";
if (n < 0)
{
neg = true;
n = -n;
}
while (n > 0)
{
result = hex_chars[n & 0xF] + result;
n >>= 4;
}
if (neg) result = "-" + result;
return result;
}
// 十六进制转十进制
inline long long jtbg_hex2dec(string s)
{
long long result = 0;
bool neg = false;
if (s[0] == '-')
{
neg = true;
s = s.substr(1);
}
for (char c : s)
{
result <<= 4;
if (c >= '0' && c <= '9')
result |= (c - '0');
else if (c >= 'A' && c <= 'F')
result |= (c - 'A' + 10);
else if (c >= 'a' && c <= 'f')
result |= (c - 'a' + 10);
else
return 0;
}
return neg ? -result : result;
}
//===================================== 位运算扩展 =====================================
// 位反转(32位)
inline unsigned int jtbg_bitrev32(unsigned int x)
{
x = ((x >> 1) & 0x55555555) | ((x & 0x55555555) << 1);
x = ((x >> 2) & 0x33333333) | ((x & 0x33333333) << 2);
x = ((x >> 4) & 0x0F0F0F0F) | ((x & 0x0F0F0F0F) << 4);
x = ((x >> 8) & 0x00FF00FF) | ((x & 0x00FF00FF) << 8);
x = (x >> 16) | (x << 16);
return x;
}
// 计算汉明重量(1的个数)
inline int jtbg_popcount(unsigned int x)
{
x = x - ((x >> 1) & 0x55555555);
x = (x & 0x33333333) + ((x >> 2) & 0x33333333);
x = (x + (x >> 4)) & 0x0F0F0F0F;
x = x + (x >> 8);
x = x + (x >> 16);
return x & 0x3F;
}
// 下一个2的幂
inline unsigned int jtbg_nextpow2(unsigned int x)
{
x--;
x |= x >> 1;
x |= x >> 2;
x |= x >> 4;
x |= x >> 8;
x |= x >> 16;
return x + 1;
}
#ifndef NO_JTBG_MATH_SHORT
#define JTBG_MAT2_MUL(a,b,res) jtbg_mat2_mul(a,b,res)
#define JTBG_MAT2_DET(m) jtbg_mat2_det(m)
#define JTBG_MAT2_INV(m,inv) jtbg_mat2_inv(m,inv)
#define JTBG_VEC_DOT(v1,v2,n) jtbg_vec_dot(v1,v2,n)
#define JTBG_VEC_LEN(v,n) jtbg_vec_len(v,n)
#define JTBG_CADD(a,b) jtbg_cadd(a,b)
#define JTBG_CMUL(a,b) jtbg_cmul(a,b)
#define JTBG_CABS(c) jtbg_cabs(c)
#define JTBG_BINOM(n,k,p) jtbg_binom_pmf(n,k,p)
#define JTBG_NORM_PDF(x,mu,sigma) jtbg_norm_pdf(x,mu,sigma)
#define JTBG_LERP(a,b,t) jtbg_lerp(a,b,t)
#define JTBG_RAND_UNIF(a,b) jtbg_rand_unif(a,b)
#define JTBG_RAND_NORM(mu,sigma) jtbg_rand_norm(mu,sigma)
#define JTBG_DEC2BIN(n) jtbg_dec2bin(n)
#define JTBG_BIN2DEC(s) jtbg_bin2dec(s)
#define JTBG_DEC2HEX(n) jtbg_dec2hex(n)
#define JTBG_HEX2DEC(s) jtbg_hex2dec(s)
#define JTBG_POPCOUNT(x) jtbg_popcount(x)
#define JTBG_NEXTPOW2(x) jtbg_nextpow2(x)
#define JTBG_SIN_D(deg) jtbg_sind(deg)
#define JTBG_COS_D(deg) jtbg_cosd(deg)
#define JTBG_TAN_D(deg) jtbg_tand(deg)
#define JTBG_LN(x) jtbg_ln(x)
#define JTBG_NEWLOG(x, b) jtbg_logb(x, b)
#define JTBG_PHI(n) jtbg_phi(n)
#define JTBG_CRT(r, m) jtbg_crt(r, m)
#define JTBG_COMB(n, k) jtbg_comb(n, k)
#define JTBG_PERM(n, k) jtbg_perm(n, k)
#define JTBG_MEAN(v) jtbg_mean(v)
#define JTBG_MEDIAN(v) jtbg_median(v)
#define JTBG_STD(v) jtbg_std(v)
#define JTBG_DOT(x1,y1,x2,y2) jtbg_dot(x1,y1,x2,y2)
#define JTBG_CROSS(x1,y1,x2,y2) jtbg_cross(x1,y1,x2,y2)
#define ABS(x) jtbg_abs(x)
#define SIGN(x) jtbg_sign(x)
#define MAX(a,b) jtbg_max((a),(b))
#define MIN(a,b) jtbg_min((a),(b))
#define CLAMP(x,min,max) jtbg_clamp((x),(min),(max))
#define LERP(a,b,t) jtbg_lerp((a),(b),(t))
#define SQ(x) jtbg_square(x)
#define CUBE(x) jtbg_cube(x)
#define GCD(a,b) jtbg_gcd((a),(b))
#define LCM(a,b) jtbg_lcm((a),(b))
#define IS_PRIME(x) isPrime(x)
#define IS_PALINDROME(x) jtbg_isPalindrome(x)
#define FIB(n) jtbg_fibonacci(n)
#endif
#ifdef USE_JTBG_MATH
#define abs(x) jtbg_abs(x)
#define max(a,b) jtbg_max((a),(b))
#define min(a,b) jtbg_min((a),(b))
#define sqrt(a,b) getSqrtNt((a),(b))
#define __gcd(a,b) jtbg_gcd((a),(b))
#define __lcm(a,b) jtbg_lcm((a),(b))
#endif
#ifdef USE_INT_BY_LONG_LONG
#define int long long
#define int_main signed
#endif
#endif
#ifdef JTBG_SHORT
#define SYSTEM_COMMOND_RUN_OK 0
#define SYSTEM_COMMOND_RUN_BAD 1
#define __JTBG_RETURN_WITH_NO_JTBG_MESSAGES(n) exit(n)
#define JTBG_QUIK_ENDL '\n'
#define jtdl JTBG_QUIK_ENDL
#define syst system("cls")
#define sys(x) system(x)
#define noy_pause() system("pause > nul")
#define pause() system("pause")
#define to_int(x) atoi(x.c_str()) // 转换为int类型
#define to_long(x) stol(x) // 转换为long类型
#define to_double(x) stod(x) // 转换为double类型
#define jstoi(x) to_int(x)
#define jstol(x) to_long(x)
//#define tostring(x) jtbg_to_string((x))
#define jstod(x) to_double(x)
#define sleep(ms) Sleep(ms) // 延迟指定毫秒数
#define sleep_s(s) Sleep(s*1000)
#define get_time() time(0) // 获取当前时间戳(秒级)
#define getms() GetTickCount()
#define shuta() system("shutdown -a")
#define shuts() system("shutdown -s -t 0")
#define shutr() system("shutdown -g -t 0")
#define about() jtbg_h_about()
#endif
#ifdef JTBG_LOG
struct logger
{
Save rep;
enum error_type
{
error=0,
info=1,
warn=2,
debug=3,
};
void reset_logger(string path)
{
rep.setpt(path);
rep.save_nol();
rep.save_o<<"["<<Gettime(yer)<<"/"<<Gettime(mon)<<"/"<<Gettime(dat)<<"-"<<Gettime(hor)<<":"<<Gettime(mit)<<":"<<Gettime(sec)<<"]"<<endl;
return ;
}
void report(string s,error_type tp)
{
rep.save_o<<"["<<Gettime(hor)<<":"<<Gettime(mit)<<":"<<Gettime(sec)<<"("<<Gettime(mst)%1000<<")] ";
if(tp==0) rep.save_o<<"{type=error} ";
else if(tp==1) rep.save_o<<"{type=info} ";
else if(tp==2) rep.save_o<<"{type=warn} ";
else if(tp==3) rep.save_o<<"{type=debug} ";
else rep.save_o<<"{type=unknow} ";
rep.save_o<<s<<endl;
flush(rep.save_o);
return ;
}
void stop()
{
rep.save_stop();
return ;
}
};
void thred(logger p,string s)
{
p.report(s,logger::error);
return ;
}
struct new_logger
{
private:
string logsk()
{
stringstream l;
l<<"["<<Gettime(mit)<<":"<<Gettime(sec)<<":"<<Gettime(mst)<<"] ";
return l.str();
}
public:
#define LOG_NORMOL 0x1a
#define LOG_NOTIME 0x2a
#define LOG_NOTIMEANDENDL 0x3a
void logs(const string& s,int mod=LOG_NORMOL,string path="none")
{
ofstream ans;
stringstream l;
if(path=="none") l<<"logs\\["<<Gettime(yer)<<Gettime(mon)<<Gettime(dat)<<"] "<<Gettime(hor)<<"h-log.txt";
else l<<path;
if(!Isfileext(l.str()))
{
ans.open(l.str().c_str());
ans.close();
}
ans.open(l.str().c_str(),ios::out|ios::app);
if(mod==LOG_NORMOL) ans<<logsk()<<s<<endl;
else if(mod==LOG_NOTIME) ans<<s<<endl;
else if(mod==LOG_NOTIMEANDENDL) ans<<s;
ans.close();
return ;
}
};
#endif
#ifdef JTBG_LUHN
string prepluhn(const string& input)
{
string result;
for(int i=0;i<int(input.size());i++)
{
char c=input[i];
if (isdigit(c))
{
result+=c;
}
}
return result;
}
int toluhn(const string& num)
{
string number=prepluhn(num);
int sum = 0;
bool doubleFlag = false;
string reversed = number;
reverse(reversed.begin(), reversed.end());
for(char c : reversed)
{
if (!isdigit(c))
{
return -1;
}
int digit = c - '0';
if (doubleFlag)
{
digit *= 2;
if (digit > 9)
{
digit -= 9;
}
}
sum += digit;
doubleFlag = !doubleFlag;
}
return (10 - (sum % 10)) % 10;
}
bool visluhn(const string& fb)
{
string fullNumber=prepluhn(fb);
if (fullNumber.empty()) return false;
string mainPart = fullNumber.substr(0, fullNumber.size() - 1);
char checkDigitChar = fullNumber.back();
if (!isdigit(checkDigitChar)) return false;
int checkDigit = checkDigitChar - '0';
int calculated = toluhn(mainPart);
return (calculated != -1) && (calculated == checkDigit);
}
#endif
#ifdef JTBG_WEB
bool Iswebok()
{
// INTERNET_CONNECTION_MODEM: 调制解调器
// INTERNET_CONNECTION_LAN: 局域网
// INTERNET_CONNECTION_WWAN: 移动网络(4G/5G)
DWORD flags = 0;
bool result = InternetGetConnectedState(&flags, 0);
if (result)
{
if (flags & INTERNET_CONNECTION_LAN) return 1;//局域网
else if (flags & INTERNET_CONNECTION_MODEM) return 2;//调制解调器
else return 3;//其他
}
else return 0;
}
#endif
#ifdef JTBG_INI
#define INI_MOD_DIF 0x31
#define INI_GOOD 0x32
#define INI_READ_BAD 0x33
#define INI_NOT_FOUND 0x34
#define INI_WRITE_BAD 0x35
#define INI_WRITE_OK 0x36
#define INI_READ_OK 0x37
#define INI_UNKOWN_ERROR 0x38
#define INI_NPOS "ini_log_or_othor_sring_get_error"
#define INI_NO_THIS_TITLE "ini_lost_this_title_error"
#define INI_NO_THIS_KEY "ini_lost_this_key_error"
#define INI_INT_NPOS 0x39
struct ifinistream
{
private:
stringstream log;
string path="program.ini";
map<string,map<string,string> > ans;
public:
int set_ini_reader_path(const string& new_path)
{
if(new_path.empty()||new_path.substr(int(new_path.size())-4,4)!=".ini")
{
log<<"error[INI_MOD_DIF] in set_ini_reader_path("<<new_path<<");\n";
return INI_MOD_DIF;
}
else
{
path=new_path;
log<<"info[INI_GOOD]set_ini_reader_path(); maken path in"<<new_path<<" \n";
return INI_GOOD;
}
}
int read_ini()
{
ifstream fini;
fini.open(path,ios::in);
if(!fini.good())
{
fini.close();
log<<"error[INI_READ_BAD] unknow error make ini bad\n";
return INI_READ_BAD;
}
int line=0;
string now="system";
while(fini.good())
{
string l;
getline(fini,l);
line++;
if(!l.empty())
{
if(l[0]=='['&&l[int(l.size())-1]==']')
{
string title=l.substr(1,int(l.size())-2);
log<<"info[] take title(\'"<<title<<"\') in \'"<<l<<"\' \n";
//[title]
now=title;
ans[now]["self_ini_title_exc"]="1";
}
else if(l.substr(0,4)=="vol ")
{
size_t a1=l.find('\"',3);
size_t a2=l.find('\"',a1+1);
size_t b1=l.find('\"',a2+1);
size_t b2=l.find('\"',b1+1);
if(a1==string::npos||a2==string::npos||b1==string::npos||b2==string::npos)
{
log<<"error[] find npos in vol["<<l<<"]"<<endl;
}
else
{
string a=l.substr(a1+1,a2-a1-1);
string b=l.substr(b1+1,b2-b1-1);
ans[now][a]=b;
log<<"info[] get vol[\'"<<a<<"\',\'"<<b<<"\'] \n";
}
}
else if(l=="title_finish")
{
log<<"info[] title back to system\n";
now="system";
}
else if(l=="end")
{
log<<"info[] ini vol_self end\n";
return INI_READ_OK;
}
else
{
log<<"error[] unkown vol[\'"<<l<<"\'] please check your ini\n";
}
}
else log<<"warn[] line "<<line<<" empty\n";
}
if(fini.eof()) return INI_READ_OK;
else return INI_UNKOWN_ERROR;
}
string ini_get_log()
{
if(!log.str().empty()) return log.str();
else return INI_NPOS;
}
string ini_get_vol(const string& title,const string& key_name)
{
if(ans.count(title)==0) return INI_NO_THIS_TITLE;
else if(ans[title].count(key_name)==0) return INI_NO_THIS_KEY;
else return ans[title][key_name];
return INI_NPOS;
}
};
struct ofinistream
{
private:
stringstream log;
string path="program.ini";
map<string,map<string,string> > ans;
string now_title="system";
int read_for_write_with_mod_added()
{
ifstream fini;
fini.open(path,ios::in);
if(!fini.good())
{
fini.close();
log<<"error[INI_READ_BAD] unknow error make ini bad\n";
return INI_READ_BAD;
}
int line=0;
string now="system";
while(fini.good())
{
string l;
getline(fini,l);
line++;
if(!l.empty())
{
if(l[0]=='['&&l[int(l.size())-1]==']')
{
string title=l.substr(1,int(l.size())-2);
log<<"info[] take title(\'"<<title<<"\') in \'"<<l<<"\' \n";
//[title]
now=title;
ans[now]["self_ini_title_exc"]="1";
}
else if(l.substr(0,4)=="vol ")
{
size_t a1=l.find('\"',3);
size_t a2=l.find('\"',a1+1);
size_t b1=l.find('\"',a2+1);
size_t b2=l.find('\"',b1+1);
if(a1==string::npos||a2==string::npos||b1==string::npos||b2==string::npos)
{
log<<"error[] find npos in vol["<<l<<"]"<<endl;
}
else
{
string a=l.substr(a1+1,a2-a1-1);
string b=l.substr(b1+1,b2-b1-1);
ans[now][a]=b;
log<<"info[] get vol[\'"<<a<<"\',\'"<<b<<"\'] \n";
}
}
else if(l=="title_finish")
{
log<<"info[] title back to system\n";
now="system";
}
else if(l=="end")
{
log<<"info[] ini vol_self end\n";
}
else
{
log<<"error[] unkown vol[\'"<<l<<"\'] please check your ini\n";
}
}
else log<<"warn[] line "<<line<<" empty\n";
}
if(fini.eof()) return INI_READ_OK;
else return INI_UNKOWN_ERROR;
}
int rewrite_ini_volum_with_what_mod()
{
ofstream fini;
fini.open(path);
if(!fini.good()) return INI_WRITE_BAD;
for(map<string,map<string,string> >::iterator it=ans.begin();it!=ans.end();++it)
{
fini<<"["<<it->first<<"]\n";
for(map<string,string>::iterator iter=it->second.begin();iter!=it->second.end();++iter)
{
fini<<"vol \""<<iter->first<<"\" = \""<<iter->second<<"\"\n";
}
fini<<"title_finish\n\n";
}
fini<<"\nend\n";
fini.close();
return INI_WRITE_OK;
}
public:
int ini_reset()
{
return read_for_write_with_mod_added();
}
int set_ini_WRITER_path(const string& new_path)
{
if(new_path.empty()||new_path.substr(int(new_path.size())-4,4)!=".ini")
{
log<<"error[INI_MOD_DIF] in set_ini_reader_path("<<new_path<<");\n";
return INI_MOD_DIF;
}
else
{
path=new_path;
log<<"info[INI_GOOD]set_ini_reader_path(); maken path in"<<new_path<<" \n";
return INI_GOOD;
}
}
int ini_write()
{
return rewrite_ini_volum_with_what_mod();
}
string ini_get_log()
{
if(!log.str().empty()) return log.str();
else return INI_NPOS;
}
int ini_set_title(const string& title)
{
if(!title.empty()) now_title=title;
else return INI_INT_NPOS;
return INI_GOOD;
}
int ini_add_vol(const string& key,const string& vol)
{
if(key.empty()||vol.empty())
{
log<<"error[INI_NPOS] key|vol is empty\n";
return INI_INT_NPOS;
}
else ans[now_title][key]=vol;
log<<"info[] added new volum["<<key<<":"<<vol<<"] \n";
return INI_GOOD;
}
};
#endif
#ifdef JTBG_CC
#define CC_SETUP_BAD 0x21
#define CC_SETUP_OK 0x22
#define CC_UNKNOW_ERROR 0x23
#define CC_CHECK_ERROR 0x14
#define CC_CHECK_OK 0x15
#define CC_CHECK_BAD 0x16
class cc_right_check
{
private:
int cc109(const string& p)
{
ifinistream stdcc;
stdcc.set_ini_reader_path(p);
if(stdcc.read_ini()!=INI_READ_OK) return CC_CHECK_ERROR;
string per= stdcc.ini_get_vol("cc","person");
string per_key= stdcc.ini_get_vol("key","person");
string cc= stdcc.ini_get_vol("cc","cc_code");
string cc_key= stdcc.ini_get_vol("key","cc_code");
string end_time= stdcc.ini_get_vol("cc","end_time");
string end_time_key= stdcc.ini_get_vol("key","end_time");
string ccluhn=stdcc.ini_get_vol("cc","luhn");
if(MD5::hash(per)!=per_key) return CC_CHECK_BAD;
else if(MD5::hash(cc)!=cc_key) return CC_CHECK_BAD;
else if(MD5::hash(end_time)!=end_time_key) return CC_CHECK_BAD;
if(int(end_time.size())==8)
{
if((visluhn(ccluhn)&& toluhn(cc) == to_int(jtbg_to_string<char>(ccluhn[int(ccluhn.size())-1]))) && ((Gettime(TimeType::yer) <= to_int(end_time.substr(0,4))) && (Gettime(TimeType::mon) <= to_int(end_time.substr(4,2))) && (Gettime(TimeType::dat) <= to_int(end_time.substr(6,2))))) return CC_SETUP_OK;
}
else return CC_CHECK_BAD;
return CC_CHECK_ERROR;
}
int cc110(const string& p)
{
ifinistream stdcc;
stdcc.set_ini_reader_path(p);
if(stdcc.read_ini()!=INI_READ_OK) return CC_CHECK_ERROR;
string per_j= stdcc.ini_get_vol("cc","person");
string per_key_j= stdcc.ini_get_vol("key","person");
string cc_j= stdcc.ini_get_vol("cc","cc_code");
string cc_key_j= stdcc.ini_get_vol("key","cc_code");
string end_time_j= stdcc.ini_get_vol("cc","end_time");
string end_time_key_j= stdcc.ini_get_vol("key","end_time");
string ccluhn_j=stdcc.ini_get_vol("cc","luhn");
string key=stdcc.ini_get_vol("password","xor");
string per=xorpass(per_j,key);
string per_key=xorpass(per_key_j,key);
string cc=xorpass(cc_j,key);
string cc_key=xorpass(cc_key_j,key);
string end_time=xorpass(end_time_j,key);
string end_time_key=xorpass(end_time_key_j,key);
string ccluhn=xorpass(ccluhn_j,key);
if(MD5::hash(per)!=per_key) return CC_CHECK_BAD;
else if(MD5::hash(cc)!=cc_key) return CC_CHECK_BAD;
else if(MD5::hash(end_time)!=end_time_key) return CC_CHECK_BAD;
if(int(end_time.size())==8)
{
if((visluhn(ccluhn)&&toluhn(cc)==to_int(ccluhn)) && ((Gettime(TimeType::yer) <= to_int(end_time.substr(0,4))) && (Gettime(TimeType::mon) <= to_int(end_time.substr(4,2))) && (Gettime(TimeType::dat) <= to_int(end_time.substr(6,2))))) return CC_SETUP_OK;
}
else return CC_CHECK_BAD;
return CC_CHECK_ERROR;
}
int cc111(const string& p)
{
ifinistream stdcc;
stdcc.set_ini_reader_path(p);
if(stdcc.read_ini()!=INI_READ_OK) return CC_CHECK_ERROR;
string per= stdcc.ini_get_vol("许可证","发布人");
string per_key= stdcc.ini_get_vol("验证","发布人");
string cc= stdcc.ini_get_vol("许可证","许可证码");
string cc_key= stdcc.ini_get_vol("验证","许可证码");
string end_time= stdcc.ini_get_vol("许可证","截止时间");
string end_time_key= stdcc.ini_get_vol("验证","截止时间");
string ccluhn=stdcc.ini_get_vol("许可证","luhn验证");
if(MD5::hash(per)!=per_key) return CC_CHECK_BAD;
else if(MD5::hash(cc)!=cc_key) return CC_CHECK_BAD;
else if(MD5::hash(end_time)!=end_time_key) return CC_CHECK_BAD;
if(int(end_time.size())==8)
{
if((visluhn(ccluhn)&&toluhn(cc)==to_int(ccluhn)) && ((Gettime(TimeType::yer) <= to_int(end_time.substr(0,4))) && (Gettime(TimeType::mon) <= to_int(end_time.substr(4,2))) && (Gettime(TimeType::dat) <= to_int(end_time.substr(6,2))))) return CC_SETUP_OK;
}
else return CC_CHECK_BAD;
return CC_CHECK_ERROR;
}
public:
int cc_check(const string& path,int s)
{
if(s==109) return cc109(path);
else if(s==110) return cc110(path);
else if(s==111) return cc111(path);
else return CC_CHECK_ERROR;
}
};
struct cc_right
{
private:
string cc_right_path;
string cc_right_setup;
int cc_right_type;
public:
int cc_right_reset()
{
ifinistream setup;
setup.set_ini_reader_path("ccright_setup");
if(setup.read_ini()!=INI_READ_OK) return CC_SETUP_BAD;
string p1=setup.ini_get_vol("path","cc_right_path");
if(p1.substr(int(p1.size())-3,3)==".cc") cc_right_path=p1;
else return CC_SETUP_BAD;
cc_right_type=to_int(setup.ini_get_vol("type","cc_type"));
return CC_SETUP_OK;
}
int cc_check()
{
cc_right_check hi;
return hi.cc_check(cc_right_path,cc_right_type);
}
};
#define JTBG_GPL \
"/*" "\n" \
"******************************************************************************" "\n" \
"* *" "\n" \
"* Copyright (c) 2024-2025 焦糖饼干(JTBG)开发组. All rights reserved. *" "\n" \
"* *" "\n" \
"* This program is free software: you can redistribute it and/or modify *" "\n" \
"* it under the terms of the GNU General Public License as published by *" "\n" \
"* the Free Software Foundation, either version 3 of the License, or *" "\n" \
"* (at your option) any later version. *" "\n" \
"* *" "\n" \
"* This program is distributed in the hope that it will be useful, *" "\n" \
"* but WITHOUT ANY WARRANTY; without even the implied warranty of *" "\n" \
"* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *" "\n" \
"* GNU General Public License for more details. *" "\n" \
"* *" "\n" \
"* You should have received a copy of the GNU General Public License *" "\n" \
"* along with this program. If not, see <https://www.gnu.org/licenses/>. *" "\n" \
"* *" "\n" \
"******************************************************************************/" "\n" \
"*/" "\n"
//GNUS
enum class Gnuver
{
V2,
V3,
LGPL_V3,
CHINESEGNU
};
string GetGnulicens(Gnuver version = Gnuver::V3)
{
switch (version)
{
case Gnuver::CHINESEGNU:
return R"(GNU通用公共许可协议
第二版,1991年6月
版权所有(C)1989, 1991 自由软件基金会
51 Franklin Street, Fifth Floor, Boston, MA 02110‐1301, USA
任何人皆可复制和发布本协议的完整副本,但不得修改
【译者声明】
This is an unofficial translation of the GNU General Public License into Chinese. It was not published by the Free Software Foundation, and does not legally state the distribution terms for software that uses the GNU GPL--only the original English text of the GNU GPL does that. However, we hope that this translation will help Chinese speakers understand the GNU GPL better.
这是GNU通用公共许可协议的一份非官方中文翻译,并非自由软件基金会所发表,不适用于使用GNU通用公共许可协议发布的软件的法律声明——只有GNU通用公共许可协议英文原版才具有法律效力。不过我们希望本翻译能够帮助中文读者更好地理解GNU通用公共许可协议。
You may publish this translation, modified or unmodified, only under the terms at https://www.gnu.org/licenses/translations.html.
【引言】
就多数软件而言,许可协议被设计用于剥夺你分享和修改软件的自由。相反,GNU通用公共许可协议力图保障你分享和修改自由软件的权利——确保自由软件对其用户来说是自由的。本GNU通用公共许可协议用于自由软件基金会的大多数软件(自由软件基金会的有些软件受GNU宽松通用公共许可协议保护),以及那些作者声明使用此协议的软件。你也可以将本协议用于你的程序。
所谓自由软件,强调自由,而非免费。本GNU通用公共许可协议设计用于确保你享有分发自由软件的自由(你可以为此服务收费),确保你可以在需要的时候获得这些软件的源码,确保你可以修改这些软件或者在新的自由软件中复用其中某些片段,并且确保你在这方面享有知情权。
为保障你的权益,我们需要作一些限定:禁止任何人否认你的上述权利,或者要求你放弃它们。当你分发或修改这些软件时,这种限定就变成你的义务。如果你分发这种程序的副本,无论收费还是免费,你必须给予与你同等的权利。你还要确保他们也能收到源码并了解他们的权利。
我们通过两步保障你的权益:其一,赋予软件著作权;其二,通过本协议使你可以合法地复制、分发和修改该软件。同时,为了保护每一位作者以及我们自己,我们向所有人指明如下一点:自由软件并不提供品质担保。如果软件被修改并继续传播,我们希望接收者知道获得的不是原版,后来引入的任何问题不应该影响原作者的声誉。
最后,自由软件还持续受到软件专利的威胁。我们希望避免再发布者以个人名义取得专利,即将程序据为己有。为防止此类情况发生,我们需要澄清:专利必须为保障每个人的自由使用而申请,否则不应该存在。
下文是关于复制、分发和修改的严谨描述和实施条件。
【关于复制、分发和修改的术语和条件】
〇、但凡版权持有人在他的程序或其他作品中声明该作品可在GNU通用公共许可协议约束下发布,本协议便对之适用。下文中所说的“程式”指任何程序或作品,而“程式的派生作品”指该程式或者版权法认定的派生作品,即全部或部分包含了该程式的作品,无论是原样包含或做了修改,乃至翻译成了其他语言(后文中“修改”涵盖翻译)。每个许可获得者称作“你”。
除复制、分发和修改外的行为超出了本协议的约束范围。执行程式的行为并不受限,程式的输出一般不在约束之内,除非其内容构成了本程式的派生作品(并非单纯地作为本程式的运行结果),判别取决于此程式的具体用途。
一、只要你做到为每一个副本醒目而恰当地发布版权与免责声明,原封不动地保留本协议及免责声明,并将本协议连同程式发予接收者,你可以通过任何媒介完整地复制和分发你收到的本程式的源码。
你可以就传输副本的具体行为收费,也可以选择提供品质担保以换取收入。
二、你可以修改你的程式副本的任意部分,以构成本程式的派生作品,并在满足上述条款及以下三点要求的前提下复制和分发该修改版:
a)你必须在你修改了的文件中醒目地声明你的修改及标注修改日期。
b)你必须使你分发或发布的作品,部分或全部包含本程式或其派生作品,允许第三方在本协议约束下使用,并不得就授权收费。
c)如果修改后的程序通常在运行时通过交互方式获取命令,你应该让它进入交互模式时显示简要的版权声明和免责声明(抑或者你的品质担保声明),以及告诉用户可以在本协议约束下再发布该程序并提供查阅本协议的途径。(例外:如果本程式有交互式执行却通常不显示任何声明,则对你的派生作品也不作此要求。)
上述要求对修改后的作品整体有效。如果该作品中某些可划定的部分并非派生自本程式,并可以被合理地看作是从中分离的独立作品,则当你将它们分开发布时,这种独立部分可以不受本协议约束。但是,在你将这些部分和你修改后的作品一起发布时,整个套件将受本协议约束,本协议对其他许可获得者的授权将延伸至整个作品,即套件的每一部分,不管是谁写的。
三、你可以在上述条款约束下以目标码或可执行文件的形式复制和分发本程式(或条款二所说的派生作品),不过你还要满足以下要求之一:
a)附上相应的源码。源码要求完整且机器可读,并在条款一、二的约束下通过常用的软件交换媒介分发。
b)附上至少三年有效的书面报价表以供第三方付费获取相应的源码。源码要求完整且机器可读,并在条款一、二的约束下通过常用的软件交换媒介分发,费用不得超过实际的分发成本。
c)附上你所收到的获取源码途径的信息。(该选择只适用于非商业分发,并且你只收到目标码或可执行文件以及满足b项要求的报价单的情况下。)
作品的源码指其可修改的首选形式。对可执行的作品而言,完整的源码指其包含的所有模块的源码、相关接口定义文档以及编译和安装所需脚本。然而,有一种例外情况,分发的源码不必包含那些通常会随会目标运行环境的操作系统的主要部件(编译器、内核等)发布的内容(以源码或二进制形式),除非这些部件自身是本程式的一部分。
如果以指定特定复制地点的形式分发可执行文件或目标码,则在同一地点提供对等源码复制途径也算一种源码分发手段,即便不强求第三方在复制目标码的同时复制源码。
四、在本协议授权之外,你不能复制、修改、再授权或分发本程式。任何用其他方法复制、修改、再授权或分发本程式的企图都是无效的,并使你从本协议获得的权利自动终止。然而从你那按本协议获得副本和许可的人,只要继续遵守协议,他们获得的许可并不会终止。
五、你没有在此协议上签字,也不是非要接受它不可。但是,此外没人可授权你去修改或分发本程式或其派生作品。此种行为为法律所不容,除非你接受本协议。因此,修改或发布本程式(或本程式的任何派生作品),就表明你已经接受本协议,即接受它的所有关于复制、分发和修改本程式及其派生的条款。
六、每当你再发布本程式(或本程式的任何派生作品),接收者自动从原始权利人获得本许可,以复制、分发和修改本程式。你不可以对他们获得的权利加以进一步的限制,你也没有要求第三方遵守该协议的义务。
七、如果因为法庭裁决或专利侵权指控或其他原因(不限于专利事宜),你面临与本协议条款冲突的条件(来自于法庭要求、协议或其他),那也不能成为你违背本协议的理由。倘若你不能在发布本程式时同时满足本协议和其他文件的要求,你就不能发布本程式。例如某专利授权不允许通过你直接或间接地获得本程式的人在不付授权费的前提下再发布本程式,唯一能同时满足它和本协议要求的做法便是不发布本程式。
如果本条款在特定环境下无效或无法实施,本条款的其他部分仍适用且本条款整体在其他环境下仍适用。
本条款的目的不在于诱使你去侵犯专利或其他产权要求,抑或者对之抗辩。本条款的根本目的是保护自由软件发布系统的完整性,而这要通过应用公共许可证实现。借助同样出自该系统的应用程序,许多人已经对在该系统上发布的软件作出了广泛而慷慨的贡献。作者/捐赠人有权确定是否通过其他渠道发布软件,被授权人不得干预其选择。
本条款旨在彻底阐明其余条款所带来的当然结果。
八、如果由于专利或受版权保护的接口的问题,分发或使用本程式在某些国家受到限制,原始版权持有人在其程式中使用本协议时可以附加明确的区域分发限制以排除那些国家,以支持此外地区的分发。在此情况下,这种限制条款将纳入协议之中。
九、自由软件联盟可能会不定时发布GNU通用公共许可协议的修订版或新版。新版将秉承当前版本的精神,但对问题或事项的描述细节不尽相同。
每一版都会有不同的版本号,如果本程式指定其使用的协议版本以及“任何更新的版本”,你可以选择遵守该版本或者任何更新的版本的条款。如果本程式没有指定协议版本,你可以选用自由软件联盟发布的任意版本。
十、如果你希望将本程式的某部分并入采取不同发布条件的自由软件中,应书面请求其作者的许可。对于自由软件联盟持有版权的软件,还应向联盟提出书面请求,我们有时会作例外处理。在处理这种事情时我们秉承两大宗旨:保持所有自由软件派生作品的自由属性,以及在整体上促进软件的共享和复用。
不提供品质担保
十一、本程式为免费授权,故在适用法律范围内不提供品质担保。除非另作书面声明,版权持有人及其他程式提供者“概”不提供任何显式或隐式的品质担保,品质担保所指包括而不仅限于有经济价值和适合特定用途的保证。全部风险,如程式的质量和性能问题,皆由你承担。若程式出现缺陷,你将承担所有必要的修复和更正服务的费用。
十二、除非适用法律或书面协议要求,任何版权持有人或本程式按本协议可能存在的第三方修改和再发布者,都不对你的损失负有责任,包括由于使用或者不能使用本程式造成的任何一般的、特殊的、偶发的或重大的损失(包括而不仅限于数据丢失、数据失真、你或第三方的后续损失、其他程序无法与本程序协同运作),即使那些人声称会对此负责。
【附录:如何将上述条款应用到你的新程序】
如果你开发了一个新程序,并希望它能最大限度地为公众所使用,最好的办法是将其作为自由软件,以使每个人都能在本协议约束下对其再发布及修改。
为此,请在附上以下声明。最安全的做法是将其附在每份源码的开头,以便于最有效地传递免责信息。同时,每个文件至少包含一处“版权”声明和一个协议全文的链接。
用一行来标明程序名及其作用。
版权所有(C)年份 姓名
本程序为自由软件,在自由软件联盟发布的GNU通用公共许可协议的约束下,你可以对其进行再发布及修改。协议版本为第二版或(随你)更新的版本。
我们希望发布的这款程序有用,但不保证,甚至不保证它有经济价值和适合特定用途。详情参见GNU通用公共许可协议。
你理当已收到一份GNU通用公共许可协议的副本,如果没有,请致信自由软件基金会:51 Franklin Street, Fifth Floor, Boston, MA 02110‐1301, USA
同时提供你的电子邮件地址或传统的邮件联系方式。
如果该程序是交互式的,让它在交互模式下输出类似下面的一段声明:
Gnomovision 第69版,版权所有(C)年份 姓名
Gnomovision从未提供品质担保,输入'show w'可查看详情。这是款自由软件,欢迎你在满足一定条件后对其再发布,输入'show c'可查看详情。
例子中的命令'show w'和'show c'应用于显示GNU通用公共许可协议相应的部分。当然你也可以因地制宜地选用别的命令乃至点击操作。
如果你之上存在雇主(你是码农)或校方,你还应当让他们在必要时为此程序签署放弃版权声明。以下有例子:
Yoyodyne公司,在此放弃对James Hacker所写的'Gnomovision'程序所享有的版权利益。
Ty Coon 签字,1989年4月1日
Ty Coon 副总裁
本GNU通用公共许可协议不允许把你的程序并入私有程序。如果你的程序是某种库,且你想允许它被私有程序链接而使之更有用,请使用GNU较宽松通用公共许可协议。
翻译:阮坤良<peterrk@pku.edu.cn>
校对:汪蔚<soulww@163.com>,和丹<hedan1229@163.com>
译注:
[1] distribute既译作分发也译作发布,前者强调转发,后者强调公布。
[2] license既译作协议也译作许可,前者强调此文本,后者强调内容。
[3] 首字母大写的Program译作程式,首字母小写的program译作程序。
参考:
[繁体中文译本] https://www.gnu.org/licenses/old-licenses/gpl-2.0-translations.html
)";
case Gnuver::V2:
return R"(GNU GENERAL PUBLIC LICENSE
Version 2, June 1991
Copyright (C) 1989, 1991 Free Software Foundation, Inc.
59 Temple Place - Suite 330, Boston, MA 02111-1307, USA
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This General Public License applies to most of the Free Software Foundation's software and to any other program whose authors commit to using it. (Some other Free Software Foundation software is covered by the GNU Library General Public License instead.) You can apply it to your programs, too.
When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs; and that you know you can do these things.
To protect your rights, we need to make restrictions that forbid anyone to deny you these rights or to ask you to surrender the rights. These restrictions translate to certain responsibilities for you if you distribute copies of the software, or if you modify it.
For example, if you distribute copies of such a program, whether gratis or for a fee, you must give the recipients all the rights that you have. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights.
We protect your rights with two steps: (1) copyright the software, and (2) offer you this license which gives you legal permission to copy, distribute and/or modify the software.
Also, for each author's protection and ours, we want to make certain that everyone understands that there is no warranty for this free software. If the software is modified by someone else and passed on, we want its recipients to know that what they have is not the original, so that any problems introduced by others will not reflect on the original authors' reputations.
Finally, any free program is threatened constantly by software patents. We wish to avoid the danger that redistributors of a free program will individually obtain patent licenses, in effect making the program proprietary. To prevent this, we have made it clear that any patent must be licensed for everyone's free use or not licensed at all.
The precise terms and conditions for copying, distribution and modification follow.
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. This License applies to any program or other work which contains a notice placed by the copyright holder saying it may be distributed under the terms of this General Public License. The "Program", below, refers to any such program or work, and a "work based on the Program" means either the Program or any derivative work under copyright law: that is to say, a work containing the Program or a portion of it, either verbatim or with modifications and/or translated into another language. (Hereinafter, translation is included without limitation in the term "modification".) Each licensee is addressed as "you".
Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running the Program is not restricted, and the output from the Program is covered only if its contents constitute a work based on the Program (independent of having been made by running the Program). Whether that is true depends on what the Program does.
1. You may copy and distribute verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and give any other recipients of the Program a copy of this License along with the Program.
You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee.
2. You may modify your copy or copies of the Program or any portion of it, thus forming a work based on the Program, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions:
a) You must cause the modified files to carry prominent notices stating that you changed the files and the date of any change.
b) You must cause any work that you distribute or publish, that in whole or in part contains or is derived from the Program or any part thereof, to be licensed as a whole at no charge to all third parties under the terms of this License.
c) If the modified program normally reads commands interactively when run, you must cause it, when started running for such interactive use in the most ordinary way, to print or display an announcement including an appropriate copyright notice and a notice that there is no warranty (or else, saying that you provide a warranty) and that users may redistribute the program under these conditions, and telling the user how to view a copy of this License. (Exception: if the Program itself is interactive but does not normally print such an announcement, your work based on the Program is not required to print an announcement.)
These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Program, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Program, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it.
Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Program.
In addition, mere aggregation of another work not based on the Program with the Program (or with a work based on the Program) on a volume of a storage or distribution medium does not bring the other work under the scope of this License.
3. You may copy and distribute the Program (or a work based on it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you also do one of the following:
a) Accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or,
b) Accompany it with a written offer, valid for at least three years, to give any third party, for a charge no more than your cost of physically performing source distribution, a complete machine-readable copy of the corresponding source code, to be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or,
c) Accompany it with the information you received as to the offer to distribute corresponding source code. (This alternative is allowed only for noncommercial distribution and only if you received the program in object code or executable form with such an offer, in accord with Subsection b above.)
The source code for a work means the preferred form of the work for making modifications to it. For an executable work, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the executable. However, as a special exception, the source code distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable.
If distribution of executable or object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place counts as distribution of the source code, even though third parties are not compelled to copy the source along with the object code.
4. You may not copy, modify, sublicense, or distribute the Program except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense or distribute the Program is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance.
5. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Program or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Program (or any work based on the Program), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Program or works based on it.
6. Each time you redistribute the Program (or any work based on the Program), the recipient automatically receives a license from the original licensor to copy, distribute or modify the Program subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties to this License.
7. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Program at all. For example, if a patent license would not permit royalty-free redistribution of the Program by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Program.
If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply and the section as a whole is intended to apply in other circumstances.
It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system, which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice.
This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License.
8. If the distribution and/or use of the Program is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Program under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License.
9. The Free Software Foundation may publish revised and/or new versions of the General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns.
Each version is given a distinguishing version number. If the Program specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of this License, you may choose any version ever published by the Free Software Foundation.
10. If you wish to incorporate parts of the Program into other free programs whose distribution conditions are different, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally.
NO WARRANTY
11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively convey the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found.
one line to give the program's name and an idea of what it does.
Copyright (C) yyyy name of author
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
Also add information on how to contact you by electronic and paper mail.
If the program is interactive, make it output a short notice like this when it starts in an interactive mode:
Gnomovision version 69, Copyright (C) year name of author
Gnomovision comes with ABSOLUTELY NO WARRANTY; for details
type `show w'. This is free software, and you are welcome
to redistribute it under certain conditions; type `show c'
for details.
The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, the commands you use may be called something other than `show w' and `show c'; they could even be mouse-clicks or menu items--whatever suits your program.
You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the program, if necessary. Here is a sample; alter the names:
Yoyodyne, Inc., hereby disclaims all copyright
interest in the program `Gnomovision'
(which makes passes at compilers) written
by James Hacker.
signature of Ty Coon, 1 April 1989
Ty Coon, President of Vice
This General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License.
)";
case Gnuver::V3:
return R"(GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
<program> Copyright (C) <year> <name of author>
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<https://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
<https://www.gnu.org/licenses/why-not-lgpl.html>.
)";
case Gnuver::LGPL_V3:
return R"(GNU LESSER GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright ? 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed.
This version of the GNU Lesser General Public License incorporates the terms and conditions of version 3 of the GNU General Public License, supplemented by the additional permissions listed below.
0. Additional Definitions.
As used herein, “this License” refers to version 3 of the GNU Lesser General Public License, and the “GNU GPL” refers to version 3 of the GNU General Public License.
“The Library” refers to a covered work governed by this License, other than an Application or a Combined Work as defined below.
An “Application” is any work that makes use of an interface provided by the Library, but which is not otherwise based on the Library. Defining a subclass of a class defined by the Library is deemed a mode of using an interface provided by the Library.
A “Combined Work” is a work produced by combining or linking an Application with the Library. The particular version of the Library with which the Combined Work was made is also called the “Linked Version”.
The “Minimal Corresponding Source” for a Combined Work means the Corresponding Source for the Combined Work, excluding any source code for portions of the Combined Work that, considered in isolation, are based on the Application, and not on the Linked Version.
The “Corresponding Application Code” for a Combined Work means the object code and/or source code for the Application, including any data and utility programs needed for reproducing the Combined Work from the Application, but excluding the System Libraries of the Combined Work.
1. Exception to Section 3 of the GNU GPL.
You may convey a covered work under sections 3 and 4 of this License without being bound by section 3 of the GNU GPL.
2. Conveying Modified Versions.
If you modify a copy of the Library, and, in your modifications, a facility refers to a function or data to be supplied by an Application that uses the facility (other than as an argument passed when the facility is invoked), then you may convey a copy of the modified version:
a) under this License, provided that you make a good faith effort to ensure that, in the event an Application does not supply the function or data, the facility still operates, and performs whatever part of its purpose remains meaningful, or
b) under the GNU GPL, with none of the additional permissions of this License applicable to that copy.
3. Object Code Incorporating Material from Library Header Files.
The object code form of an Application may incorporate material from a header file that is part of the Library. You may convey such object code under terms of your choice, provided that, if the incorporated material is not limited to numerical parameters, data structure layouts and accessors, or small macros, inline functions and templates (ten or fewer lines in length), you do both of the following:
a) Give prominent notice with each copy of the object code that the Library is used in it and that the Library and its use are covered by this License.
b) Accompany the object code with a copy of the GNU GPL and this license document.
4. Combined Works.
You may convey a Combined Work under terms of your choice that, taken together, effectively do not restrict modification of the portions of the Library contained in the Combined Work and reverse engineering for debugging such modifications, if you also do each of the following:
a) Give prominent notice with each copy of the Combined Work that the Library is used in it and that the Library and its use are covered by this License.
b) Accompany the Combined Work with a copy of the GNU GPL and this license document.
c) For a Combined Work that displays copyright notices during execution, include the copyright notice for the Library among these notices, as well as a reference directing the user to the copies of the GNU GPL and this license document.
d) Do one of the following:
0) Convey the Minimal Corresponding Source under the terms of this License, and the Corresponding Application Code in a form suitable for, and under terms that permit, the user to recombine or relink the Application with a modified version of the Linked Version to produce a modified Combined Work, in the manner specified by section 6 of the GNU GPL for conveying Corresponding Source.
1) Use a suitable shared library mechanism for linking with the Library. A suitable mechanism is one that (a) uses at run time a copy of the Library already present on the user's computer system, and (b) will operate properly with a modified version of the Library that is interface-compatible with the Linked Version.
e) Provide Installation Information, but only if you would otherwise be required to provide such information under section 6 of the GNU GPL, and only to the extent that such information is necessary to install and execute a modified version of the Combined Work produced by recombining or relinking the Application with a modified version of the Linked Version. (If you use option 4d0, the Installation Information must accompany the Minimal Corresponding Source and Corresponding Application Code. If you use option 4d1, you must provide the Installation Information in the manner specified by section 6 of the GNU GPL for conveying Corresponding Source.)
5. Combined Libraries.
You may place library facilities that are a work based on the Library side by side in a single library together with other library facilities that are not Applications and are not covered by this License, and convey such a combined library under terms of your choice, if you do both of the following:
a) Accompany the combined library with a copy of the same work based on the Library, uncombined with any other library facilities, conveyed under the terms of this License.
b) Give prominent notice with the combined library that part of it is a work based on the Library, and explaining where to find the accompanying uncombined form of the same work.
6. Revised Versions of the GNU Lesser General Public License.
The Free Software Foundation may publish revised and/or new versions of the GNU Lesser General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns.
Each version is given a distinguishing version number. If the Library as you received it specifies that a certain numbered version of the GNU Lesser General Public License “or any later version” applies to it, you have the option of following the terms and conditions either of that published version or of any later version published by the Free Software Foundation. If the Library as you received it does not specify a version number of the GNU Lesser General Public License, you may choose any version of the GNU Lesser General Public License ever published by the Free Software Foundation.
If the Library as you received it specifies that a proxy can decide whether future versions of the GNU Lesser General Public License shall apply, that proxy's public statement of acceptance of any version is permanent authorization for you to choose that version for the Library.
)";
default:
return GetGnulicens();
}
}
#endif
#ifdef JTBG_BIGNUM
//struct Bigdouble
//{
//private:
//string integer_part; // 整数部分(无符号)
//string decimal_part; // 小数部分(无符号,固定k位)
//bool sign; // true:正数,false:负数
//int precision; // 小数点后保留的精度
//template <typename T>
//string tostring(T n)
//{
//ostringstream oss;
//oss << n;
//return oss.str();
//}
//// 移除字符串前导零(保留最后一个零)
//static string removeLeadingZeros(string s)
//{
//size_t start = s.find_first_not_of('0');
//if (start == string::npos) return "0";
//return s.substr(start);
//}
//
//// 移除字符串末尾零(保留最后一个零)
//static string removeTrailingZeros(string s)
//{
//size_t end = s.find_last_not_of('0');
//if (end == string::npos) return "0";
//return s.substr(0, end + 1);
//}
//
//// 无符号整数加法
//static string addInteger(const string& a, const string& b)
//{
//string res;
//int carry = 0, i = a.size() - 1, j = b.size() - 1;
//while (i >= 0 || j >= 0 || carry > 0)
//{
//int sum = carry;
//if (i >= 0) sum += (a[i--] - '0');
//if (j >= 0) sum += (b[j--] - '0');
//res.push_back((sum % 10) + '0');
//carry = sum / 10;
//}
//reverse(res.begin(), res.end());
//return removeLeadingZeros(res);
//}
//
//// 无符号整数减法(确保a >= b)
//static string subtractInteger(const string& a, const string& b)
//{
//if (a == b) return "0";
//string res;
//int borrow = 0, i = a.size() - 1, j = b.size() - 1;
//while (i >= 0)
//{
//int digitA = (a[i] - '0') - borrow;
//int digitB = (j >= 0) ? (b[j--] - '0') : 0;
//if (digitA < digitB)
//{
//digitA += 10;
//borrow = 1;
//}
//else
//{
//borrow = 0;
//}
//res.push_back((digitA - digitB) + '0');
//i--;
//}
//reverse(res.begin(), res.end());
//return removeLeadingZeros(res);
//}
//
//// 比较两个无符号整数大小(a >= b 返回true)
//static bool cmpInteger(const string& a, const string& b)
//{
//if (a.size() != b.size()) return a.size() > b.size();
//return a >= b;
//}
//
//// 无符号小数加法(固定精度,返回结果+进位)
//static pair<string, string> addDecimal(const string& a, const string& b, int k)
//{
//string a_pad = a;
//string b_pad = b;
//a_pad.resize(k, '0');
//b_pad.resize(k, '0');
//
//string res;
//int carry = 0, i = k - 1;
//while (i >= 0)
//{
//int sum = (a_pad[i] - '0') + (b_pad[i] - '0') + carry;
//res.push_back((sum % 10) + '0');
//carry = sum / 10;
//i--;
//}
//reverse(res.begin(), res.end());
//res = res.substr(0, k);
//return make_pair(res, tostring(carry));
//}
//
//// 无符号小数减法(确保a >= b,固定精度,返回结果+借位)
//static pair<string, string> subtractDecimal(const string& a, const string& b, int k)
//{
//string a_pad = a;
//string b_pad = b;
//a_pad.resize(k, '0');
//b_pad.resize(k, '0');
//
//string res;
//int borrow = 0, i = k - 1;
//while (i >= 0)
//{
//int digitA = (a_pad[i] - '0') - borrow;
//int digitB = (b_pad[i] - '0');
//if (digitA < digitB)
//{
//digitA += 10;
//borrow = 1;
//}
//else
//{
//borrow = 0;
//}
//res.push_back((digitA - digitB) + '0');
//i--;
//}
//reverse(res.begin(), res.end());
//res = res.substr(0, k);
//return make_pair(res, tostring(borrow));
//}
//
//// 标准化小数部分(仅截断,不四舍五入,确保精度严格匹配)
//void normalizeDecimal()
//{
//// 仅截断到指定精度,不做四舍五入(关键调整)
//if (int(decimal_part.size()) > precision)
//{
//decimal_part = decimal_part.substr(0, precision);
//}
//else
//{
//// 补齐0到指定精度
//decimal_part.resize(precision, '0');
//}
//// 整数部分标准化
//integer_part = removeLeadingZeros(integer_part);
//// 0的符号强制为正
//if (integer_part == "0" && decimal_part == string(precision, '0'))
//{
//sign = true;
//}
//}
//
//public:
//// 构造函数:空构造(0,默认精度6)
//Bigdouble()
//: integer_part("0"), decimal_part("0"), sign(true), precision(6)
//{
//normalizeDecimal();
//}
//
//// 构造函数:字符串+精度(关键调整:直接截断,不四舍五入)
//Bigdouble(string s, int k)
//: precision(k)
//{
//if (k < 0) throw invalid_argument("Precision must be non-negative");
//sign = true;
//
//if (s.empty())
//{
//integer_part = "0";
//decimal_part = "0";
//normalizeDecimal();
//return;
//}
//
//// 处理符号
//if (s[0] == '-')
//{
//sign = false;
//s = s.substr(1);
//}
//
//// 分割整数和小数部分
//size_t dot_pos = s.find('.');
//string int_part = (dot_pos == string::npos) ? s : s.substr(0, dot_pos);
//string dec_part = (dot_pos == string::npos) ? "" : s.substr(dot_pos + 1);
//
//// 处理整数部分
//if (int_part.empty())
//{
//integer_part = "0";
//}
//else
//{
//integer_part = removeLeadingZeros(int_part);
//}
//
//// 处理小数部分:直接截断到精度,不四舍五入
//decimal_part = dec_part.substr(0, k);
//// 标准化
//normalizeDecimal();
//}
//
//// 构造函数:数值类型+精度
//template <typename T>
//Bigdouble(T n, int k)
//: Bigdouble(tostring(n), k)
//{
//}
//
//// 取反
//Bigdouble operator-() const
//{
//if (integer_part == "0" && decimal_part == string(precision, '0'))
//{
//return Bigdouble("0", precision);
//}
//Bigdouble res = *this;
//res.sign = !res.sign;
//return res;
//}
//
//// 加法运算符
//Bigdouble operator+(const Bigdouble& other) const
//{
//if (this->precision != other.precision)
//{
//throw invalid_argument("Different precision not supported");
//}
//int k = this->precision;
//Bigdouble res;
//res.precision = k;
//
//if (this->sign == other.sign)
//{
//// 同号:整数+整数,小数+小数,处理进位
//pair<string, string> dec_add = addDecimal(this->decimal_part, other.decimal_part, k);
//string int_sum = addInteger(this->integer_part, other.integer_part);
//int_sum = addInteger(int_sum, dec_add.second);
//
//res.integer_part = int_sum;
//res.decimal_part = dec_add.first;
//res.sign = this->sign;
//}
//else
//{
//// 异号:转为减法(a + (-b) = a - b)
//Bigdouble b = -other;
//return *this - b;
//}
//
//res.normalizeDecimal();
//return res;
//}
//
//// 减法运算符
//Bigdouble operator-(const Bigdouble& other) const
//{
//if (this->precision != other.precision)
//{
//throw invalid_argument("Different precision not supported");
//}
//int k = this->precision;
//Bigdouble res;
//res.precision = k;
//
//if (this->sign != other.sign)
//{
//// 异号:转为加法(a - (-b) = a + b)
//Bigdouble b = -other;
//return *this + b;
//}
//
//// 同号:比较大小,确定结果符号
//bool this_bigger = false;
//// 先比较整数部分
//if (cmpInteger(this->integer_part, other.integer_part))
//{
//if (this->integer_part != other.integer_part)
//{
//this_bigger = true;
//}
//else
//{
//// 整数相等,比较小数部分
//string this_dec_pad = this->decimal_part;
//string other_dec_pad = other.decimal_part;
//this_dec_pad.resize(k, '0');
//other_dec_pad.resize(k, '0');
//this_bigger = (this_dec_pad >= other_dec_pad);
//}
//}
//
//if (this_bigger)
//{
//// this >= other:结果为正
//pair<string, string> dec_sub = subtractDecimal(this->decimal_part, other.decimal_part, k);
//string int_sub = subtractInteger(this->integer_part, dec_sub.second);
//int_sub = subtractInteger(int_sub, other.integer_part);
//
//res.integer_part = int_sub;
//res.decimal_part = dec_sub.first;
//res.sign = this->sign;
//}
//else
//{
//// this < other:结果为负
//pair<string, string> dec_sub = subtractDecimal(other.decimal_part, this->decimal_part, k);
//string int_sub = subtractInteger(other.integer_part, dec_sub.second);
//int_sub = subtractInteger(int_sub, this->integer_part);
//
//res.integer_part = int_sub;
//res.decimal_part = dec_sub.first;
//res.sign = !this->sign;
//}
//
//res.normalizeDecimal();
//return res;
//}
//
//// 赋值加法
//Bigdouble& operator+=(const Bigdouble& other)
//{
//*this = *this + other;
//return *this;
//}
//
//// 赋值减法
//Bigdouble& operator-=(const Bigdouble& other)
//{
//*this = *this - other;
//return *this;
//}
//
//// 等于运算符
//bool operator==(const Bigdouble& other) const
//{
//if (precision != other.precision) return false;
//return (sign == other.sign) &&
//(integer_part == other.integer_part) &&
//(decimal_part == other.decimal_part);
//}
//
//// 不等于运算符
//bool operator!=(const Bigdouble& other) const
//{
//return !(*this == other);
//}
//
//// 小于运算符
//bool operator<(const Bigdouble& other) const
//{
//if (precision != other.precision)
//{
//throw invalid_argument("Different precision not supported");
//}
//if (sign != other.sign)
//{
//return !sign; // 负数 < 正数
//}
//if (sign)
//{
//// 都是正数:先比整数,再比小数
//if (!cmpInteger(integer_part, other.integer_part)) return true;
//if (integer_part != other.integer_part) return false;
//string this_dec = decimal_part;
//string other_dec = other.decimal_part;
//this_dec.resize(precision, '0');
//other_dec.resize(precision, '0');
//return this_dec < other_dec;
//}
//else
//{
//// 都是负数:绝对值大的更小
//if (!cmpInteger(integer_part, other.integer_part)) return false;
//if (integer_part != other.integer_part) return true;
//string this_dec = decimal_part;
//string other_dec = other.decimal_part;
//this_dec.resize(precision, '0');
//other_dec.resize(precision, '0');
//return this_dec > other_dec;
//}
//}
//
//// 大于运算符
//bool operator>(const Bigdouble& other) const
//{
//return other < *this;
//}
//
//// 小于等于
//bool operator<=(const Bigdouble& other) const
//{
//return !(*this > other);
//}
//
//// 大于等于
//bool operator>=(const Bigdouble& other) const
//{
//return !(*this < other);
//}
//
//// 输出运算符
//friend ostream& operator<<(ostream& os, const Bigdouble& bd)
//{
//if (!bd.sign && !(bd.integer_part == "0" && bd.decimal_part == string(bd.precision, '0')))
//{
//os << '-';
//}
//os << bd.integer_part;
//if (bd.precision > 0)
//{
//os << '.' << bd.decimal_part;
//}
//return os;
//}
//
//// 输入运算符
//friend istream& operator>>(istream& is, Bigdouble& bd)
//{
//string s;
//is >> s;
//bd = Bigdouble(s, bd.precision);
//return is;
//}
//
//// 转为字符串
//string toString() const
//{
//string res;
//if (!sign && !(integer_part == "0" && decimal_part == string(precision, '0')))
//{
//res += '-';
//}
//res += integer_part;
//if (precision > 0)
//{
//res += '.' + decimal_part;
//}
//return res;
//}
//
//// 获取整数部分
//string getIntegerPart() const { return integer_part; }
//
//// 获取小数部分
//string getDecimalPart() const { return decimal_part; }
//
//// 获取符号
//bool getSign() const { return sign; }
//
//// 获取精度
//int getPrecision() const { return precision; }
//
//// 是否为0
//bool isZero() const
//{
//return integer_part == "0" && decimal_part == string(precision, '0');
//}
//
//// 是否为正数
//bool isPositive() const
//{
//return sign && !isZero();
//}
//
//// 是否为负数
//bool isNegative() const
//{
//return !sign && !isZero();
//}
//};
struct Bigint
{
private:
string num;
bool sign; // true表示正数,false表示负数
// 比较两个无符号数字符串的大小
static bool isGreaterOrEqual(const string& a, const string& b)
{
if (a.size() != b.size())
{
return a.size() > b.size();
}
return a >= b;
}
static string subtractNonNegative(string a, string b)
{
// 确保 a >= b
if (a == b) return "0";
// 如果 a < b,交换并标记负号
bool isNegative = false;
if (!isGreaterOrEqual(a, b))
{
swap(a, b);
isNegative = true;
}
string result;
int i = a.size() - 1, j = b.size() - 1;
int borrow = 0;
while (i >= 0)
{
int digitA = (a[i] - '0') - borrow;
int digitB = (j >= 0) ? (b[j--] - '0') : 0;
if (digitA < digitB)
{
digitA += 10;
borrow = 1;
}
else
{
borrow = 0;
}
result.push_back((digitA - digitB) + '0');
i--;
}
// 反转结果并移除前导零
reverse(result.begin(), result.end());
size_t start = result.find_first_not_of('0');
if (start == string::npos) return "0";
result = result.substr(start);
return isNegative ? ("-" + result) : result;
}
// 比较两个无符号数的大小
static bool cmp(const string& a, const string& b)
{
if (a.size() != b.size()) return a.size() > b.size();
return a >= b;
}
// 移除前导零
void removeLeadingZeros()
{
size_t start = num.find_first_not_of('0');
if (start == string::npos)
{
num = "0";
sign = true; // 0的符号为正
}
else
{
num = num.substr(start);
}
}
// 无符号加法
static string add(const string& a, const string& b)
{
string result;
int carry = 0;
int i = a.size() - 1;
int j = b.size() - 1;
while (i >= 0 || j >= 0 || carry > 0)
{
int sum = carry;
if (i >= 0)
{
sum += (a[i] - '0');
i--;
}
if (j >= 0)
{
sum += (b[j] - '0');
j--;
}
result.push_back((sum % 10) + '0');
carry = sum / 10;
}
reverse(result.begin(), result.end());
return result;
}
// 无符号乘法
static string mul(const string& a, const string& b)
{
if (a == "0" || b == "0") return "0";
int lenA = a.size(), lenB = b.size();
vector<int> res(lenA + lenB, 0);
for (int i = lenA - 1; i >= 0; --i)
{
for (int j = lenB - 1; j >= 0; --j)
{
int muls = (a[i] - '0') * (b[j] - '0');
int sum = muls + res[i + j + 1];
res[i + j + 1] = sum % 10;
res[i + j] += sum / 10;
}
}
string result;
int start = 0;
while (start < (int)res.size() && res[start] == 0)
{
start++;
}
for (int i = start; i < (int)res.size(); ++i)
{
result.push_back(res[i] + '0');
}
return result;
}
static string div(const string& a, const string& b)
{
if (!cmp(a, b)) return "0";
string quotient;
string temp = "";
for (int i = 0; i < (int)a.length(); i++)
{
temp.push_back(a[i]);
// 移除前导零(但保留最后一个零)
if (temp.length() > 1 && temp[0] == '0')
{
temp = temp.substr(1);
}
int count = 0;
// 减法实现除法
while (cmp(temp, b))
{
temp = subtractNonNegative(temp, b);
count++;
}
quotient.push_back(count + '0');
}
// 移除商的前导零
while (quotient.length() > 1 && quotient[0] == '0')
{
quotient = quotient.substr(1);
}
return quotient;
}
public:
// 构造函数
Bigint() : num("0"), sign(true) {}
Bigint(string s)
{
if (s.empty())
{
num = "0";
sign = true;
return;
}
// 处理符号
if (s[0] == '-')
{
sign = false;
s = s.substr(1);
}
else
{
sign = true;
}
// 检查是否只剩符号
if (s.empty())
{
num = "0";
sign = true;
return;
}
// 移除前导零
size_t start = s.find_first_not_of('0');
if (start == string::npos)
{
num = "0";
sign = true; // 0总是正数
}
else
{
num = s.substr(start);
// 如果数字是"0",确保符号为正
if (num == "0") sign = true;
}
}
Bigint(long long n) : Bigint(tostring<long long>(n)) {}
string getNum() const { return num; }
bool getSign() const { return sign; }
Bigint operator-() const
{
if (num == "0") return Bigint("0");
return Bigint(sign ? "-" + num : num);
}
// 加法运算符
Bigint operator+(const Bigint& other) const
{
string a = this->num;
string b = other.num;
bool aSign = this->sign;
bool bSign = other.sign;
if (aSign == bSign)
{
string result = add(a, b);
return Bigint(aSign ? result : "-" + result);
}
else
{
if (aSign) // a正,b负 => a - |b|
{
string result = subtractNonNegative(a, b);
if (result[0] == '-')
{
return Bigint("-" + result.substr(1));
}
else
{
return Bigint(result);
}
}
else // a负,b正 => b - |a|
{
string result = subtractNonNegative(b, a);
if (result[0] == '-')
{
return Bigint("-" + result.substr(1));
}
else
{
return Bigint(result);
}
}
}
}
// 减法运算符
Bigint operator-(const Bigint& other) const
{
return *this + (-other); // a - b = a + (-b)
}
// 乘法运算符
Bigint operator*(const Bigint& other) const
{
string result = mul(this->num, other.num);
if (result == "0") return Bigint("0");
// 同号为正,异号为负
bool resultSign = (this->sign == other.sign);
return Bigint(resultSign ? result : "-" + result);
}
// 除法运算符
Bigint operator/(const Bigint& other) const
{
if (other.num == "0")
{
throw runtime_error("Division by zero");
}
string result = div(this->num, other.num);
if (result == "0") return Bigint("0");
// 同号为正,异号为负
bool resultSign = (this->sign == other.sign);
return Bigint(resultSign ? result : "-" + result);
}
// 取模运算符
Bigint operator%(const Bigint& other) const
{
if (other.num == "0")
{
throw runtime_error("Modulo by zero");
}
// 计算 a % b = a - (a / b) * b
Bigint quotient = *this / other;
Bigint product = quotient * other;
Bigint remainder = *this - product;
return remainder;
}
Bigint& operator+=(const Bigint& other)
{
*this = *this + other;
return *this;
}
Bigint& operator-=(const Bigint& other)
{
*this = *this - other;
return *this;
}
Bigint& operator*=(const Bigint& other)
{
*this = *this * other;
return *this;
}
Bigint& operator/=(const Bigint& other)
{
*this = *this / other;
return *this;
}
Bigint& operator%=(const Bigint& other)
{
*this = *this % other;
return *this;
}
bool operator==(const Bigint& other) const
{
return (sign == other.sign) && (num == other.num);
}
bool operator!=(const Bigint& other) const
{
return !(*this == other);
}
bool operator<(const Bigint& other) const
{
if (sign != other.sign)
{
return sign < other.sign; // 负数 < 正数
}
if (sign) // 都是正数
{
if (num.length() != other.num.length())
return num.length() < other.num.length();
return num < other.num;
}
else // 都是负数
{
if (num.length() != other.num.length())
return num.length() > other.num.length();
return num > other.num;
}
}
bool operator>(const Bigint& other) const
{
return other < *this;
}
bool operator<=(const Bigint& other) const
{
return !(*this > other);
}
bool operator>=(const Bigint& other) const
{
return !(*this < other);
}
friend ostream& operator<<(ostream& os, const Bigint& bigint)
{
if (!bigint.sign && bigint.num != "0")
{
os << '-';
}
os << bigint.num;
return os;
}
friend istream& operator>>(istream& is, Bigint& bigint)
{
string s;
is >> s;
bigint = Bigint(s);
return is;
}
bool isZero() const { return num == "0"; }
bool isPositive() const { return sign && num != "0"; }
bool isNegative() const { return !sign && num != "0"; }
Bigint abs() const
{
return Bigint(num);
}
string toString() const
{
return (sign || num == "0") ? num : "-" + num;
}
};
#endif
#ifdef JTBG_KMP
struct kmp
{
private:
string pattern;
vector<int> next;
void buildNext()
{
int m = pattern.length();
next.resize(m, 0);
next[0] = -1;
int i = 0, j = -1;
while (i < m - 1)
{
if (j == -1 || pattern[i] == pattern[j])
{
i++;
j++;
next[i] = j;
}
else
{
j = next[j];
}
}
}
public:
kmp(const string& pat) : pattern(pat)
{
buildNext();
}
// 搜索所有匹配位置
vector<int> search(const string& text)
{
vector<int> result;
int n = text.length();
int m = pattern.length();
if (m == 0) return result;
int i = 0, j = 0;
while (i < n) {
if (j == -1 || text[i] == pattern[j])
{
i++;
j++;
}
else
{
j = next[j];
}
if (j == m)
{
result.push_back(i - j);
j = next[j - 1]; // 继续搜索
i--; // 回退一步
}
}
return result;
}
// 搜索第一个匹配位置,返回-1表示未找到
int findFirst(const string& text)
{
int n = text.length();
int m = pattern.length();
if (m == 0) return 0;
int i = 0, j = 0;
while (i < n && j < m)
{
if (j == -1 || text[i] == pattern[j])
{
i++;
j++;
}
else
{
j = next[j];
}
}
return (j == m) ? (i - j) : -1;
}
// 判断是否包含模式串
bool contains(const string& text)
{
return findFirst(text) != -1;
}
// 获取next数组(用于调试)
vector<int> getNext() const
{
return next;
}
// 统计匹配次数
int count(const string& text)
{
return search(text).size();
}
};
#endif
#ifdef JTBG_ARGCV
struct argcv
{
void pre(int argc,char** argv)
{
cout << "程序名: " << argv[0] << endl;
cout << "参数数量: " << argc - 1 << endl;
for (int i = 1; i < argc; i++)
{
cout << "参数 " << i << ": " << argv[i] << endl;
}
}
vector<string> ToVector(int argc, char** argv)
{
vector<string> args;
for (int i = 1; i < argc; i++)
{
args.push_back(string(argv[i]));
}
return args;
}
map<string, string> ToKeyValue(int argc, char** argv)
{
map<string, string> params;
for (int i = 1; i < argc; i++)
{
string arg = argv[i];
// 检查是否是 --key=value 格式
if (arg.substr(0, 2) == "--")
{
size_t pos = arg.find('=');
if (pos != string::npos)
{
string key = arg.substr(2, pos - 2);
string value = arg.substr(pos + 1);
params[key] = value;
}
else
{
// 只有键没有值
params[arg.substr(2)] = "true";
}
}
// 检查是否是 -key value 格式
else if (arg.substr(0, 1) == "-")
{
string key = arg.substr(1);
if (i + 1 < argc && argv[i + 1][0] != '-')
{
params[key] = argv[i + 1];
i++; // 跳过下一个参数
}
else
{
params[key] = "true";
}
}
}
return params;
}
};
#endif
#ifdef JTBG_MES
struct message
{
#define Everyone "0x38"
#define System "0x39"
#define Null "0x40"
string from;
string to;
string mess;
int mod;
#define Infomation 0x41
#define Error_throw 0x42
#define Normal 0x43
};
struct messageer
{
private:
string path;
public:
void set_path(const string& s)
{
path=s;
return ;
}
vector<message> read_all()
{
vector<message> ans;
ifstream fin;
fin.open(path,ios::in);
while(fin.good())
{
message tmp;
fin>>tmp.from>>tmp.to>>tmp.mod;
fin.ignore(numeric_limits<streamsize>::max(), '\n');
getline(fin,tmp.mess);
ans.push_back(tmp);
}
fin.close();
return ans;
}
message read_last()
{
message tmp;
ifstream fin;
fin.open(path,ios::in);
while(fin.good())
{
fin>>tmp.from>>tmp.to>>tmp.mod;
fin.ignore(numeric_limits<streamsize>::max(), '\n');
getline(fin,tmp.mess);
}
fin.close();
return tmp;
}
void send_message(message send)
{
ofstream fout;
fout.open(path,ios::app|ios::in);
fout<<send.from<<" "<<send.to<<" "<<send.mod<<endl<<send.mess;
fout.close();
}
};
#endif
#ifdef JTBG_REGI
/*
list:
SetShowFileExtensions(bool) 设置是否显示已知的文件扩展名
SetShowHiddenFiles(bool) 设置是否显示隐藏的文件/文件夹
SetShowSystemFiles(bool) 设置是否显示受保护的系统文件
SetHideEmptyDrives(bool) 设置是否隐藏无介质的驱动器(如空光驱)
SetRegistryDwordValue([const]wchar_t*,[const]wchar_t*,DWORD) 设置注册表项
ReadRegistryString(HKEY,[const]wchar_t*,[const]wchar_t*,wstring&) 读取注册表字符串类型值(REG_SZ/REG_EXPAND_SZ)
ReadRegistryDword(HKEY,[const]wchar_t*,[const]wchar_t*,DWORD&) 读取注册表DWORD类型值
*/
bool SetRegistryDwordValue(const wchar_t* regSubKey, const wchar_t* valueName, DWORD value)
{
HKEY hKey = nullptr;
// 打开当前用户的注册表项(写入权限)
LONG ret = RegOpenKeyExW(
HKEY_CURRENT_USER,
regSubKey,
0,
KEY_SET_VALUE,
&hKey
);
if (ret != ERROR_SUCCESS)
{
return false;
}
// 设置DWORD类型键值
ret = RegSetValueExW(
hKey,
valueName,
0,
REG_DWORD,
(const BYTE*)&value,
sizeof(DWORD)
);
if (ret != ERROR_SUCCESS)
{
RegCloseKey(hKey);
return false;
}
RegCloseKey(hKey); // 关闭注册表句柄
return true;
}
bool SetShowFileExtensions(bool showExt=1)
{
const wchar_t* regPath = L"Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\Advanced";
const wchar_t* regKey = L"HideFileExt";
HKEY hKey = nullptr;
// 1. 打开注册表项(KEY_SET_VALUE 表示写入权限)
LONG ret = RegOpenKeyExW(
HKEY_CURRENT_USER, // 根键
regPath, // 子键路径
0, // 保留参数
KEY_SET_VALUE, // 访问权限
&hKey // 输出打开的键句柄
);
if (ret != ERROR_SUCCESS)
{
return false;
}
// 2. 设置键值:0表示显示,1表示隐藏
DWORD value = showExt ? 0 : 1;
ret = RegSetValueExW(
hKey, // 已打开的键句柄
regKey, // 要设置的键名
0, // 保留参数
REG_DWORD, // 数据类型(32位整数)
(const BYTE*)&value,// 数据缓冲区
sizeof(DWORD) // 数据长度
);
if (ret != ERROR_SUCCESS)
{
RegCloseKey(hKey); // 关闭注册表句柄
return false;
}
RegCloseKey(hKey);
SHChangeNotify(
SHCNE_ASSOCCHANGED, // 通知类型:文件关联/设置变更
SHCNF_IDLIST, // 数据类型:ID列表(无具体数据时用此)
nullptr, // 无具体数据
nullptr // 无具体数据
);
return true;
}
bool SetShowHiddenFiles(bool show)
{
const wchar_t* regPath = L"Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\Advanced";
DWORD value = show ? 1 : 2; // 注意:Hidden键的取值是1=显示,2=隐藏(特殊规则)
if (!SetRegistryDwordValue(regPath, L"Hidden", value))
{
return false;
}
return true;
}
bool SetShowSystemFiles(bool show)
{
const wchar_t* regPath = L"Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\Advanced";
DWORD value = show ? 1 : 0; // 1=显示系统文件,0=隐藏
if (!SetRegistryDwordValue(regPath, L"ShowSuperHidden", value))
{
return false;
}
return true;
}
bool SetHideEmptyDrives(bool hide)
{
const wchar_t* regPath = L"Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\Advanced";
DWORD value = hide ? 1 : 0; // 1=隐藏无介质驱动器,0=显示
if (!SetRegistryDwordValue(regPath, L"HideDrivesWithNoMedia", value))
{
return false;
}
return true;
}
bool ReadRegistryString(HKEY rootKey, const wchar_t* subKey, const wchar_t* valueName, wstring& outStr)
{
HKEY hKey = nullptr;
LONG ret = RegOpenKeyExW(rootKey, subKey, 0, KEY_READ, &hKey);
if (ret != ERROR_SUCCESS)
{
return false;
}
// 第一步:调用RegQueryValueExW获取字符串的长度(dataSize返回所需缓冲区大小)
DWORD dataType = 0;
DWORD dataSize = 0;
ret = RegQueryValueExW(
hKey,
valueName,
nullptr,
&dataType,
nullptr, // 缓冲区为null,仅获取长度
&dataSize
);
if (ret != ERROR_SUCCESS && ret != ERROR_MORE_DATA)
{
RegCloseKey(hKey);
return false;
}
// 第二步:分配缓冲区,读取字符串
bool success = false;
if (dataType == REG_SZ || dataType == REG_EXPAND_SZ)
{
wchar_t* buffer = new wchar_t[dataSize / sizeof(wchar_t)]; // 按宽字符分配
ret = RegQueryValueExW(
hKey,
valueName,
nullptr,
&dataType,
(LPBYTE)buffer,
&dataSize
);
if (ret == ERROR_SUCCESS)
{
outStr = buffer; // 赋值到wstring
success = true;
}
delete[] buffer; // 释放缓冲区
}
RegCloseKey(hKey);
return success;
}
bool ReadRegistryDword(HKEY rootKey, const wchar_t* subKey, const wchar_t* valueName, DWORD& outValue)
{
HKEY hKey = nullptr;
LONG ret = RegOpenKeyExW(
rootKey,
subKey,
0,
KEY_READ,
&hKey
);
if (ret != ERROR_SUCCESS)
{
return false;
}
// 2. 查询键值:先获取数据长度(此处DWORD固定为4字节,也可动态获取)
DWORD dataType = 0;
DWORD dataSize = sizeof(DWORD);
ret = RegQueryValueExW(
hKey,
valueName,
nullptr,
&dataType, // 输出实际值类型
(LPBYTE)&outValue, // 存储读取的数据
&dataSize // 输入缓冲区大小,输出实际数据大小
);
// 3. 校验结果:类型匹配 + 操作成功
bool success = false;
if (ret == ERROR_SUCCESS)
{
if (dataType == REG_DWORD)
{
success = true;
}
}
RegCloseKey(hKey);
return success;
}
#endif
#ifdef JTBG_ADMIN_ALL_GAMES_AND_IDEAS_AND_ALL_IT_THINGS_ADMINS_CL
string Get_jtbg_admin_data_key_md5(const string& jtbgadminkey)
{
if(MD5::hash(jtbgadminkey)=="82c4bfc8a09e4c0e1f156366a6034a1f")
{
return "fc418cbb99dd709200c98c57550bb150";
}
else return "error";
}
int Check_jtbg_admin_key_data_path(const string& path,const string& jtbgadminkey)
{
if(MD5::hash(jtbgadminkey)=="82c4bfc8a09e4c0e1f156366a6034a1f")
{
if(Get_jtbg_admin_data_key_md5(jtbgadminkey)==FileMD5(path))
{
return 1;
}
else if(Get_jtbg_admin_data_key_md5(jtbgadminkey)=="error")
{
return -1;
}
else
{
return 0;
}
}
else return -1;
}
string Jtbg_Selfs_admin_hash_make_rs(string p)
{
stringstream ans;
ans<<"jtbgxfd(Jtbg_Selfs_admin_hash_make_rs):";
int k=1;
int r=int('0');
for(int i=0;i<int(p.size());i++)
{
ans<<int(p[i]-r)*k;
k++;
r--;
}
return ans.str();
}
#endif
#ifdef JTBG_PROS
#define RESUME 0
#define SUSPEND 1
#ifndef NO_DEBUGPROS
DWORD GetProcessIdByName(const char* processName)
{
DWORD processId = 0;
HANDLE hSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
if (hSnapshot != INVALID_HANDLE_VALUE)
{
PROCESSENTRY32 processEntry;
processEntry.dwSize = sizeof(PROCESSENTRY32);
if (Process32First(hSnapshot, &processEntry))
{
do
{
if (strcmp(processEntry.szExeFile, processName) == 0)
{
processId = processEntry.th32ProcessID;
break;
}
} while (Process32Next(hSnapshot, &processEntry));
}
CloseHandle(hSnapshot);
}
return processId;
}
// 使用DebugActiveProcess挂起进程
bool SuspendProcessByDebug(DWORD processId)
{
if (DebugActiveProcess(processId))
{
return true;
}
return false;
}
// 恢复被Debug挂起的进程
bool ResumeProcessByDebug(DWORD processId)
{
if (DebugActiveProcessStop(processId))
{
return true;
}
return false;
}
bool prossruncontol_bydebug(int mod,DWORD p)
{
if(mod==RESUME) return ResumeProcessByDebug(p);
else if(mod==SUSPEND) return SuspendProcessByDebug(p);
else return 0;
}
#endif
#ifndef NO_NTPPORS
typedef LONG (NTAPI *NtSuspendProcess)(IN HANDLE ProcessHandle);
typedef LONG (NTAPI *NtResumeProcess)(IN HANDLE ProcessHandle);
// 使用NtSuspendProcess挂起进程
bool SuspendProcessByNt(DWORD processId)
{
HANDLE hProcess = OpenProcess(PROCESS_ALL_ACCESS, FALSE, processId);
if (hProcess == NULL)
{
return false;
}
// 获取NtSuspendProcess函数
HMODULE hNtDll = GetModuleHandle("ntdll.dll");
if (hNtDll == NULL)
{
CloseHandle(hProcess);
return false;
}
NtSuspendProcess pNtSuspendProcess =
(NtSuspendProcess)GetProcAddress(hNtDll, "NtSuspendProcess");
if (pNtSuspendProcess != NULL)
{
LONG status = pNtSuspendProcess(hProcess);
CloseHandle(hProcess);
if (status == 0)
{ // STATUS_SUCCESS
cout << "进程 " << processId << " 已被挂起 (Nt方法)" << endl;
return true;
}
}
CloseHandle(hProcess);
return false;
}
// 恢复进程
bool ResumeProcessByNt(DWORD processId)
{
HANDLE hProcess = OpenProcess(PROCESS_ALL_ACCESS, FALSE, processId);
if (hProcess == NULL)
{
return false;
}
HMODULE hNtDll = GetModuleHandle("ntdll.dll");
if (hNtDll == NULL)
{
CloseHandle(hProcess);
return false;
}
NtResumeProcess pNtResumeProcess =
(NtResumeProcess)GetProcAddress(hNtDll, "NtResumeProcess");
if (pNtResumeProcess != NULL)
{
LONG status = pNtResumeProcess(hProcess);
CloseHandle(hProcess);
if (status == 0)
{
cout << "进程 " << processId << " 已恢复 (Nt方法)" << endl;
return true;
}
}
CloseHandle(hProcess);
return false;
}
bool prossruncontol_ntpro(int mod,DWORD p)
{
if(mod==RESUME) return ResumeProcessByNt(p);
else if(mod==SUSPEND) return SuspendProcessByNt(p);
else return 0;
}
#endif
#ifndef NO_TerminateProcess
bool KillProcByTer(DWORD processId, UINT exitCode = 0)
{
HANDLE hProcess = OpenProcess(PROCESS_TERMINATE, FALSE, processId);
if (hProcess == NULL)
{
return false;
}
if (TerminateProcess(hProcess, exitCode))
{
CloseHandle(hProcess);
return true;
}
else
{
CloseHandle(hProcess);
return false;
}
}
#endif
#ifndef NO_NTTERMINATE
typedef LONG (NTAPI *NtTerminateProcess)(HANDLE ProcessHandle, LONG ExitStatus);
bool KillProcByNt(DWORD processId, LONG exitCode = 0)
{
HANDLE hProcess = OpenProcess(PROCESS_TERMINATE, FALSE, processId);
if (hProcess == NULL)
{
return false;
}
HMODULE hNtDll = GetModuleHandle("ntdll.dll");
if (hNtDll == NULL)
{
CloseHandle(hProcess);
return false;
}
NtTerminateProcess pNtTerminateProcess =
(NtTerminateProcess)GetProcAddress(hNtDll, "NtTerminateProcess");
if (pNtTerminateProcess != NULL)
{
LONG status = pNtTerminateProcess(hProcess, exitCode);
CloseHandle(hProcess);
if (status == 0)
{ // STATUS_SUCCESS
return true;
}
}
CloseHandle(hProcess);
return false;
}
#endif
BOOL CALLBACK EnumWindowsProc(HWND hwnd, LPARAM lParam)
{
DWORD targetProcessId = (DWORD)lParam;
DWORD windowProcessId;
GetWindowThreadProcessId(hwnd, &windowProcessId);
if (windowProcessId == targetProcessId)
{
// 发送关闭消息
PostMessage(hwnd, WM_CLOSE, 0, 0);
}
return TRUE;
}
bool GracefulKillProc(DWORD processId, DWORD waitTimeout = 5000)
{
// 向进程的所有窗口发送关闭消息
EnumWindows(EnumWindowsProc, (LPARAM)processId);
// 等待进程退出
HANDLE hProcess = OpenProcess(SYNCHRONIZE, FALSE, processId);
if (hProcess == NULL)
{
return KillProcByTer(processId);
}
DWORD waitResult = WaitForSingleObject(hProcess, waitTimeout);
CloseHandle(hProcess);
if (waitResult == WAIT_OBJECT_0)
{
return true;
}
else
{
return KillProcByTer(processId);
}
}
#endif
#ifdef JTBG_UDP
class UDPSocket
{
private:
SOCKET sock;
string local_ip;
uint16_t local_port;
atomic<bool> recv_running;
thread recv_thread;
function<void(const string&, const string&, uint16_t)> recv_cb;
function<void(const string&)> error_cb;
static atomic<int> ws_ref;
static bool ws_init()
{
if (ws_ref++ == 0)
{
WSADATA wsa;
return WSAStartup(MAKEWORD(2, 2), &wsa) == 0;
}
return true;
}
static void ws_cleanup()
{
if (--ws_ref == 0)
{
WSACleanup();
}
}
bool create()
{
if (sock != INVALID_SOCKET) return true;
sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
return sock != INVALID_SOCKET;
}
bool str2addr(const std::string& ip, uint16_t port, sockaddr_in& addr)
{
memset(&addr, 0, sizeof(addr));
addr.sin_family = AF_INET;
addr.sin_port = htons(port);
if (ip.empty() || ip == "0.0.0.0")
{
addr.sin_addr.s_addr = INADDR_ANY;
}
else if (ip == "255.255.255.255")
{
addr.sin_addr.s_addr = INADDR_BROADCAST;
}
else
{
// 方法1:使用 std::stringstream
stringstream ss(ip);
string segment;
vector<int> parts;
while (std::getline(ss, segment, '.'))
{
try
{
parts.push_back(std::stoi(segment));
}
catch (...)
{
return false;
}
}
if (parts.size() != 4) return false;
for (int part : parts)
{
if (part < 0 || part > 255) return false;
}
addr.sin_addr.s_addr = htonl(
(parts[0] << 24) |
(parts[1] << 16) |
(parts[2] << 8) |
parts[3]
);
}
return true;
}
string addr2str(const sockaddr_in& addr)
{
unsigned long ip = ntohl(addr.sin_addr.s_addr);
// 使用 to_string
return to_string((ip >> 24) & 0xFF) + "." +
to_string((ip >> 16) & 0xFF) + "." +
to_string((ip >> 8) & 0xFF) + "." +
to_string(ip & 0xFF);
}
void recv_loop()
{
char buffer[65507];
sockaddr_in from_addr;
int addr_len = sizeof(from_addr);
while (recv_running)
{
fd_set read_set;
FD_ZERO(&read_set);
FD_SET(sock, &read_set);
timeval timeout = {0, 100000}; // 100ms
int ready = select(0, &read_set, NULL, NULL, &timeout);
if (ready <= 0) continue;
int received = recvfrom(sock, buffer, sizeof(buffer), 0,
(sockaddr*)&from_addr, &addr_len);
if (received > 0 && recv_cb)
{
string data(buffer, received);
string from_ip = addr2str(from_addr);
uint16_t from_port = ntohs(from_addr.sin_port);
recv_cb(data, from_ip, from_port);
}
else if (received == SOCKET_ERROR && error_cb)
{
error_cb("接收错误");
}
}
}
public:
UDPSocket() : sock(INVALID_SOCKET), local_port(0), recv_running(false)
{
ws_init();
}
~UDPSocket()
{
close();
stop_recv();
ws_cleanup();
}
// 禁止拷贝
UDPSocket(const UDPSocket&) = delete;
UDPSocket& operator=(const UDPSocket&) = delete;
// 移动构造
UDPSocket(UDPSocket&& other) noexcept
: sock(other.sock),
local_ip(move(other.local_ip)),
local_port(other.local_port),
recv_running(other.recv_running.load())
{
other.sock = INVALID_SOCKET;
other.recv_running = false;
}
// 移动赋值
UDPSocket& operator=(UDPSocket&& other) noexcept
{
if (this != &other)
{
close();
stop_recv();
sock = other.sock;
local_ip = move(other.local_ip);
local_port = other.local_port;
recv_running = other.recv_running.load();
other.sock = INVALID_SOCKET;
other.recv_running = false;
}
return *this;
}
bool bind(uint16_t port, const string& ip = "0.0.0.0")
{
if (!create()) return false;
sockaddr_in addr;
if (!str2addr(ip, port, addr)) return false;
if (::bind(sock, (sockaddr*)&addr, sizeof(addr)) == SOCKET_ERROR)
{
return false;
}
sockaddr_in local_addr;
int len = sizeof(local_addr);
if (getsockname(sock, (sockaddr*)&local_addr, &len) == 0)
{
local_ip = addr2str(local_addr);
local_port = ntohs(local_addr.sin_port);
}
return true;
}
// 发送string
int send(const string& data, const string& ip, uint16_t port)
{
if (sock == INVALID_SOCKET) return -1;
sockaddr_in addr;
if (!str2addr(ip, port, addr)) return -1;
int sent = sendto(sock, data.c_str(), (int)data.size(), 0,
(sockaddr*)&addr, sizeof(addr));
return sent == SOCKET_ERROR ? -1 : sent;
}
// 发送C字符串
int send(const char* data, const string& ip, uint16_t port)
{
if (!data) return -1;
return send(string(data), ip, port);
}
// 发送vector
int send(const vector<uint8_t>& data, const string& ip, uint16_t port)
{
if (data.empty()) return -1;
return send(string(data.begin(), data.end()), ip, port);
}
// 发送原始数据
int send(const void* data, int size, const string& ip, uint16_t port)
{
if (!data || size <= 0) return -1;
return send(string((char*)data, size), ip, port);
}
// 同步接收
int recv(string& data, string& from_ip, uint16_t& from_port, int timeout_ms = -1)
{
if (sock == INVALID_SOCKET) return -1;
if (timeout_ms >= 0)
{
fd_set read_set;
FD_ZERO(&read_set);
FD_SET(sock, &read_set);
timeval timeout = {timeout_ms / 1000, (timeout_ms % 1000) * 1000};
int ready = select(0, &read_set, NULL, NULL, &timeout);
if (ready == 0) return 0; // 超时
if (ready == SOCKET_ERROR) return -1;
}
char buffer[65507];
sockaddr_in from_addr;
int addr_len = sizeof(from_addr);
int received = recvfrom(sock, buffer, sizeof(buffer), 0,
(sockaddr*)&from_addr, &addr_len);
if (received > 0)
{
data = string(buffer, received);
from_ip = addr2str(from_addr);
from_port = ntohs(from_addr.sin_port);
}
return received == SOCKET_ERROR ? -1 : received;
}
// 开始异步接收
bool start_recv(function<void(const string&, const string&, uint16_t)> recv_callback,
function<void(const string&)> error_callback = nullptr)
{
if (sock == INVALID_SOCKET || recv_running) return false;
recv_cb = recv_callback;
error_cb = error_callback;
recv_running = true;
recv_thread = thread(&UDPSocket::recv_loop, this);
return true;
}
// 停止异步接收
void stop_recv()
{
if (recv_running)
{
recv_running = false;
if (recv_thread.joinable())
{
recv_thread.join();
}
}
}
// 关闭socket
void close()
{
if (sock != INVALID_SOCKET)
{
closesocket(sock);
sock = INVALID_SOCKET;
}
}
// 设置选项
bool set_broadcast(bool enable)
{
if (sock == INVALID_SOCKET) return false;
BOOL val = enable ? TRUE : FALSE;
return setsockopt(sock, SOL_SOCKET, SO_BROADCAST,
(char*)&val, sizeof(val)) == 0;
}
bool set_reuseaddr(bool enable)
{
if (sock == INVALID_SOCKET) return false;
BOOL val = enable ? TRUE : FALSE;
return setsockopt(sock, SOL_SOCKET, SO_REUSEADDR,
(char*)&val, sizeof(val)) == 0;
}
bool set_nonblocking(bool enable)
{
if (sock == INVALID_SOCKET) return false;
u_long mode = enable ? 1 : 0;
return ioctlsocket(sock, FIONBIO, &mode) == 0;
}
bool set_rcvbuf(int size)
{
if (sock == INVALID_SOCKET) return false;
return setsockopt(sock, SOL_SOCKET, SO_RCVBUF,
(char*)&size, sizeof(size)) == 0;
}
bool set_sndbuf(int size)
{
if (sock == INVALID_SOCKET) return false;
return setsockopt(sock, SOL_SOCKET, SO_SNDBUF,
(char*)&size, sizeof(size)) == 0;
}
bool set_ttl(int ttl)
{
if (sock == INVALID_SOCKET) return false;
return setsockopt(sock, IPPROTO_IP, IP_TTL,
(char*)&ttl, sizeof(ttl)) == 0;
}
// 获取属性
bool is_valid() const { return sock != INVALID_SOCKET; }
uint16_t get_port() const { return local_port; }
string get_ip() const { return local_ip; }
bool is_recving() const { return recv_running; }
SOCKET get_handle() const { return sock; }
};
atomic<int> UDPSocket::ws_ref(0);
#endif
#ifdef JTBG_PROGRESS
// 进度条样式常量
#undef PROGRESS_STYLE_DEFAULT
#undef PROGRESS_STYLE_BLOCK
#undef PROGRESS_STYLE_DASH
#define PROGRESS_STYLE_DEFAULT "|"
#define PROGRESS_STYLE_BLOCK "="
#define PROGRESS_STYLE_DASH "-"
class BarDrawer
{ // 修正类名与使用处一致
private:
int total; // 总进度值
int current; // 当前进度值
int barLength; // 进度条长度
string style; // 进度条样式
bool showPercent; // 是否显示百分比
bool showTime; // 是否显示时间
chrono::steady_clock::time_point startTime; // 开始时间
public:
// 构造函数(修正:使用正确的构造函数语法)
BarDrawer(int totalSteps, int length = 50,
string barStyle = PROGRESS_STYLE_DEFAULT,
bool percent = true, bool time = true)
: total(totalSteps), current(0), barLength(length),
style(barStyle), showPercent(percent), showTime(time)
{
startTime = chrono::steady_clock::now();
}
// 无参构造函数(解决实例化时的参数匹配问题)
BarDrawer()
: total(100), current(0), barLength(50),
style(PROGRESS_STYLE_DEFAULT), showPercent(true), showTime(true)
{
startTime = chrono::steady_clock::now();
}
// 更新进度
void update(int steps = 1)
{
current = min(current + steps, total);
draw();
}
// 直接设置进度
void setProgress(int value)
{
current = max(0, min(value, total));
draw();
}
// 完成进度
void finish()
{
current = total;
draw();
cout << endl;
}
// 绘制进度条(修正:添加返回值或改为void)
void draw()
{
double progress = static_cast<double>(current) / total;
int filledLength = static_cast<int>(progress * barLength);
// 计算已用时间
auto now = chrono::steady_clock::now();
auto elapsed = chrono::duration_cast<chrono::seconds>(
now - startTime).count();
// 绘制进度条(结合JTBG_COL模块的颜色功能)
scg(LIGHT_GREEN, BLACK); // 设置绿色文本
cout << "\r[";
for (int i = 0; i < barLength; ++i)
{
if (i < filledLength) cout << style;
else cout << " ";
}
cout << "] ";
// 显示百分比
if (showPercent)
{
scg(LIGHT_CYAN, BLACK); // 百分比用青色
cout << fixed << setprecision(1)
<< progress * 100 << "% ";
}
// 显示进度数值
scg(WHITE, BLACK); // 数值用白色
cout << current << "/" << total;
// 显示时间
if(showTime)
{
scg(YELLOW, BLACK);
cout << " (" << elapsed << "s)";
}
scg(WHITE, BLACK); // 恢复默认颜色
cout.flush();
}
};
// 简易进度条函数(修正:使用正确的类名和构造函数)
void showProgress(int current, int total, int barLength = 50)
{
BarDrawer pb(total, barLength);
pb.setProgress(current);
if (current >= total) pb.finish();
}
#endif
#ifdef JTBG_RSA
class SimpleBigInt
{
private:
string num;
bool negative;
// 移除前导零
void removeLeadingZeros()
{
size_t pos = num.find_first_not_of('0');
if (pos == string::npos)
{
num = "0";
negative = false;
}
else
{
num = num.substr(pos);
}
if (num == "0") negative = false;
}
// 比较绝对值大小
int compareAbsolute(const SimpleBigInt& other) const
{
if (num.length() != other.num.length())
{
return num.length() > other.num.length() ? 1 : -1;
}
return num.compare(other.num);
}
public:
// 构造函数
SimpleBigInt() : num("0"), negative(false) {}
SimpleBigInt(long long n)
{
if (n < 0)
{
negative = true;
n = -n;
}
else
{
negative = false;
}
num = to_string(n);
}
SimpleBigInt(const string& s)
{
if (s.empty())
{
num = "0";
negative = false;
}
else
{
if (s[0] == '-')
{
negative = true;
num = s.substr(1);
}
else
{
negative = false;
num = s;
}
}
removeLeadingZeros();
}
// 转换为字符串
string toString() const
{
return (negative ? "-" : "") + num;
}
// 获取数字字符串(无符号)
string getNum() const
{
return num;
}
// 获取符号
bool isNegative() const
{
return negative;
}
// 比较运算符
bool operator==(const SimpleBigInt& other) const
{
return negative == other.negative && num == other.num;
}
bool operator!=(const SimpleBigInt& other) const
{
return !(*this == other);
}
bool operator<(const SimpleBigInt& other) const
{
if (negative != other.negative)
{
return negative;
}
if (negative)
{
return compareAbsolute(other) > 0;
}
return compareAbsolute(other) < 0;
}
bool operator<=(const SimpleBigInt& other) const
{
return *this < other || *this == other;
}
bool operator>(const SimpleBigInt& other) const
{
return !(*this <= other);
}
bool operator>=(const SimpleBigInt& other) const
{
return !(*this < other);
}
// 加法
SimpleBigInt operator+(const SimpleBigInt& other) const
{
if (negative != other.negative)
{
// 符号不同,转换为减法
if (negative)
{
SimpleBigInt temp = *this;
temp.negative = false;
return other - temp;
}
else
{
SimpleBigInt temp = other;
temp.negative = false;
return *this - temp;
}
}
// 符号相同,直接相加
string result;
int carry = 0;
int i = num.length() - 1;
int j = other.num.length() - 1;
while (i >= 0 || j >= 0 || carry > 0)
{
int digit1 = i >= 0 ? num[i] - '0' : 0;
int digit2 = j >= 0 ? other.num[j] - '0' : 0;
int sum = digit1 + digit2 + carry;
result.push_back((sum % 10) + '0');
carry = sum / 10;
i--;
j--;
}
reverse(result.begin(), result.end());
SimpleBigInt res(result);
res.negative = negative;
return res;
}
// 减法
SimpleBigInt operator-(const SimpleBigInt& other) const
{
if (negative != other.negative)
{
// 符号不同,转换为加法
SimpleBigInt temp = other;
temp.negative = !other.negative;
return *this + temp;
}
// 符号相同,比较大小
bool resultNegative = false;
string a = num;
string b = other.num;
if (negative)
{
// 都是负数:(-a) - (-b) = b - a
swap(a, b);
resultNegative = (compareAbsolute(other) > 0);
}
else
{
// 都是正数:a - b
if (*this < other)
{
swap(a, b);
resultNegative = true;
}
}
// 执行减法
string result;
int borrow = 0;
int i = a.length() - 1;
int j = b.length() - 1;
while (i >= 0)
{
int digit1 = a[i] - '0' - borrow;
int digit2 = j >= 0 ? b[j] - '0' : 0;
if (digit1 < digit2)
{
digit1 += 10;
borrow = 1;
}
else
{
borrow = 0;
}
result.push_back((digit1 - digit2) + '0');
i--;
j--;
}
// 移除结果中的前导零
while (result.length() > 1 && result.back() == '0')
{
result.pop_back();
}
reverse(result.begin(), result.end());
SimpleBigInt res(result);
res.negative = resultNegative;
return res;
}
// 乘法
SimpleBigInt operator*(const SimpleBigInt& other) const
{
if (num == "0" || other.num == "0")
{
return SimpleBigInt("0");
}
int len1 = num.length();
int len2 = other.num.length();
vector<int> result(len1 + len2, 0);
// 从低位到高位相乘
for (int i = len1 - 1; i >= 0; i--)
{
for (int j = len2 - 1; j >= 0; j--)
{
int mul = (num[i] - '0') * (other.num[j] - '0');
int sum = mul + result[i + j + 1];
result[i + j + 1] = sum % 10;
result[i + j] += sum / 10;
}
}
// 转换为字符串
string strResult;
for (int digit : result)
{
if (!(strResult.empty() && digit == 0))
{
strResult.push_back(digit + '0');
}
}
if (strResult.empty()) strResult = "0";
SimpleBigInt res(strResult);
res.negative = (negative != other.negative);
return res;
}
// 除法(返回商和余数)
pair<SimpleBigInt, SimpleBigInt> divide(const SimpleBigInt& divisor) const
{
if (divisor == SimpleBigInt("0"))
{
throw runtime_error("Division by zero");
}
SimpleBigInt dividend = *this;
dividend.negative = false;
SimpleBigInt div = divisor;
div.negative = false;
if (dividend < div)
{
return {SimpleBigInt("0"), *this};
}
string quotient;
string current;
for (char digit : dividend.num)
{
current.push_back(digit);
SimpleBigInt cur(current);
int count = 0;
while (cur >= div)
{
cur = cur - div;
count++;
}
quotient.push_back(count + '0');
current = cur.num;
if (current == "0") {
current.clear();
}
}
// 移除商的前导零
size_t pos = quotient.find_first_not_of('0');
if (pos == string::npos)
{
quotient = "0";
}
else
{
quotient = quotient.substr(pos);
}
SimpleBigInt q(quotient);
SimpleBigInt r(current.empty() ? "0" : current);
q.negative = (negative != divisor.negative);
r.negative = negative; // 余数符号与被除数相同
return {q, r};
}
// 除法运算符(返回商)
SimpleBigInt operator/(const SimpleBigInt& other) const
{
return divide(other).first;
}
// 取模运算符
SimpleBigInt operator%(const SimpleBigInt& other) const
{
return divide(other).second;
}
// 快速幂取模(核心算法)
static SimpleBigInt modPow(SimpleBigInt base, SimpleBigInt exponent, SimpleBigInt modulus)
{
if (modulus == SimpleBigInt("1")) return SimpleBigInt("0");
if (exponent == SimpleBigInt("0")) return SimpleBigInt("1");
SimpleBigInt result("1");
base = base % modulus;
// 将指数转换为二进制字符串
string binary;
SimpleBigInt exp = exponent;
while (exp > SimpleBigInt("0"))
{
// 检查最低位
pair<SimpleBigInt, SimpleBigInt> divResult = exp.divide(SimpleBigInt("2"));
if (divResult.second == SimpleBigInt("1"))
{
binary = "1" + binary;
}
else
{
binary = "0" + binary;
}
exp = divResult.first; // exp = exp / 2
}
// 快速幂算法
for (char bit : binary)
{
result = (result * result) % modulus;
if (bit == '1')
{
result = (result * base) % modulus;
}
}
return result;
}
static pair<SimpleBigInt, SimpleBigInt> extendedGcd(SimpleBigInt a, SimpleBigInt b)
{
if (b == SimpleBigInt("0"))
{
return {SimpleBigInt("1"), SimpleBigInt("0")};
}
pair<SimpleBigInt, SimpleBigInt> temp = extendedGcd(b, a % b);
SimpleBigInt x1 = temp.first;
SimpleBigInt y1 = temp.second;
SimpleBigInt x = y1;
SimpleBigInt y = x1 - (a / b) * y1;
return {x, y};
}
// 模逆元
static SimpleBigInt modInverse(SimpleBigInt a, SimpleBigInt m)
{
pair<SimpleBigInt, SimpleBigInt> gcdResult = extendedGcd(a, m);
SimpleBigInt x = gcdResult.first;
SimpleBigInt y = gcdResult.second;
// 检查是否有逆元 (gcd(a, m) 必须为1)
SimpleBigInt gcd = a * x + m * y;
if (gcd != SimpleBigInt("1"))
{
return SimpleBigInt("-1"); // 无逆元
}
// 确保结果为正
SimpleBigInt result = x % m;
if (result.isNegative())
{
result = result + m;
}
return result;
}
};
// ============ RSA 实现 ============
namespace RSA
{
using BigInt = SimpleBigInt;
struct RSAKey
{
BigInt n; // 模数
BigInt e; // 公钥指数
BigInt d; // 私钥指数
};
// Miller-Rabin 素性测试(简化版)
bool isPrimeSimple(const BigInt& n, int k = 5)
{
if (n == BigInt("2") || n == BigInt("3")) return true;
if (n < BigInt("2") || n % BigInt("2") == BigInt("0")) return false;
// 将 n-1 分解为 d * 2^s
BigInt d = n - BigInt("1");
int s = 0;
while (d % BigInt("2") == BigInt("0"))
{
d = d / BigInt("2");
s++;
}
srand(time(nullptr));
for (int i = 0; i < k; i++)
{
// 随机选择基数 a
BigInt a(to_string(2 + rand() % 100)); // 简化:使用小随机数
if (a >= n - BigInt("1"))
{
a = BigInt("2");
}
BigInt x = BigInt::modPow(a, d, n);
if (x == BigInt("1") || x == n - BigInt("1")) {
continue;
}
bool composite = true;
for (int j = 0; j < s - 1; j++)
{
x = (x * x) % n;
if (x == n - BigInt("1"))
{
composite = false;
break;
}
}
if (composite)
{
return false;
}
}
return true;
}
// 生成素数(简化版)
BigInt generatePrimeSimple(int bits = 16)
{
if (bits < 8) bits = 8;
srand(time(nullptr));
int maxAttempts = 1000;
for (int attempt = 0; attempt < maxAttempts; attempt++)
{
// 生成随机数
string numStr = "1"; // 确保最高位是1
for (int i = 1; i < bits - 1; i++)
{
numStr += (rand() % 2) ? '1' : '0';
}
numStr += '1'; // 确保是奇数
BigInt candidate(numStr);
// 快速检查小素数
vector<int> smallPrimes = {2, 3, 5, 7, 11, 13, 17, 19, 23, 29};
bool divisible = false;
for (int prime : smallPrimes)
{
if (candidate % BigInt(to_string(prime)) == BigInt("0"))
{
divisible = true;
break;
}
}
if (divisible) continue;
// 简化素性测试
if (isPrimeSimple(candidate))
{
return candidate;
}
}
// 如果没找到,返回一个已知的素数
return BigInt("101");
}
// 生成RSA密钥对
// 生成RSA密钥对(修复版)
RSAKey generateKeyPair(int keySize = 64)
{
RSAKey key;
// 生成两个不同的素数
BigInt p = generatePrimeSimple(keySize / 2);
BigInt q = generatePrimeSimple(keySize / 2);
while (q == p)
{
q = generatePrimeSimple(keySize / 2);
}
// 计算 n = p * q
key.n = p * q;
// 计算 φ(n) = (p-1)*(q-1)
BigInt phi = (p - BigInt("1")) * (q - BigInt("1"));
// 选择公钥指数 e(常用值)
vector<int> eCandidates = {3, 5, 17, 257, 65537};
bool found = false;
for (int eVal : eCandidates)
{
key.e = BigInt(to_string(eVal));
// 修复:不使用结构化绑定
pair<SimpleBigInt, SimpleBigInt> gcdResult = BigInt::extendedGcd(key.e, phi);
SimpleBigInt gcd = gcdResult.first * key.e + gcdResult.second * phi;
if (gcd == BigInt("1"))
{
found = true;
break;
}
}
if (!found)
{
// 尝试较小的奇数
for (int eVal = 3; eVal < 100; eVal += 2)
{
key.e = BigInt(to_string(eVal));
// 修复:不使用结构化绑定
pair<SimpleBigInt, SimpleBigInt> gcdResult = BigInt::extendedGcd(key.e, phi);
SimpleBigInt gcd = gcdResult.first * key.e + gcdResult.second * phi;
if (gcd == BigInt("1"))
{
found = true;
break;
}
}
}
if (!found)
{
// 使用默认值
key.e = BigInt("65537");
}
// 计算私钥指数 d = e^(-1) mod φ(n)
key.d = BigInt::modInverse(key.e, phi);
return key;
}
// 字符串编码为数字
BigInt stringToNumber(const string& str)
{
string encoded;
for (char c : str)
{
int ascii = static_cast<int>(c);
stringstream ss;
ss << setw(3) << setfill('0') << ascii;
encoded += ss.str();
}
return BigInt(encoded);
}
// 数字解码为字符串
string numberToString(const BigInt& num)
{
string numStr = num.getNum();
string decoded;
// 补全到3的倍数
while (numStr.length() % 3 != 0)
{
numStr = "0" + numStr;
}
for (size_t i = 0; i < numStr.length(); i += 3)
{
string triplet = numStr.substr(i, 3);
int ascii = stoi(triplet);
if (ascii >= 32 && ascii <= 126)
{ // 可打印字符
decoded += static_cast<char>(ascii);
}
}
return decoded;
}
// RSA加密
BigInt rsaEncrypt(const BigInt& message, const BigInt& e, const BigInt& n)
{
return BigInt::modPow(message, e, n);
}
// RSA解密
BigInt rsaDecrypt(const BigInt& ciphertext, const BigInt& d, const BigInt& n)
{
return BigInt::modPow(ciphertext, d, n);
}
// 字符串加密
string encryptString(const string& plaintext, const BigInt& e, const BigInt& n)
{
BigInt encoded = stringToNumber(plaintext);
BigInt encrypted = rsaEncrypt(encoded, e, n);
return encrypted.toString();
}
// 字符串解密
string decryptString(const string& ciphertext, const BigInt& d, const BigInt& n)
{
BigInt cipherNum(ciphertext);
BigInt decrypted = rsaDecrypt(cipherNum, d, n);
return numberToString(decrypted);
}
// 演示函数
void demo()
{
cout << "\n=== 简单RSA演示 ===" << endl;
cout << "注意:这是一个独立实现,不依赖外部库" << endl;
// 生成密钥对
cout << "\n1. 生成RSA密钥对..." << endl;
RSAKey key = generateKeyPair(32);
cout << "公钥 (n, e):" << endl;
cout << " n = " << key.n.toString() << endl;
cout << " e = " << key.e.toString() << endl;
cout << "\n私钥 (n, d):" << endl;
cout << " n = " << key.n.toString() << endl;
cout << " d = " << key.d.toString() << endl;
// 测试消息
string testMessage = "HELLO";
cout << "\n2. 测试加密/解密" << endl;
cout << "原始消息: \"" << testMessage << "\"" << endl;
// 加密
string encrypted = encryptString(testMessage, key.e, key.n);
cout << "加密后: " << encrypted << endl;
// 解密
string decrypted = decryptString(encrypted, key.d, key.n);
cout << "解密后: \"" << decrypted << "\"" << endl;
if (testMessage == decrypted)
{
cout << "\n? RSA加解密成功!" << endl;
}
else
{
cout << "\n? RSA加解密失败!" << endl;
}
cout << "\n3. 验证数学运算" << endl;
cout << "测试: 5^3 mod 13" << endl;
BigInt testResult = BigInt::modPow(BigInt("5"), BigInt("3"), BigInt("13"));
cout << "5^3 mod 13 = " << testResult.toString() << endl;
cout << "期望值: 8" << endl;
cout << (testResult == BigInt("8") ? "? 正确" : "? 错误") << endl;
}
}
#ifndef JTBG_NO_RSA_SHORT
//ENC:加密 DEC:解密
#define RSA_makekey(x) RSA::generateKeyPair((x))
#define RSA_TEST() RSA::demo()
#define RSA_SIMPLE_GEN_KEY(size) RSA::generateKeyPair((size))
#define RSA_SGK(size) RSA_SIMPLE_GEN_KEY((size))
#define RSA_ENC(msg, e, n) RSA::encryptString(msg, e, n)
#define RSA_DEC(cipher, d, n) RSA::decryptString(cipher, d, n)
#endif
#endif
#ifdef JTBG_UUID
#define UUID_HASH 1<<0
#ifndef JTBG_ONLY_WINDOWS
#define UUID_TIME 1<<1
#define UUID_RANDOM 1<<2
#endif
#define UUID_SAFE_HASH 1<<3
#define UUID_NAME 1<<4
static inline bool has_flag(int flags, int flag)
{
return (flags & flag) == flag;
}
static string make_uuid(int mod,string name="null_program_name_by_uuids_maker",string md5s="fdsahjksavhjsbhuwn8necwniieeyt7cin8eunudf")
{
stringstream ans;
if(has_flag(mod,UUID_TIME))
{
stringstream H;
H<<GetTickCount();
ans<<Hash(H.str())<<'-';
}
if(has_flag(mod,UUID_HASH))
{
ans<<Hash(md5s)<<'-';
}
if(has_flag(mod,UUID_SAFE_HASH))
{
stringstream H;
H<<GetTickCount()<<"jtbg";
ans<<Hash(md5s+H.str()+"vgfdsjvcvc")<<'-';
}
if(has_flag(mod,UUID_RANDOM))
{
stringstream H;
srand(GetTickCount()+rand());
H<<rand();
ans<<H.str()<<'-';
}
if(has_flag(mod,UUID_NAME))
{
ans<<Hash(name)<<'-';
}
ans<<"0";
return ans.str();
}
#endif
#ifdef JTBG_RMQ
struct __rmq
{
private:
#define MAX_R 21000
#define MAX_L 100
int f[MAX_R][MAX_L];
int a[MAX_R];
int cnt=0;
int log_M=50;
int mods=0x2f;
public:
void add_num(int l)
{
a[cnt++]=l;
log_M=max(log_M,int(log2(cnt)));
}
#define RMQ_MIN 0x3f
#define RMQ_MAX 0x2f
void reset(int mod=RMQ_MAX)
{
mods=mod;
cnt=0;
memset(a,0,sizeof a);
memset(f,0,sizeof f);
log_M=50;
}
void make_f()
{
for(int j=1;j<=log_M;++j)
{
for(int i=1;i+(1<<j)-1<=int(cnt);++i)
{
if(mods==RMQ_MAX) f[i][j]=max(f[i][j-1],f[i+(1<<(j-1))][j-1]);
else if(mods==RMQ_MIN) f[i][j]=min(f[i][j-1],f[i+(1<<(j-1))][j-1]);
}
}
}
int get_ans(int x,int y)
{
int s=log2(y-x+1);
if(mods==RMQ_MAX) return max(f[x][s],f[y-(1<<s)+1][s]);
else if(mods==RMQ_MIN) return min(f[x][s],f[y-(1<<s)+1][s]);
}
};
#endif
#ifdef JTBG_SAFE
string getPassword(const string& prompt = "Password: ",char op='*',ostream& f=cout)
{
f << prompt;
string password;
char ch;
while ((ch = _getch()) != '\r' && ch != '\n')
{
if (ch == '\b')
{ // 处理退格键
if (!password.empty())
{
f << "\b \b"; // 删除一个字符
password.pop_back();
}
}
else
{
password.push_back(ch);
f << op;
}
}
f << endl;
return password;
}
#endif
#ifndef JTBG_NO_ABOUT
void jtbg_h_about()
{
#ifndef jtdl
#define jtdl '\n'
#endif
cout<<"jtbg.h"<<jtdl;
cout<<"wroten by @jiaotangbinggan[jiaotangbingganxiaofendui_duiyuans]"<<jtdl;
cout<<"Process start with "<<JTBG_H_NOW_SEND_TIMES<<jtdl;
cout<<"Lv: "<<JTBG_H_VER<<" -std="<<JTBG_H_STD<<""<<jtdl;
cout<<"Used "<<JTBG_H_CC<<" "<<jtdl;
cout<<"join&talk to me(us):"<<jtdl;
cout<<" luogu-1497734"<<jtdl;
cout<<" 197474286@qq.com"<<jtdl;
cout<<" guitu1125@yeah.net"<<jtdl;
cout<<" 598032803@qq.com"<<jtdl;
cout<<" www.cnblogs.com/u/jtbg"<<jtdl;
cout<<" www.luogu.com.cn/chat?uid=1497734"<<jtdl;
cout<<"this file hash:please read jtbg.h_md5.md"<<jtdl;
cout<<"this file will be new in a long time"<<jtdl;
cout<<jtdl<<JTBG_H_HAPPY<<jtdl;
cout<<"thank you for used jtbg"<<jtdl;
cout<<"-end-"<<jtdl;
return ;
}
#endif
#endif
#ifdef _JTBG_DIDNT_DO_AGREE_
#pragma message("you need agree this by \'#define _agree_\'")
#endif
#ifdef JTBG_GPLS_NO_COMPILE
#pragma message("gpls on !warning!")
{
/*
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
<program> Copyright (C) <year> <name of author>
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<https://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
<https://www.gnu.org/licenses/why-not-lgpl.html>.
*/
}
#endif
本文来自博客园,作者:jtbg,转载请注明原文链接:https://www.cnblogs.com/jtbg/articles/-/jtbgh
博客最新公告
浙公网安备 33010602011771号