【安卓12源码】adb 的dumpsys和cmd实现原理

2023-12-13 04:04

本文主要是介绍【安卓12源码】adb 的dumpsys和cmd实现原理,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

 主要分析下列 2 个流程:

// dump activity 的一些信息

adb shell dumpsys activity > D:\dumpsys\activity2.txt


// a11 打开 ActivityManagerDebugConfig 的开关
adb shell cmd activity log_switch enable DEBUG_ALL

1. 分析 adb shell dumpsys 实现过程

还可以使用下列命令dump 具体的组件

adb shell dumpsys activity -a a // -a 是dump全部,a 是 activities

/frameworks/native/cmds/dumpsys/main.cpp

int main(int argc, char* const argv[]) {signal(SIGPIPE, SIG_IGN);sp<IServiceManager> sm = defaultServiceManager();fflush(stdout);if (sm == nullptr) {ALOGE("Unable to get default service manager!");std::cerr << "dumpsys: Unable to get default service manager!" << std::endl;return 20;}Dumpsys dumpsys(sm.get());// 执行 dumpsys 的 main 方法return dumpsys.main(argc, argv);
}

// 执行 dumpsys 的 main 方法

/frameworks/native/cmds/dumpsys/dumpsys.cpp

int Dumpsys::main(int argc, char* const argv[]) {Vector<String16> services;Vector<String16> args;String16 priorityType;Vector<String16> skippedServices;Vector<String16> protoServices;Type type = Type::DUMP;
。。。optind = 1;
。。。for (int i = optind; i < argc; i++) {if (skipServices) {skippedServices.add(String16(argv[i]));} else {// 将输入的servicename 保存到 services 中,如adb shell dumpsys activity -a a
// 则将 activity 保存到 services 中if (i == optind) {services.add(String16(argv[i]));} else {const String16 arg(argv[i]);
// args 保存其他参数 -a aargs.add(arg);const size_t N = services.size();
。。。。for (size_t i = 0; i < N; i++) {const String16& serviceName = services[i];if (IsSkipped(skippedServices, serviceName)) continue;// 调用startDumpThread 方法  type 类型为 DUMPif (startDumpThread(type, serviceName, args) == OK) {bool addSeparator = (N > 1);if (addSeparator) {writeDumpHeader(STDOUT_FILENO, serviceName, priorityFlags);}std::chrono::duration<double> elapsedDuration;size_t bytesWritten = 0;
// 输出结果status_t status =writeDump(STDOUT_FILENO, serviceName, std::chrono::milliseconds(timeoutArgMs),asProto, elapsedDuration, bytesWritten);==========
// 调用startDumpThread 方法  type 类型为 DUMPstatus_t Dumpsys::startDumpThread(Type type, const String16& serviceName,const Vector<String16>& args) {// 找到对应服务的客户端sp<IBinder> service = sm_->checkService(serviceName);if (service == nullptr) {std::cerr << "Can't find service: " << serviceName << std::endl;return NAME_NOT_FOUND;}int sfd[2];
// 管道通信if (pipe(sfd) != 0) {std::cerr << "Failed to create pipe to dump service info for " << serviceName << ": "<< strerror(errno) << std::endl;return -errno;}redirectFd_ = unique_fd(sfd[0]);unique_fd remote_end(sfd[1]);sfd[0] = sfd[1] = -1;// dump blocks until completion, so spawn a thread..activeThread_ = std::thread([=, remote_end{std::move(remote_end)}]() mutable {status_t err = 0;switch (type) {case Type::DUMP:
// binder 通信调用dump 方法err = service->dump(remote_end.get(), args);break;

// binder 通信调用dump 方法

/frameworks/native/libs/binder/BpBinder.cpp

status_t BpBinder::dump(int fd, const Vector<String16>& args)
{Parcel send;Parcel reply;
// send 封装了文件描述符send.writeFileDescriptor(fd);const size_t numArgs = args.size();send.writeInt32(numArgs);for (size_t i = 0; i < numArgs; i++) {
// 保存了 args 参数send.writeString16(args[i]);}status_t err = transact(DUMP_TRANSACTION, send, &reply);return err;
}=========
status_t BpBinder::transact(uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
{// Once a binder has died, it will never come back to life.if (mAlive) {bool privateVendor = flags & FLAG_PRIVATE_VENDOR;// don't send userspace flags to the kernelflags = flags & ~FLAG_PRIVATE_VENDOR;// user transactions require a given stability levelif (code >= FIRST_CALL_TRANSACTION && code <= LAST_CALL_TRANSACTION) {using android::internal::Stability;auto stability = Stability::get(this);auto required = privateVendor ? Stability::VENDOR : Stability::kLocalStability;if (CC_UNLIKELY(!Stability::check(stability, required))) {ALOGE("Cannot do a user transaction on a %s binder in a %s context.",Stability::stabilityString(stability).c_str(),Stability::stabilityString(required).c_str());return BAD_TYPE;}}
/// 通过binder 驱动去找到对端服务器端status_t status = IPCThreadState::self()->transact(mHandle, code, data, reply, flags);

===========服务端执行流程===========

走到服务器端的 BBinder

/frameworks/base/core/jni/android_util_Binder.cpp

// javabinder 继承了 BBinder
class JavaBBinder : public BBinder
{
public:JavaBBinder(JNIEnv* env, jobject /* Java Binder */ object): mVM(jnienv_to_javavm(env)), mObject(env->NewGlobalRef(object)){。。。status_t onTransact(uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags = 0) override{JNIEnv* env = javavm_to_jnienv(mVM);ALOGV("onTransact() on %p calling object %p in env %p vm %p\n", this, mObject, env, mVM);IPCThreadState* thread_state = IPCThreadState::self();const int32_t strict_policy_before = thread_state->getStrictModePolicy();//printf("Transact from %p to Java code sending: ", this);//data.print();//printf("\n");// 调用java 层的execTransact 方法jboolean res = env->CallBooleanMethod(mObject, gBinderOffsets.mExecTransact,code, reinterpret_cast<jlong>(&data), reinterpret_cast<jlong>(reply), flags);// mExecTransact 为java 层的 execTransact 方法gBinderOffsets.mExecTransact = GetMethodIDOrDie(env, clazz, "execTransact", "(IJJI)Z");

// 调用java 层的execTransact 方法

/frameworks/base/core/java/android/os/Binder.java

    @UnsupportedAppUsageprivate boolean execTransact(int code, long dataObj, long replyObj,int flags) {// At that point, the parcel request headers haven't been parsed so we do not know what// WorkSource the caller has set. Use calling uid as the default.final int callingUid = Binder.getCallingUid();final long origWorkSource = ThreadLocalWorkSource.setUid(callingUid);try {return execTransactInternal(code, dataObj, replyObj, flags, callingUid);===========private boolean execTransactInternal(int code, long dataObj, long replyObj, int flags,int callingUid) {final BinderInternal.Observer observer = sObserver;final CallSession callSession =observer != null ? observer.callStarted(this, code, UNSET_WORKSOURCE) : null;Parcel data = Parcel.obtain(dataObj);Parcel reply = Parcel.obtain(replyObj);boolean res;// Log any exceptions as warnings, don't silently suppress them.// If the call was FLAG_ONEWAY then these exceptions disappear into the ether.final boolean tracingEnabled = Binder.isTracingEnabled();try {if ((flags & FLAG_COLLECT_NOTED_APP_OPS) != 0) {AppOpsManager.startNotedAppOpsCollection(callingUid);try {res = onTransact(code, data, reply, flags);} finally {AppOpsManager.finishNotedAppOpsCollection();}} else {
// 调用 onTransact 方法res = onTransact(code, data, reply, flags);}=============protected boolean onTransact(int code, @NonNull Parcel data, @Nullable Parcel reply,int flags) throws RemoteException {// 如果是dump 命令,则执行 dump 方法} else if (code == DUMP_TRANSACTION) {ParcelFileDescriptor fd = data.readFileDescriptor();String[] args = data.readStringArray();if (fd != null) {try {dump(fd.getFileDescriptor(), args);// 如果是 adb shell cmd,则调用 shellCommand 方法} else if (code == SHELL_COMMAND_TRANSACTION) {ParcelFileDescriptor in = data.readFileDescriptor();ParcelFileDescriptor out = data.readFileDescriptor();ParcelFileDescriptor err = data.readFileDescriptor();String[] args = data.readStringArray();ShellCallback shellCallback = ShellCallback.CREATOR.createFromParcel(data);ResultReceiver resultReceiver = ResultReceiver.CREATOR.createFromParcel(data);try {if (out != null) {shellCommand(in != null ? in.getFileDescriptor() : null,out.getFileDescriptor(),err != null ? err.getFileDescriptor() : out.getFileDescriptor(),args, shellCallback, resultReceiver);}=========public void dump(@NonNull FileDescriptor fd, @Nullable String[] args) {FileOutputStream fout = new FileOutputStream(fd);PrintWriter pw = new FastPrintWriter(fout);try {doDump(fd, pw, args);=========void doDump(FileDescriptor fd, PrintWriter pw, String[] args) {final String disabled = sDumpDisabled;if (disabled == null) {try {dump(fd, pw, args);

 由 aidl 自动生成的  IActivityManager.Stub 是继承于Binder 对象的


public IActivityManager IRemoteService extends android.os.IInterface {public static abstract class Stub extends android.os.Binder implements xxx

而 ActivityManagerService 是继承了 IActivityManager.Stub,所以走到其 dump(fd, pw, args) 方法

/frameworks/base/services/core/java/com/android/server/am/ActivityManagerService.java

10510      @Override
10511      protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
// 传入参数是 mPriorityDumper
10512          PriorityDump.dump(mPriorityDumper, fd, pw, args);
10513      }=============

调用 PriorityDump 工具类的dump 方法

/frameworks/base/services/core/java/com/android/server/utils/PriorityDump.java 

    public static void dump(PriorityDumper dumper, FileDescriptor fd, PrintWriter pw,String[] args) {boolean asProto = false;@PriorityType int priority = PRIORITY_TYPE_INVALID;
...String[] strippedArgs = new String[args.length];int strippedCount = 0;for (int argIndex = 0; argIndex < args.length; argIndex++) {if (args[argIndex].equals(PROTO_ARG)) {asProto = true;} else if (args[argIndex].equals(PRIORITY_ARG)) {if (argIndex + 1 < args.length) {argIndex++;priority = getPriorityType(args[argIndex]);}} else {
// 分离出命令args 来strippedArgs[strippedCount++] = args[argIndex];}}if (strippedCount < args.length) {strippedArgs = Arrays.copyOf(strippedArgs, strippedCount);}switch (priority) {
...default: {
// 调用 PriorityDumper  去dumpdumper.dump(fd, pw, strippedArgs, asProto);return;}}

// 调用 PriorityDumper  去dump

/frameworks/base/services/core/java/com/android/server/am/ActivityManagerService.java

674      private final PriorityDump.PriorityDumper mPriorityDumper = new PriorityDump.PriorityDumper() {
675          @Override
676          public void dumpCritical(FileDescriptor fd, PrintWriter pw, String[] args,
677                  boolean asProto) {
678              if (asProto) return;
679              doDump(fd, pw, new String[]{"activities"}, asProto);
680              doDump(fd, pw, new String[]{"service", "all-platform-critical"}, asProto);
681          }。。。。。
687  
688          @Override
689          public void dump(FileDescriptor fd, PrintWriter pw, String[] args, boolean asProto) {// dump 方法
690              doDump(fd, pw, args, asProto);
691          }
692      };========

// dump 方法

10666      private void doDump(FileDescriptor fd, PrintWriter pw, String[] args, boolean useProto) {
10667          if (!DumpUtils.checkDumpAndUsageStatsPermission(mContext, TAG, pw)) return;
10668  
10669          boolean dumpAll = false;
10670          boolean dumpClient = false;
10671          boolean dumpCheckin = false;
10672          boolean dumpCheckinFormat = false;
10673          boolean dumpNormalPriority = false;
10674          boolean dumpVisibleStacksOnly = false;
10675          boolean dumpFocusedStackOnly = false;
10676          String dumpPackage = null;
10677  
10678          int opti = 0;
10679          while (opti < args.length) {
10680              String opt = args[opti];
10681              if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
10682                  break;
10683              }
10684              opti++;// 先判断输入命令是否有 -a ,如果有则dump全部信息
10685              if ("-a".equals(opt)) {
10686                  dumpAll = true;。。。// useProto 为false
10718          if (useProto) {
10719              final ProtoOutputStream proto = new ProtoOutputStream(fd);
10720              String cmd = opti < args.length ? args[opti] : "";
10721              opti++;
。。。
10786          int dumpAppId = getAppId(dumpPackage);
10787          boolean more = false;
10788          // Is the caller requesting to dump a particular piece of data?
10789          if (opti < args.length) {
10790              String cmd = args[opti];
10791              opti++;// DUMP_ACTIVITIES_CMD 为 activities,DUMP_ACTIVITIES_SHORT_CMD 为a
10792              if (DUMP_ACTIVITIES_CMD.equals(cmd) || DUMP_ACTIVITIES_SHORT_CMD.equals(cmd)
10793                      || DUMP_LASTANR_CMD.equals(cmd) || DUMP_LASTANR_TRACES_CMD.equals(cmd)
10794                      || DUMP_STARTER_CMD.equals(cmd) || DUMP_CONTAINERS_CMD.equals(cmd)
10795                      || DUMP_RECENTS_CMD.equals(cmd) || DUMP_RECENTS_SHORT_CMD.equals(cmd)) {
10796                  mAtmInternal.dump(
10797                          cmd, fd, pw, args, opti, true /* dumpAll */, dumpClient, dumpPackage);

调用 ActivityTaskManagerService 的方法

6979          @Override
6980          public void dump(String cmd, FileDescriptor fd, PrintWriter pw, String[] args, int opti,
6981                  boolean dumpAll, boolean dumpClient, String dumpPackage) {
6982              synchronized (mGlobalLock) {
6983                  if (DUMP_ACTIVITIES_CMD.equals(cmd) || DUMP_ACTIVITIES_SHORT_CMD.equals(cmd)) {
6984                      dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage);

2. 分析 adb shell cmd 实现过程

adb shell cmd activity -h

/frameworks/native/cmds/cmd/main.cpp

int main(int argc, char* const argv[]) {signal(SIGPIPE, SIG_IGN);std::vector<std::string_view> arguments;arguments.reserve(argc - 1);// 0th argument is a program name, skipping.for (int i = 1; i < argc; ++i) {arguments.emplace_back(argv[i]);}// 调用 cmdMain 方法return cmdMain(arguments, android::aout, android::aerr, STDIN_FILENO, STDOUT_FILENO,STDERR_FILENO, RunMode::kStandalone);

// 调用 cmdMain 方法

/frameworks/native/cmds/cmd/cmd.cpp

int cmdMain(const std::vector<std::string_view>& argv, TextOutput& outputLog, TextOutput& errorLog,int in, int out, int err, RunMode runMode) {sp<ProcessState> proc = ProcessState::self();proc->startThreadPool();#if DEBUGALOGD("cmd: starting");
#endifsp<IServiceManager> sm = defaultServiceManager();int argc = argv.size();// 如果命令是:adb shell cmd -l 则列出所有的service 的名字if ((argc == 1) && (argv[0] == "-l")) {Vector<String16> services = sm->listServices();services.sort(sort_func);
// 会打印出下列string 值outputLog << "Currently running services:" << endl;for (size_t i=0; i<services.size(); i++) {sp<IBinder> service = sm->checkService(services[i]);if (service != nullptr) {outputLog << "  " << services[i] << endl;}}return 0;}// 这里是 false 的bool waitForService = ((argc > 1) && (argv[0] == "-w"));
// index 的值为 0int serviceIdx = (waitForService) ? 1 : 0;
// cmd 为第一个参数为 servicenameconst auto cmd = argv[serviceIdx];Vector<String16> args;
// 通过cmd 获取到 servicenameString16 serviceName = String16(cmd.data(), cmd.size());// 遍历service 后面的参数,保存到 args 中for (int i = serviceIdx + 1; i < argc; i++) {args.add(String16(argv[i].data(), argv[i].size()));}sp<IBinder> service;if(waitForService) {service = sm->waitForService(serviceName);} else {// 获取到对应的serviceservice = sm->checkService(serviceName);}。。。// TODO: block until a result is returned to MyResultReceiver.
// 调用 shellCommand 方法status_t error = IBinder::shellCommand(service, in, out, err, args, cb, result);if (error < 0) {

// 调用 shellCommand 方法

 /frameworks/native/libs/binder/Binder.cpp

status_t IBinder::shellCommand(const sp<IBinder>& target, int in, int out, int err,Vector<String16>& args, const sp<IShellCallback>& callback,const sp<IResultReceiver>& resultReceiver)
{Parcel send;Parcel reply;
// 将传入的参数封装为 Parcel send.writeFileDescriptor(in);send.writeFileDescriptor(out);send.writeFileDescriptor(err);const size_t numArgs = args.size();send.writeInt32(numArgs);for (size_t i = 0; i < numArgs; i++) {send.writeString16(args[i]);}send.writeStrongBinder(callback != nullptr ? IInterface::asBinder(callback) : nullptr);send.writeStrongBinder(resultReceiver != nullptr ? IInterface::asBinder(resultReceiver) : nullptr);// 调用对应的service 的客户端去binder 通信return target->transact(SHELL_COMMAND_TRANSACTION, send, &reply);
}

如前面的分析也会调用 java 层的execTransact 方法

/frameworks/base/core/java/android/os/Binder.java

    private boolean execTransactInternal(int code, long dataObj, long replyObj, int flags,int callingUid) {final BinderInternal.Observer observer = sObserver;final CallSession callSession =observer != null ? observer.callStarted(this, code, UNSET_WORKSOURCE) : null;Parcel data = Parcel.obtain(dataObj);Parcel reply = Parcel.obtain(replyObj);boolean res;// Log any exceptions as warnings, don't silently suppress them.// If the call was FLAG_ONEWAY then these exceptions disappear into the ether.final boolean tracingEnabled = Binder.isTracingEnabled();try {if ((flags & FLAG_COLLECT_NOTED_APP_OPS) != 0) {AppOpsManager.startNotedAppOpsCollection(callingUid);try {res = onTransact(code, data, reply, flags);} finally {AppOpsManager.finishNotedAppOpsCollection();}} else {
// 调用 onTransact 方法res = onTransact(code, data, reply, flags);}=============protected boolean onTransact(int code, @NonNull Parcel data, @Nullable Parcel reply,int flags) throws RemoteException {// 如果是dump 命令,则执行 dump 方法} else if (code == DUMP_TRANSACTION) {ParcelFileDescriptor fd = data.readFileDescriptor();String[] args = data.readStringArray();if (fd != null) {try {dump(fd.getFileDescriptor(), args);// 如果是 adb shell cmd,则调用 shellCommand 方法} else if (code == SHELL_COMMAND_TRANSACTION) {ParcelFileDescriptor in = data.readFileDescriptor();ParcelFileDescriptor out = data.readFileDescriptor();ParcelFileDescriptor err = data.readFileDescriptor();String[] args = data.readStringArray();ShellCallback shellCallback = ShellCallback.CREATOR.createFromParcel(data);ResultReceiver resultReceiver = ResultReceiver.CREATOR.createFromParcel(data);try {if (out != null) {shellCommand(in != null ? in.getFileDescriptor() : null,out.getFileDescriptor(),err != null ? err.getFileDescriptor() : out.getFileDescriptor(),args, shellCallback, resultReceiver);}================
// shellCommand 方法的实现public void shellCommand(@Nullable FileDescriptor in, @Nullable FileDescriptor out,@Nullable FileDescriptor err,@NonNull String[] args, @Nullable ShellCallback callback,@NonNull ResultReceiver resultReceiver) throws RemoteException {// 同样去调用 ams 的 onShellCommand 方法onShellCommand(in, out, err, args, callback, resultReceiver);}

// 同样去调用 ams 的 onShellCommand 方法

/frameworks/base/services/core/java/com/android/server/am/ActivityManagerService.java

10502      @Override
10503      public void onShellCommand(FileDescriptor in, FileDescriptor out,
10504              FileDescriptor err, String[] args, ShellCallback callback,
10505              ResultReceiver resultReceiver) {// 创建 ActivityManagerShellCommand 对象去执行 exec
10506          (new ActivityManagerShellCommand(this, false)).exec(
10507                  this, in, out, err, args, callback, resultReceiver);
10508      }

// 创建 ActivityManagerShellCommand 对象去执行 exec

/frameworks/base/services/core/java/com/android/server/am/ActivityManagerShellCommand.java

// 继承了 ShellCommand  方法
124  final class ActivityManagerShellCommand extends ShellCommand {
125      public static final String NO_CLASS_ERROR_CODE = "Error type 3";

/frameworks/base/core/java/android/os/ShellCommand.java

// ShellCommand 又继承了 BasicShellCommandHandler 
36  public abstract class ShellCommand extends BasicShellCommandHandler {
37      private ShellCallback mShellCallback;
38      private ResultReceiver mResultReceiver;
39  // 执行 exec 方法
40      public int exec(Binder target, FileDescriptor in, FileDescriptor out, FileDescriptor err,
41              String[] args, ShellCallback callback, ResultReceiver resultReceiver) {
42          mShellCallback = callback;
43          mResultReceiver = resultReceiver;// 调用父类BasicShellCommandHandler 的 exec 方法
44          final int result = super.exec(target, in, out, err, args);
45  // 发送结果给cmd 进程
46          if (mResultReceiver != null) {
47              mResultReceiver.send(result, null);
48          }
49  
50          return result;
51      }

// 调用父类BasicShellCommandHandler 的 exec 方法

 /frameworks/base/core/java/android/os/BasicShellCommandHandler.java

75      public int exec(Binder target, FileDescriptor in, FileDescriptor out, FileDescriptor err,
76              String[] args) {
77          String cmd;
78          int start;
79          if (args != null && args.length > 0) {// 获取adb shell cmd activity 后面的第一个参数 
80              cmd = args[0];
81              start = 1;
82          } else {
83              cmd = null;
84              start = 0;
85          }
86          init(target, in, out, err, args, start);
87          mCmd = cmd;
88  
89          if (DEBUG) {
90              RuntimeException here = new RuntimeException("here");
91              here.fillInStackTrace();
92              Log.d(TAG, "Starting command " + mCmd + " on " + mTarget, here);
93              Log.d(TAG, "Calling uid=" + Binder.getCallingUid()
94                      + " pid=" + Binder.getCallingPid());
95          }
96          int res = -1;
97          try {// 回调子类ActivityManagerShellCommand.java的方法 onCommand
98              res = onCommand(mCmd);
99              if (DEBUG) Log.d(TAG, "Executed command " + mCmd + " on " + mTarget);

// 回调子类ActivityManagerShellCommand.java的方法 onCommand

/frameworks/base/services/core/java/com/android/server/am/ActivityManagerShellCommand.java

    @Overridepublic int onCommand(String cmd) {if (cmd == null) {return handleDefaultCommands(cmd);}final PrintWriter pw = getOutPrintWriter();try {switch (cmd) {// 启动activity 命令case "start":case "start-activity":return runStartActivity(pw);// 启动service 的命令case "startservice":case "start-service":return runStartService(pw, false);//如果都不满足上述情形,则执行 default:return handleDefaultCommands(cmd);}

/frameworks/base/core/java/android/os/BasicShellCommandHandler.java

// 调用到 父类的方法
289      public int handleDefaultCommands(String cmd) {
290          if (cmd == null || "help".equals(cmd) || "-h".equals(cmd)) {
291              onHelp();

又调用到子类的方法

/frameworks/base/services/core/java/com/android/server/am/ActivityManagerShellCommand.java

    @Overridepublic void onHelp() {PrintWriter pw = getOutPrintWriter();
// mDumping 为falsedumpHelp(pw, mDumping);}============static void dumpHelp(PrintWriter pw, boolean dumping) {if (dumping) {
。。。。。} else {pw.println("Activity manager (activity) commands:");pw.println("  help");pw.println("      Print this help text.");pw.println("  start-activity [-D] [-N] [-W] [-P <FILE>] [--start-profiler <FILE>]");

总结:

adb shell cmd 命令:

1. 对应命令会调用到service 的  onCommand

2. 帮助命令会调用到  onHelp

adb shell dumpsys 命令:

对应命令调用到 service 的 dump方法

这篇关于【安卓12源码】adb 的dumpsys和cmd实现原理的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/487069

相关文章

hdu1043(八数码问题,广搜 + hash(实现状态压缩) )

利用康拓展开将一个排列映射成一个自然数,然后就变成了普通的广搜题。 #include<iostream>#include<algorithm>#include<string>#include<stack>#include<queue>#include<map>#include<stdio.h>#include<stdlib.h>#include<ctype.h>#inclu

深入探索协同过滤:从原理到推荐模块案例

文章目录 前言一、协同过滤1. 基于用户的协同过滤(UserCF)2. 基于物品的协同过滤(ItemCF)3. 相似度计算方法 二、相似度计算方法1. 欧氏距离2. 皮尔逊相关系数3. 杰卡德相似系数4. 余弦相似度 三、推荐模块案例1.基于文章的协同过滤推荐功能2.基于用户的协同过滤推荐功能 前言     在信息过载的时代,推荐系统成为连接用户与内容的桥梁。本文聚焦于

JAVA智听未来一站式有声阅读平台听书系统小程序源码

智听未来,一站式有声阅读平台听书系统 🌟&nbsp;开篇:遇见未来,从“智听”开始 在这个快节奏的时代,你是否渴望在忙碌的间隙,找到一片属于自己的宁静角落?是否梦想着能随时随地,沉浸在知识的海洋,或是故事的奇幻世界里?今天,就让我带你一起探索“智听未来”——这一站式有声阅读平台听书系统,它正悄悄改变着我们的阅读方式,让未来触手可及! 📚&nbsp;第一站:海量资源,应有尽有 走进“智听

【C++】_list常用方法解析及模拟实现

相信自己的力量,只要对自己始终保持信心,尽自己最大努力去完成任何事,就算事情最终结果是失败了,努力了也不留遗憾。💓💓💓 目录   ✨说在前面 🍋知识点一:什么是list? •🌰1.list的定义 •🌰2.list的基本特性 •🌰3.常用接口介绍 🍋知识点二:list常用接口 •🌰1.默认成员函数 🔥构造函数(⭐) 🔥析构函数 •🌰2.list对象

【Prometheus】PromQL向量匹配实现不同标签的向量数据进行运算

✨✨ 欢迎大家来到景天科技苑✨✨ 🎈🎈 养成好习惯,先赞后看哦~🎈🎈 🏆 作者简介:景天科技苑 🏆《头衔》:大厂架构师,华为云开发者社区专家博主,阿里云开发者社区专家博主,CSDN全栈领域优质创作者,掘金优秀博主,51CTO博客专家等。 🏆《博客》:Python全栈,前后端开发,小程序开发,人工智能,js逆向,App逆向,网络系统安全,数据分析,Django,fastapi

hdu4407(容斥原理)

题意:给一串数字1,2,......n,两个操作:1、修改第k个数字,2、查询区间[l,r]中与n互质的数之和。 解题思路:咱一看,像线段树,但是如果用线段树做,那么每个区间一定要记录所有的素因子,这样会超内存。然后我就做不来了。后来看了题解,原来是用容斥原理来做的。还记得这道题目吗?求区间[1,r]中与p互质的数的个数,如果不会的话就先去做那题吧。现在这题是求区间[l,r]中与n互质的数的和

让树莓派智能语音助手实现定时提醒功能

最初的时候是想直接在rasa 的chatbot上实现,因为rasa本身是带有remindschedule模块的。不过经过一番折腾后,忽然发现,chatbot上实现的定时,语音助手不一定会有响应。因为,我目前语音助手的代码设置了长时间无应答会结束对话,这样一来,chatbot定时提醒的触发就不会被语音助手获悉。那怎么让语音助手也具有定时提醒功能呢? 我最后选择的方法是用threading.Time

Android实现任意版本设置默认的锁屏壁纸和桌面壁纸(两张壁纸可不一致)

客户有些需求需要设置默认壁纸和锁屏壁纸  在默认情况下 这两个壁纸是相同的  如果需要默认的锁屏壁纸和桌面壁纸不一样 需要额外修改 Android13实现 替换默认桌面壁纸: 将图片文件替换frameworks/base/core/res/res/drawable-nodpi/default_wallpaper.*  (注意不能是bmp格式) 替换默认锁屏壁纸: 将图片资源放入vendo

安卓链接正常显示,ios#符被转义%23导致链接访问404

原因分析: url中含有特殊字符 中文未编码 都有可能导致URL转换失败,所以需要对url编码处理  如下: guard let allowUrl = webUrl.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) else {return} 后面发现当url中有#号时,会被误伤转义为%23,导致链接无法访问

C#实战|大乐透选号器[6]:实现实时显示已选择的红蓝球数量

哈喽,你好啊,我是雷工。 关于大乐透选号器在前面已经记录了5篇笔记,这是第6篇; 接下来实现实时显示当前选中红球数量,蓝球数量; 以下为练习笔记。 01 效果演示 当选择和取消选择红球或蓝球时,在对应的位置显示实时已选择的红球、蓝球的数量; 02 标签名称 分别设置Label标签名称为:lblRedCount、lblBlueCount