key-pair 相关问题


如何查找给定的键是否存在于 std::map 中

我正在尝试检查给定的键是否在地图中,但有些无法做到: typedef 映射::迭代器 mi; 地图米; m.insert(make_pair("f","++--")); 一对 我正在尝试检查给定的键是否在地图中,但有些做不到: typedef map<string,string>::iterator mi; map<string, string> m; m.insert(make_pair("f","++--")); pair<mi,mi> p = m.equal_range("f");//I'm not sure if equal_range does what I want cout << p.first;//I'm getting error here 那么我怎样才能打印p中的内容呢? 使用 map::find 和 map::end: if (m.find("f") == m.end()) { // not found } else { // found } 要检查映射中是否存在特定键,请通过以下方式之一使用 count 成员函数: m.count(key) > 0 m.count(key) == 1 m.count(key) != 0 map::find的文档说:“另一个成员函数map::count可用于仅检查特定键是否存在。” map::count的文档说:“因为地图容器中的所有元素都是唯一的,所以该函数只能返回1(如果找到该元素)或零(否则)。” 要通过您知道存在的键从映射中检索值,请使用 map::at: value = m.at(key) 与 map::operator[] 不同,如果指定的键不存在,map::at 不会在映射中创建新键。 C++20 为我们提供了 std::map::contains 来做到这一点。 #include <iostream> #include <string> #include <map> int main() { std::map<int, std::string> example = {{1, "One"}, {2, "Two"}, {3, "Three"}, {42, "Don\'t Panic!!!"}}; if(example.contains(42)) { std::cout << "Found\n"; } else { std::cout << "Not found\n"; } } 您可以使用.find(): map<string,string>::iterator i = m.find("f"); if (i == m.end()) { /* Not found */ } else { /* Found, i->first is f, i->second is ++-- */ } C++17 通过带有初始化器的 If 语句进一步简化了这一点。 这样你就可以鱼与熊掌兼得了。 if ( auto it{ m.find( "key" ) }; it != std::end( m ) ) { // Use `structured binding` to get the key // and value. const auto&[ key, value ] { *it }; // Grab either the key or value stored in the pair. // The key is stored in the 'first' variable and // the 'value' is stored in the second. const auto& mkey{ it->first }; const auto& mvalue{ it->second }; // That or just grab the entire pair pointed // to by the iterator. const auto& pair{ *it }; } else { // Key was not found.. } m.find == m.end() // not found 如果您想使用其他API,请找到m.count(c)>0 if (m.count("f")>0) cout << " is an element of m.\n"; else cout << " is not an element of m.\n"; 我想你想要map::find。如果 m.find("f") 等于 m.end(),则未找到密钥。否则,find 返回一个指向找到的元素的迭代器。 错误是因为p.first是一个迭代器,它不适用于流插入。将最后一行更改为 cout << (p.first)->first;。 p 是一对迭代器,p.first 是迭代器,p.first->first 是键字符串。 一张地图对于给定的键只能有一个元素,所以 equal_range 不是很有用。它是为映射定义的,因为它是为所有关联容器定义的,但它对于多重映射更有趣。 template <typename T, typename Key> bool key_exists(const T& container, const Key& key) { return (container.find(key) != std::end(container)); } 当然,如果你想变得更奇特,你可以随时模板化一个函数,该函数也采用已找到的函数和未找到的函数,如下所示: template <typename T, typename Key, typename FoundFunction, typename NotFoundFunction> void find_and_execute(const T& container, const Key& key, FoundFunction found_function, NotFoundFunction not_found_function) { auto& it = container.find(key); if (it != std::end(container)) { found_function(key, it->second); } else { not_found_function(key); } } 并像这样使用它: std::map<int, int> some_map; find_and_execute(some_map, 1, [](int key, int value){ std::cout << "key " << key << " found, value: " << value << std::endl; }, [](int key){ std::cout << "key " << key << " not found" << std::endl; }); 这样做的缺点是想出一个好名字,“find_and_execute”很尴尬,我想不出更好的名字...... map<string, string> m; 检查 key 是否存在,并返回出现次数(map 中为 0/1): int num = m.count("f"); if (num>0) { //found } else { // not found } 检查key是否存在,并返回迭代器: map<string,string>::iterator mi = m.find("f"); if(mi != m.end()) { //found //do something to mi. } else { // not found } 在你的问题中,由坏的operator<<过载引起的错误,因为p.first是map<string, string>,你无法打印出来。尝试这个: if(p.first != p.second) { cout << p.first->first << " " << p.first->second << endl; } 小心地将查找结果与地图“m”的结尾进行比较,因为所有答案都有 上面完成 地图::迭代器 i = m.find("f"); if (i == m.end()) { } else { } 您不应该尝试执行任何操作,例如如果迭代器 i 等于 m.end() 则打印键或值,否则会导致分段错误。 比较 std::map::find 和 std::map::count 的代码,我认为第一个可能会产生一些性能优势: const_iterator find(const key_type& _Keyval) const { // find an element in nonmutable sequence that matches _Keyval const_iterator _Where = lower_bound(_Keyval); // Here one looks only for lower bound return (_Where == end() || _DEBUG_LT_PRED(this->_Getcomp(), _Keyval, this->_Key(_Where._Mynode())) ? end() : _Where); } size_type count(const key_type& _Keyval) const { // count all elements that match _Keyval _Paircc _Ans = equal_range(_Keyval); // Here both lower and upper bounds are to be found, which is presumably slower. size_type _Num = 0; _Distance(_Ans.first, _Ans.second, _Num); return (_Num); } find() 和 contains() 都可以使用。根据文档。两种方法平均时间为常数,最坏情况下为线性时间。 我知道这个问题已经有一些很好的答案,但我认为我的解决方案值得分享。 它适用于 std::map 和 std::vector<std::pair<T, U>>,并且可从 C++11 开始使用。 template <typename ForwardIterator, typename Key> bool contains_key(ForwardIterator first, ForwardIterator last, Key const key) { using ValueType = typename std::iterator_traits<ForwardIterator>::value_type; auto search_result = std::find_if( first, last, [&key](ValueType const& item) { return item.first == key; } ); if (search_result == last) { return false; } else { return true; } } map <int , char>::iterator itr; for(itr = MyMap.begin() ; itr!= MyMap.end() ; itr++) { if (itr->second == 'c') { cout<<itr->first<<endl; } } 如果你想比较成对的地图,你可以使用这个方法: typedef map<double, double> TestMap; TestMap testMap; pair<map<double,double>::iterator,bool> controlMapValues; controlMapValues= testMap.insert(std::pair<double,double>(x,y)); if (controlMapValues.second == false ) { TestMap::iterator it; it = testMap.find(x); if (it->second == y) { cout<<"Given value is already exist in Map"<<endl; } } 这是一项有用的技术。


一个专注于 StreamBuilder 的小部件刷新整个屏幕

我有这个小部件。 类 YourStreamBuilder 扩展 StatefulWidget { 最终字符串postId; const YourStreamBuilder({Key? key, required this.postId}) : super(key: key); @覆盖 状态<


如何在MultiversX区块链上的Rust中实现USDT到EGLD代币的兑换?

我正在尝试获取 EGLD 中 USDT 的价格。我正在使用这个:https://github.com/multiversx/mx-exchange-sc/blob/main/dex/pair/src/lib.rs#L604 端点来获取价格。但不确定是否正确


迭代地将任意深度列表转换为字典

输入有一个模式,列表中的每个元素都是一个字典并且有固定的键 [{'key': 'a', 'children': [{'key': 'a1', 'children': [{'key': 'a11', 'children': []}]}]}, {'key': 'b', 'children': ...


如何从另一个 Sub 使用 KeyEventArgs 调用 Sub

我有两个替补 Private Sub kbHook_KeyDown(ByVal Key As System.Windows.Forms.Keys) 处理 KeyHook.KeyDown 和 Private Sub Form1_KeyPressCaps(ByVal key As Object, e As KeyEventArgs) 处理我。


合并和更新数据框

假设我有2个数据框, df1 = pd.DataFrame({'key': ['a', 'A',], 'value': [1, 1,]}) df2 = pd.DataFrame({'key': ['A', 'B'], '值': [5, 6,]}) 数据框具有相同的列,但不同......


在 AKS 中使用 nginx 入口控制器,并使用工作负载身份从 Key Vault 中提取 TLS 证书终止

我正在将 AKS 与 nginx 入口控制器结合使用。 我正在使用包含 .key 和 .crt 的 kubernetes tls Secret 并将其引用到 ingress.yaml 中 Kubectl 创建秘密 tls $secret_name --key=...


MySQL 中的“INSERT IGNORE”和“INSERT ... ON DUPLICATE KEY UPDATE”有什么区别? [重复]

INSERT IGNORE 和 INSERT…ON DUPLICATE KEY UPDATE 有什么区别。我也想知道哪一个比另一个更受青睐。有人可以帮忙吗?


Laravel 8 验证数组

我有一个 Laravel 8 表单,其中包含一系列用户联系方式。 我有一个 Laravel 8 表单,其中包含一系列用户联系方式。 <div> <input name="contactdetails[{{ $key }}][email]" type="text"> <input name=" contactdetails [{{ $key }}][mobile]" type="text"> </div <div> <input name=" contactdetails [{{ $key }}][email]" type="text"> <input name=" contactdetails [{{ $key }}][mobile]" type="text"> </div <div> <input name=" contactdetails [{{ $key }}][email]" type="text"> <input name=" contactdetails [{{ $key }}][mobile]" type="text"> </div 我的验证规则如下所示: contactdetails.*.email=> ‘email:rfc,dns’, contactdetails.*. mobile => required_with:email|numeric', 我需要验证是否至少输入了一封电子邮件(但不是全部)以及相应的手机。 你必须这样做: 'contactdetails' => 'array|min:1', 'contactdetails.*.email' => 'email:rfc,dns', 'contactdetails.*.mobile' => 'required_with:contactdetails.*.email|numeric|nullable', 这意味着 contactdetails 必须是数组并且至少有一个成员 并更好地添加正则表达式移动角色来验证正确的手机号码


Azure Key Vault 是否适合存储客户端应用程序生成的加密密钥?

我有客户端应用程序,可以生成在设备上加密的数据。加密密钥通过 HTTPS 发送到使用 Azure Key Vault 存储加密密钥的 Azure 函数...


比较两个列表并使用rejectattr文件将结果写入文件中

鉴于列表已过期: [ { "cert": "help.abc.com.cer", "certkey": "help.abc.com-key", “到期天数”:0, &...


React 中的filter() 和map() 数据到单选按钮

我正在从 API 获取以下格式的数据: const 汽车属性 = [ { "key": "品牌", “价值观”:[ { ...


在 macOS 的本地主机上设置 HTTPS [mac os catalina 10.15.2]

cd ~/ mkdir .localhost-ssl sudo openssl genrsa -out ~/.localhost-ssl/localhost.key 2048 sudo openssl req -new -x509 -key ~/.localhost-ssl/localhost.key -out ~/.localhost-ssl/localhost.crt -days 3...


检查 bash 中数组是否为空

我想看看 bash 中的数组是否为空 键=[] key1=["2014"] 我尝试过以下方法: [[ -z "$key" ]] && echo "空" || echo“非空”...


如何在f格式中使用string.len()函数?

如何让 len() 在 Python f 字符串格式中工作? 对于dictionary.items()中的键、值: (f'{键:<(len(key)+2)}<->{值:>4} ')


“Google play 应用程序 - 签名问题”NoSuchAlgorithmException 异常

运行以下命令时出现以下错误 java -jar pepk.jar --keystore=foo.keystore --alias=foo --output=encrypted_private_key_path --rsa-aes-encryption --encryption-key-path=/path/to/


如何在 f 字符串格式化中使用 string.len() 函数?

如何让 len() 在 Python f 字符串格式中工作? 对于dictionary.items()中的键、值: (f'{键:<(len(key)+2)}<->{值:>4} ')


Microsoft Bing v7 搜索参数不起作用

我正在尝试 MS Bing v7 API。 如果我输入一个curl请求: 卷曲-H“Ocp-Apim-Subscription-Key:” https://api.bing.microsoft.com/v7.0/search?q=vintage+cars&count=25&


移动设备友好测试 API 到 2024 年仍然有效吗?

我即将使用谷歌搜索控制台API从Mobile-FriendlyTest获取数据 $request = new Request('POST', 'https://searchconsole.googleapis.com/v1/urlTestingTools/mobileFriendlyTest:run?key='.$


有没有办法读取 PySimpleGUI 组合框的值属性?

我创建了一个 PySimpleGUI 组合框,其代码简化为: combo_list = ['选择 1', '选择 2'] 布局 = [[sg.Combo(combo_list, default_value=combo_list[0], key='-COMBO-',


Aerospike 多组内存计算

我需要在共享内存Aerospike主索引中存储大量Key。 我的规格如下: 命名空间:2, 记录数:500M, TTL:1D, 复制:2 根据 Aerospike


为什么我不能使用数据类的字段作为jetpack compose中lazyColumn的item的key?

一个非常非常简单的例子(implementation(platform("androidx.compose:compose-bom:2023.08.00"))): com.study.myapplication 包 导入 android.os.Bundle 导入 androidx.activity。


如何在 Neovim 中映射 Ctrl+Shift+<key> + Alacritty 中的 Tmux

我在 alacritty 中使用 neovim 和 tmux,目前我正在尝试为组合 和 创建键盘映射( 和 已经映射),但我无法得到...


Redis HMGET 命令的性能问题

在生产环境中使用Redis HMGET命令检索数据时,如果命令中包含的key数量超过10000个,且请求量较大,CPU占用率


C++ SIMD 屏蔽高于分隔符位置的字节的最快方法

uint8_t 数据[] = "mykeyxyz:1234 啊啊啊啊啊”; 我的字符串行的格式为 key:value,其中 len(key) <= 16 guaranteed. I want to load mykeyxyz into a __m128i, but fill out the higher


使用kafka密钥的kafka s3连接器分区

如何使用 kafka msg key 作为 s3 连接器中的分区标准或 我怎样才能获得密钥并将其存储在 s3 对象中 谢谢!


使用 MongoDB API 为 CosmosDB 创建唯一索引失败

我正在将 Azure CosmosDB 与 MongoDB API 结合使用。我正在尝试执行以下操作: db.createCollection('测试') db.test.createIndex({key: 1}, {name: 'key_1', unique: true}) 然而,这样做失败了......


如何在React-Native中从选择器中获取多个值?

这是我的反应本机选择器的代码。 我想获取所选 json 数组的所有值。 我想提供多项选择。 这是我的反应本机选择器的代码。 我想获取所选 json 数组的所有值。 我想提供多项选择。 <Picker mode="dropdown" style={styles.droplist} selectedValue={this.state.mode} onValueChange={this.funcValueChanged}> <Picker.Item label="Select Company" value="Select Company" /> { this.state.data.map((item, key) => ( <Picker.Item label={item.Co_Name + ' (' + item.CompCode + ')'} value={key} key={key} /> ))) } </Picker> 您可以用于单选/多选 从“react-native-dropdown-picker”导入 DropDownPicker; <DropDownPicker items={getAllStates} searchable={true} searchablePlaceholder="Search for an item" searchablePlaceholderTextColor="gray" placeholder="Select States" placeholderTextColor={"grey"} multiple={true} multipleText="%d items have been selected." containerStyle={{ marginTop: 8, marginBottom: 8, width: "92%", alignSelf: "center", }} onChangeItem={item => { } } /> 这里使用的包是@react-native-picker/picker,不支持多选。 GitHub 问题 请使用 npm i react-native-multiple-select 来代替。 尝试这个轻量级且完全可定制的包**rn-multipicker** - https://www.npmjs.com/package/rn-multipicker 完整文章:https://dev.to/rahul04/add-multi-select-dropdown-to-react-native-applications-53ef


导出ssh密钥对的位置

在我的 bash 配置文件中包含 $KEY="path/to/sshkey" 是否安全? 它有效,我只是想确保它不是一个漏洞。 一切都符合我的工作流程,只是想让...


如何检索 Azure 资源组模板中 Application Insights 实例的检测密钥?

有没有办法在 Azure 资源组模板中检索 Application Insights 实例的 Instrumentation Key ? 我已尝试此处的说明来检索 list* opera 的列表...


为什么这个程序专门使用负整数?

我正在阅读 C API LUA 文档,我注意到这段代码: lua_pushnil(L); /* 第一个键 */ while (lua_next(L, t) != 0) { /* 使用“key”(在索引-2处)和“value”(在索引-1处)*/ printf(&q...


Micronaut Key Store Path中可以设置S3路径吗?

我有一个使用 Micronaut 3.9.x(从 Micronaut 1 迁移)的 lambda 应用程序,它使用 HttpClient 并具有指向我的资源文件夹内的证书的 SSL 配置。我有


无法从S3存储桶下载文件。 (Langchain + s3)

我正在编写一个项目,使用s3来存储文件pdf,并使用langchain来连接和加载文件。 这是我的代码: const loader = new S3Loader({ bucket: process.env.BUCKET, key: filekey, // 示例: test/


使用复合模板创建信封并为自定义选项卡设置值

我录制了下面的视频来解释我想要实现的目标。 https://www.awesomescreenshot.com/video/23765847?key=c6107a99bee1285ea91f533a1e52b1f6 如果有人知道如何创建,请帮助我


没有匹配的函数可用于调用“std::thread::thread(<unresolved overloaded function type>)”

无效show_image(){ // 创建一个Mat来存储图像 马特凸轮图像; ERROR_CODE 错误; // 循环直到'e'被按下 字符键=''; while (key!= 'e') { // 抓取图像 错误= cam.grab(); ...


Aes 加密 Galois/Counter 模式尝试登录服务器端出现无效凭证问题,

下面是dart Aes加密逻辑的代码 静态字符串 encryptAESGCM(字符串明文, 字符串密钥) { 尝试 { 最终 keyBytes = Uint8List.fromList(utf8.encode(key)); // 安全...


为什么这个程序专门使用负无符号整数?

所以我正在阅读 c api lua 文档,我注意到这段代码: lua_pushnil(L); /* 第一个键 */ while (lua_next(L, t) != 0) { /* 使用“key”(在索引-2处)和“value”(在索引-1处)*/ 打印(...


从消费计划Azure功能访问Azure KV

我在 VNET 中部署了一个 Azure Key Vault,并且禁用了公共访问。我需要从无服务器的消费 Azure 函数中获取该 KV 的秘密。 问题是,作为那种类型...


Vue.js v-for 不渲染图像

我正在尝试使用 v-for 渲染四个图像,范围为 1 到 4。 v-for="n in 4" :key"n" 但是,使用 'n' 作为 src 的一部分不起作用。为什么? 我正在尝试使用 v-for 渲染四个图像,范围为 1 到 4。 v-for="n in 4" :key"n" 但是,使用 'n' 作为 src 的一部分不起作用。为什么? <div v-for="n in 4" :key="n"> <img :src="`../assets/images/image-product-${n}-thumbnail.jpg`" class="rounded-xl h-16 w-16 hover:cursor-pointer" /> </div> 尝试使用“key”代替“n”,将“n”转换为字符串...没有成功 如果我像这样硬编码,它会起作用 <img src="../assets/images/image-product-1-thumbnail.jpg" class="rounded-xl h-16 w-16 hover:cursor-pointer" /> 如果您有可用的全局别名(@),我建议您使用它。 因为使用相对路径可以在本地工作,但是当项目编译(构建)时,相关路径可能会被破坏。 使用动态 src 路径时,您可以在加载之前需要它。 使用别名,您可以执行以下操作: :src="`require(@/assets/images/image-product-${n}-thumbnail.jpg`)"


这个看似简单的TTL缓存访问模式的bug在哪里?

遇到问题。我将使用 python 显示代码片段: 从缓存工具导入 TTLCache 缓存 = TTLCache(maxsize=SOME_SIZE, ttl=SOME_TTL) def fetch(key): 如果密钥不在缓存中: 结果=数据...


Leaflet 图层控件出现在其他 z 索引较低的 div 后面

从截图中可以看出,Leaflet 图层控件出现在其他 div 的后面,而我希望它出现在它们的前面。 “Key”和“Participants”div 的 z-index 为 20。 传单


如何在 SQL Server 身份验证中使用始终加密访问表?

在 Azure SQL Server 上工作 我使用 Azure AD 访问 Key Vault,并生成了列主密钥和列加密密钥,以将 Always Encrypted 应用于特定表 因此,如果登录Al...


使用 Azure SDK for Java 创建 KeyClient 时出现问题

我正在尝试在代码中创建一个 KeyClient 对象,以便我可以在 azure key Vault 中创建密钥。 但我的对象不断出现服务错误,直到现在我才解决它。 这是我的代码: @Overri...


嵌套 useFetch 导致 Nuxt 3 中的 Hydration 节点不匹配

在 Nuxt 3 页面内,我通过从 pinia 存储调用操作来获取帖子数据: {{ 发布数据 }} {{ 帖子内容... 在 Nuxt 3 页面内,我通过从 pinia 商店调用操作来获取帖子数据: <template> <div v-if="postData && postContent"> {{ postData }} {{ postContent }} </div> </template> <script setup> const config = useRuntimeConfig() const route = useRoute() const slug = route.params.slug const url = config.public.wpApiUrl const contentStore = useContentStore() await contentStore.fetchPostData({ url, slug }) const postData = contentStore.postData const postContent = contentStore.postContent </script> 那是我的商店: import { defineStore } from 'pinia' export const useContentStore = defineStore('content',{ state: () => ({ postData: null, postContent: null }), actions: { async fetchPostData({ url, slug }) { try { const { data: postData, error } = await useFetch(`${url}/wp/v2/posts`, { query: { slug: slug }, transform(data) { return data.map((post) => ({ id: post.id, title: post.title.rendered, content: post.content.rendered, excerpt: post.excerpt.rendered, date: post.date, slug: post.slug, })); } }) this.postData = postData.value; if (postData && postData.value && postData.value.length && postData.value[0].id) { const {data: postContent} = await useFetch(`${url}/rl/v1/get?id=${postData.value[0].id}`, { method: 'POST', }); this.postContent = postContent.value; } } catch (error) { console.error('Error fetching post data:', error) } } } }); 浏览器中的输出正常,但我在浏览器控制台中收到以下错误: entry.js:54 [Vue warn]: Hydration node mismatch: - rendered on server: <!----> - expected on client: div at <[slug] onVnodeUnmounted=fn<onVnodeUnmounted> ref=Ref< undefined > > at <Anonymous key="/news/hello-world()" vnode= {__v_isVNode: true, __v_skip: true, type: {…}, props: {…}, key: null, …} route= {fullPath: '/news/hello-world', hash: '', query: {…}, name: 'news-slug', path: '/news/hello-world', …} ... > at <RouterView name=undefined route=undefined > at <NuxtPage> at <Default ref=Ref< undefined > > at <LayoutLoader key="default" layoutProps= {ref: RefImpl} name="default" > at <NuxtLayoutProvider layoutProps= {ref: RefImpl} key="default" name="default" ... > at <NuxtLayout> at <App key=3 > at <NuxtRoot> 如何解决这个问题? 我尝试在 onMounted 中获取帖子数据,但在这种情况下 postData 和 postContent 保持为空 onMounted(async () => { await contentStore.fetchPostData({ url, slug }) }) 您可以使用 ClientOnly 组件来消除该警告。请参阅文档了解更多信息。 该组件仅在客户端渲染其插槽。


如何获取 Azure 证书客户端响应和证书指纹

我正在尝试对进行证书验证的服务进行单元测试。它将给定指纹与存储在 Azure Key Vault 中的证书上的指纹进行比较。 我的代码运行良好,但现在我......


Cod:401“消息”使用开放天气 API 时 API 密钥无效

我正在尝试构建一个天气应用程序,每当我尝试搜索城市时,它都会显示未定义,并且湿度和风速值不会改变。我还收到 Cod:401 invalid API key 错误。 我已经尝试过...


{"cod":401, "message": "使用 Moya 时出现 Open Weather API 错误,API 密钥无效

所以我使用moya创建了一个对openweatherAPI的API请求。现在 Postman 的返回似乎没问题,但 X 代码上的 API 调用返回 401: Invalid API key 我已经尝试了很多方法来看看到底是什么......


如何使用webpack 5向脚本标签添加nonce属性

我使用 webpack 5 和 HtmlWebpackPlugin 来构建我的前端 SPA。 我需要向 添加随机数属性 <question vote="0"> <p>我正在使用 webpack 5 和 <pre><code>HtmlWebpackPlugin</code></pre> 来构建我的前端 SPA。</p> <p>我需要将 <pre><code>nonce</code></pre> 属性添加到 <pre><code>&lt;script ...</code></pre> 注入的 <pre><code>HtmlWebpackPlugin</code></pre> 标签中。</p> <p>我该怎么做?</p> <p>额外问题:之后我在服务之前使用此页面作为 Thymeleaf 模板。如何注入<pre><code>nonce</code></pre>值?</p> </question> <answer tick="false" vote="0"> <p>如果您使用的是 webpack 4,海里有很多鱼——只需使用任何注入属性的插件,例如 <a href="https://github.com/numical/script-ext-html-webpack-plugin" rel="nofollow noreferrer">script-ext-html-webpack-plugin</a> 或 <a href="https://github.com/dyw934854565/html-webpack-inject-attributes-plugin" rel="nofollow noreferrer">html-webpack-inject-attributes-plugin</a> </p> <p>但是,上面提到的大多数插件都不适用于 webpack 5。解决方法是使用 <pre><code>HtmlWebpackPlugin</code></pre> <a href="https://github.com/jantimon/html-webpack-plugin#writing-your-own-templates" rel="nofollow noreferrer">templates</a>。</p> <ol> <li>将<pre><code>inject</code></pre>中指定的<pre><code>false</code></pre>选项中的<pre><code>HtmlWebpackPlugin</code></pre>设置为<pre><code>webpack.config</code></pre>。</li> <li>在模板中添加以下代码,将所有生成的脚本插入到结果文件中:</li> </ol> <pre><code> &lt;% for (key in htmlWebpackPlugin.files.js) { %&gt; &lt;script type=&#34;text/javascript&#34; defer=&#34;defer&#34; src=&#34;&lt;%= htmlWebpackPlugin.files.js[key] %&gt;&#34;&gt;&lt;/script&gt; &lt;% } %&gt; </code></pre> <ol start="3"> <li>在 <pre><code>script</code></pre> 中添加所有必要的属性。百里香示例:</li> </ol> <pre><code> &lt;% for (key in htmlWebpackPlugin.files.js) { %&gt; &lt;script type=&#34;text/javascript&#34; defer=&#34;defer&#34; th:attr=&#34;nonce=${cspNonce}&#34; src=&#34;&lt;%= htmlWebpackPlugin.files.js[key] %&gt;&#34;&gt;&lt;/script&gt; &lt;% } %&gt; </code></pre> <p>基于 <a href="https://github.com/jantimon/html-webpack-plugin/issues/538#issuecomment-270340587" rel="nofollow noreferrer">github 帖子</a></p>的答案 </answer> </body></html>


如何捕获 React-Bootstrap 下拉列表的值?

我弄清楚了如何使用react-bootstrap来显示下拉列表: 我想出了如何使用react-bootstrap来显示下拉列表: <DropdownButton bsStyle="success" title="Choose" onSelect={this.handleSelect} > <MenuItem key="1">Action</MenuItem> <MenuItem key="2">Another action</MenuItem> <MenuItem key="3">Something else here</MenuItem> </DropdownButton> 但是我该如何编写 onSelect 的处理程序来捕获正在选择的选项呢?我尝试了这个,但不知道里面写什么: handleSelect: function () { // what am I suppose to write in there to get the value? }, 还有,有没有办法设置默认选择的选项? onSelect函数传递所选值 <DropdownButton title='Dropdowna' onSelect={function(evt){console.log(evt)}}> <MenuItem eventKey='abc'>Dropdown link</MenuItem> <MenuItem eventKey={['a', 'b']}>Dropdown link</MenuItem> </DropdownButton> 在这种情况下,如果您选择第一个选项,则会打印“abc”,在第二个选项中您可以看到也可以传入一个对象。 所以在你的代码中 handleSelect: function (evt) { // what am I suppose to write in there to get the value? console.log(evt) }, 我不确定默认值是什么意思,因为这不是一个选择 - 按钮文本是标题属性中的任何内容。如果你想处理默认值,你可以在值为 null 时设置一个值。 您忘记提及 eventKey 作为第二个参数传递,这是获取您单击的值的正确形式: handleSelect: function (evt,evtKey) { // what am I suppose to write in there to get the value? console.log(evtKey) }, 您可能需要针对您的情况使用 FormControl >> 选择组件: <FormControl componentClass="select" placeholder="select"> <option value="select">select</option> <option value="other">...</option> </FormControl> 您应该按如下方式更改handleSelect签名(在组件类中): handleSelect = (evtKey, evt) => { // Get the selectedIndex in the evtKey variable } 要设置默认值,您需要使用 title 上的 DropdownButton 属性 参考:https://react-bootstrap.github.io/components/dropdowns/


Laravel 动态扩展或使用 Traits

可以在运行时扩展或使用不同的类吗? 例子: 假设我们有一个名为 Player 的模型(我们的 A 模型) 可以在运行时扩展或使用不同的类吗? 示例: 假设我们有一个 model 称为 Player(我们的 A 模型) <?php namespace App\Models; use Illuminate\Database\Eloquent\Model; class Player extends Model{ } 我们还有另外 2 个型号(B 和 C 型号) <?php namespace App\Models; use Illuminate\Database\Eloquent\Model; protected $connection= 'db_b'; class PlayerInfoB extends Model{ function getName(){ return $this->name; } } 我们的C型号 <?php namespace App\Models; use Illuminate\Database\Eloquent\Model; protected $connection= 'db_c'; class PlayerInfoC extends Model{ function getName(){ return $this->name_g; } } 模型A (Player)如何在运行时根据配置或其他数据扩展Model B or C 为什么我需要这个。 我有 2 个或更多不同的表,这些表的列有不同的名称,例如: Table 1 - name Table 2 - name_g Table 3 - name_full 所以我需要一个可以随时调用的包装器getName(),而无需检查现在使用的表。 $player = Player::get(); echo $player->getName(); 如果有不清楚的地方,请评论,我会更新我的问题。 更新基于madalin-ivascu答案可以这样完成吗? class Player extends Model{ protected $model; public function __construct(){ $this->setModel(); parent::__construct(); } protected function setModel(){ $this->model = $this->column_model_name } function getAttributeName(){ return $this->model->getName(); } } 如果不使用 eval 或 dirty hacks,就不可能在运行时编写一个类。您必须重新考虑您的类设计,因为您不太可能需要通过良好的设计来做到这一点。 您可以做的是使用方法 setTable 和 on: 在运行时更改模型实例上的表和数据库连接 Player::on('db_b')->setTable('player_info_b')->find($id); 另一种方法(首选)是定义模型 PlayerInfoC 和 PlayerInfoB 来扩展您的 Player 模型,然后根据您的情况在需要时实例化类 B 或 C。 在您的代码中,您的脚本必须具有您检查的状态,以便知道何时使用正确的模型? 既然如此,为什么不在 get name 中使用参数呢? class Player extends Model{ function getName($field){ return isset($this->{$field}) ? $this->{$field} : null; } } 如果你经常这样做,那么使用魔法方法: class Player extends Model{ function __get($key){ return isset($this->{$field}) ? $this->{$field} : null; } } ... echo $myModelInstance->{$field}; http://php.net/manual/en/language.oop5.overloading.php#object.get 在 Laravel 中,当你通过集合方法拉回数据时,它无论如何都会执行这个神奇的方法,因为所有属性都存储在称为属性的嵌套对象中,因此 __set() 和 __get() 看起来像这样: function __get($key){ return isset($this->attributes->{$key}) ? $this->attributes->{$key} : null; } function __set($key, $value){ return $this->attributes->{$key} = $value; } 建议后者带有属性子集,这样可以防止数据与返回的数据库列名称与模型中已使用的名称发生冲突。 这样,您只需在创建的每个模型中将一个属性名称作为保留名称进行管理,而不必担心您使用的数百个 var 名称会覆盖模型或模型扩展中的另一个属性名称。 使用该模型值来调用函数 $player = Player::get(); echo Player::getName($player->id,'PlayerInfoC'); 在 Player 模型中您只需调用 public static function getName($id,$class) return $class::where('player_id',$id)->getName();//each class will have the function } ps:您需要进行一些验证来测试该名称是否存在 另一种选择是在模型之间创建关系 您可以在模型中使用与以下相同的启动方法来执行此操作: protected static function booted() { if (<--your condition-- >) { $traitInitializers[static::class][] = 'boot' . ExampleTrait::class; $traitInitializers[static::class][] = 'boot' . Organizations::class; } }


© www.soinside.com 2019 - 2024. All rights reserved.