当前位置: 首页 > news >正文

Chromium 中chrome.cookies扩展接口c++实现分析

chrome.cookies

使用 chrome.cookies API 查询和修改 Cookie,并在 Cookie 发生更改时收到通知。

更多参考官网定义:chrome.cookies  |  API  |  Chrome for Developers (google.cn)

本文以加载一个清理cookies功能扩展为例 https://github.com/GoogleChrome/chrome-extensions-samples/tree/main/api-samples/cookies/cookie-clearer

 摘自官网扩展例子:

manifest.json

{"name": "Cookie Clearer","manifest_version": 3,"version": "1.0","description": "Uses the chrome.cookies API by letting a user delete their cookies via a popup.","permissions": ["cookies"],"host_permissions": ["<all_urls>"],"action": {"default_popup": "popup.html"}
}

popup.js

const form = document.getElementById('control-row');
const input = document.getElementById('input');
const message = document.getElementById('message');// The async IIFE is necessary because Chrome <89 does not support top level await.
(async function initPopupWindow() {let [tab] = await chrome.tabs.query({ active: true, currentWindow: true });if (tab?.url) {try {let url = new URL(tab.url);input.value = url.hostname;} catch {// ignore}}input.focus();
})();form.addEventListener('submit', handleFormSubmit);async function handleFormSubmit(event) {event.preventDefault();clearMessage();let url = stringToUrl(input.value);if (!url) {setMessage('Invalid URL');return;}let message = await deleteDomainCookies(url.hostname);setMessage(message);
}function stringToUrl(input) {// Start with treating the provided value as a URLtry {return new URL(input);} catch {// ignore}// If that fails, try assuming the provided input is an HTTP hosttry {return new URL('http://' + input);} catch {// ignore}// If that fails ¯\_(ツ)_/¯return null;
}async function deleteDomainCookies(domain) {let cookiesDeleted = 0;try {const cookies = await chrome.cookies.getAll({ domain });if (cookies.length === 0) {return 'No cookies found';}let pending = cookies.map(deleteCookie);await Promise.all(pending);cookiesDeleted = pending.length;} catch (error) {return `Unexpected error: ${error.message}`;}return `Deleted ${cookiesDeleted} cookie(s).`;
}function deleteCookie(cookie) {// Cookie deletion is largely modeled off of how deleting cookies works when using HTTP headers.// Specific flags on the cookie object like `secure` or `hostOnly` are not exposed for deletion// purposes. Instead, cookies are deleted by URL, name, and storeId. Unlike HTTP headers, though,// we don't have to delete cookies by setting Max-Age=0; we have a method for that ;)//// To remove cookies set with a Secure attribute, we must provide the correct protocol in the// details object's `url` property.// https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie#Secureconst protocol = cookie.secure ? 'https:' : 'http:';// Note that the final URL may not be valid. The domain value for a standard cookie is prefixed// with a period (invalid) while cookies that are set to `cookie.hostOnly == true` do not have// this prefix (valid).// https://developer.chrome.com/docs/extensions/reference/cookies/#type-Cookieconst cookieUrl = `${protocol}//${cookie.domain}${cookie.path}`;return chrome.cookies.remove({url: cookieUrl,name: cookie.name,storeId: cookie.storeId});
}function setMessage(str) {message.textContent = str;message.hidden = false;
}function clearMessage() {message.hidden = true;message.textContent = '';
}

popup.html

<!doctype html>
<html><head><script src="popup.js" type="module"></script></head><body><form id="control-row"><label for="input">Domain:</label><input type="text" id="input" /><br /><button id="go">Clear Cookies</button></form><span id="message" hidden></span></body>
</html>

一、看下c++提供 的cookies接口定义  chrome\common\extensions\api\cookies.json

// Copyright 2012 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.[{"namespace": "cookies","description": "Use the <code>chrome.cookies</code> API to query and modify cookies, and to be notified when they change.","types": [{"id": "SameSiteStatus","type": "string","enum": ["no_restriction", "lax", "strict", "unspecified"],"description": "A cookie's 'SameSite' state (https://tools.ietf.org/html/draft-west-first-party-cookies). 'no_restriction' corresponds to a cookie set with 'SameSite=None', 'lax' to 'SameSite=Lax', and 'strict' to 'SameSite=Strict'. 'unspecified' corresponds to a cookie set without the SameSite attribute."},{"id": "CookiePartitionKey","type": "object","description": "Represents a partitioned cookie's partition key.","properties": {"topLevelSite": {"type": "string", "optional": true, "description": "The top-level site the partitioned cookie is available in."}}},{"id": "Cookie","type": "object","description": "Represents information about an HTTP cookie.","properties": {"name": {"type": "string", "description": "The name of the cookie."},"value": {"type": "string", "description": "The value of the cookie."},"domain": {"type": "string", "description": "The domain of the cookie (e.g. \"www.google.com\", \"example.com\")."},"hostOnly": {"type": "boolean", "description": "True if the cookie is a host-only cookie (i.e. a request's host must exactly match the domain of the cookie)."},"path": {"type": "string", "description": "The path of the cookie."},"secure": {"type": "boolean", "description": "True if the cookie is marked as Secure (i.e. its scope is limited to secure channels, typically HTTPS)."},"httpOnly": {"type": "boolean", "description": "True if the cookie is marked as HttpOnly (i.e. the cookie is inaccessible to client-side scripts)."},"sameSite": {"$ref": "SameSiteStatus", "description": "The cookie's same-site status (i.e. whether the cookie is sent with cross-site requests)."},"session": {"type": "boolean", "description": "True if the cookie is a session cookie, as opposed to a persistent cookie with an expiration date."},"expirationDate": {"type": "number", "optional": true, "description": "The expiration date of the cookie as the number of seconds since the UNIX epoch. Not provided for session cookies."},"storeId": {"type": "string", "description": "The ID of the cookie store containing this cookie, as provided in getAllCookieStores()."},"partitionKey": {"$ref": "CookiePartitionKey", "optional": true, "description": "The partition key for reading or modifying cookies with the Partitioned attribute."}}},{"id": "CookieStore","type": "object","description": "Represents a cookie store in the browser. An incognito mode window, for instance, uses a separate cookie store from a non-incognito window.","properties": {"id": {"type": "string", "description": "The unique identifier for the cookie store."},"tabIds": {"type": "array", "items": {"type": "integer"}, "description": "Identifiers of all the browser tabs that share this cookie store."}}},{"id": "OnChangedCause","type": "string","enum": ["evicted", "expired", "explicit", "expired_overwrite", "overwrite"],"description": "The underlying reason behind the cookie's change. If a cookie was inserted, or removed via an explicit call to \"chrome.cookies.remove\", \"cause\" will be \"explicit\". If a cookie was automatically removed due to expiry, \"cause\" will be \"expired\". If a cookie was removed due to being overwritten with an already-expired expiration date, \"cause\" will be set to \"expired_overwrite\".  If a cookie was automatically removed due to garbage collection, \"cause\" will be \"evicted\".  If a cookie was automatically removed due to a \"set\" call that overwrote it, \"cause\" will be \"overwrite\". Plan your response accordingly."},{"id": "CookieDetails","type": "object","description": "Details to identify the cookie.","properties": {"url": {"type": "string", "description": "The URL with which the cookie to access is associated. This argument may be a full URL, in which case any data following the URL path (e.g. the query string) is simply ignored. If host permissions for this URL are not specified in the manifest file, the API call will fail."},"name": {"type": "string", "description": "The name of the cookie to access."},"storeId": {"type": "string", "optional": true, "description": "The ID of the cookie store in which to look for the cookie. By default, the current execution context's cookie store will be used."},"partitionKey": {"$ref": "CookiePartitionKey", "optional": true, "description": "The partition key for reading or modifying cookies with the Partitioned attribute."}}}],"functions": [{"name": "get","type": "function","description": "Retrieves information about a single cookie. If more than one cookie of the same name exists for the given URL, the one with the longest path will be returned. For cookies with the same path length, the cookie with the earliest creation time will be returned.","parameters": [{"name": "details","$ref": "CookieDetails"}],"returns_async": {"name": "callback","parameters": [{"name": "cookie", "$ref": "Cookie", "optional": true, "description": "Contains details about the cookie. This parameter is null if no such cookie was found."}]}},{"name": "getAll","type": "function","description": "Retrieves all cookies from a single cookie store that match the given information.  The cookies returned will be sorted, with those with the longest path first.  If multiple cookies have the same path length, those with the earliest creation time will be first. Only retrieves cookies for domains which the extension has host permissions to.","parameters": [{"type": "object","name": "details","description": "Information to filter the cookies being retrieved.","properties": {"url": {"type": "string", "optional": true, "description": "Restricts the retrieved cookies to those that would match the given URL."},"name": {"type": "string", "optional": true, "description": "Filters the cookies by name."},"domain": {"type": "string", "optional": true, "description": "Restricts the retrieved cookies to those whose domains match or are subdomains of this one."},"path": {"type": "string", "optional": true, "description": "Restricts the retrieved cookies to those whose path exactly matches this string."},"secure": {"type": "boolean", "optional": true, "description": "Filters the cookies by their Secure property."},"session": {"type": "boolean", "optional": true, "description": "Filters out session vs. persistent cookies."},"storeId": {"type": "string", "optional": true, "description": "The cookie store to retrieve cookies from. If omitted, the current execution context's cookie store will be used."},"partitionKey": {"$ref": "CookiePartitionKey", "optional": true, "description": "The partition key for reading or modifying cookies with the Partitioned attribute."}}}],"returns_async": {"name": "callback","parameters": [{"name": "cookies", "type": "array", "items": {"$ref": "Cookie"}, "description": "All the existing, unexpired cookies that match the given cookie info."}]}},{"name": "set","type": "function","description": "Sets a cookie with the given cookie data; may overwrite equivalent cookies if they exist.","parameters": [{"type": "object","name": "details","description": "Details about the cookie being set.","properties": {"url": {"type": "string", "description": "The request-URI to associate with the setting of the cookie. This value can affect the default domain and path values of the created cookie. If host permissions for this URL are not specified in the manifest file, the API call will fail."},"name": {"type": "string", "optional": true, "description": "The name of the cookie. Empty by default if omitted."},"value": {"type": "string", "optional": true, "description": "The value of the cookie. Empty by default if omitted."},"domain": {"type": "string", "optional": true, "description": "The domain of the cookie. If omitted, the cookie becomes a host-only cookie."},"path": {"type": "string", "optional": true, "description": "The path of the cookie. Defaults to the path portion of the url parameter."},"secure": {"type": "boolean", "optional": true, "description": "Whether the cookie should be marked as Secure. Defaults to false."},"httpOnly": {"type": "boolean", "optional": true, "description": "Whether the cookie should be marked as HttpOnly. Defaults to false."},"sameSite": {"$ref": "SameSiteStatus", "optional": true, "description": "The cookie's same-site status. Defaults to \"unspecified\", i.e., if omitted, the cookie is set without specifying a SameSite attribute."},"expirationDate": {"type": "number", "optional": true, "description": "The expiration date of the cookie as the number of seconds since the UNIX epoch. If omitted, the cookie becomes a session cookie."},"storeId": {"type": "string", "optional": true, "description": "The ID of the cookie store in which to set the cookie. By default, the cookie is set in the current execution context's cookie store."},"partitionKey": {"$ref": "CookiePartitionKey", "optional": true, "description": "The partition key for reading or modifying cookies with the Partitioned attribute."}}}],"returns_async": {"name": "callback","optional": true,"min_version": "11.0.674.0","parameters": [{"name": "cookie", "$ref": "Cookie", "optional": true, "description": "Contains details about the cookie that's been set.  If setting failed for any reason, this will be \"null\", and $(ref:runtime.lastError) will be set."}]}},{"name": "remove","type": "function","description": "Deletes a cookie by name.","parameters": [{"name": "details","$ref": "CookieDetails"}],"returns_async": {"name": "callback","optional": true,"min_version": "11.0.674.0","parameters": [{"name": "details","type": "object","description": "Contains details about the cookie that's been removed.  If removal failed for any reason, this will be \"null\", and $(ref:runtime.lastError) will be set.","optional": true,"properties": {"url": {"type": "string", "description": "The URL associated with the cookie that's been removed."},"name": {"type": "string", "description": "The name of the cookie that's been removed."},"storeId": {"type": "string", "description": "The ID of the cookie store from which the cookie was removed."},"partitionKey": {"$ref": "CookiePartitionKey", "optional": true, "description": "The partition key for reading or modifying cookies with the Partitioned attribute."}}}]}},{"name": "getAllCookieStores","type": "function","description": "Lists all existing cookie stores.","parameters": [],"returns_async": {"name": "callback","parameters": [{"name": "cookieStores", "type": "array", "items": {"$ref": "CookieStore"}, "description": "All the existing cookie stores."}]}}],"events": [{"name": "onChanged","type": "function","description": "Fired when a cookie is set or removed. As a special case, note that updating a cookie's properties is implemented as a two step process: the cookie to be updated is first removed entirely, generating a notification with \"cause\" of \"overwrite\" .  Afterwards, a new cookie is written with the updated values, generating a second notification with \"cause\" \"explicit\".","parameters": [{"type": "object","name": "changeInfo","properties": {"removed": {"type": "boolean", "description": "True if a cookie was removed."},"cookie": {"$ref": "Cookie", "description": "Information about the cookie that was set or removed."},"cause": {"min_version": "12.0.707.0", "$ref": "OnChangedCause", "description": "The underlying reason behind the cookie's change."}}}]}]}
]

同时会生成

out\Debug\gen\chrome\common\extensions\api\cookies.h

out\Debug\gen\chrome\common\extensions\api\cookies.cc

此文件是cookies.json 定义的一个c++实现,自动生成请勿手动更改【tools\json_schema_compiler\compiler.py】。

二、cookies api接口定义:

       chrome\browser\extensions\api\cookies\cookies_api.h

       chrome\browser\extensions\api\cookies\cookies_api.cc

// Copyright 2012 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.// Defines the Chrome Extensions Cookies API functions for accessing internet
// cookies, as specified in the extension API JSON.#ifndef CHROME_BROWSER_EXTENSIONS_API_COOKIES_COOKIES_API_H_
#define CHROME_BROWSER_EXTENSIONS_API_COOKIES_COOKIES_API_H_#include <memory>
#include <string>#include "base/memory/raw_ptr.h"
#include "base/values.h"
#include "chrome/browser/ui/browser_list_observer.h"
#include "chrome/common/extensions/api/cookies.h"
#include "extensions/browser/browser_context_keyed_api_factory.h"
#include "extensions/browser/event_router.h"
#include "extensions/browser/extension_function.h"
#include "mojo/public/cpp/bindings/receiver.h"
#include "mojo/public/cpp/bindings/remote.h"
#include "net/cookies/canonical_cookie.h"
#include "net/cookies/cookie_access_result.h"
#include "net/cookies/cookie_change_dispatcher.h"
#include "services/network/public/mojom/cookie_manager.mojom.h"
#include "third_party/abseil-cpp/absl/types/optional.h"
#include "url/gurl.h"class Profile;namespace extensions {// Observes CookieManager Mojo messages and routes them as events to the
// extension system.
class CookiesEventRouter : public BrowserListObserver {public:explicit CookiesEventRouter(content::BrowserContext* context);CookiesEventRouter(const CookiesEventRouter&) = delete;CookiesEventRouter& operator=(const CookiesEventRouter&) = delete;~CookiesEventRouter() override;// BrowserListObserver:void OnBrowserAdded(Browser* browser) override;private:// This helper class connects to the CookieMonster over Mojo, and relays Mojo// messages to the owning CookiesEventRouter. This rather clumsy arrangement// is necessary to differentiate which CookieMonster the Mojo message comes// from (that associated with the incognito profile vs the original profile),// since it's not possible to tell the source from inside OnCookieChange().class CookieChangeListener : public network::mojom::CookieChangeListener {public:CookieChangeListener(CookiesEventRouter* router, bool otr);CookieChangeListener(const CookieChangeListener&) = delete;CookieChangeListener& operator=(const CookieChangeListener&) = delete;~CookieChangeListener() override;// network::mojom::CookieChangeListener:void OnCookieChange(const net::CookieChangeInfo& change) override;private:raw_ptr<CookiesEventRouter> router_;bool otr_;};void MaybeStartListening();void BindToCookieManager(mojo::Receiver<network::mojom::CookieChangeListener>* receiver,Profile* profile);void OnConnectionError(mojo::Receiver<network::mojom::CookieChangeListener>* receiver);void OnCookieChange(bool otr, const net::CookieChangeInfo& change);// This method dispatches events to the extension message service.void DispatchEvent(content::BrowserContext* context,events::HistogramValue histogram_value,const std::string& event_name,base::Value::List event_args,const GURL& cookie_domain);raw_ptr<Profile> profile_;// To listen to cookie changes in both the original and the off the record// profiles, we need a pair of bindings, as well as a pair of// CookieChangeListener instances.CookieChangeListener listener_{this, false};mojo::Receiver<network::mojom::CookieChangeListener> receiver_{&listener_};CookieChangeListener otr_listener_{this, true};mojo::Receiver<network::mojom::CookieChangeListener> otr_receiver_{&otr_listener_};
};// Implements the cookies.get() extension function.
class CookiesGetFunction : public ExtensionFunction {public:DECLARE_EXTENSION_FUNCTION("cookies.get", COOKIES_GET)CookiesGetFunction();protected:~CookiesGetFunction() override;// ExtensionFunction:ResponseAction Run() override;private:void GetCookieListCallback(const net::CookieAccessResultList& cookie_list,const net::CookieAccessResultList& excluded_cookies);// Notify the extension telemetry service when API is called.void NotifyExtensionTelemetry();GURL url_;mojo::Remote<network::mojom::CookieManager> store_browser_cookie_manager_;absl::optional<api::cookies::Get::Params> parsed_args_;
};// Implements the cookies.getAll() extension function.
class CookiesGetAllFunction : public ExtensionFunction {public:DECLARE_EXTENSION_FUNCTION("cookies.getAll", COOKIES_GETALL)CookiesGetAllFunction();protected:~CookiesGetAllFunction() override;// ExtensionFunction:ResponseAction Run() override;private:// For the two different callback signatures for getting cookies for a URL vs// getting all cookies. They do the same thing.void GetAllCookiesCallback(const net::CookieList& cookie_list);void GetCookieListCallback(const net::CookieAccessResultList& cookie_list,const net::CookieAccessResultList& excluded_cookies);// Notify the extension telemetry service when API is called.void NotifyExtensionTelemetry();GURL url_;mojo::Remote<network::mojom::CookieManager> store_browser_cookie_manager_;absl::optional<api::cookies::GetAll::Params> parsed_args_;
};// Implements the cookies.set() extension function.
class CookiesSetFunction : public ExtensionFunction {public:DECLARE_EXTENSION_FUNCTION("cookies.set", COOKIES_SET)CookiesSetFunction();protected:~CookiesSetFunction() override;ResponseAction Run() override;private:void SetCanonicalCookieCallback(net::CookieAccessResult set_cookie_result);void GetCookieListCallback(const net::CookieAccessResultList& cookie_list,const net::CookieAccessResultList& excluded_cookies);enum { NO_RESPONSE, SET_COMPLETED, GET_COMPLETED } state_;GURL url_;bool success_;mojo::Remote<network::mojom::CookieManager> store_browser_cookie_manager_;absl::optional<api::cookies::Set::Params> parsed_args_;
};// Implements the cookies.remove() extension function.
class CookiesRemoveFunction : public ExtensionFunction {public:DECLARE_EXTENSION_FUNCTION("cookies.remove", COOKIES_REMOVE)CookiesRemoveFunction();protected:~CookiesRemoveFunction() override;// ExtensionFunction:ResponseAction Run() override;private:void RemoveCookieCallback(uint32_t /* num_deleted */);GURL url_;mojo::Remote<network::mojom::CookieManager> store_browser_cookie_manager_;absl::optional<api::cookies::Remove::Params> parsed_args_;
};// Implements the cookies.getAllCookieStores() extension function.
class CookiesGetAllCookieStoresFunction : public ExtensionFunction {public:DECLARE_EXTENSION_FUNCTION("cookies.getAllCookieStores",COOKIES_GETALLCOOKIESTORES)protected:~CookiesGetAllCookieStoresFunction() override {}// ExtensionFunction:ResponseAction Run() override;
};class CookiesAPI : public BrowserContextKeyedAPI, public EventRouter::Observer {public:explicit CookiesAPI(content::BrowserContext* context);CookiesAPI(const CookiesAPI&) = delete;CookiesAPI& operator=(const CookiesAPI&) = delete;~CookiesAPI() override;// KeyedService implementation.void Shutdown() override;// BrowserContextKeyedAPI implementation.static BrowserContextKeyedAPIFactory<CookiesAPI>* GetFactoryInstance();// EventRouter::Observer implementation.void OnListenerAdded(const EventListenerInfo& details) override;private:friend class BrowserContextKeyedAPIFactory<CookiesAPI>;raw_ptr<content::BrowserContext> browser_context_;// BrowserContextKeyedAPI implementation.static const char* service_name() {return "CookiesAPI";}static const bool kServiceIsNULLWhileTesting = true;// Created lazily upon OnListenerAdded.std::unique_ptr<CookiesEventRouter> cookies_event_router_;
};}  // namespace extensions#endif  // CHROME_BROWSER_EXTENSIONS_API_COOKIES_COOKIES_API_H_

三、开发者模式打开加载下扩展看下堆栈效果:

     

至此分析完毕,如果想拦截 chrome.cookies.getAll等方法在  chrome\browser\extensions\api\cookies\cookies_api.cc中更改即可。

相关文章:

Chromium 中chrome.cookies扩展接口c++实现分析

chrome.cookies 使用 chrome.cookies API 查询和修改 Cookie&#xff0c;并在 Cookie 发生更改时收到通知。 更多参考官网定义&#xff1a;chrome.cookies | API | Chrome for Developers (google.cn) 本文以加载一个清理cookies功能扩展为例 https://github.com/Google…...

excel筛选多个单元格内容

通常情况下&#xff0c;excel单元格筛选时&#xff0c;只筛选一个条件&#xff0c;如果要筛选多个条件&#xff0c;可以如下操作&#xff1a; 字符串中间用空格分隔就行。...

Instant 和 Duration 类(进行时间处理)

Instant Instant 类是 Java 8 中引入的&#xff0c;用于表示一个具体的时间点&#xff0c;它基于 UTC&#xff08;协调世界时&#xff09;时区。以下是 Instant 类的一些常用方法及其简要说明&#xff1a; now()&#xff1a;获取当前的 Instant 对象&#xff0c;表示当前时间…...

Java每日面试题(Spring)(day19)

目录 Spring的优点什么是Spring AOP&#xff1f;AOP有哪些实现方式&#xff1f;JDK动态代理和CGLIB动态代理的区别&#xff1f;Spring AOP相关术语Spring通知有哪些类型&#xff1f;什么是Spring IOC&#xff1f;Spring中Bean的作用域有哪些&#xff1f;Spring中的Bean什么时候…...

【多线程】线程池(上)

文章目录 线程池基本概念线程池的优点线程池的特点 创建线程池自定义线程池线程池的工作原理线程池源码分析内置线程池newFixedThreadPoolSingleThreadExecutornewCachedThreadPoolScheduledThreadPool 线程池的核心线程是否会被回收?拒绝策略ThreadPoolExecutor.AbortPolicyT…...

ansible 语句+jinjia2+roles

文章目录 1、when语句1、判断表达式1、比较运算符2、逻辑运算符3、根据rc的返回值判断task任务是否执行成功5、通过条件判断路径是否存在6、in 2、when和其他关键字1、block关键字2、rescue关键字3、always关键字 3、ansible循环语句1、基于列表循环(whith_items)2、基于字典循…...

【Docker项目实战】使用Docker部署HumHub社交网络平台

【Docker项目实战】使用Docker部署HumHub社交网络平台 一、HumHub介绍1.1 HumHub简介1.2 HumHub特点1.3 主要使用场景二、本次实践规划2.1 本地环境规划2.2 本次实践介绍三、本地环境检查3.1 检查Docker服务状态3.2 检查Docker版本3.3 检查docker compose 版本四、下载HumHub镜…...

“医者仁术”再进化,AI让乳腺癌筛查迎难而上

世卫组织最新数据显示&#xff0c;我国肿瘤疾病仍然呈上升趋势&#xff0c;肿瘤防控形势依然比较严峻。尤其是像乳腺癌等发病率较高的疾病&#xff0c;早诊断和早治疗意义重大&#xff0c;能够有效降低病死率。 另一方面&#xff0c;中国地域广阔且发展不平衡&#xff0c;各地…...

安卓流式布局实现记录

效果图&#xff1a; 1、导入第三方控件 implementation com.google.android:flexbox:1.1.0 2、布局中使用 <com.google.android.flexbox.FlexboxLayoutandroid:id"id/baggageFl"android:layout_width"match_parent"android:layout_height"wrap_co…...

-bash gcc command not found解决方案(CentOS操作系统)

以 CentOS7 为例&#xff0c;执行以下语句 : yum install gcc如果下载不成功&#xff0c;并且网络没有问题。 执行以下语句 : cp -r /etc/yum.repos.d /etc/yum.repos.d.bakrm -f /etc/yum.repos.d/*.repocurl -o /etc/yum.repos.d/CentOS-Base.repo http://mirrors.aliyun.…...

(二)Python输入输出函数

一、输入函数 input函数&#xff1a;用户输入的数据&#xff0c;以字符串形式返回&#xff1b;若需数值类型&#xff0c;则进行类型转换。 xinput("请入你喜欢的蔬菜&#xff1a;") print(x) 二、输出函数 print函数 输出单一数值 x666 print(x) 输出混合类型…...

从调用NCCL到深入NCCL源码

本小白目前研究GPU多卡互连的方案&#xff0c;主要参考NCCL和RCCL进行学习&#xff0c;如有错误&#xff0c;请及时指正&#xff01; 内容还在整理中&#xff0c;近期不断更新&#xff01;&#xff01; 背景介绍 在大模型高性能计算时会需要用到多卡&#xff08;GPU&#xf…...

深入理解Transformer的笔记记录(精简版本)NNLM → Word2Vec

文章的整体介绍顺序为&#xff1a; NNLM → Word2Vec → Seq2Seq → Seq2Seq with Attention → Transformer → Elmo → GPT → BERT 自然语言处理相关任务中要将自然语言交给机器学习中的算法来处理&#xff0c;通常需要将语言数学化&#xff0c;因为计算机机器只认数学符号…...

优选算法第一讲:双指针模块

优选算法第一讲&#xff1a;双指针模块 1.移动零2.复写零3.快乐数4.盛最多水的容器5.有效三角形的个数6.查找总价格为目标值的两个商品7.三数之和8.四数之和 1.移动零 链接: 移动零 下面是一个画图&#xff0c;其中&#xff0c;绿色部分标出的是重点&#xff1a; 代码实现&am…...

智能优化算法-水循环优化算法(WCA)(附源码)

目录 1.内容介绍 2.部分代码 3.实验结果 4.内容获取 1.内容介绍 水循环优化算法 (Water Cycle Algorithm, WCA) 是一种基于自然界水循环过程的元启发式优化算法&#xff0c;由Shah-Hosseini于2012年提出。WCA通过模拟水滴在河流、湖泊和海洋中的流动过程&#xff0c;以及蒸发…...

基于SpringBoot的个性化健康建议平台

1系统概述 1.1 研究背景 随着计算机技术的发展以及计算机网络的逐渐普及&#xff0c;互联网成为人们查找信息的重要场所&#xff0c;二十一世纪是信息的时代&#xff0c;所以信息的管理显得特别重要。因此&#xff0c;使用计算机来管理基于智能推荐的卫生健康系统的相关信息成为…...

Mapsui绘制WKT的示例

步骤 创建.NET Framework4.8的WPF应用在NuGet中安装Mapsui.Wpf 4.1.7添加命名空间和组件 <Window x:Class"TestMapsui.MainWindow"xmlns"http://schemas.microsoft.com/winfx/2006/xaml/presentation"xmlns:x"http://schemas.microsoft.com/winf…...

Modbus TCP 西门子PLC指令以太口地址配置以及 Poll Slave调试软件地址配置

1前言 本篇文章讲了 Modbus TCP通讯中的一些以太网端口配置和遇到的一些问题&#xff0c; 都是肝货自己测试的QAQ。 2西门子 SERVER 指令 该指令是让外界设备主动连接此PLC被动连接&#xff0c; 所以这里应该填 外界设备的IP地址。 这边 我因为是电脑的Modbus Poll 主机来…...

MySQL表的基本查询上

1&#xff0c;创建表 前面基础的文章已经讲了很多啦&#xff0c;直接上操作&#xff1a; 非常简单&#xff01;下一个&#xff01; 2&#xff0c;插入数据 1&#xff0c;全列插入 前面也说很多了&#xff0c;直接上操作&#xff1a; 以上插入和全列插入类似&#xff0c;全列…...

MySQL中什么情况下类型转换会导致索引失效

文章目录 1. 问题引入2. 准备工作3. 案例分析3.1 正常情况3.2 发生了隐式类型转换的情况 4. MySQL隐式类型转换的规则4.1 案例引入4.2 MySQL 中隐式类型转换的规则4.3 验证 MySQL 隐式类型转换的规则 5. 总结 如果对 MySQL 索引不了解&#xff0c;可以看一下我的另一篇博文&…...

Java如何权衡是使用无序的数组还是有序的数组

在 Java 中,选择有序数组还是无序数组取决于具体场景的性能需求与操作特点。以下是关键权衡因素及决策指南: ⚖️ 核心权衡维度 维度有序数组无序数组查询性能二分查找 O(log n) ✅线性扫描 O(n) ❌插入/删除需移位维护顺序 O(n) ❌直接操作尾部 O(1) ✅内存开销与无序数组相…...

FastAPI 教程:从入门到实践

FastAPI 是一个现代、快速&#xff08;高性能&#xff09;的 Web 框架&#xff0c;用于构建 API&#xff0c;支持 Python 3.6。它基于标准 Python 类型提示&#xff0c;易于学习且功能强大。以下是一个完整的 FastAPI 入门教程&#xff0c;涵盖从环境搭建到创建并运行一个简单的…...

2024年赣州旅游投资集团社会招聘笔试真

2024年赣州旅游投资集团社会招聘笔试真 题 ( 满 分 1 0 0 分 时 间 1 2 0 分 钟 ) 一、单选题(每题只有一个正确答案,答错、不答或多答均不得分) 1.纪要的特点不包括()。 A.概括重点 B.指导传达 C. 客观纪实 D.有言必录 【答案】: D 2.1864年,()预言了电磁波的存在,并指出…...

JVM垃圾回收机制全解析

Java虚拟机&#xff08;JVM&#xff09;中的垃圾收集器&#xff08;Garbage Collector&#xff0c;简称GC&#xff09;是用于自动管理内存的机制。它负责识别和清除不再被程序使用的对象&#xff0c;从而释放内存空间&#xff0c;避免内存泄漏和内存溢出等问题。垃圾收集器在Ja…...

智能在线客服平台:数字化时代企业连接用户的 AI 中枢

随着互联网技术的飞速发展&#xff0c;消费者期望能够随时随地与企业进行交流。在线客服平台作为连接企业与客户的重要桥梁&#xff0c;不仅优化了客户体验&#xff0c;还提升了企业的服务效率和市场竞争力。本文将探讨在线客服平台的重要性、技术进展、实际应用&#xff0c;并…...

学习STC51单片机31(芯片为STC89C52RCRC)OLED显示屏1

每日一言 生活的美好&#xff0c;总是藏在那些你咬牙坚持的日子里。 硬件&#xff1a;OLED 以后要用到OLED的时候找到这个文件 OLED的设备地址 SSD1306"SSD" 是品牌缩写&#xff0c;"1306" 是产品编号。 驱动 OLED 屏幕的 IIC 总线数据传输格式 示意图 …...

python如何将word的doc另存为docx

将 DOCX 文件另存为 DOCX 格式&#xff08;Python 实现&#xff09; 在 Python 中&#xff0c;你可以使用 python-docx 库来操作 Word 文档。不过需要注意的是&#xff0c;.doc 是旧的 Word 格式&#xff0c;而 .docx 是新的基于 XML 的格式。python-docx 只能处理 .docx 格式…...

Rapidio门铃消息FIFO溢出机制

关于RapidIO门铃消息FIFO的溢出机制及其与中断抖动的关系&#xff0c;以下是深入解析&#xff1a; 门铃FIFO溢出的本质 在RapidIO系统中&#xff0c;门铃消息FIFO是硬件控制器内部的缓冲区&#xff0c;用于临时存储接收到的门铃消息&#xff08;Doorbell Message&#xff09;。…...

【数据分析】R版IntelliGenes用于生物标志物发现的可解释机器学习

禁止商业或二改转载&#xff0c;仅供自学使用&#xff0c;侵权必究&#xff0c;如需截取部分内容请后台联系作者! 文章目录 介绍流程步骤1. 输入数据2. 特征选择3. 模型训练4. I-Genes 评分计算5. 输出结果 IntelliGenesR 安装包1. 特征选择2. 模型训练和评估3. I-Genes 评分计…...

九天毕昇深度学习平台 | 如何安装库?

pip install 库名 -i https://pypi.tuna.tsinghua.edu.cn/simple --user 举个例子&#xff1a; 报错 ModuleNotFoundError: No module named torch 那么我需要安装 torch pip install torch -i https://pypi.tuna.tsinghua.edu.cn/simple --user pip install 库名&#x…...